0

启用指针锁定 API 时,有什么方法可以识别右键单击事件(“上下文菜单”)和滚动事件?我正在尝试创建一个基于浏览器的 3d 游戏,其中玩家将能够通过左键单击、右键单击、中键单击和滚动来执行不同的活动——同时锁定指针。

索引.html

<body><button id="lock">Start game</button</body>

应用程序.js

$("#lock").on("click", function(e) {
  lockPointer(); // invokes the requestPointerLock API
  e.stopPropagation();
});

// this works perfectly
$("body").on("click", function(e) {
  // do stuff on left click
});

// this does not work
$("body").on("contextmenu", function(e) {
  // do stuff on right click
});
4

1 回答 1

1

对于右键单击,您可以使用mousedownmouseup事件,它适用于requestPointerLock

$('body').on('mousedown', function(e) {
    if (e.which === 1) {
        // left button
    } else if (e.which === 2) {
        // middle button
    } else if (e.which === 3) {
        // right button
    }
});

对于滚动,您可以使用wheel事件:

$('body').on('wheel', function(e) {
    var dx = e.originalEvent.deltaX;
    var dy = e.originalEvent.deltaY;

    if (dy < 0) {
        // scroll up
    } else if (dy > 0) {
        // scroll down
    }

    if (dx < 0) {
        // scroll left (some mice support this)
    } else if (dx > 0) {
        // scroll right (some mice support this)
    }
});
于 2017-03-16T09:03:16.453 回答