我正在使用Cocos2d-JS,需要找到一种方法来监听鼠标的按住。似乎有限,因为只有onMousemove,onMouseDown和onMouseUp。所有这些只被解雇一次。我如何使用它们来检测何时按住了鼠标键?我不能只使用onMouseDown,因为如果单击该按钮,它将被用于执行操作。
我可以为此建议以下解决方案。您可以有一个柜台。 onMouseDown
将启动一种方法,该方法将通过setInterval
递增计数器并检查计数器是否达到目标值。如果达到该值,它将触发您希望通过鼠标按住来触发的任何事件。 onMouseUp
将清除间隔计数器。这是简化的代码。假设这些是对象的方法。
onMouseDown: function() {
this.launchTimer();
},
launchTimer: function() {
//Timer will update every 100ms
this.counter = 0;
this.timer = setInterval(() => {
//Assume our target value is 1s or 1000ms
if (this.counter === 1000) {
//Launch your function here
this.onMouseHold();
this.clearTimer();
} else {
this.counter += 100;
}
}, 100);
this.timer();
},
clearTimer: function() {
this.couner = 0;
clearInterval(this.timer);
},
onMouseUp: function() {
this.clearTimer();
}