Creating a Hover Car with Physics

Checked with version: 4.6

-

Difficulty: Beginner

In this session we'll look at using physics to create a simple hover car prototype. This session will cover some basic physics functions like using AddForce to move our vehicle and Raycast to cause it to maintain it's distance from the ground. We'll also add some dynamic audio to create sound for our engine. Tutor - Matthew Schell

Creating a Hover Car with Physics

Beginner Physics

HoverMotor

Code snippet

using UnityEngine;
using System.Collections;

public class HoverMotor : MonoBehaviour {

    public float speed = 90f;
    public float turnSpeed = 5f;
    public float hoverForce = 65f;
    public float hoverHeight = 3.5f;
    private float powerInput;
    private float turnInput;
    private Rigidbody carRigidbody;


    void Awake () 
    {
        carRigidbody = GetComponent ();
    }

    void Update () 
    {
        powerInput = Input.GetAxis ("Vertical");
        turnInput = Input.GetAxis ("Horizontal");
    }

    void FixedUpdate()
    {
        Ray ray = new Ray (transform.position, -transform.up);
        RaycastHit hit;

        if (Physics.Raycast(ray, out hit, hoverHeight))
        {
            float proportionalHeight = (hoverHeight - hit.distance) / hoverHeight;
            Vector3 appliedHoverForce = Vector3.up * proportionalHeight * hoverForce;
            carRigidbody.AddForce(appliedHoverForce, ForceMode.Acceleration);
        }

        carRigidbody.AddRelativeForce(0f, 0f, powerInput * speed);
        carRigidbody.AddRelativeTorque(0f, turnInput * turnSpeed, 0f);

    }
}

HoverAudio

Code snippet

using UnityEngine;
using System.Collections;

public class HoverAudio : MonoBehaviour {

    public AudioSource jetSound;
    private float jetPitch;
    private const float LowPitch = .1f;
    private const float HighPitch = 2.0f;
    private const float SpeedToRevs = .01f;
    Vector3 myVelocity;
    Rigidbody carRigidbody;
    
    void Awake () 
    {
        carRigidbody = GetComponent();
    }

    private void FixedUpdate()
    {
        myVelocity = carRigidbody.velocity;
        float forwardSpeed = transform.InverseTransformDirection(carRigidbody.velocity).z;
        float engineRevs = Mathf.Abs (forwardSpeed) * SpeedToRevs;
        jetSound.pitch = Mathf.Clamp (engineRevs, LowPitch, HighPitch);
    }

}

Related tutorials