3Dキャラクターのコントロール方法(追記1)
bankzhy.hatenablog.com
前回の記事で、回転情報がモデルに含まれてい
ない素材に対する制御方法を実装しました。しかし、前回の実装方法のままだと、2.5Dゲームに十分対応できるが、3Dゲームのように動くことができない。3Dゲームのキャラクターのコントロール方法以下
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityStandardAssets.CrossPlatformInput; [RequireComponent(typeof(Rigidbody))] public class PlayerController : MonoBehaviour { public float RunSpeed = 100.0f; public float TurnSmoothTime = 0.2f; private Rigidbody m_Rigidbody; private Animator m_Anim; private float m_TurnSmoothVelocity; private Vector3 m_CurrentRotation;//現在キャラクターの方向を記録する変数 // Use this for initialization void Start () { m_Rigidbody = GetComponent<Rigidbody>(); m_Anim = GetComponent<Animator>(); Debug.Log(Vector3.up); m_CurrentRotation = transform.eulerAngles; } // Update is called once per frame void Update() { float inputX = 0f; float inputZ = 0f; inputX = CrossPlatformInputManager.GetAxis("Horizontal"); inputZ = CrossPlatformInputManager.GetAxis("Vertical"); Vector2 inputDir = new Vector2(inputX,inputZ).normalized; if (inputDir != Vector2.zero) { //z方向とx方向のtanを求め、その角度をrotationに代入する。 //Mathf.Rad2Degはradianから度に変換する。これは ” 360/(PI * 2) " に等しいです。 float rotation = Mathf.Atan2(inputDir.x, inputDir.y) * Mathf.Rad2Deg; //現在キャラクターの方向に対する方向へ変換 float targetrotation = m_CurrentRotation.y + rotation; //キャラクターのRotationを指定する。 transform.localEulerAngles =Vector3.up* Mathf.SmoothDampAngle(transform.eulerAngles.y, targetrotation, ref m_TurnSmoothVelocity,TurnSmoothTime); } else { UpdateCurrentRotation(); } // m_Rigidbody.velocity=new Vector3(inputX, 0, inputZ)*RunSpeed*Time.deltaTime; //入力の方向を現在キャラクターの方向に対する方向へ変換 Vector3 velocityDirection = Quaternion.Euler(0, m_CurrentRotation.y, 0) * new Vector3(inputX, 0, inputZ); m_Rigidbody.velocity = velocityDirection * RunSpeed * Time.deltaTime; m_Anim.SetFloat("inputX", inputX); m_Anim.SetFloat("inputZ", inputZ); } //キャラクターの方向を更新する public void UpdateCurrentRotation() { m_CurrentRotation = transform.eulerAngles; } }