I’m trying to add recoil to my fps game. The cross hair and gun are parented to the camera so I thought that I could just rotate the camera slightly up every time the player fired. But for some reason, the camera rotates up for a split second and then snaps back to where it was, which I definitely don’t want. The first script I have on my camera and the other on my gun .Thanks.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MouseLook : MonoBehaviour
{
public float mouseSensitivity = 100f;
public Transform playerBody;
private float xRotation = 0f;
// Start is called before the first frame update
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
}
// Update is called once per frame
void Update()
{
float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;
playerBody.Rotate(Vector3.up * mouseX);
xRotation -= mouseY;
transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
if (Input.GetButtonDown("Fire1"))
{
transform.Rotate(Vector3.left, 20f);
}
}
}
using UnityEngine;
public class Gun : MonoBehaviour
{
public float damage = 10f;
public float range = 100f;
public Camera fpsCam;
public ParticleSystem muzzleFlash;
void Update()
{
if (Input.GetButtonDown("Fire1"))
{
Shoot();
}
}
void Shoot()
{
muzzleFlash.Play();
RaycastHit hit;
if (Physics.Raycast(fpsCam.transform.position, fpsCam.transform.forward, out hit, range))
{
Debug.Log(hit.transform.name);
}
}
}