hello guys, i am working on bike racing game prototype for iphone. and i am stuck in turning and tilting the bike. here is my code with this code it tilts right to left but its not working smoothly and bike falls down. kindle give me some suggestion or hints to resolve this issue.
void Update () {
Vector3 accelerator = Input.acceleration;
float z = accelerator.z * -1;
//transform.Translate(Vector3.forward * z * 5);
rigidbody.AddRelativeForce(Vector3.forward * z * 100);
float y = accelerator.y;
//transform.Rotate(-(Vector3.up * y * 10));
rigidbody.AddRelativeTorque(Vector3.up * accelerator.y * 200);
}
thanks in advance
The problem with this approach is that every frame the accelerometer reports a non-zero acceleration, you ADD force and torque. This means that if you hold the device at a constant angle, force (and/or torque) will be added and won't stop being added until finally it knocks down the bike.
If you want to use this approach, you'll probably need to limit how much force you can add - clamp it.
something like
Vector3 v3MaxAngularVelocity = new Vector3(3f, 3f, 3f);
if (rigidbody.angularVelocity.y <= v3MaxAngularVelocity.y)
rigidbody.AddRelativeTorque(Vector3.up * accelerator.y * 200);
Don't take the axis or the value I've put in as an example, just as a clarification about what you need to do...
Only add force/torque if your bike haven't reached the maximum velocity on that particular axis.
Another option is to give the bike some force/torque that will make it try and stand straight up each frame. Think about it - in real life, when the bike reaches a certain speed - you can take the hands from the handlebars. The acceleration of the bike forward will straighten it up. If you try and turn - you'll have some resistance.
This way, each frame your accelerometer reports some angle - you add the force/torque just like you did in your example, and right after that add a reverse force that will straighten the bike. If the force you add to the bike based from the angle the accelerometer reports is stronger than the force/torque that makes the bike return to the original position - the bike will tilt.
Is it really necessary for you to use physics? If you want an arcade style bike control, it will be much easier for you to "fake" physics. You'll have much more control over it.