9
1

More than 5 years have passed since last update.

リアルと連動する糸通しゲームを作る

Last updated at Posted at 2018-07-31

糸通しや,Flappy Birdのような迫りくる壁を回避するゲームをobnizで作りました
距離センサを使って入力しますので,より直感的な操作で遊べます

20180731_124627.GIF

youtubeでみる

材料

作り方(ハードウェア)

obnizに距離センサをつなぐだけです.どこに挿してもいいですが,下記のようにつなぎました.

  • io0 : 信号線(黄色)
  • io1 : GND(黒)
  • io2 : VCC(赤)

IMG_8313.JPG

作り方(ソフトウェア)

全体のソースコードはこちらにあります

ハードウェアとの連携

距離センサからの入力はinputHeight変数に自動で入るように設定しておき,使いたいタイミングで使うようにします.


  let inputHeight = 0;
  let obniz = new Obniz("OBNIZ_ID_HERE");
  obniz.onconnect = async function () {
    let sensor = obniz.wired("GP2Y0A21YK0F", {vcc: 2, gnd: 1, signal: 0});
    sensor.start(function (height) {
      inputHeight = height;
    })

  };

コードの中の{vcc: 2, gnd: 1, signal: 0}は距離センサを接続した場所によって変えます.「作り方(ハードウェア)」にて同じように接続していれば,そのままで大丈夫です.

ここでとった値は,毎フレーム内の処理の際に入力値として使っています

   let input = (300 - inputHeight);
   input = Math.min(Math.max(0, input), canvas.height);
   dot.push(input);

ゲームロジック

dot(糸)とbar(壁)の変数を作り,そこにそれぞれの値を入れていきます.
どちらも配列にしていて,複数個対応しています.

//新しい壁を追加
bars.push({x: canvas.width, y: Math.random() * 380 - 80, width: 16, height: 160});

//入力値に応じて糸を動かす
let input = (300 - inputHeight);
input = Math.min(Math.max(0, input), canvas.height);
dot.push(input);
dot.shift();

描画

HTML5のcanvasをゴリゴリ使っていきます

<canvas id="field" width="300" height="300"/>
  let canvas = document.getElementById('field');
  let ctx = canvas.getContext('2d');



  function drawDots() {
    ctx.strokeStyle = "white";
    ctx.lineWidth = 1;
    ctx.beginPath();

    for (let i = 0; i < dot.length - 1; i++) {

      if (dot[i] !== undefined && dot[i + 1] !== undefined) {

        ctx.moveTo(i, dot[i]);
        ctx.lineTo(i + 1, dot[i + 1]);
      }
    }
    ctx.closePath();
    ctx.stroke();


  }

  function drawBars() {
    ctx.fillStyle = "red";
    ctx.beginPath();

    for (let i = 0; i < bars.length; i++) {

      ctx.fillRect(bars[i].x, bars[i].y, bars[i].width, bars[i].height);
    }

  }

完成型

20180731_124627.GIF

まとめ

物理的な動きで遊べるの結構楽しい!
リープモーション/キネクト等でも同じことができますがobnizも簡単でおすすめです

9
1
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
9
1