There is no doubt that each of you has played a 2D game with airplanes. Today we’ll show you how to program such aircraft movement in Unity.


STEP 1 – Make your own plane

As a first step you should create your aircraft, which you will later control. As in the previous tutorials, choose a sprite to represent your plane. After you drag it into your scene, you’ll need to add a Rigidbody 2D component to your plane, in which we’ll set the Gravity Scale to zero and don’t forget to set Collision Detection to Continuous.

STEP 2 – Make a point

The next thing we need to do is to create a point to control the plane. This point will help us make the movement of the plane look more like the real thing. In the top bar under Game Object, click on Create Empty. This will create your point. Move the point to the plane so that your plane will be the parent of the point. Then move the point a little more to the right.

This is what it should look like

STEP 3 – Make the aircraft rotate with the arrow keys

In order to turn the plane, we need to create an “Airplane” script. This time we use the command float xAxis = Input.GetAxis("Horizontal"); to capture the keys, which tells us whether we are pressing the turn keys or not. We do the rotation with the command Rigidbody2D.MoveRotation(rb.rotation + (-xAxis * rotationSpeed) * Time.fixedDeltaTime);.

STEP 4 – Forward motion programming

We will now use the previously mentioned point to move the aircraft to where it is currently facing. To move it, we’ll use the command Vector3.Lerp(transform.position, point.position, speed * Time.fixedDeltaTime);, which will try to move the plane to the point, but will never succeed. This is what the code should look like:

using UnityEngine;

public class Airplane : MonoBehaviour
{
    Rigidbody2D rb;

    public float speed = 5.0f;
    public float rotationSpeed = 200.0f;
    
    public Transform point;

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    void FixedUpdate()
    {
        float xAxis = Input.GetAxis("Horizontal");

        transform.position = Vector3.Lerp(transform.position, point.position, speed * Time.deltaTime);
        rb.MoveRotation(rb.rotation + (-xAxis * rotationSpeed) * Time.fixedDeltaTime);  
    }   
}