アクションRPG Day3 プレイヤー
前回はフィールドの表示をしました
今回はプレイヤーを表示して移動させます
画像はいつものenchantのクマです
画像をpreloadで読み込む
フィールド読み込みの後に追加します
function preload() { // 背景画像の読み込み 16x16のマップチップの画像 this.load.image('ground', 'http://jsrun.it/assets/K/e/w/N/KewNo.png'); // プレイヤー 32x32 this.load.spritesheet('player', 'http://jsrun.it/assets/e/N/V/L/eNVLk.png', { frameWidth: 32, frameHeight: 32 }); }
プレイヤーを表示する
プレイヤーもクラス化します
Playerクラスを使う側の実装
まずは使う側から
var player;// グローバルに定義 function create() { const ground = new Ground(this); ground.create(); // キャラクタの生成 player = new Player(this); player.create(); player.cursors = this.input.keyboard.createCursorKeys(); } function update() { // フレーム単位の処理 player.update(); }
今回作るPlayerはcreateメソッドとupdateメソッドから利用するため、player変数をグローバルに作っておきます
(あんまり嬉しくないけどしょうがない)
そしてcreateメソッド内でplayerを生成し、テンキーでプレイヤーを移動させるためにcursors
をセットします
updateメソッドでplayer.update()
を呼びます
player.update()
の中で、カーソルの状態に応じてプレイヤーを移動させます
Playerクラス
プレイヤー画像の表示と移動をします
class Player { constructor(scene) { this.scene = scene; this.sprite = null; this.cursors = null; } create() { this.sprite = this.scene.physics.add.sprite(32, 32, 'player'); } update () { if (this.cursors.left.isDown) { this.sprite.setVelocityX(-160); } else if (this.cursors.right.isDown) { this.sprite.setVelocityX(160); } else { this.sprite.setVelocityX(0); } if (this.cursors.up.isDown) { this.sprite.setVelocityY(-160); } else if(this.cursors.down.isDown) { this.sprite.setVelocityY(160); } else { this.sprite.setVelocityY(0); } } }
createの中身
createメソッドでspriteを生成します
このタイミングで画面にプレイヤーが表示されます
this.scene.physics.add.sprite()
これはsprite生成のメソッドですが、ドキュメントによると
"Creates a new Arcade Sprite object with a Dynamic body."
だそうです
物理演算対象のスプライトを生成するってことですかね
戻り値はSpriteです
Phaser 3 API Documentation - Class: Factory
Phaser 3 API Documentation - Class: Sprite
前回のGroundクラスではphyisicsを意識してなかったけど大丈夫か...?
まぁいいや
updateの中身
上下左右に押されたらその方向に速度をセットします
ただこの値の単位がわからない...
px/frameだとすると、1フレームごとに160px移動するから早すぎるし...
なので勝手にpx/secということにするw
今日はここまで
jsdo.it
ここまででプレイヤーを画面に表示して移動させることができました
PCのテンキーで操作できます(スマホの人はごめんなさい)
ただ現段階では移動中のアニメーションや壁との衝突判定がないのでそれは次回以降実装します