Very stuttery movement

Hi, I’m trying to make a gun that currently moves around the player when the player rotates. It works currently but is very buggy and moves back and forth extremely snappy. Why is this happening?

using UnityEngine;

public class GunController : MonoBehaviour
{
    [Header("Objects")]
    public Transform camera;

    [Header("Gun Settings")]
    //Aiming
    public Vector3 normalLocalPosition;
    public Vector3 aimingLocalPosition;
    public Vector3 weaponDistanceAmount;

    public float aimSmoothing = 10;

    [Header("Mouse Settings")]
    public float mouseSensitivity = 1;
    private Vector2 _currentRotation;
    public float weaponSwayAmount = 10;

    private void Update()
    {
        DetermineRotation();
    }

    private void DetermineRotation()
    {
        Vector2 mouseAxis = new Vector2(Input.GetAxisRaw("Mouse X"), Input.GetAxisRaw("Mouse Y"));

        mouseAxis *= mouseSensitivity;
        _currentRotation += mouseAxis;

        _currentRotation.y = Mathf.Clamp(_currentRotation.y, -90, 90);

        transform.localPosition = (Vector3)mouseAxis + weaponDistanceAmount;

        transform.root.localRotation = Quaternion.AngleAxis(_currentRotation.x, Vector3.up);
        camera.localRotation = Quaternion.AngleAxis(-_currentRotation.y, Vector3.right);

    }
}

You should use Time.deltaTime to smooth movements.
Depending on how you game is running, Update() is called multiple items per seconds. If it’s running at 60 fps then it’s 60 calls to Update() par second so there’s ~ 0.016 second between each call. So a movement of 10 degrees per frame would quickly make you spinning really fast.

If you multiply mouseAxis by Time.deltaTime, speed will be easier to adjust because you can think about it in a more humain understandable way : If you want your object to rotate at a speed of 90 degrees per second you should add 90 * Time.deltaTime to it’s current rotation, giving you a smooth and constant movement.
_currentRotation += mouseAxis * Time.deltaTime;

I would also recommend to reorganize your gameobject hierarchy like this :

You can use Player transform to change position, camera to change rotation and you don’t need to rotate the Gun because it will follow the camera’s rotation. All you need to do is to place correctly the gun relatively to the camera and to rotate the camera.

1 Like

Thanks! I don’t believe that I forgot to do that.