鼠標(biāo)事件
//鼠標(biāo)事件
this.node.on(cc.Node.EventType.MOUSE_DOWN, (e: cc.Event.EventMouse) => {
cc.log(e.getLocation() + "")
if (e.getButton() == cc.Event.EventMouse.BUTTON_LEFT) {
cc.log("鼠標(biāo)左鍵")
}
})
鍵盤(pán)事件
//鍵盤(pán)事件
cc.systemEvent.on(cc.SystemEvent.EventType.KEY_DOWN, (e: cc.Event.EventKeyboard) => {
cc.log(e.keyCode + "")
if (e.keyCode == cc.macro.KEY.a) {
cc.log("點(diǎn)擊a")
}
})
觸摸事件
//觸摸事件
this.node.on(cc.Node.EventType.TOUCH_START, (e: cc.Event.EventTouch) => {
cc.log("觸摸" + e.getLocation())
})
自定義事件(消息通知)
- 發(fā)送通知(2種方式)
this.node.on(cc.Node.EventType.MOUSE_DOWN, () => {
cc.log("點(diǎn)擊按鈕,發(fā)送事件1")
cc.find("human").emit("msg")
})
this.node.on(cc.Node.EventType.MOUSE_DOWN, () => {
cc.log("點(diǎn)擊按鈕,發(fā)送事件2")
let event = new cc.Event.EventCustom("msg", true)
event.detail = {date: new Date(), text: "hello"}
cc.find("human").dispatchEvent(event)
}
)
- 接收方
//自定義事件,例如通知
this.node.on("msg", (e:cc.Event.EventCustom) => {
cc.log("自定義事件觸發(fā)")
cc.log(e.detail.text)
})
Demo,控制精靈移動(dòng)
isFocus: boolean = false
speed: number = 50
start() {
//鼠標(biāo)(MOUSE_DOWN)、或手指拖拽人物移動(dòng)
this.node.on(cc.Node.EventType.TOUCH_START, () => {
this.isFocus = true
})
this.node.on(cc.Node.EventType.TOUCH_END, () => {
this.isFocus = false
})
this.node.on(cc.Node.EventType.TOUCH_MOVE, (e: cc.Event.EventTouch) => {
if (this.isFocus) {
this.node.setPosition(e.getLocation())
}
})
//鍵盤(pán)控制人物移動(dòng)
cc.systemEvent.on(cc.SystemEvent.EventType.KEY_DOWN, (e: cc.Event.EventKeyboard) => {
if (e.keyCode == cc.macro.KEY.up){
this.node.y += this.speed;
}else if (e.keyCode == cc.macro.KEY.down){
this.node.y -= this.speed;
}else if (e.keyCode == cc.macro.KEY.left){
this.node.x -= this.speed;
}else if (e.keyCode == cc.macro.KEY.right){
this.node.x += this.speed;
}
})
}
文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-808831.html
文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-808831.html
到了這里,關(guān)于Cocos creator 的事件處理(鼠標(biāo)事件、鍵盤(pán)事件、觸摸事件、自定義事件、控制精靈移動(dòng)Demo)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!