如何为此底座上的 mouseConstraint 创建 HTML 消息?

问题描述 投票:0回答:1

这就是我现在正在尝试从 Matter.js 库中进行的工作。我想使用两个事件来触发两条 HTML 消息,方法是抓住摇篮左侧的球,它会说“嘿,你抓住了摇篮”,然后当你放开时,它会说“哇,看看那个!” .

// Matter.js - http://brm.io/matter-js/

// Matter module aliases
var Engine = Matter.Engine,
    World = Matter.World,
    Body = Matter.Body,
    Composites = Matter.Composites,
    MouseConstraint = Matter.MouseConstraint;

// create a Matter.js engine
var engine = Engine.create(document.body, {
  render: {
    options: {
      showAngleIndicator: true,
      showVelocity: true,
      wireframes: false
    }
  }
});

// add a mouse controlled constraint
var mouseConstraint = MouseConstraint.create(engine);
World.add(engine.world, mouseConstraint);

// add a Newton's Cradle (using the Composites factory method!)
var cradle = Composites.newtonsCradle(280, 150, 5, 30, 200);
World.add(engine.world, cradle);

// offset the first body in the cradle so it will swing
Body.translate(cradle.bodies[0], { x: 0, y: 0 });

// run the engine
Engine.run(engine);

我目前正在努力实现这一目标的地方是:

cradle.mouseConstraint=function(){alert("hi")};

欲了解更多信息,请参阅 Codepen: http://codepen.io/liabru/pen/abFml

javascript events dom-events mouseevent matter.js
1个回答
0
投票

有很多方法可以做到这一点。

一种方法是测试

mouseConstraint.body
以查看鼠标是否握住要跟踪捕获和释放的身体。如果此条件为真,则使用布尔值来确定身体是否已被鼠标拖动或携带。

如果布尔值为 true,则主体已经被拖动,否则这是新拖动的开始,您可以闪烁一条消息。

当主体不在鼠标上且布尔值为 true 时,主体刚刚被释放;将布尔值设置为 false,以便可以检测到下一次交互。

在下面的最小示例中,我们想要跟踪与圆形的交互,而不是与正方形的交互。我正在使用

console.log()
,但您可以将其替换为您想要显示/隐藏的任何 HTML 消息。

const engine = Matter.Engine.create();
const runner = Matter.Runner.create();
const render = Matter.Render.create({
  element: document.body,
  engine: engine,
});
const bodies = [
  Matter.Bodies.rectangle(400, 100, 810, 60, {isStatic: true}),
  Matter.Bodies.rectangle(200, 0, 50, 50),
  Matter.Bodies.circle(300, 0, 25),
];
const carryableBody = bodies.at(-1); // make the circle carryable
let carrying = false;
const mouseConstraint = Matter.MouseConstraint.create(
  engine, {element: document.body}
);
Matter.Events.on(runner, "tick", event => {
  if (mouseConstraint.body === carryableBody && !carrying) {
    console.log("begin carrying body");
    carrying = true;
  }
  else if (!mouseConstraint.body && carrying) {
    console.log("release carried body");
    carrying = false;
  }
});
Matter.Composite.add(engine.world, [...bodies, mouseConstraint]);
Matter.Runner.run(runner, engine);
Matter.Render.run(render);
<script src="https://cdnjs.cloudflare.com/ajax/libs/matter-js/0.20.0/matter.js"></script>

如果需要,您可以使用碰撞过滤器和/或数组将上述模式推广到多个实体。

© www.soinside.com 2019 - 2024. All rights reserved.