Help with physics in a train game

Godot Version

4.2.1

Question

Hello everyone, I’m working on an educational game about freight stations and I’m stuck on the physics of my freight cars. I use Area2D with CollisionShape2D in front and rear of the freight cars.

Because there move freight cars without locomotives in a freight station there could be a collision in front or rear with different speeds.

In the picture you can see 4 freight cars. The car with speed -80 will hit the car with speed 0 first and it works. Around the same time the car with speed 150 will hit the car with speed 100 which also works and both will hit the car with speed 0 but after that it gets weird.

Maybe someone has a better solution to the whole problem or at least a better idea when I can set the Collision_Object = null again.

if Collision_Object_front != null:
		if absf(Collision_Object_front.get_speed()) > absf(speed):
			speed = Collision_Object_front.get_speed()
		else:
			Collision_Object_front.set_speed(speed - 20)
			Collision_Object_front = null
	
	if Collision_Object_rear != null:
		if absf(Collision_Object_rear.get_speed()) > absf(speed):
			speed = Collision_Object_rear.get_speed()
		else:
			Collision_Object_rear.set_speed(speed - 20)
			Collision_Object_rear = null

I’m not quite sure what your question and/or the problem is here. You write that something works, something else also works, and then “it gets weird”. What do you mean? What happens? And what did you expect to happen instead?

Sorry, I can’t express this very well in English. A video is worth a thousand words.

The first Video is with Collision_Object.set_speed(speed - 20) and a little bounce effect:

The second Video is only with Collision_Object.set_speed(speed):

In both cases when there is a collision in front and rear the freight cars transfer speed at each other and the forces of rolling resistance and the locomotive (in red) are ignored and they are in something like a endless loop of pushing each other.