Can collision forces be negated at the moment of collision?

Godot Version

Godot 4.4

Question

Is it possible to prevent collision forces between two bodies from applying at the moment of a collision? Essentially, what I would like to do is detect when two bodies collide with each other for the first time (such as body_entered), and then apply a collision exception BEFORE they exert any forces on each other. I tried simply applying a collision exception during body_entered (I’m using RigidBody2Ds), but the bodies still apply forces on each other for a single frame rather than moving past each other without any forces being applied.

For my purposes it would be ideal to be able to dynamically prevent collisions prior to the moment they occur, since I want a class of objects to collide/not collide with another class of objects under specific conditions which may change and vary by object.

Maybe you could avoid this by putting them in different collision layers?

Like I said if possible I’d like to disable collisions at the moment they occur rather than updating collisions layers/exceptions every frame based on a condition which may change arbitrarily.

I don’t think there’s a way to filter collisions when they happen. What you can do is to add a slightly bigger Area2D to the rigid bodies that detect the overlap between them and add the exceptions then.

For example:

extends RigidBody2D


func _on_area_2d_body_entered(body: Node2D) -> void:
	if body is RigidBody2D:
		var exceptions = get_collision_exceptions()
		if body in exceptions:
			remove_collision_exception_with(body)
		else:
			add_collision_exception_with(body)

Result: