ヒキニートがゲームを作るブログ

Unityでゲームを作る過程を投稿します

プレイヤーの移動【UnityでRTSを作る 2】

前回の記事ではざっくりと開発計画をしましたが、
ついに今回ゲーム制作が始まります。

今回はプレイヤーの移動です。

モデル

まずはプレイヤーのモデルの紹介です。

f:id:MackySoft:20170413205955j:plain
キューブ君(CubeKun)と呼びます。
ゲーム制作を始めた当初に作ったキャラクターです。

このキューブ君がプレイヤーとなります。

そしてこのプロジェクトの名前は「CubeKun Wars」となりました。
(変更の可能性もあります)

カメラ

まず最初にカメラを制御するためのコードを書きます。
トップダウン型のゲームなのでカメラが下に向いている前提のコードです。

CameraController.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace MackySoft.CubeKunWars {
	public class CameraController : MonoBehaviour {

		public Transform target;
		public float height = 10;

		private Transform tr;

		void Start () {
			tr = transform;
		}
		
		void Update () {
			if (!target) return;
			tr.position = target.position + Vector3.up * height;
		}
	}
}

移動処理

経路探索にはA* Pathfinding Projectを使用します。

CubeKun.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

using Pathfinding;

namespace MackySoft.CubeKunWars {

	public abstract class CubeKun : AIPath {

		public float sleepVelocity = 0.4F;
		
		public Transform Tr { get ; private set; }

		protected override void Awake () {
			base.Awake();
			Tr = transform;
		}

		public void MoveTo (Vector3 position) {
			if (canMove) {
				var dir = CalculateVelocity(GetFeetPosition());
				RotateTowards(targetDirection);

				dir.y = 0;
				if (dir.sqrMagnitude > sleepVelocity * sleepVelocity) {

				} else {
					dir = Vector3.zero;
				}
				Tr.Translate(dir * Time.deltaTime,Space.World);
			}
		}

		public override Vector3 GetFeetPosition () {
			return Tr.position;
		}

	}
}


Player.cs

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace MackySoft.CubeKunWars {
	public class Player : CubeKun {

		public Transform Pointer { get; private set; }

		protected override void Awake () {
			base.Awake();
			canMove = false;
			Pointer = new GameObject("pointer").transform;
			target = Pointer;

			Camera.main.orthographic = true;
		}

		private new void Update () {
			canMove = Input.GetMouseButton(0);
			canSearch = canMove;
			if (canMove) {
				Pointer.position = Camera.main.ScreenToWorldPoint(Input.mousePosition);
				MoveToPointerPosition();
			}
		}

		public void MoveToPointerPosition () {
			MoveTo(Pointer.position);
		}

	}
}

動画

クリックし続けるとキューブ君がカーソルのある方向へ向かいます。

Make RTS with Unity Part.1[Player Mover]