import SScript from './SScript'; import { SSoundManager } from "../core/SSoundManager"; import Sprite = Laya.Sprite; import Button = Laya.Button; /** 此脚本为宿主提供以下功能 * 1. 可点击范围扩大 * 2. 阻止点击事件往上冒泡 * 3. 点击效果(能够发出声音以及进行缩放等) */ export default class SButton extends SScript{ /** @prop {name:touchAreaX, tips:"在左侧和右侧拓展的点击范围", type:Number, default:0} */ touchAreaX:number = 0; /** @prop {name:touchAreaY, tips:"在上侧和下侧拓展的点击范围", type:Number, default:0} */ touchAreaY:number = 0; /** @prop {name:stopPropagation, tips:"是否阻止点击事件冒泡", type:Boolean, default:false} */ stopPropagation:boolean = false; /** @prop {name:playScale, tips:"是否启动点击缩放效果", type:Boolean, default:false} */ playScale:boolean = false; /** @prop {name:playSound, tips:"是否启动点击音效", type:Boolean, default:false} */ playSound:boolean = false; /** @prop {name:playLabelFade, tips:"是否启动点击Label褪色效果", type:Boolean, default:false} */ playLabelFade:boolean = false; private _btnLabel:Laya.Text; constructor(){ super(); } onEnable(){ let o:Button = (this.owner as Button); if(this.touchAreaX || this.touchAreaY) { this._resetHitArea(); o.on(Laya.Event.RESIZE, this, this._resetHitArea); } if(this.stopPropagation || this.playSound) { o.on(Laya.Event.CLICK, this, this._onOwnerClick); } if(this.playScale || this.playLabelFade) { o.on(Laya.Event.MOUSE_DOWN, this, this._onOwnerDown); } this._btnLabel = o.text; } onDisable(){ this.owner.offAllCaller(this); } private _onOwnerClick(e:Event){ if(this.stopPropagation)e.stopPropagation(); if(this.playSound)SSoundManager.playSound('click'); } private _onOwnerDown(e:Event){ let o:Sprite = (this.owner as Sprite); if(this.playScale) { o.scaleX = o.scaleY = 0.9; } if(this.playLabelFade && this._btnLabel) { this._btnLabel.alpha = 0.5; } o.on(Laya.Event.MOUSE_UP, this, this._onOwnerUp); o.on(Laya.Event.MOUSE_OUT, this, this._onOwnerUp); } private _onOwnerUp(e:Event){ let o:Sprite = (this.owner as Sprite); if(this.playScale) { o.scaleX = o.scaleY = 1; } if(this.playLabelFade && this._btnLabel) { this._btnLabel.alpha = 1; } o.off(Laya.Event.MOUSE_UP, this, this._onOwnerUp); o.off(Laya.Event.MOUSE_OUT, this, this._onOwnerUp); } private _resetHitArea(){ let o:Sprite = (this.owner as Sprite); o.hitArea = new Laya.Rectangle(-this.touchAreaX, -this.touchAreaY, o.width + 2 * this.touchAreaX, o.height + 2 * this.touchAreaY); } }