phi

I'm a Game Programmer and Frontend Engineer passionate about programming education. Math / C / C++ / C# / JavaScript / HTML5 / CSS3 / Python

phiaryjust a creator

phina.js tips - 要素を画面からはみ出ないように制御しよう

9 years ago

phina.js には, 要素に top, bottom, left, right というプロパティがあります.
これを上手く活用することで簡単に要素を画面からはみ出ないよう制御することができます.

Runstant Demo

ランダムに動くボールですが, 画面の縁に当たる画面外に出ずに跳ね返っているのが分かるかと思います.

Code

デモの実装コードです.

/*
 * runstant
 */

phina.globalize();

var SCREEN_WIDTH  = 960;  
var SCREEN_HEIGHT = 640;  
var BALL_NUM      = 64;

phina.define('MainScene', {  
  superClass: 'CanvasScene',

  init: function(options) {
    this.superInit(options);

    (BALL_NUM).times(function(i) {
      var elm = Ball().addChildTo(this);
      elm.x = Math.randint(0, SCREEN_WIDTH);
      elm.y = Math.randint(0, SCREEN_HEIGHT);
    }, this);
  },

});

phina.define('Ball', {  
  superClass: 'CircleShape',

  init: function() {
    this.superInit({
      stroke: false,
      fill: 'hsl({0}, 80%, 60%)'.format(Math.randint(0, 360)),
    });

    this.physical.force(Math.randint(-10, 10), Math.randint(-10, 10));
  },

  update: function() {
    if (this.left < 0) {
      this.left = 0;
      this.physical.velocity.x *= -1;
    }
    else if (this.right > SCREEN_WIDTH) {
      this.right = SCREEN_WIDTH;
      this.physical.velocity.x *= -1;
    }
    if (this.top < 0) {
      this.top = 0;
      this.physical.velocity.y *= -1;
    }
    else if (this.bottom > SCREEN_HEIGHT) {
      this.bottom = SCREEN_HEIGHT;
      this.physical.velocity.y *= -1;
    }
  }
});

phina.main(function() {  
  var app = GameApp({
    startLabel: 'main',
    width: SCREEN_WIDTH,
    height: SCREEN_HEIGHT,
  });

  app.run();
});

Detail

ShapeSprite, Label といった要素は全て Object2D というクラスを継承しています. Object2D は, top, bottom, left, right という自身の上下左右の座標を取得/設定できるプロパティを持っています.

今回のサンプルはこのプロパティを使って画面外に出たかを判定し, 値と移動方向を設定し直すことで 画面からはみ出さないよう制御しています.

実際にそれを行っているコードはこちらになります.

update: function() {  
  if (this.left < 0) {
    this.left = 0;
    this.physical.velocity.x *= -1;
  }
  else if (this.right > SCREEN_WIDTH) {
    this.right = SCREEN_WIDTH;
    this.physical.velocity.x *= -1;
  }
  if (this.top < 0) {
    this.top = 0;
    this.physical.velocity.y *= -1;
  }
  else if (this.bottom > SCREEN_HEIGHT) {
    this.bottom = SCREEN_HEIGHT;
    this.physical.velocity.y *= -1;
  }
}

移動後に update で毎フレームはみ出し判定をし, はみ出していたら値をはみ出す前の値に戻して 移動方向を反転させています.

Last

簡単な紹介でした. 不明な点などありましたら気軽にコメントもしくは @phi_jp までメッセージ下さい.

phina.js には, こういった便利な機能がたくさんあります.
今後もちょこちょこ紹介していきたいと思います.