所以我正在制作愤怒的小鸟游戏,我正在使用p5.js和matter.js。
我在游戏中创建了一个mouseConstraint来移动附着在弹弓上的小鸟,但我也可以移动输出中的所有物体。
我如何将mouseConstraint仅附加到单个物体,即此案例中的鸟,以便我仅可以移动该特定对象而不是其他任何东西?
如果这不可能,是否有替代方案可供我使用弹弓?
所以我正在制作愤怒的小鸟游戏,我正在使用p5.js和matter.js。
我在游戏中创建了一个mouseConstraint来移动附着在弹弓上的小鸟,但我也可以移动输出中的所有物体。
我如何将mouseConstraint仅附加到单个物体,即此案例中的鸟,以便我仅可以移动该特定对象而不是其他任何东西?
如果这不可能,是否有替代方案可供我使用弹弓?
要将mouseConstraint附加到单个物体上,您需要将该物体作为第二个参数传递:
mouseConstraint = MouseConstraint.create(engine, {body: bird});
您可以使用碰撞过滤器:
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.19.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
。
另请参见: