My Capsule/Camera Flips out When Turning Around
So I've just started in Unity and have been trying to make a first-person game, starting with being able to move and look around. Although when I try to do a 180 or look behind me, my capsule freaks out. I've locked the X and Z position which stops it from falling over, and when locking the Y position, it stops the problem altogether. But when locking the Y position for the RigidBody, my character can no longer jump. Is there a way around this, I'll post my code below.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class characterController : MonoBehaviour {
public float speed = 10.0F;
// Start is called before the first frame update
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
if (transform.position.y <= 1.85f)
{
GetComponent<Rigidbody>().AddForce(Vector3.up * 150);
}
}
float translation = Input.GetAxis("Vertical") * speed;
float straffe = Input.GetAxis("Horizontal") * speed;
translation *= Time.deltaTime;
straffe *= Time.deltaTime;
transform.Translate(straffe, 0, translation);
if (Input.GetKeyDown("escape"))
Cursor.lockState = CursorLockMode.None;
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class camMouseLook : MonoBehaviour
{
Vector2 mouseLook;
Vector2 smoothV;
public float sensitivity = 5.0f;
public float smoothing = 2.0f;
GameObject character;
void Start()
{
character = this.transform.parent.gameObject;
}
void Update()
{
var md = new Vector2(Input.GetAxisRaw("Mouse X"), Input.GetAxisRaw("Mouse Y"));
md = Vector2.Scale(md, new Vector2(sensitivity * smoothing, sensitivity * smoothing));
smoothV.x = Mathf.Lerp(smoothV.x, md.x, 1f / smoothing);
smoothV.y = Mathf.Lerp(smoothV.y, md.y, 1f / smoothing);
mouseLook += smoothV;
transform.localRotation = Quaternion.AngleAxis(-mouseLook.y, Vector3.right);
character.transform.localRotation = Quaternion.AngleAxis(mouseLook.x, character.transform.up);
}
}
Answer by Lucium_Radon · Dec 10, 2019 at 09:37 PM
Update: Freezing the Y position still makes it flip, but I may have found a solution. Completely freezing all the rotations but the Y in RigidBody has stopped this issue and my character can still jump. Don't know if this will affect me much in the future.
Your answer
Follow this Question
Related Questions
camera movement on a sphere 0 Answers
Help rotating camera script 0 Answers
Code Optimization 1 Answer
Issue with getting the mouse position in 3D and moving a gameobject on the y & z axis 0 Answers
RayCast From Centre of Camera 1 Answer