ダメージを実装する
このままではSandyちゃんは無敵なのでダメージを実装します。
ここでは、
ゴブリンに横からぶつかったらSandyちゃんのダメージ
上からぶつかったら敵にダメージ
という処理を実装します。
当たった位置の判定
enemy.jsの54行目に以下のコードを追記してください。
var distance = ev.other.getLocalPosition().clone().sub(this.entity.getLocalPosition().clone());
console.log(distance);
ぶつかった際に、ぶつかってきたエンティティと自分自身の座標を算出し距離を求めるような処理を追記してみました
保存してコンソールを確認してみましょう
横からぶつかった時と、上からぶつかった時で、distanceの値が異なっていることが確認できます
この値を利用してぶつかった位置を取得してみましょう
enemy.jsを以下のように書き換えます
var Enemy = pc.createScript('enemy');
/*attributesに右、左それぞれの移動量を定義*/
Enemy.attributes.add("RIGHT_MOVE",{type:"number",default:0.01});
Enemy.attributes.add("LEFT_MOVE",{type:"number",default:-0.01});
// initialize code called once per entity
Enemy.prototype.initialize = function() {
/*カウンタ初期化*/
this.count = 0;
/*左右移動を変更するインターバル*/
this.change_interval = parseInt(50 + Math.random() * 20,10);
/*どちらに進むか*/
this.movefor = (Math.random() > 0.4)? this.RIGHT_MOVE : this.LEFT_MOVE;
/*衝突した際のイベントハンドラ*/
this.entity.collision.on("collisionstart",this._colstart,this);
/*死んだかどうか*/
this.isdie = false;
};
// update code called every frame
Enemy.prototype.update = function(dt) {
if(!this.isdie){//生きている状態
/*毎フレーム加算する*/
this.count ++;
/*インターバルごとに向きをランダムで変更する*/
if(this.count % this.change_interval === 0){
this.movefor = (Math.random() > 0.4)? this.RIGHT_MOVE : this.LEFT_MOVE;
}
/*指定した方向へ移動*/
this.entity.translate(this.movefor,0,0);
/*移動方向に合わせてspriteの向きを変更*/
this.setDirection(this.movefor);
}else{//死んでいる状態
if (!this.entity.sprite._currentClip._playing){//現在再生しているclipが終了したら
/*自分自身を削除する*/
this.entity.destroy();
}
}
};
/*ベクトルに応じてspriteの向きを変更するメソッド 引数:x軸の移動量*/
Enemy.prototype.setDirection = function(accu) {
this.entity.sprite.flipX = (accu < 0);
};
/*衝突した瞬間に呼ばれるコールバック*/
Enemy.prototype._colstart = function(ev){
if(ev.other.tags.has("player")){//衝突したentityが"player"tagを所持していたら
/*playerと自分自身の距離*/
var distance = ev.other.getLocalPosition().clone().sub(this.entity.getLocalPosition().clone());
if(distance.y > 0.7){//上からぶつかった
/*自分自身が死ぬ*/
this.die();
}else{//横からぶつかった
/*playerのスクリプトからdamage()メソッドを呼び出す*/
ev.other.script.player.damage();
}
}
};
/*自分自身が死ぬときの処理 */
Enemy.prototype.die = function(){
/*isdieフラグを立たせる*/
this.isdie = true;
/*RigidbodyとCollisionを切る*/
this.entity.rigidbody.enabled = false;
this.entity.collision.enabled = false;
/*deathのアニメーションクリップを再生*/
this.entity.sprite.play("death");
};
[コードの解説]
55行目以降を追記しました。distanceのyが0.7よりも大きかったら上からぶつかったと定義し、this.die()メソッドを呼び出します。それ以下だとSandyちゃんへのダメージとし、ぶつかってきたエンティティ(Sandyちゃん)のscriptコンポーネントにアタッチされたplayer.js内にあらかじめ定義してあるdamage()メソッドを実行します。
実行して正しく動作することが確認できればOKです
チュートリアル -2Dアクションゲーム-
チュートリアル -2Dアクションゲーム- 7/8
コメント
0件のコメント
サインインしてコメントを残してください。