Cocos creator 的事件处理(鼠标事件、键盘事件、触摸事件、自定义事件、控制精灵移动Demo)

鼠标事件

        //鼠标事件
        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())
        })

自定义事件(消息通知)

  • 发送通知(2种方式)
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() {
        
        //鼠标(MOUSE_DOWN)、或手指拖拽人物移动
        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())
            }
        })

        //键盘控制人物移动
        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;
            }
        })
    }

  • 6
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值