【Unity】Blend Treeを使用したRPG風8方向移動の作成
前回RPG風のマップの作成をしたので今回は
キャラクターを置いて、一旦WASDキーで8方向に移動する様にしたいと思います。
キャラクターオブジェクトを作成する
空のオブジェクトを作成してCharaとでも適当に付けておきます。
これにこんな感じでコンポーネントをアタッチします。
Animator Controllerの作成
BaseCharacterMotionという名前でAnimatorControllerを作成します。
これを先ほどのキャラクターオブジェクトにアタッチしておきます。
8方向アニメーションの作成
walk@[方向]のネーミングでアニメーションを8個作ります。
アニメーションの作り方は大体ここに書いてあります。
raharu0425.hatenablog.com
方向のパラメータを追加
XYの移動方向をセットする為に2つパラメータを追加します。名前は適当に
Direction_X,Direction_Yとでも付けておきます。
AnimatorにBlend Tree ステートを追加する。
名前をWalkにしておきます。
これでBlendTreeを持っているステートができました。
BrendTree設定
Walkステートをダブルクリックすると詳細が見れます。
InspectorのBrendTypeを[2D Simple Directional]に変更して
Parametersを[Direction_X]と[Direction_Y]をセットします。
Motion Filedを8つ追加します。
これに先ほど作成した8方向アニメーションを追加します。
スクリプトを作る
//キャラクターのコントローラー
BaseCharacterController
//モーションを管理する基底クラス
BaseMortionController
BaseCharacterController.cs
using UnityEngine;
using System.Collections;
using UnityStandardAssets.CrossPlatformInput;
[RequireComponent(typeof (BaseMortionController))]
public class BaseCharacterController : MonoBehaviour {
private BaseMortionController m_Character;
private void Awake()
{
m_Character = GetComponent<BaseMortionController>();
}
private void Update()
{
}
private void FixedUpdate()
{
// WASDの入力取得
float h = CrossPlatformInputManager.GetAxis("Horizontal");
float v = CrossPlatformInputManager.GetAxis ("Vertical");
//移動
m_Character.Move(h, v);
}
}
BaseMortionController.cs
using UnityEngine;
using System.Collections;
public class BaseMortionController : MonoBehaviour {
private Animator m_Anim;
private Rigidbody2D m_Rigidbody2D;
[SerializeField]
private float move_speed = 7.0f;
private void Awake()
{
m_Anim = GetComponent<Animator>();
m_Rigidbody2D = GetComponent<Rigidbody2D>();
}
/**
* 移動
*/
public void Move(float h_move, float v_move)
{
// 移動方向に力を加える
Vector2 direction = new Vector2 (h_move, v_move).normalized;
m_Rigidbody2D.velocity = direction * move_speed;
//モーション判定用のパラメータ
m_Anim.SetFloat("Direction_X", h_move);
m_Anim.SetFloat("Direction_Y", v_move);
}
}
これらをCharaオブジェクトにアタッチして
完成
Unity4.3から追加されたらしいBlendTreeとても便利です。
簡単に8方向移動ができました。
素材はこちらを使わせて頂いております。有り難うございます。
こちらの記事を参考させて頂きました有り難うございます。