matter.jsのイベントについて教えてください

実現したいこと

matter.jsを使って20個のボールを生成し、そのボそのボールをクリックして、どのボールをタッチしたのかをalertで表示させたい。

前提

いろいろなサイトのサンプルコードを参照し、このコードを作りました。
Matter.Bodies.circleで labelを設定し、クリックイベントでそのlabelの値を取得しようとした。

発生している問題・エラーメッセージ

alertが表示されません。

該当のソースコード

javascript
ソースコード

matter.js demo

const engWidth = 680;
const engHeight = 400;
const wall = 10;
const ball = 20;
var ballSize = 20;
var objs = [];

var engine = Matter.Engine.create(document.getElementById("matter"), {
render: {
options: {
wireframes: false,
width: engWidth,
height: engHeight,
background: "rgba(0, 0, 0, 1)"
}
}
});

objs.push(Matter.Bodies.rectangle(engWidth/2, wall/2, engWidth, wall, {isStatic: true}));
objs.push(Matter.Bodies.rectangle(engWidth-wall/2, engHeight/2, wall, engHeight, {isStatic: true}));
objs.push(Matter.Bodies.rectangle(engWidth/2, engHeight-wall/2, engWidth, wall, {isStatic: true}));
objs.push(Matter.Bodies.rectangle(wall/2, engHeight/2, wall, engHeight, {isStatic: true}));

for (var i = 0; i < ball; i++) {
var x = Math.random()*engWidth;
var y = Math.random()*engHeight;
// ボールに番号のラベルをつける
objs.push(Matter.Bodies.circle(x, y, ballSize, {
label: i+1,
render:{
fillStyle: "#FFFFFF",

}

}));
}

Matter.World.add(engine.world, objs);

var MouseConstraint = Matter.MouseConstraint;
// マウスドラッグではなく、マウスクリックのイベントを設定する
var mouseclick = MouseConstraint.create(engine, {
element: document.getElementById("matter").childNodes[0],
constraint: {
stiffness: 0.2,
render: {
visible: false
}
}
});
Matter.World.add(engine.world, mouseclick);

// マウスクリックしたボールの番号をalertで表示する
Matter.Events.on(mouseclick, 'mousedown', function(e) {

alert("You clicked on ball number " + e.body.label);

});

Matter.Engine.run(engine);

コメントを投稿

0 コメント