Hello, I have only just started my unity coding experience and have little to no idea of how most things work yet, I have started off with pretty basic movement tutorials to get where I am at in one of my movement scripts but I am struggling with making the players facing direction relative to where the camera is facing. This is my entire movement script so far, any feedback would help or even any moderations to improve the efficiency of the code would greatly help me out. Again, I have no idea what I am doing so sorry if this code hurts to see in the sloppiness sense.
public class PlayerMovement : MonoBehaviour
{
[SerializeField] private float Speed = 1.5f;
[SerializeField] private float sprintSpeed = 2f;
[SerializeField] private float JumpHeight = 7f;
[SerializeField] private float groundcheckdistance;
[SerializeField] private float BufferCheckDistance = 0.1f;
[SerializeField] private bool PlayerGrounded = true;
[SerializeField]private float PlayerSensitivity = 100f;
[SerializeField] private float sensMultiplier = 1f;
private float desiredX;
private float xRotation;
public Transform playerCam;
public Transform orientation;
private Rigidbody rb;
private void Start()
{
rb = GetComponent<Rigidbody>();
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
private void Update()
{
PlayerMovements();
sprinting();
Jumping();
GroundedCheck();
LookRotations();
}
private void PlayerMovements()
{
float HorizontalInput = Input.GetAxis("Horizontal");
float VerticalInput = Input.GetAxis("Vertical");
Vector3 Movement = new Vector3(HorizontalInput, 0f, VerticalInput) * Speed;
rb.MovePosition(rb.position + Movement * Time.fixedDeltaTime);
}
private void sprinting()
{
if(Input.GetKey(KeyCode.LeftShift) == true && PlayerGrounded)
{
Speed = sprintSpeed;
}
else
{
Speed = 1.5f;
}
}
private void Jumping()
{
if(Input.GetButtonDown("Jump") && PlayerGrounded)
{
rb.AddForce(new Vector3(0f, JumpHeight, 0f), ForceMode.Impulse);
PlayerGrounded = false;
}
}
private void GroundedCheck()
{
groundcheckdistance = (GetComponent<CapsuleCollider>().height / 2) + BufferCheckDistance;
RaycastHit GroundHit;
if (Physics.Raycast(transform.position, -transform.up, out GroundHit, groundcheckdistance))
{
PlayerGrounded = true;
}
else
{
PlayerGrounded = false;
}
}
private void LookRotations()
{
float mouseX = Input.GetAxis("Mouse X") * PlayerSensitivity * Time.fixedDeltaTime * sensMultiplier;
float mouseY = Input.GetAxis("Mouse Y") * PlayerSensitivity * Time.fixedDeltaTime * sensMultiplier;
Vector3 rot = playerCam.transform.localRotation.eulerAngles;
desiredX = rot.y + mouseX;
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
playerCam.transform.localRotation = Quaternion.Euler(xRotation, desiredX, 0);
orientation.transform.localRotation = Quaternion.Euler(0, desiredX, 0);
}
}