所以我正在制作一款愤怒的小鸟游戏,我使用的是p5.js和matter.js.
我在游戏中创建了一个MouseConstraint来移动连接到弹弓上的鸟,但我也能够移动输出中的所有身体.
如何将MouseConstraint仅附加到单个身体,即本例中的鸟,以便我只能移动该特定对象,而不能移动其他对象?
如果不能的话,有没有其他方法可以让我用弹弓呢?
所以我正在制作一款愤怒的小鸟游戏,我使用的是p5.js和matter.js.
我在游戏中创建了一个MouseConstraint来移动连接到弹弓上的鸟,但我也能够移动输出中的所有身体.
如何将MouseConstraint仅附加到单个身体,即本例中的鸟,以便我只能移动该特定对象,而不能移动其他对象?
如果不能的话,有没有其他方法可以让我用弹弓呢?
您可以使用collision filters:
const makeBox = (x, y, w, h, props, elem) => ({
w, h, body: Matter.Bodies.rectangle(
x, y, w, h, props
),
elem,
render() {
const {x, y} = this.body.position;
this.elem.style.top = `${y - this.h / 2}px`;
this.elem.style.left = `${x - this.w / 2}px`;
this.elem.style.transform = `rotate(${this.body.angle}rad)`;
},
});
const boxes = [...document.querySelectorAll(".box")]
.map((el, i) =>
makeBox(
// x y w h
100 * i + 100, 0, 40, 30,
{collisionFilter: i === 0 ? {category: 0b10} : {}},
el,
)
);
const ground = Matter.Bodies.rectangle(
// x y w h
200, 200, 400, 120, {
isStatic: true,
}
);
const engine = Matter.Engine.create();
const mouseConstraint = Matter.MouseConstraint.create(
engine, {
collisionFilter: {mask: 0b10},
element: document.body
}
);
Matter.Composite.add(
engine.world, [
...boxes.map(e => e.body), ground, mouseConstraint
]
);
(function rerender() {
boxes.forEach(e => e.render());
Matter.Engine.update(engine);
requestAnimationFrame(rerender);
})();
.box {
position: absolute;
background: #d00;
transition: background 0.2s;
width: 40px;
height: 30px;
cursor: move;
}
.box:not(:first-child) {
background: #111;
cursor: not-allowed;
}
.box:first-child:hover {
background: #f00;
}
#ground {
position: absolute;
background: #666;
top: 140px;
height: 120px;
width: 400px;
}
html, body {
position: relative;
height: 100%;
margin: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/matter-js/0.18.0/matter.min.js"></script>
<div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>
<div id="ground"></div>
在这里,鼠标约束被赋予了0b10
的掩码,并且被允许与鼠标交互的唯一实体的红色框被设置为0b10
的类别.
默认掩码值为32位全部设置,即4294967295
/0xffffffff
.您可能希望更精确,只禁用第一位:0xfffffffe
.这允许鼠标约束与除2以外的其他类别交互,仅禁用与类别1的交互.
要创建相反的情况,即鼠标与除红色框之外的任何实体交互,可以将鼠标约束的遮罩设置为禁用第二个最低有效位的值,如0b1
或0xfffffffd
.
另见: