以前の解説したバイオハザードタイプの移動処理とJavaScriptの記述以外は全て同じです。その他の部分の作成はその時のエントリーを参照下さい。
キャラクターの移動処理(バイオハザードタイプ) - 強火で進め
http://d.hatena.ne.jp/nakamura001/20110612/1307893603
プログラムはこちらになります。
【PlayerScript.js】
private var moveDirection : Vector3 = Vector3.zero; var gravity : float = 20.0; function Start() { animation.Play("idle"); } function FixedUpdate() { controller = GetComponent(CharacterController); moveDirection = Vector3.zero; moveDirection.y -= gravity; var targetDirection : Vector3 = Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical")); if (targetDirection.magnitude > 0.1) { transform.rotation = Quaternion.LookRotation(targetDirection); moveDirection += transform.forward*2; animation.CrossFade("walk"); } else { animation.CrossFade("idle"); } controller.Move(moveDirection*Time.deltaTime); }
キャラクターの移動処理のプログラムが22行で出来ちゃいました。まぁ、その他の作業が色々とGUI上で必要ですが… でもまぁ、それを考慮しても開発効率の良い開発環境だなぁと改めて実感しました。
さて、続いて主な処理について解説します。
var targetDirection : Vector3 = Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
ここでキーボードやゲームパッドで入力された方向を移動方向として targetDirection に代入しています。
if (targetDirection.magnitude > 0.1) {
magnitude メソッドは targetDirection の移動量(距離)を取得し移動量が大きい(=キー入力が有る)時にその方向へ移動する処理を行っています。
transform.rotation = Quaternion.LookRotation(targetDirection); moveDirection += transform.forward*2;
移動方向のベクトル targetDirection を Quaternion.LookRotation の引数にし、その方向の rotation (X,Y,Z軸の回転量)を取得→キャラクターの向きに設定。回転が適用されたキャラクターの正面方向へ移動させる事により入力方向へキャラクターを移動させています。
Unity Script Reference – Quaternion.LookRotation
http://unity3d.com/support/documentation/ScriptReference/Quaternion.LookRotation.html
今回のサンプルはこちらで試せます。一度画面をクリックしてフォーカスを当ててからキー入力をする様にして下さい。ソースファイルは前回のものを使って、プログラムの部分だけ書き換えて下さい。