Dear!くろうどぃあ!

このブログでは、私、くろうどの趣味に関する事を記述します。
当面は、「RPGツクールMV」をメインにします。

ソースコード解説「隣接時フキダシ表示プラグイン」

2022-07-23 21:45:33 | RPGツクールMZ
こんばんは。くろうどです。
今回は、「隣接時フキダシ表示プラグイン」を作ったので、そのソースコードの解説をしたいと思います。

 

今回の機能はマップイベント(Game_Event)を基準にプレイヤーの位置を取得して隣接しているか判断します。

ソースコードの上から順に見ていくと、まずは、Game_Event の refresh です。
これはプレイヤーから隣接してきた時の処理です。

const KRD_Game_Event_refresh = Game_Event.prototype.refresh;
Game_Event.prototype.refresh = function() {
	KRD_Game_Event_refresh.apply(this, arguments);
	this.doNeighborBalloon();
};

次に updateStop です。
これはマップイベントの移動でプレイヤーに隣接した時の処理です。
ここは、毎フレームかなんかのタイミング(よく知らない)で実行されるので注意が必要です。
const KRD_Game_Event_updateStop = Game_Event.prototype.updateStop;
Game_Event.prototype.updateStop = function() {
	KRD_Game_Event_updateStop.apply(this, arguments);
	this.doNeighborBalloon();
};

実際の処理は次からです。
マップイベントのメモ欄に書いたタグ(balloonId)を取得して、requestBalloon でフキダシを表示させます。
他の部分は、updateStop が繰り返し実行されるので、プレイヤーが移動してなければフキダシを表示させないようにしています。
あと、マップイベントが出現条件を満たしていない時はフキダシを表示させないようにしています。

Game_Event.prototype.doNeighborBalloon = function() {
	if (this._pageIndex < 0) {
		return;
	}

	const balloonId = Number(this.event().meta.balloonId);
	if (!isNaN(balloonId)) {
		this._oldPosition = this._oldPosition ? this._oldPosition : 0;
		const newPosition = this.neighborPlayer();
		if (this._oldPosition !== newPosition && newPosition > 0) {
			$gameTemp.requestBalloon(this, balloonId);
		}
		this._oldPosition = newPosition;
	}
};

次の処理はプレイヤーとマップイベントが隣接しているかのチェックです。
プレイヤーのX座標、Y座標とマップイベントのX座標、Y座標を比較しています。
プレイヤーは $gamePlayer で取得できますし、マップイベントは今回は Game_Event の中なので this で取得できます。
Game_Event.prototype.neighborPlayer = function() {
	if (this.x === $gamePlayer.x && this.y === $gamePlayer.y + 1) {
		// console.log("プレイヤーの下にイベントあるよ!");
		return 2;
	}
	if (this.x === $gamePlayer.x - 1 && this.y === $gamePlayer.y) {
		// console.log("プレイヤーの左にイベントあるよ!");
		return 4;
	}
	if (this.x === $gamePlayer.x + 1 && this.y === $gamePlayer.y) {
		// console.log("プレイヤーの右にイベントあるよ!");
		return 6;
	}
	if (this.x === $gamePlayer.x && this.y === $gamePlayer.y - 1) {
		// console.log("プレイヤーの上にイベントあるよ!");
		return 8;
	}
	return 0;
};

というわけで、「隣接時フキダシ表示プラグイン」はこれだけです。

このプラグインにどんどん機能追加していくと、「近づいた時にメッセージ表示するプラグイン」になるとは思いますが、うちは満足したのでココまでです。

それでは~。