Javascript matter.js创建一个旋转平台
我需要创建一个可以用鼠标旋转的平台。我试图创建一个矩形并用Javascript matter.js创建一个旋转平台,javascript,jquery,html,Javascript,Jquery,Html,我需要创建一个可以用鼠标旋转的平台。我试图创建一个矩形并用Matter.Constraint.create()将其连接到点,但这样的平台不能用鼠标旋转。我还没有在演示或示例中找到替代方案 这是我使用的代码: (function(){ // Matter.js module aliases var Engine = Matter.Engine; World = Matter.World; Render = Matter.Render;
Matter.Constraint.create()
将其连接到点,但这样的平台不能用鼠标旋转。我还没有在演示或示例中找到替代方案
这是我使用的代码:
(function(){
// Matter.js module aliases
var Engine = Matter.Engine;
World = Matter.World;
Render = Matter.Render;
Bodies = Matter.Bodies;
Composites = Matter.Composites;
Constraint = Matter.Constraint;
MouseConstraint = Matter.MouseConstraint;
// create a Matter.js engine
var _engine = Engine.create(document.body);
var rotatingPlatform = Bodies.rectangle(100, 200, 200, 30);
World.add(_engine.world, [
MouseConstraint.create(_engine),
rotatingPlatform,
Constraint.create({ pointA: {x: 100, y: 200}, bodyB: rotatingPlatform}),
]);
// run the engine
Engine.run(_engine);
})();
以及标记:
<!doctype html>
<html>
<head></head>
<body>
<script src="matter-0.8.0.js"></script>
<script src="myJsFile.js"></script>
</body>
</html>
我该怎么做才能让这个平台用鼠标旋转呢?这个问题有点老了,但因为没有人回答 将此添加到脚本底部对我很有用:
Matter.Events.on(_engine, "mousemove", function(event) {
if (Matter.Bounds.contains(rotatingPlatform.bounds, event.mouse.position) && event.mouse.button == 0) {
targetAngle = Matter.Vector.angle(rotatingPlatform.position, event.mouse.position);
Matter.Body.rotate(rotatingPlatform, targetAngle - rotatingPlatform.angle);
}
});
_engine.world.gravity.y = 0;
我喜欢这个主意,@oxdeadbeef,奇怪的是,对我来说mousemove事件从未发生过。我最后做了这件事,效果很好:
document.body.addEventListener("mousemove", function(event) {
var mousePosition = {x: event.offsetX, y: event.offsetY};
if (Matter.Bounds.contains(rotatingPlatform.bounds, mousePosition) && event.button == 0) {
targetAngle = Matter.Vector.angle(rotatingPlatform.position, mousePosition);
Matter.Body.rotate(rotatingPlatform, targetAngle - rotatingPlatform.angle);
}
});
再次感谢您的建议。我很好奇为什么活动没有启动。我在Engine.run()之后添加它。但不管怎样,因为你的纯js事件也能工作。很高兴它有帮助!