Matter.js创建一个旋转平台



我需要创建一个可以用鼠标旋转的平台。我尝试用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,奇怪的是,对我来说,鼠标移动事件从未触发。我最后这样做了,这是有效的:

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);
  }
});

谢谢你的主意。

最新更新