- Home /
How to rotate the player to the direction of the camera
I am really new to C#, and when i wanted to make the player turn around with the camera i've failed. The camera itself moves around but the direction my player goes when i press w or d never changes. Of course i've tried looking it up but saw only raw code without explanations where to put it and how it works. Would really appreciate at least the code itself.
Answer by rage_co · Jul 02, 2021 at 04:05 PM
I followed a brackeys tutorial on fps movement when i was a beginner and the script works super, so i didn't change it much...here's the script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FpCameraLook : MonoBehaviour
{
public GameObject shadow;
public UImanager uimanager;
public CameraManager cammanager;
public Transform playerBody;
public Camera myCamera;
public float fov = 70f;
public float fovdif = 10f;
public float fovtime = 0.9f;
public float clampup = -80f;
public float clampdown = 80f;
public float mouseSensitivity = 100f;
public float setvolume;
public string sprintkey = "left shift";
float xRotation = 0f;
// Start is called before the first frame update
void Start()
{
myCamera.fieldOfView = fov;
}
// Update is called once per frame
void Update()
{
if(uimanager.pauseactive == "n" && cammanager.currentcam == "fp")
{
if(Input.GetKey(shadow.GetComponent<PlayerMovement>().sprintkey) && shadow.GetComponent<PlayerMovement>().isgrounded)
{
myCamera.fieldOfView = Mathf.Lerp(myCamera.fieldOfView, fov + fovdif, fovtime * Time.deltaTime);
}
else
{
myCamera.fieldOfView = Mathf.Lerp(myCamera.fieldOfView, fov, fovtime * Time.deltaTime);
}
float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -clampup, clampdown);
transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
playerBody.Rotate(Vector3.up * mouseX);
}
}
}
the relevant part is
float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -clampup, clampdown);
transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
playerBody.Rotate(Vector3.up * mouseX);
the rest is just customised according to my needs....hope this helps!! The link to the video brackeys' tutorial video
Your answer
Follow this Question
Related Questions
I need animate arms with script when I rotate my character like in Escape of Tarkov 0 Answers
Camera not rotate when following player 1 Answer
How to set the player in front of the camera in any rotation 1 Answer
Rotating GameObject Around Player With "Mouse Y" Position 2 Answers
Rotating objects to specific angle 3 Answers