- Home /
Question by
hveeck · Mar 31, 2018 at 08:56 PM ·
camerafpscamera-movementcamera rotatecamera-look
Camera movement and gun follow in unity
I am making an fps and I have a lot of things down, but I really cant make it so the camera moves with your mouse movement + the gun following your camera movement (on X and Y) Thanks!
Comment
Answer by Llama_w_2Ls · Jul 23, 2020 at 04:01 PM
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class MouseComponent : MonoBehaviour
{
public float MouseSensitivity = 500f;
public Transform PlayerBody;
float Xrotation = 0f;
//Start is called before the first frame update
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
}
// Update is called once per frame
public void Update()
{
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);
transform.localRotation = Quaternion.Euler(Xrotation, 0f, 0f);
PlayerBody.Rotate(Vector3.up * MouseX);
}
}
Attach script to camera and set the playerbody as the gameobject that your character controller is sitting under
You can parent the gun to the camera so that the gun also follows the position of your camera
Your answer
Follow this Question
Related Questions
Camera gets stuck when cursor is locked 0 Answers
Camera follow a sphere which look at another object on the ground 0 Answers
camera zoom 1 Answer
Free camera look question 2 Answers
Jerky 3rd Person Camera Following Movement and Rotation 0 Answers