Skip to content

Making the Cars

This is a tutorial for a basic 2D racing game in Godot. This will follow on from previous learning we did in the 2D Platformer. We will be starting with a new project.

Please download the asset pack linked here (it is free so you don’t need to pay).

Making the Cars

  1. Make a CharacterBody2D, then give it 2 child nodes: Sprite2D and CollisionShape2D.

  2. On Sprite2D, drag and drop spritesheet_vehicles.png into the empty texture in the inspector.

  3. In the region drop down, enable the region, click on edit region, and then cover a single car using the red dots. Screenshot showing edited region

  4. For the Collisionshape2D, select new CapsuleShape2D and cover the car.

  5. In Project > Project Settings > Input Map, we will create other keys for the player to use. In the “add new action” box, type in something like Left1 and then click add.

  6. On the right, click the plus button and and then press a key to represent it. E.g. for left you could use the left arrow key. Repeat the steps for all 4 directions. Screenshot showing Input Map

  7. Now go into the car script and change the "ui_left", "ui_right" etc. to the inputs you made before.

  8. Attach a script to CharacterBody2D and replace the code with this:

    extends CharacterBody2D
    const ACC = 25.0
    const MAX = 750.0
    const DEC = 5.0
    var motion = 0.0
    func _physics_process(delta: float) -> void:
    # Add the gravity.
    # Get the input direction and handle the movement/deceleration.
    # As good practice, you should replace UI actions with custom gameplay actions.
    var direction := Input.get_axis("Left1", "Right1")
    if direction:
    rotate(2.0 * direction * delta)
    var moving := Input.get_axis("Forward1", "Backward1")
    if moving:
    motion += ACC * moving
    if motion > MAX:
    motion = MAX
    elif motion < -MAX:
    motion = -MAX
    velocity = lerp(motion * transform.y, Vector2.ZERO, 0.2)
    if velocity != Vector2.ZERO:
    if motion > 0:
    motion = max(motion - DEC, -ACC)
    elif motion < 0:
    motion = min(motion + DEC, ACC)
    move_and_slide()

    This will allow your car to turn, accelerate, and decelerate.

  9. To test this, create a new scene and give it a Node2D, give it a child node Camera2D and your car scene as a child node. If you now play the track scene, you should be able to drive around.

  10. To make the second car, all you need to do is duplicate your car scene and add more inputs to the Input Map so you can control both cars on one keyboard. Don’t forget to change the controls in the script.

Checklist

  • I have imported the assets
  • I have added the nodes to the scene
  • I have added in the script