在做項目的過程中,經常會用到鼠標的交互和鍵盤交互,這節我們就來學習一下
大致原理就是在需要用到的地方,監聽鼠標和鍵盤的輸入狀態
on(開啟監聽)和off(移除監聽)
1.要接收鼠標事件必須設置寬高,否則不會被命中
rect.size(200, 200);
2.或者設置mouseThrough為true,檢測區域為實際顯示的邊界
rect.mouseThrough = true;
3.如果要開啟多點觸摸的話
Laya.MouseManager.multiTouchEnabled = true;
1.鼠標交互
var rect = new Sprite();
rect.graphics.drawRect(0, 0, 200, 200, "#D2691E");
rect.size(200, 200);
rect.x = (Laya.stage.width - 200) / 2;
rect.y = (Laya.stage.height - 200) / 2;
Laya.stage.addChild(rect);
//增加鼠標事件
//鼠標按下
rect.on(Laya.Event.MOUSE_DOWN, this, mouseHandler);
//鼠標抬起
rect.on(Laya.Event.MOUSE_UP, this, mouseHandler);
//鼠標單擊
rect.on(Laya.Event.CLICK, this, mouseHandler);
//鼠標右鍵按下
rect.on(Laya.Event.RIGHT_MOUSE_DOWN, this, mouseHandler);
//鼠標右鍵抬起
rect.on(Laya.Event.RIGHT_MOUSE_UP, this, mouseHandler);
//鼠標右鍵單擊
rect.on(Laya.Event.RIGHT_CLICK, this, mouseHandler);
//鼠標移動
rect.on(Laya.Event.MOUSE_MOVE, this, mouseHandler);
//鼠標經過目標范圍
rect.on(Laya.Event.MOUSE_OVER, this, mouseHandler);
//鼠標移出目標范圍
rect.on(Laya.Event.MOUSE_OUT, this, mouseHandler);
//鼠標左鍵雙擊
rect.on(Laya.Event.DOUBLE_CLICK, this, mouseHandler);
//鼠標滾輪滾動
rect.on(Laya.Event.MOUSE_WHEEL, this, mouseHandler);
2.鍵盤交互
//鍵盤按下
Laya.stage.on(Laya.Event.KEY_DOWN,this,this.keyboardHandle);
//鍵盤摁住
Laya.stage.on(Laya.Event.KEY_PRESS,this,this.keyboardHandle);
//鍵盤抬起
Laya.stage.on(Laya.Event.KEY_UP,this,this.keyboardHandle);
3.自定義事件
原理就是設置監聽-->發送對應的事件-->執行回調
function createSprite()
{
sp = new Sprite();
sp.graphics.drawRect(0, 0, 200, 200, "#D2691E");
sp.pivot(100, 100);
sp.x = Laya.stage.width / 2;
sp.y = Laya.stage.height / 2;
sp.size(200, 200);
Laya.stage.addChild(sp);
// 偵聽自定義的事件
sp.on(ROTATE, this, onRotate);
sp.on(Event.CLICK, this, onSpriteClick);
}
function onSpriteClick(e)
{
var randomAngle = Math.random() * 180;
//發送自定義事件
sp.event(ROTATE, [randomAngle]);
}
// 觸發自定義的rotate事件
function onRotate(newAngle)
{
Tween.to(sp,
{
"rotation": newAngle
}, 1000, Ease.elasticOut);
}