🗂

Phaserで円運動

2023/09/28に公開

画像の円運動

画像オブジェクトが円運動をします。画面中央を中心として、円形に回転移動します

画像の読み込み

mainScene.preload = function() {
    // スプライト画像の読み込み
    this.load.spritesheet('jets', 'assets/images/jets.png', {frameWidth: 64, frameHeight: 64});
};

createメソッド

ジェット機を作成します

mainScene.create = function() {
    // 画面中央のX座標
    this.centerX = this.game.config.width / 2;
    // 画面中央のY座標
    this.centerY = this.game.config.height / 2;

    // ジェット機の作成
    this.createJets();
};

画面中央に表示

ジェット機を作成します。回転を表す「this.jets.angle」を作成します

mainScene.createJets = function() {
    // ジェット機の作成
    this.jets = this.add.sprite(0, 0, 'jets');
    this.jets.setDisplaySize(50,50);
    this.jets.setFrame(1);
    this.jets.angle = 0;
    this.jets.radius = 100;
};

updateメソッド

円運動を呼び出す

mainScene.update = function() {
    this.circularMoveJets();
};

単純な回転処理

ジェット機が円運動します。画面中心を起点にして円運動します

mainScene.circularMoveJets  = function() {
    // ジェット機が円運動する
    this.jets.angle--;
    // デグリーをラジアン値に変換
    const rad = this.degreeToRadian(this.jets.angle);
    // x = 半径 * Math.con(ラジアン値)
    const x = this.jets.radius * Math.cos(rad);
    // y = 半径 * Math.sin(ラジアン値)
    const y = this.jets.radius * Math.sin(rad);
    this.jets.x = this.centerX + x;
    this.jets.y = this.centerY + y;
};

degreeをラジアン値に変換

mainScene.degreeToRadian = function(degree) {
    // 角度の単位の変換 デグリーからラジアン
    // degree * (pi / 180)
    return degree * (Math.PI/180);
};

実行結果

完成版

https://github.com/hiroshees/phaser-game-sample/blob/main/src/work14.html

Discussion