- Home /
How to rotate Character on Y axis along with the mouse rotation?
So I have gameobject "Player" and "Player Camera" as a child of the "Player". MouseLookScript is attached to the camera:
public class MouseLookScript : MonoBehaviour
{
float mouseSensitivity = 2.5f;
float xRotation;
public float yRotation;
private void Update()
{
xRotation -= Input.GetAxis("Mouse Y") * mouseSensitivity;
yRotation += Input.GetAxis("Mouse X") * mouseSensitivity;
transform.rotation = Quaternion.Euler(0, yRotation, 0);
}
}
and PlayerMovementScript is attached to the Player itself:
public class PlayerScript : MonoBehaviour
{
public string cameraName;
public float movementSpeed = 20f;
private void Update()
{
float moveHorizontal = Input.GetAxis("Horizontal") * Time.deltaTime * movementSpeed;
float moveVertical = Input.GetAxis("Vertical") * Time.deltaTime * movementSpeed;
transform.position += new Vector3(moveHorizontal, 0, moveVertical);
transform.rotation = Quaternion.Euler(0, GameObject.Find(cameraName).GetComponent<MouseLookScript>().yRotation, 0);
}
}
and for some reason when I rotate my mouse left or right, my character doesn't rotate along with the camera, which means, when I press W (to move forward), with camera facing slightly left or right, my character doesn't go in that direction, it just keeps going global forward.
Where is the problem? please help.
Comment
Your answer
Follow this Question
Related Questions
Flip over an object (smooth transition) 3 Answers
Change character's Y rotation based on velocity. 1 Answer
Making a bubble level (not a game but work tool) 1 Answer
Character Rotation 2 Answers
Character MoveLook rotation locked? 1 Answer