開啟按鈕效果
官網點擊效果範例:https://pixijs.io/examples/#/basics/click.js
預設sprite是無法被點擊到的,因為要偵測這些事件會讓sprite更耗資源,因此如果我們想要讓一個sprite可以被點擊,則要特別對元件設定:
// Opt-in to interactivity sprite.interactive = true; // Shows hand cursor sprite.buttonMode = true; // Pointers normalize touch and mouse sprite.on('pointerdown', onClick); sprite.on('click', onClick); // mouse-only sprite.on('tap', onClick); // touch-only
在連連看專案加入按鈕
ButtonBase
因為連連看裡面有許多個按鈕,每個按鈕雖然功能不同,但是會有許多相似的設定,因此將按鈕抽出一個ButtonBase
的父類別
ButtonBase.ts的內容如下:
import Sprite = PIXI.Sprite; import {Loader} from "../core/Loader"; export class ButtonBase extends Sprite{ constructor(_id:string, textureID:string, _x:number, _y:number) { super(); this.texture = Loader.resources[_id].textures[textureID]; this.interactive = true; this.buttonMode = true; this.x = _x; this.y = _y; this.anchor.set(0.5); //按下效果 this.on("mousedown", this.mouseDownEffect.bind(this)); this.on("mouseup", this.mouseUpEffect.bind(this)); this.on("mouseout", this.mouseOutEffect.bind(this)); this.on("touchstart", this.mouseDownEffect.bind(this)); this.on("touchend", this.mouseUpEffect.bind(this)); this.on("mouseup", this.trigger.bind(this)); this.on("touchend", this.trigger.bind(this)); } public trigger(){ } public mouseDownEffect():void{ } public mouseUpEffect():void{ } public mouseOutEffect():void{ } }
SoundBtn
新增一個檔案SoundBtn.ts
,製作聲音開/關按鈕,內容如下:
import {ButtonBase} from "./ButtonBase"; import {Loader} from "../core/Loader"; import {SoundMgr} from "../core/SoundMgr"; export class SoundBtn extends ButtonBase { private isMute: boolean = false; constructor() { super('Button','Sound_On',50,170); this.updateImage(); } public trigger(){ this.isMute = !this.isMute; SoundMgr.mute(this.isMute); this.updateImage(); } updateImage = ()=>{ if (this.isMute){ this.texture = this.texture = Loader.resources['Button'].textures['Sound_Off']; } else{ this.texture = this.texture = Loader.resources['Button'].textures['Sound_On']; } } }
GameScene
因為除了聲音按鈕外,要設定整個場景還需要加入非常多東西,因此我新增了一個類別叫GameScene
,主要在將所有場景上的物件加進場景裡
GameScene.ts其內容如下
import {Loader} from "../core/Loader"; import {application} from "../Main"; import {SoundBtn} from "./SoundBtn"; export class GameScene { public static draw(){ //加入背景 application.stage.addChild(PIXI.Sprite.from(Loader.resources["background"].texture)); //加入按鈕 application.stage.addChild(new SoundBtn()); } }
實作靜音功能
在SoundMgr.ts加上靜音功能
static isMute: boolean = false; public static mute(value:boolean):void { this.isMute = value; if (this.isMute) { //禁聲 Howler.mute(true); } else { //出聲 Howler.mute(false); } }
今日成果
線上demo:http://claire-chang.com/ironman2018/1102/
檔案下載:ironman20181102