[Unity] Rigidbodyを使用してプレイヤーを動かす
3, PlayerControllerを作り、下記コードを記述する
(下記でキーボード入力で動作する)
PlayerController.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
float x;
float z;
public float moveSpeed = 2f;
Rigidbody rb;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
x = Input.GetAxisRaw("Horizontal");
z = Input.GetAxisRaw("Vertical");
}
void FixedUpdate()
{
rb.velocity = new Vector3(x, 0, z) * moveSpeed;
}
}
一度ここで動作の確認をする。
アニメーションの作成
1 , AnimatorControllerを作成し、PlayerのAnimatorにアタッチする
(PlayerにAnimatorがない場合はAddComponentから作成してあげる)
2 , Speedのパラメータを作成し、MakeTransitionを設定。各ConditionsにSpeedを設定する。
HasExitTimeのチェックを外す、TransitionDuratiorは0にする。
3, 下記コメント箇所のコードを追加する
PlayerController.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
float x;
float z;
public float moveSpeed = 2;
Rigidbody rb;
//アニメーターを設定
Animator animator;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody>();
//アニメーターを取得
animator = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
x = Input.GetAxisRaw("Horizontal");
z = Input.GetAxisRaw("Vertical");
}
void FixedUpdate()
{
rb.velocity = new Vector3(x, 0, z) * moveSpeed;
//パラメータを取得
animator.SetFloat("Speed", rb.velocity.magnitude);
}
}
4, アニメーションのループがうまくいかない場合はLoopTimeとLoopPoseのチェックを確認する
Playerの方向転換
1, 下記コメント部分を追加する
PlayerController
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
float x;
float z;
public float moveSpeed = 2;
Rigidbody rb;
Animator animator;
void Start()
{
rb = GetComponent<Rigidbody>();
animator = GetComponent<Animator>();
}
void Update()
{
x = Input.GetAxisRaw("Horizontal");
z = Input.GetAxisRaw("Vertical");
}
void FixedUpdate()
{
// 方向を取得
Vector3 direction = transform.position + new Vector3(x, 0, z) * moveSpeed;
// directionの方向に向く
transform.LookAt(direction);
rb.velocity = new Vector3(x, 0, z) * moveSpeed;
animator.SetFloat("Speed", rb.velocity.magnitude);
}
}