获得“mouse"使用EaselJS在触摸设备上定位

Get "mouse" position on touch devices using EaselJS

本文关键字:触摸 定位 EaselJS 使用 mouse quot 获得      更新时间:2023-09-26

我正在使用带有EaselJS库的<canvas>标签创造一款街机风格的HTML5游戏,今天我在尝试执行触控支持时发现了一个问题。有人能帮帮我吗?

我已经成功地实现了当用户触摸英雄时的跳跃动作,但是现在我想再添加两件事:当用户触摸屏幕左侧时,英雄将向左移动,当用户触摸屏幕右侧时,英雄将向右移动。此外,我也在考虑当用户用两个手指触摸屏幕时执行跳跃,但我不知道这是否可行,如果不可行,那么我将需要其他方法在行走时执行跳跃。

我认为问题的解决方案是非常简单的,但搜索它没有帮助,我找到了非常复杂的答案,我的目标是尽可能保持代码的简单性。提前谢谢。

相关代码如下:

        var x = 0, y = 0;
        document.addEventListener("mousemove", function(e){
            x = e.pageX,
            y = e.pageY;
        });
        document.addEventListener("mousedown", function(e){
            if (!key.holdingUp) { // Checks if event was fired again before "mouseup"
                if(x > hero.x+hero.width+hero.offset){
                    key.right = true;
                }
                if(x < hero.x-hero.offset){
                    key.left = true;
                }
                if(x > hero.x-hero.offset && x < hero.x+hero.width+hero.offset){
                    key.up = true;
                }
            }else{
                key.up = true;
            }
        });
        document.addEventListener("mouseup", function(){
            setTimeout(function(){
                key.up = false;
                key.right = false;
                key.left = false;
                key.holdingUp = false;
            },1000/60); // Wait for one tick loop
        });

JSFiddle(相关代码从160行开始)

这里是工作小提琴:http://jsfiddle.net/4ABMN/4/

我已经在Android的Firefox上测试过了。我遵循这个指南:http://www.createjs.com/tutorials/Mouse%20Interaction/

本质上,你需要使用框架事件而不是直接的DOM:

stage.on("stagemousedown", function(evt) {
    alert("the canvas was clicked at "+evt.stageX+","+evt.stageY);
})
编辑:

我忘了说,你需要加上这一行:

createjs.Touch.enable(stage);