Limit rotation relative to velocity

Hello, I’m trying to make a game where you snowboard down a hill. It’s a simple game but the snowboard tends to spin around and is very hard to control. I’m trying to make a script that limits the rotation in the x axis (so the board doesn’t flip over) within a certain range, and also limit the rotation in the y axis (left and right). I’ve looked at a few other questions but they don’t seem to work that well. I’m new to Unity so I’m still getting familiar with it all. Here is what I have so far:

        rigidbody.rotation.SetLookRotation (transform.forward);

		var planarVel = new Vector2 (rigidbody.velocity.x, rigidbody.velocity.z);
		var planarForward = new Vector2 (transform.localRotation.x, transform.localRotation.z);
		var deviation = Vector2.Angle (planarVel, planarForward);
		if (rigidbody.velocity.magnitude > 5 && deviation>45f) {
			Quaternion velQuat = new Quaternion();
			velQuat.eulerAngles = rigidbody.velocity;
			rigidbody.rotation = Quaternion.RotateTowards(transform.localRotation, velQuat, 2f);
		}

This code is only for the y axis rotation lock. I don’t want to completely lock the rotation with the check box in the inspector as I do want to allow for some flexibility in movement.

Look in to clamp, you basically want to clamp the rotation between two values, clamp lets you assign a min/max value for the rotation. See this

Answering specifically how to clamp a 3D “direction” vector to be within a certain angle of some other direction called “forwards”:

direction = Vector3.RotateTowards( forwards, direction, maxRadians, 0 );

If “direction” is already within the given angle of “forwards” then it won’t be changed, but if it is at a greater angle then it will be clamped onto the cone of vectors offset by that angle from “forwards”.

For the rest, I get very nervous when I see people forcing rigid bodies to specific positions and orientations. Your first port of call with rigid bodies should be forces and torques. Your second port of call is velocities (linear and angular), though it’s usually still clearer to express velocity changes as impulses. The third port of call is constraints. Directly modifying position or orientation on a frame-by-frame basis should be a last resort.