我正在尝试用Matter.js创建一个迪斯尼Tsum Tsum游戏的HTML版本
游戏参考- https://www.youtube.com/watch?v=iqQrQtorM9c
但是目前,我不知道当玩家拖着几个身体时,如何识别被选中的身体。似乎鼠标约束只识别它点击的第一个主体。
发布于 2022-08-23 18:00:48
一种方法是通过翻转一个标志来检测鼠标何时关闭,然后在拖动时使用Matter.Query.point查询当前鼠标位置,将任何物体推到数组上。鼠标释放后,数组将包含该拖动的选定主体,并且可以在对其内容执行操作后将其清空。
这里有一个概念的证明:
const engine = Matter.Engine.create();
const render = Matter.Render.create({
element: document.body,
engine: engine,
options: {wireframes: false},
});
const bodies = [
Matter.Bodies.rectangle(
400, 200, 810, 60, {isStatic: true, angle: 0.0}
),
...[...Array(100)].map(() =>
Matter.Bodies.circle(
Math.random() * 400, // x
Math.random() * 100, // y
Math.random() * 10 + 10, // r
{
angle: Math.random() * (Math.PI * 2),
render: {fillStyle: "white"}
},
)
),
];
const mouseConstraint = Matter.MouseConstraint.create(
engine, {
element: document.body,
collisionFilter: {mask: 0} // disable collision
}
);
const runner = Matter.Runner.create();
let mouseDown = false;
const selected = [];
Matter.Events.on(mouseConstraint, "mousedown", () => {
mouseDown = true;
addSelection();
});
Matter.Events.on(mouseConstraint, "mouseup", () => {
mouseDown = false;
selected.forEach(e => e.render.fillStyle = "red");
selected.length = 0;
});
Matter.Events.on(mouseConstraint, "mousemove", () => {
if (mouseDown) {
addSelection();
}
});
const addSelection = () => {
const p = mouseConstraint.mouse.position;
const justSelected = Matter.Query.point(bodies, p);
selected.push(...justSelected);
justSelected.forEach(e => e.render.fillStyle = "yellow");
};
Matter.Composite.add(engine.world, [...bodies, mouseConstraint]);
Matter.Runner.start(runner, engine);
Matter.Render.run(render);<script src="https://cdnjs.cloudflare.com/ajax/libs/matter-js/0.18.0/matter.js"></script>
如果您不使用内部渲染器,则概念是相同的。
https://stackoverflow.com/questions/65702688
复制相似问题