How to swap out positions between 2 CharacterBody2D objects?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Capnsockless

I’m trying to have 2 objects swap out positions with each other.

I tried this:

func get_swapped(block : Rubble):
  print("old player position ", global_position)
  print("old block position ", block.global_position)

  var temp_loc = get_global_position()

  print("new player position ", global_position)
  print("new block position ", block.global_position)

in the output the positions seem to be correct:
old player position (112, -12.00104)
old block position (48, -21.46708)
new player position (48, -21.46708)
new block position (112, -12.00104)
old player position (95.30371, -12.00213)
old block position (112, -15.75306)
new player position (112, -15.75306)
new block position (95.30371, -12.00213)

but it rarely works correctly ingame, sometimes the block gets put into the player’s(caller’s) position and shoves him away or completely hides him behind itself, sometimes it almost works but the player ends up in a slightly incorrect horizontal position (I need it to be pixel perfect).

I had another attempt:

var temp_loc = Vector2(-128, -128)
func get_swapped(block : Rubble):
  var new_pos_player = block.get_global_position()
  var new_pos_rubble = global_position

but this gives me the same results.
I also tried to relocate them into bit more elevated positions so that they wouldn’t be near the ground and collide with it instantly and this seemed to make it work correctly more often but it still sometimes behaves strangely on the x axis.

Is there anything I’m forgetting or any feature that may be affecting this?