前提・実現したいこと
FPSのような、マウスで視点を操作するプログラムを作ろうとしています。
発生している問題・エラーメッセージ
視点を移動するためにマウスを動かすと、マウスを動かした方向(X軸の+の方向に動かしたらプレイヤーのX軸の+の方向)にプレイヤーのX軸またはZ軸の値がものすごい勢いで加算され続けてしまい制御不能になってしまいます。
該当のソースコード
C#
1public class Playercontroller : MonoBehaviour { 2 3 private CharacterController chara; 4 private Vector3 vec3; 5 public float speed; 6 private Transform camera; 7 [SerializeField] 8 private float cameraRotatelimit = 30f; 9 [SerializeField] 10 private bool cameraRotForward = true; 11 private Quaternion initCameraRot; 12 [SerializeField] 13 private float rotateSpeed = 2f; 14 private float xRotate; 15 private float yRotate; 16 [SerializeField] 17 private float mouseSpeed = 2f; 18 private Quaternion charaRotate; 19 private Quaternion cameraRotate; 20 21 void Start() 22 { 23 chara = GetComponent<CharacterController>(); 24 camera = GetComponentInChildren<Camera>().transform; 25 initCameraRot = camera.localRotation; 26 charaRotate = transform.localRotation; 27 cameraRotate = camera.localRotation; 28 } 29 30 void Update() 31 { 32 RotateCamera(); 33 34 RotateChara(); 35 36 if (chara.isGrounded) 37 { 38 vec3 = Vector3.zero; 39 vec3.x = Input.GetAxis("Horizontal"); 40 vec3.y = 0; 41 vec3.z = Input.GetAxis("Vertical"); 42 } 43 44 if (Input.GetKeyDown(KeyCode.LeftShift)) 45 { 46 speed = speed + 10; 47 } 48 49 if (Input.GetKeyUp(KeyCode.LeftShift)) 50 { 51 speed = speed - 10; 52 } 53 54 vec3.y += Physics.gravity.y * Time.deltaTime; 55 chara.Move(vec3 * speed * Time.deltaTime); 56 } 57 void RotateChara() 58 { 59 float yRotate = Input.GetAxis("Mouse X") * mouseSpeed; 60 61 charaRotate *= Quaternion.Euler(0f, yRotate, 0f); 62 63 transform.localRotation = Quaternion.Slerp(transform.localRotation, charaRotate, rotateSpeed * Time.deltaTime); 64 } 65 66 void RotateCamera() 67 { 68 69 float xRotate = Input.GetAxis("Mouse Y") * mouseSpeed; 70 71 if (cameraRotForward) 72 { 73 xRotate *= -1; 74 } 75 76 cameraRotate *= Quaternion.Euler(xRotate, 0f, 0f); 77 var resultYRot = Mathf.Clamp(Mathf.DeltaAngle(initCameraRot.eulerAngles.x, cameraRotate.eulerAngles.x), -cameraRotatelimit, cameraRotatelimit); 78 cameraRotate = Quaternion.Euler(resultYRot, cameraRotate.eulerAngles.y, cameraRotate.eulerAngles.z); 79 camera.localRotation = Quaternion.Slerp(camera.localRotation, cameraRotate, rotateSpeed * Time.deltaTime); 80 } 81 }
試したこと
charaRotate *= Quaternion.Euler(0f, yRotate, 0f);
charaRotateをcameraRotateに変えてみたりしましたが、そうするとY軸の値が変動してしまい視界が斜めになってしまいます。
補足情報(FW/ツールのバージョンなど)
親子関係は chara(Player)の子としてCameraがあるだけで他のオブジェクトは全部Playerと同じ階層にあります。
Unity 2018.2.5f1 Personal(64bit)
Visual Stadio
回答2件
あなたの回答
tips
プレビュー