美文网首页
【从0开始学Laya】13-鼠标交互和键盘交互

【从0开始学Laya】13-鼠标交互和键盘交互

作者: 会奔跑的蘑菇 | 来源:发表于2020-05-02 16:06 被阅读0次

    在做项目的过程中,经常会用到鼠标的交互和键盘交互,这节我们就来学习一下
    大致原理就是在需要用到的地方,监听鼠标和键盘的输入状态
    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);
    }

    相关文章

      网友评论

          本文标题:【从0开始学Laya】13-鼠标交互和键盘交互

          本文链接:https://www.haomeiwen.com/subject/jnlhghtx.html