Godot Version
Currently on 3.5 but happy to upgrade if it helps
Question
I have a very simple 2D driving game. There is a single button to control it. Press the button and the car accelerate, release the button and the car slows to a stop. The car is a RigidBody2D with pin joint wheels. Pressing the button applies a torque to the wheels and the car moves. I have the basics working based on this tutorial: https://www.youtube.com/watch?v=nPX9MrnvNLo (which was great)
The issue I am currently dealing with is that the car won’t actually stop. It rolls on even the slightest slope. To counter this I have created a “brake” variable which is set when the car first stops. Once this is set I fix the wheels angular_velocity to zero. This does help but it slows the roll rather than completely stop it. I’ve tried a few clunky solutions like setting all the movement variables to zero or used sleeping but that messes up other movement, like when the car is jumping, and doesn’t actually fully solve the problem. It isn’t sliding, the wheels are turning, albeit slowly.
Is there another solution to this? Maybe friction, but I can’t find that anywhere that might help.
Code with some of the methods I have tried commented out (car is going right to left so all speed numbers are negative):
extends RigidBody2D
var wheels=[]
var accerationRate = -30000
var decelerationRate = 3000
var maxSpeed = -50
var brakes = true
func _ready():
wheels = get_tree().get_nodes_in_group("Wheel")
func _physics_process(delta):
if Input.is_action_pressed("MoveCar"):
$BrakeLight.visible = false
brakes = false
for wheel in wheels:
if wheel.angular_velocity > maxSpeed:
wheel.apply_torque_impulse(accerationRate * delta * 60)
else:
$BrakeLight.visible = true
for wheel in wheels:
if wheel.angular_velocity < 0:
wheel.apply_torque_impulse(decelerationRate * delta * 60)
if wheel.angular_velocity >= 0:
brakes = true
if brakes:
$Indicator.visible = true
#linear_velocity.x = 0
for wheel in wheels:
wheel.angular_velocity = 0
#wheel.linear_velocity.x = 0
#wheel.sleeping = true
else:
$Indicator.visible = false
#for wheel in wheels:
#wheel.sleeping = false