Scripting control of rotation on collision exit of terrain

I’m making a stunt car game and I want to be able to control the rotation of the vehicle when it’s in the air but I’ve got a problem.

I pieced together this script

var rotatespeed : float = 5.0;

function OnCollisionExit(collisionInfo : Collision) {}
(
transform.Rotate(Vector3(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"), 0) * Time.deltaTime * rotatespeed));

It doesn’t give me any errors in unity but it also doesn’t do anything…

Sure the code is laughable but I would be happy to hear any input.

Do you want the player to be able to rotate the car while being airborne?

If so, you should know that OnCollisionExit doesn’t mean the rigidbody is airborne. It simply means that it stopped touching something it had previously been touching.

I recommend doing it like this:

var rotatespeed : float = 5.0;
var isAirBorne: bool = true;

function OnCollisionStay() : void
{
    isAirBorne = false;
}

function Update() : void
{
    if(isAirBorne)
    {
        rigidbody.AddRelativeTorque
        (
            new Vector3
            (
                Input.GetAxis("Vertical"),
                Input.GetAxis("Horizontal"),
                0
            ) * rotatespeed,
            ForceMode.Acceleration
        );
    }
    isAirBorne = true;
}

Two other things you should have in mind:

  1. You had swapped the X and Y rotations in your Euler angles
  2. You were going to rotate the car around the global X-axis, which is weird unless your car can’t turn or if you’re moving the environment around the car instead of the car around the environment.
  • When you rotate an object around the X axis, it tilts forwards/backwards.
  • When you rotate an object around the Y axis, it turns left/right.

This is because you’re rotating around the axis,
e.g. lets say that north is up, then the earth would be rotating around it’s Y-axis.

Rotating the car around the global X-axis will tilt it back and forth while your car is heading exactly e.g. north. But when it turns west, rotating the car around the global X-axis means that you will start rolling the car sideways.

The best solution to this would be to rotate the car in the camera local space, e.g. something like this:

var cam : Transform = Camera.main.transform;
rigidbody.AddTorque
(
    rotatespeed *
    (
        cam.up * Input.GetAxis("Horizontal")
        + cam.right * Input.GetAxis("Vertical")
    ),
    ForceMode.Acceleration
);