I'm currently attempting to make a first person character using a rigid body. I am aware that the character controller exists, but I believe my game will be very physics based so it's better if my character is a rigid body. I currently can walk, and rotate the camera up and down with the mouse. I am now trying to rotate my character left and right with the mouse, but this requires me to rotate my rigid body, not just the camera. Here's my code so far.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
[SerializeField] float walkSpeed = 3;
[SerializeField] float cameraSpeed = 3;
Vector3 direction;
float cameraX;
Rigidbody myRigidBody;
[SerializeField] Camera myCamera;
// Start is called before the first frame update
void Start()
{
myRigidBody = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
direction = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
cameraX = -Input.GetAxis("Mouse Y") * cameraSpeed;
myCamera.transform.Rotate(new Vector3(cameraX, 0, 0));
}
void FixedUpdate()
{
myRigidBody.AddRelativeForce(direction * walkSpeed, ForceMode.Acceleration);
}
I believe that the rigid body function I should use to rotate left and right is MoveRotation (I'm still new to rigid bodies), but I'm open to ideas. MoveRotation uses Quaternions, and I have no idea how to translate my mouse axis into a quaternion.
Here's my question, How do i implement the Y rotation for my rigid body first person controller? Should I use torque, or somehow directly alter my rotation without using forces? Also, How do i translate the Mouse Axis into something I can use to rotate something? thnx.
Edit:
I tried adding this line of code:
myRigidBody.MoveRotation(Quaternion.Euler(0, mouseX * cameraSpeed, 0));
for some reason it has no effect on my character at all, but I feel Like it's on the right track. Why isn't this working?
Edit 2:
I added this line in Update:
rotateDirection = new Vector3(0, Input.GetAxis("Mouse X"), 0);
And this line in FixedUpdate:
myRigidBody.MoveRotation(Quaternion.Euler(rotateDirection));
Now when I move my mouse (I commented out my camera up and down movement to test) my character moves left and right for a tiny bit, but jitters back to it's original position, so It feels like I'm fighting it. The rotation in the inspector jitters in the correct direction, negative if i move the mouse left, positive if right, but only for a very small amount, 1.45 being the most, and then reverts back to zero. Also, it doesn't rotate smoothly, but jitters. Anybody know whats going on?
Edit 3: changed it from addforce to addrelativeforce because that make it move forward based on local coordinates not global.