Javascript 如何使Matter.js中的鼠标事件更具响应性?
所以我一直在尝试创造一个运球游戏,但是这游戏并没有我想要的那么灵敏。鼠标事件并不总是被触发,尤其是在触摸设备中。下面是代码Javascript 如何使Matter.js中的鼠标事件更具响应性?,javascript,events,physics-engine,matter.js,Javascript,Events,Physics Engine,Matter.js,所以我一直在尝试创造一个运球游戏,但是这游戏并没有我想要的那么灵敏。鼠标事件并不总是被触发,尤其是在触摸设备中。下面是代码 window.onload = function() { var Engine = Matter.Engine, Render = Matter.Render, World = Matter.World, Mouse = Matter.Mouse, MouseConstraint = Matter.MouseConstraint, Events =
window.onload = function() {
var Engine = Matter.Engine,
Render = Matter.Render,
World = Matter.World,
Mouse = Matter.Mouse,
MouseConstraint = Matter.MouseConstraint,
Events = Matter.Events,
Bodies = Matter.Bodies,
Body = Matter.Body;
var options = {
friction: 0.5,
restitution: 0.8,
label: 'ball'
};
var canvas = document.querySelector('canvas'),
cWidth = canvas.offsetWidth,
cHeight = canvas.offsetHeight;
var engine = Engine.create();
var render = Render.create({
canvas: canvas,
engine: engine,
options: {
width: cWidth,
height: cHeight
}
});
engine.world.gravity.y = 6;
const margin = 31;
var ballShape = Bodies.circle(200, 200, 80, options);
var ground = Bodies.rectangle(cWidth / 2, cHeight + margin, cWidth, 60, { isStatic: true, restitution: -2, label: 'ground' });
var leftWall = Bodies.rectangle(-1 * margin, cHeight, 60, cHeight * 4, { isStatic: true });
var rigthWall = Bodies.rectangle(cWidth + margin, cHeight, 60, cHeight * 4, { isStatic: true });
World.add(engine.world, [ballShape, ground, leftWall, rigthWall]);
var canvasMouse = Mouse.create(document.querySelector('canvas'));
var mConstraint = MouseConstraint.create(engine, { mouse: canvasMouse });
Events.on(mConstraint, "mousedown", function(event) {
console.log(mConstraint, event);
let x, y, ball = mConstraint.body;
if(typeof ball == 'undefined' || ball == null) return;
if(ball.label === 'Rectangle Body') return;
Body.setVelocity(ball, { x: ball.velocity.x, y: 0 });
x = (ball.position.x - event.mouse.mousedownPosition.x) / 70;
Body.applyForce(ball, { x: ball.position.x, y: ball.position.y }, { x, y: -2 });
});
Events.on(mConstraint, "mouseup", function(event) {
let x, y, ball = mConstraint.body;
if(typeof ball == 'undefined' || ball == null) return;
else if(ball.label === 'Rectangle Body') return;
Body.setVelocity(ball, { x: ball.velocity.x, y: 0 });
x = (ball.position.x - event.mouse.mousedownPosition.x) / 70;
Body.applyForce(ball, { x: ball.position.x, y: ball.position.y }, { x, y: -2 });
});
Events.on(engine, 'collisionStart', function(event) {
console.log(event);
});
Engine.run(engine);
Render.run(render);
}
我认为可能游戏循环很慢,因此点击事件不知何故没有注册,但我搜索了文档,发现渲染器默认以60FPS运行。如果之前有人遇到这样的问题,我会感谢他/她的帮助。总结一下,我的问题是在快速移动的matter.js body上单击事件
您可以在此链接上找到托管的游戏: