UnityでUnityちゃんをキー操作させて、Unityちゃんをカメラが追従するということをやりたいです。Unityちゃんのキー操作もカメラの追従もスクリプトを用いてC#で動かすことを考えています。
https://unity-shoshinsha.biz/archives/189
こちらのサイトを参考にしてUnityちゃんをキー操作することはすぐにできましたが、カメラの追従の方がうまくいきません。
TPSのように常にUnityちゃんの後ろにカメラがあるようにしたいのですが、どのサイトを参考にしてもうまくできませんでした。
C#を用いてカメラを常にUnityちゃんの後ろに追従させる方法を教えてほしいです
C#
1using System.Collections; 2using System.Collections.Generic; 3using UnityEngine; 4 5public class Player : MonoBehaviour { 6 7 //Rigidbodyを変数に入れる 8 Rigidbody rb; 9 //移動スピード 10 public float speed = 3f; 11 //ジャンプ力 12 public float thrust = 200; 13 //Animatorを入れる変数 14 private Animator animator; 15 //ユニティちゃんの位置を入れる 16 Vector3 playerPos; 17 //地面に接触しているか否か 18 bool ground; 19 20 void Start() 21 { 22 //Rigidbodyを取得 23 rb = GetComponent<Rigidbody>(); 24 //ユニティちゃんのAnimatorにアクセスする 25 animator = GetComponent<Animator>(); 26 //ユニティちゃんの現在より少し前の位置を保存 27 playerPos = transform.position; 28 } 29 30 void Update() 31 { 32 //地面に接触していると作動する 33 if (ground) 34 { 35 //A・Dキー、←→キーで横移動 36 float x = Input.GetAxisRaw("Horizontal") * Time.deltaTime * speed; 37 38 //W・Sキー、↑↓キーで前後移動 39 float z = Input.GetAxisRaw("Vertical") * Time.deltaTime * speed; 40 41 //現在の位置+入力した数値の場所に移動する 42 rb.MovePosition(transform.position + new Vector3(x, 0, z)); 43 44 //ユニティちゃんの最新の位置から少し前の位置を引いて方向を割り出す 45 Vector3 direction = transform.position - playerPos; 46 47 //移動距離が少しでもあった場合に方向転換 48 if (direction.magnitude > 0.01f) 49 { 50 //directionのX軸とZ軸の方向を向かせる 51 transform.rotation = Quaternion.LookRotation(new Vector3 52 (direction.x, 0, direction.z)); 53 //走るアニメーションを再生 54 animator.SetBool("Running", true); 55 } 56 else 57 { 58 //ベクトルの長さがない=移動していない時は走るアニメーションはオフ 59 animator.SetBool("Running", false); 60 } 61 62 //ユニティちゃんの位置を更新する 63 playerPos = transform.position; 64 65 //スペースキーやゲームパッドの3ボタンでジャンプ 66 if (Input.GetButton("Jump")) 67 { 68 //thrustの分だけ上方に力がかかる 69 rb.AddForce(transform.up * thrust); 70 //速度が出ていたら前方と上方に力がかかる 71 if (rb.velocity.magnitude > 0) 72 rb.AddForce(transform.forward * thrust + transform.up * thrust); 73 } 74 } 75 } 76 77 //Planに触れている間作動 78 void OnCollisionStay(Collision col) 79 { 80 ground = true; 81 //ジャンプのアニメーションをオフにする 82 animator.SetBool("Jumping", false); 83 } 84 85 //Planから離れると作動 86 void OnCollisionExit(Collision col) 87 { 88 ground = false; 89 //ジャンプのアニメーションをオンにする 90 animator.SetBool("Jumping", true); 91 } 92}

回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2020/01/22 13:47
2020/01/22 13:50
2020/09/28 00:49
2020/09/28 01:18
2020/09/28 01:19