How do you limit the speed at which an object rotates

The game I’m working on currently has a massive bug, that is, if you move your mouse fast enough, you can get one of my game objects to glitch through walls. This game object rotates based on your mouse, but there is no max speed, so a fast enough mouse flick will get it through any wall. The entire principal of the game depends on the way that this object rotates, but I do not want it to be able to rotate at an infinite speed. Can anyone fix this?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class mouseLook : MonoBehaviour
{

    public float mouseSensativity = 100f;
    //parent is the parent of this object, and is responsible for rotation on the y axis
    public Transform parent;

    float xRotation = 0f;
    // Start is called before the first frame update
    void Start()
    {
        Cursor.lockState = CursorLockMode.Locked;
        transform.localRotation = Quaternion.Euler(-90, 0f, 0f);
    }

    // Update is called once per frame
    void Update()
    {
        float mouseX = Input.GetAxis("Mouse X") * mouseSensativity * Time.deltaTime;
        float mouseY = Input.GetAxis("Mouse Y") * mouseSensativity * Time.deltaTime;

        parent.Rotate(Vector3.forward * -mouseX);

        xRotation -= mouseY;

        transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);


    }
}

Is the object controlled by Physics, i.e., does it have a Rigidbody?

If so, don’t do line 26 and line 30 above: accessing those properties directly completely bypass all collision checking in the physics engine.

Instead, do the rotations explicitly and then call the .MoveRotation() property to keep the physics in the loop:

As far as upper limits, clamp the input values as you need to using Mathf.Clamp() or just an if check.

1 Like

I tested the script. However I never got infinite speed of rotation.
But possibly this line:

xRotation -= mouseY;

could somehow be causing it. As you have got not check to limit it’s value.

That’s what I think all the time when I see that line, until I saw a Brackeys video from which everyone got this.
In fact the line is ok, from a logical standpoint, but the practice behind it is not. So I kind of learned to ignore it.
But yeah, exactly the same reaction I have every time, it’s hardwired into my brain.

@adogsjunkmail
If you want to cap the speed, why don’t you test the actual values that come out in your tests, and cap them to a value that doesn’t allow moving through walls?

if(mySpeed > 500f) mySpeed = 500f;

You could use clamp as well to cap both minimum and maximum.

mySpeed = Mathf.Clamp(mySpeed, minimum, maximum);

That is an excellent idea thank you