How to snap things together magnet-like using transform matrices?

I’ve got these sections of track that I want to snap together. Specifically, I want them to connect so that transform B and transform C are identical. How do I move transform A so that B and C become connected? I am using Godot’s Transform3D for all transforms.

Essentially, you’ll want to find A’s local transform with respect to B (as if B was the parent of A) and use that when setting A’s position.

extends Node3D

@onready var a_mesh: Node3D = $AMesh
@onready var b_mesh: Node3D = $BMesh
@onready var c_mesh: Node3D = $CMesh

var a_offset: Transform3D

func _ready() -> void:
	# Find A's local offset relative to B
	a_offset = a_mesh.transform * b_mesh.transform.affine_inverse()

func _process(delta: float) -> void:
	c_mesh.rotate_y(PI * delta)
	b_mesh.transform = c_mesh.transform
	# Apply A's local offset relative to B
	a_mesh.transform = b_mesh.transform * a_offset

You may want to use global_transform instead of transform, if these nodes do not share the same parent.

Before:

After:

Project: test.zip (5.6 KB)

This worked great. Thank you!