How to Mathf.Clamp one axis y in update when the rotation is determined by mouse position in unity 3D

665 Views Asked by At

I'm developing a sailing simulator for a school project and Ii'm currently working on the gas handle of the boat. It's currently working so that the boat goes forward when the handle is in y axis = 0 and goes in reverse when the handle is in y axis = 90.

Currently I'm only able to test this by setting the values in the inspector because I can't get it to clamp so that it stops in those two y-rotations. The mouse moving the handle works fine as well.

My script looks the following:

public class GasHandleRotator : MonoBehaviour
{
    private float _sensitivity;
    private Vector3 _mouseReference;
    private Vector3 _mouseOffset;
    private Vector3 _rotation;
    private bool _isRotating;

    public AdvancedShipController vc;

    public Transform gasHandle;
    public Transform forwardTarget;
    public Transform reverseTarget;

    public static bool forwardTrue = false;

    void Start()
    {
        _sensitivity = 0.4f;
        _rotation = Vector3.zero;
    }

    void Update()
    {
        if (_isRotating)
        {
            // offset
            _mouseOffset = (Input.mousePosition - _mouseReference);

            Vector3 currentRotation = transform.rotation.eulerAngles;
            currentRotation.y = Mathf.Clamp(currentRotation.y, 0, 90);

            // apply rotation
            _rotation.y = -( _mouseOffset.y) * _sensitivity;

            // rotate
            transform.Rotate(_rotation);
            //transform.rotation = currentRotation;

            // store mouse
            _mouseReference = Input.mousePosition;
        }
        if (Input.GetMouseButtonDown(1))
        {
            //forwardTrue = true;

            Cursor.lockState = CursorLockMode.None;
            // rotating flag
            _isRotating = true;

            // store mouse
            _mouseReference = Input.mousePosition;
        }
        if (Input.GetMouseButtonUp(1))
        {
            //forwardTrue = false;

            Cursor.lockState = CursorLockMode.Locked;
            _isRotating = false;
        }

        if (gasHandle.rotation == forwardTarget.rotation)
        {
            vc.input.Throttle = 1.0f;
        }
        if (gasHandle.rotation == reverseTarget.rotation)
        {
            vc.input.Throttle = -1.0f;
        }
        if (Input.GetKeyDown("e"))
        {
            vc.input.EngineStartStop = true;
        }
    }
}

I also have this short video to illustrate how I move the handle: https://youtu.be/mP1wJ9o4AJw

1

There are 1 best solutions below

0
On

Have you tried moving this line

currentRotation.y = Mathf.Clamp(currentRotation.y, 0, 90);

to below these lines?

rotation.y = -( _mouseOffset.y) * _sensitivity;

// rotate
transform.Rotate(_rotation);

If i understand correctly that should fix your problem