鼠标事件
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("鼠标左键")
}
})
键盘事件
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("点击a")
}
})
触摸事件
this.node.on(cc.Node.EventType.TOUCH_START, (e: cc.Event.EventTouch) => {
cc.log("触摸" + e.getLocation())
})
自定义事件(消息通知)
this.node.on(cc.Node.EventType.MOUSE_DOWN, () => {
cc.log("点击按钮,发送事件1")
cc.find("human").emit("msg")
})
this.node.on(cc.Node.EventType.MOUSE_DOWN, () => {
cc.log("点击按钮,发送事件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("自定义事件触发")
cc.log(e.detail.text)
})
Demo,控制精灵移动
isFocus: boolean = false
speed: number = 50
start() {
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.EventMouse) => {
if (this.isFocus) {
this.node.setPosition(e.getLocation())
}
})
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;
}
})
}