Steer
Lesson 2 of 20 in Coddy's Godot Game: Neon Circuit course.
Now the car turns. Input.get_axis reads two keys at once: -1 for the first, 1 for the second, 0 for none:
var steer := Input.get_axis("move_left", "move_right")A real car only turns while it rolls, and turns less when it barely moves. So the turn is scaled by the speed. velocity.dot(forward) is how fast the car goes the way it points (negative when it rolls backwards):
var speed := velocity.dot(forward)
rotation += steer * turn_speed * delta * clampf(absf(speed) / 90.0, 0.0, 1.0) * signf(speed + 0.01)clampf(absf(speed) / 90.0, 0.0, 1.0) grows from 0 when standing to 1 at 90 pixels a second. signf flips the turn when rolling backwards, as a real car does. In Godot a bigger rotation turns clockwise, so Right adds to it.
Challenge
EasyMake the car turn with Left and Right.
- Add
@export var turn_speed := 3.2undermax_speed. - Under
throttle, addvar steer := Input.get_axis("move_left", "move_right"). - After
forward, addvar speed := velocity.dot(forward). - After the velocity grows, add the
rotation += ...line above.
Press Play, hold Up and press Left or Right: the car turns. Then Check.
Try it yourself
extends Node2D
@export var accel := 260.0
@export var max_speed := 200.0
var velocity := Vector2.ZERO
func _physics_process(delta: float) -> void:
var throttle := Input.get_action_strength("move_up")
var forward := Vector2.RIGHT.rotated(rotation)
velocity += forward * throttle * accel * delta
velocity = velocity.limit_length(max_speed)
position += velocity * delta
$Exhaust.emitting = throttle > 0.0
All lessons in Godot Game: Neon Circuit
Practice on your own: Godot playground