物理演算(Rigidbody)を考慮してプレイヤーを操作したい場合は、RigidbodyのAddForceを使用して、スクリプトを作成するので、その方法を紹介します。
※物理演算を気にする必要がない場合はTransformでスクリプトを作成する。
完成動画
上下左右キーで以下のように移動します。
作り方
プレイヤーを作成
1.例としてCylinderオブジェクトをプレイヤーとして作成します。名前はCylinderPlayerにします。

プレイヤーを操作するスクリプトを作成
1.MoveRigidbody.csという名前のスクリプトを作成して、以下のコードを記載する。
using UnityEngine;
// アタッチしたGameObjectにRigidbodyがアタッチされていない場合、アタッチする
[RequireComponent(typeof(Rigidbody))]
public class MoveRigidbody : MonoBehaviour
{
// 移動速度を設定(Inspectorタブからも値を変更できるようにする)
[SerializeField]
private float speed = 2.0f;
// アタッチしているGameObjectのRigidbodyを格納する変数
private Rigidbody rigidBody;
// Start is called before the first frame update
void Start()
{
// アタッチしているGameObjectのRigidbodyを取得
//(FixedUpdate()内で毎回取得すると処理が重くなるので、Start()で取得する
rigidBody = GetComponent<Rigidbody>();
}
//一秒間に一定の回数呼ばれる(物理演算(Rigidbody)を使った移動はFixedUpdateで行った方が良いらしい)
private void FixedUpdate()
{
// 左右のキーの入力を取得
float x = Input.GetAxis("Horizontal");
// 上下のキーの入力を取得
float z = Input.GetAxis("Vertical");
// 上下左右キーを入力して得た値にspeedをかけた値をAddForceに設定して移動させる
//(ForceMode.Forceは質量を考慮して、継続的に力を与え続ける)
rigidBody.AddForce(x * speed, 0, z * speed, ForceMode.Force);
}
}
スクリプトを操作したいGameObjectにアタッチする
1.MoveRigidbody.csを操作したいGameObject(CylinderPlayerオブジェクト)にアタッチする。

2.CylinderPlayerにMoveRigidbodyとRigidbodyコンポーネントがアタッチされていることを確認
※RigidbodyはMoveRigidbody.cs内に”[RequireComponent(typeof(Rigidbody))]”を付けたことにより自動的に追加される

※Speedの値は10くらいだといい感じに動く

完成
これで上下左右キーを押すと、プレイヤーが操作できるようになった。
※このまま上下左右キーを押すと、CylinderPlayerオブジェクトの角度も一緒に動いてしまうので、角度は変えたくなければ、以下のようにRigidbodyの”Freeze Rotation”にチェックを付ける。

キーを押したときの動きが早すぎたり遅すぎたりする場合は以下のSpeedの値変えてみよう!

Speedを変える以外の方法としては、RigidbodyコンポーネントのMass(質量)を大きくすると、動きが遅くなる。

コメント
ありがとうございます