NOBのArduino日記!

NOBのArduino日記!

趣味は車・バイク・自転車・ラジコン・電子工作です。

Arduino IDE(gb.collideRectRect関数の使い方)

■gb.collideRectRect関数
 Gamebuimo.hライブラリのgb.collideRectRect関数は、2つの矩形の間に衝突(重複)があるかどうかをチェックします。

■使用例
 gb.collideRectRect関数を使ったArduinoIDEのプログラム例は図1の通りです。
 このプログラムを実行するとsetup関数中のgb.begin関数でGamebuinoオブジェクトを初期化し、gb.titleScreen関数で画面に「collideRectRect」と表示します。
 スタート画面でキーボードの「K」(GamebuinoのA)ボタンを押すと画面左上に「Move with arrows」と表示されポイントをカーソルキーで動かすことが可能になります。
 矩形を右に移動し他の矩形に接触したとgb.collideRectRect関数が判定すると「Colliding」と画面に表示されます。
 参考に図1プログラムをHEXファイルに変換し、それをSimbuino4Webエミュレートした結果を図2に示します。

#include <SPI.h>
#include <Gamebuino.h>
Gamebuino gb;

byte player_x = 10;
byte player_y = 10;
byte player_w = 8;
byte player_h = 16;

byte oponent_x = LCDWIDTH / 2;
byte oponent_y = LCDHEIGHT / 2;
byte oponent_w = 17;
byte oponent_h = 12;

void setup() {
   gb.begin();
   gb.titleScreen(F("collideRectRect"));
}

void loop() {
   if (gb.update()) {
       gb.display.println(F("Move with arrows"));

       if (gb.buttons.pressed(BTN_C)) {
           gb.titleScreen(F("collideRectRect"));
       }
       //update player
       if (gb.buttons.repeat(BTN_RIGHT, 1)) {
           player_x = player_x + 1;
       }
       if (gb.buttons.repeat(BTN_LEFT, 1)) {
           player_x = player_x - 1;
       }
       if (gb.buttons.repeat(BTN_DOWN, 1)) {
           player_y = player_y + 1;
       }
       if (gb.buttons.repeat(BTN_UP, 1)) {
           player_y = player_y - 1;
       }

       //update collision
       if (gb.collideRectRect(player_x, player_y, player_w, player_h, oponent_x, oponent_y, oponent_w, oponent_h)) {
           gb.sound.playTick();
           gb.display.print(F("Collliding"));
       }

       //draw rectangles
       gb.display.setColor(INVERT);
       gb.display.fillRect(player_x, player_y, player_w, player_h);
       gb.display.fillRect(oponent_x, oponent_y, oponent_w, oponent_h);
       gb.display.setColor(BLACK);
   }
}
イメージ 1
図1:プログラム例
 

 イメージ 1
図2:プログラム実行結果

 

■構文
 gb.collideRectRect(x1、y1、w1,h1,x2、y2、w2、h2)

■パラメータ
 x1   :最初の矩形の左上隅の水平座標。
 y1   :最初の矩形の左上隅の垂直座標。
 w1  :最初の矩形の幅。
 h1   :最初の矩形の高さ。
 x2   :2番目の矩形の左上隅の水平座標。
 y2   :2番目の矩形の左上隅の垂直座標。
 w2  :2番目の長方形の幅。
 h2   :2番目の長方形の高さ。

■戻り値
 true(2つの矩形が重なっている場合)
 false(2つの矩形が重なっていない場合)
 

イメージ 1 イメージ 3
励みになりますのでよければクリック下さい(^o^)/

↩【Gamebuinoリファレンス】目次に戻る