LoginSignup
7
8

More than 5 years have passed since last update.

JavaScript用物理エンジン、Matter.jsをとりあえず動かす

Last updated at Posted at 2018-06-26

なかなか日本語でわかりやすい記事が見つからなかったのでメモしておきます。
とりあえず動作が確認できればいいだけなのでほぼコピペです。

インストール

いろいろ方法があるらしいけど、Githubからソースをダウンロードする方法でいきます。
https://github.com/liabru/matter-js ここから、
https://github.com/liabru/matter-js/blob/master/build/matter.js このmatter.jsというファイルだけを自分のプロジェクトにコピーします。

この時点でのフォルダ構成は

  • sample
    • main.html
    • main.js
    • matter.js ←これが最初にダウンロードしてきたファイル
    • style.css

こんな感じです。matter.js以外のファイル名は適当。

main.html

scriptのタグ部分はなぜかhead内に書くと動かなかったのでbodyに記述しました。いつもの癖でheadに書いてしまって動かなくてしばらく悩みました。



<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <!-- ここのIDは何でもいい -->
    <main id="hage"></main>

    <script src="matter.js"></script>
    <script src="main.js"></script>

</body>
</html>

main.js

とりあえず動くのが確認できればいいので、公式のhttps://github.com/liabru/matter-js/wiki/Getting-started にあるUsage exampleをそのままコピペしました。


// module aliases
var Engine = Matter.Engine,
    Render = Matter.Render,
    World = Matter.World,
    Bodies = Matter.Bodies;

// create an engine
var engine = Engine.create();

// create a renderer
var render = Render.create({
    element: document.body,
    engine: engine
});

// create two boxes and a ground
var boxA = Bodies.rectangle(400, 200, 80, 80);
var boxB = Bodies.rectangle(450, 50, 80, 80);
var ground = Bodies.rectangle(400, 610, 810, 60, { isStatic: true });

// add all of the bodies to the world
World.add(engine.world, [boxA, boxB, ground]);

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

// run the renderer
Render.run(render);

以上。
これをお好きなブラウザで開くだけで四角が上から落ちてくるだけのサンプルが確認できました。
ちょっと迷ったのはmain.jsの呼び出し部分。なぜかhead内に書いてはだめなようです。このへんでちょっとハマったくらいで、後は全部コピペです。style.cssは使ってないのでいらなかったかも…。

次はもう少し理解を深めて使い方を解説していきたいと思います。

7
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
8