Reputation: 11
I am making a game in Unity using Mirror
There are two cameras in the scene for having the experience of first person and third person, but the camera is not moving on y axis.
using Mirror;
using UnityEngine;
namespace QuickStart
{
public class PlayerScript : NetworkBehaviour
{
public float mouseSensitivity = 100f;
float xRotation = 0f;
// Public variable to access the camera
public Camera playerCamera;
public override void OnStartLocalPlayer()
{
// Assign the main camera to the playerCamera variable
if (Camera.main != null)
{
playerCamera = Camera.main;
playerCamera.transform.SetParent(transform);
playerCamera.transform.localPosition = new Vector3(0, 0, 0);
// Lock the cursor to the center of the screen
Cursor.lockState = CursorLockMode.Locked;
}
else
{
Debug.LogError("Main Camera not found in the scene!");
}
}
void Update()
{
if (!isLocalPlayer) { return; }
// Movement
float moveX = Input.GetAxis("Horizontal") * Time.deltaTime * 110.0f;
float moveZ = Input.GetAxis("Vertical") * Time.deltaTime * 4f;
transform.Rotate(0, moveX, 0);
transform.Translate(0, 0, moveZ);
// Camera Look
float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90f, 90f); // Prevents looking too far up or down
// Use the public camera variable
if (playerCamera != null)
{
playerCamera.transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
}
transform.Rotate(Vector3.up * mouseX);
}
}
}
Upvotes: 1
Views: 29
Reputation: 15649
Your xRotation
correctly clamps the vertical movement, but you are only applying this rotation to the playerCamera
. You should ensure that the player itself does not rotate on the x-axis (only the camera should).
Modified code:
// Rotate the player object left and right (Y-axis rotation)
float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
transform.Rotate(Vector3.up * mouseX);
// Rotate the camera up and down (X-axis rotation)
float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90f, 90f); // Prevent looking too far up or down
if (playerCamera != null)
{
playerCamera.transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
}
Also check if both cameras are active at the same time, which might be interfering, try debugging with Debug.Log
to see if mouseY
values are being received.
Upvotes: 0