Car stop when car touch wall

Godot Version

4.7.2

Question

Im making a car game and one of the last hurdles I want to overcome before making something else is adding collision so that when the car touches a wall it completely stops. The problem is that my movement code (I know its messy, however I really like the the actual movement it creates) keeps accelerating the player even when they’re touching a wall, causing them to zoom past as soon as they leave the wall. The main problem is knowing when the player is colliding with the wall. Im so confused :sob:

extends CharacterBody2D

var rotation_speed = 3
var max_speedOG = 500
var max_speed = 500
var min_speedOG = -100
var min_speed = 0
var accel = 500
var deaccel = 4
var speed = 0

func _physics_process(delta: float) -> void:
	print(speed, "  speed  ", velocity, "  Velocity  ")
	 #Shouldnt be if Vector2.zero as is means it will only slow down when you arent touching it (including turning)
	if not Input.is_action_pressed("Accelerate") or not Input.is_action_pressed("Brake"):
		if speed >= min_speed:
			speed -= sqrt(abs(speed))*delta
		else:
			speed += sqrt(abs(speed))*delta
	velocity = Vector2(1,min_speed).rotated(rotation)*speed*delta * abs(speed)/deaccel
	
	_movement(delta)
	move_and_slide()
func _movement(delta):
	var Dir = Input.get_vector("TurnRight","TurnLeft","Brake","Accelerate")
	if Input.is_action_pressed("TurnRight",true) or Input.is_action_pressed("TurnLeft",true): #Only turns if turning is true
		if Dir.x > 0: #Checks which way your turning
			self.rotation -= rotation_speed*delta
		else:
			self.rotation += rotation_speed*delta
	if Dir.y < 0: # Tells you if you should accelerate
		if speed <= min_speedOG:
			speed = min_speedOG
		else:
			speed -=accel*delta
	elif Dir.y > 0:
		if speed >= max_speed:
			speed += log(accel)*deaccel*delta*1.1
			if Input.is_action_pressed("Boost") and speed <= max_speed*1.5:
				speed*=1.003
		else:
			speed += accel*delta
func _on_wall_touching():
	#Wall touching function HOW HOW HOW HOW HOW I DONT UNDERSTAND
	pass

Use get_last_slide_collision() to detect whether a collision has occurred. For example:

func _physics_process(delta):
	velocity = Vector2.UP
	move_and_slide()
	var coll = get_last_slide_collision()
	if coll:
		# DO STUFF
		velocity = velocity.bounce(coll.get_normal())

If you need further explanation, feel free to ask any questions.

Resources: