- Home /
Limit Rotation of Rigidbody to 45 Degrees (Handlebars on a Bicycle)
I desperately need some help here! I have a long-term commitment to build this game so any advice you can give will be GREATLY appreciated! I've been struggling with this for hours and I feel really stupid because this seems like it should be an easy problem to solve.
I have a bicycle that is controlled with a script I bought on the asset store, however I have to add a script to make the handlebars turn in sync with the front wheel. Unfortunately the main script is written in Javascript and has no comments, so I can't really reference anything in that script. Instead, I've written a separate script in C# that turns the handlebars according to user input. I'm trying to limit the turning to 45 degrees in either direction.
The bike has a ragdoll rider, so it is important that the handlebar is a rigidbody so I can attach joints.
Here's what I have so far. It works, as long as I don't drive the bike anywhere! Once I move the bike anywhere else, the handlebar rotation resets back to the very first position, and not back to the center I'm probably going about this all wrong. REALLY need some help.
private Quaternion startRot = Quaternion.Euler(0, 0, 0);
private Quaternion targetLeft = Quaternion.Euler(0, 0, 0);
private Quaternion targetRight = Quaternion.Euler(0, 0, 0);
private float speedRot = 5.0f; //speed rotation
private float handleTurnInput;
handleTurnInput = player.GetAxis ("Steer Horizontal");
void Start()
{
startRot = this.transform.localRotation; //initialization start rotation
targetRot = startRot;
targetRot *= Quaternion.Euler(0, 0, 45);
targetRot2 = startRot;
targetRot2 *= Quaternion.Euler(0, 0, -45);
}
void FixedUpdate()
{
handleTurnInput = player.GetAxis ("Steer Horizontal");
if(handleTurnInput > 0)
{
rigidbody.rotation=Quaternion.Slerp (transform.rotation, targetRot, speedLeft*Time.deltaTime);
}
else if(handleTurnInput < 0)
{
rigidbody.rotation=Quaternion.Slerp (transform.rotation, targetRot2, speedRight*Time.deltaTime);
}
else
{
rigidbody.rotation=Quaternion.Slerp (transform.rotation, startRot, speedRot*Time.deltaTime);
}
}
Here's a screenshot showing the problem I'm having. When the user stops giving input, the handlebars should re-center with the bike. Ins$$anonymous$$d, they recenter to the very first position they were in at the start of the game. I am so stuck... really hoping for some help here.
Answer by Baste · Jan 15, 2015 at 05:12 PM
Instead of setting the rotation of your handlebar's rigidbody, set their transform's localrotation. I'm assuming that the handlebars have the main bike as their parent object.
You're already using the local rotation as the start rotation, so this should be enough:
if(handleTurnInput > 0)
{
transform.localRotation = Quaternion.Slerp (transform.localRotation, targetRot, speedLeft*Time.deltaTime);
}