hitTest(t: Laya.Image) {
let s = t.source.getPixels(t.mouseX, t.mouseY, 1, 1).join('');
if (s == '0000') return false;
return true;
}
if (hitTest(target)) {
// do hitTest action;
}
通过检测像素点颜色值来判断点击区域,这里不能用 on(Laya.Event.CLICK,只能通过 on(Laya.Event.MOUSE_DOWN 来检测。
下面是我的代码处理:
class demo {
private down:Laya.Image;
constructor() {
// 鼠标事件
Laya.stage.on(Laya.Event.MOUSE_DOWN, this, this.onMouseDown);
Laya.stage.on(Laya.Event.MOUSE_MOVE, this, this.onMouseMove);
Laya.stage.on(Laya.Event.MOUSE_UP, this, this.onMouseUp, [true]);
}
/** 按钮动画处理 */
private hitTest(t: Laya.Image) {
let s = t.source.getPixels(t.mouseX, t.mouseY, 1, 1).join('');
if (s == '0000') return false;
this.down = t;
return true;
}
private onMouseDown() {
if (this.hitTest(this.racingB)) { this.scaleSmall(this.down); }
else if (this.hitTest(this.marketB)) { this.scaleSmall(this.down); }
else if (this.hitTest(this.breedB)) { this.scaleSmall(this.down); }
else if (this.hitTest(this.mineB)) { this.scaleSmall(this.down); }
}
private onMouseMove() {
if (!this.down) return;
if (this.hitTest(this.down)) return;
this.onMouseUp(false);
}
private onMouseUp(up: boolean) {
if (!this.down) return;
this.scaleBig(this.down);
if (up) {
if (this.down === this.racingB) {
// do click
} else if (this.down === this.marketB) {
// do click
} else if (this.down === this.breedB) {
// do click
} else if (this.down === this.mineB) {
// do click
}
}
delete this.down;
}
private scaleSmall(t: Laya.Image) {
Laya.Tween.to(t, { scaleX: 0.95, scaleY: 0.95 }, 66);
t.once(Laya.Event.CLICK, t, () => Laya.SoundManager.playSound(Laya.SButton.globalClickAudio, 1));
}
private scaleBig(t: Laya.Image) { Laya.Tween.to(t, { scaleX: 1, scaleY: 1 }, 66); }
}