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);
}
}