Godot 4: How to snap a player to a moving platform

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

I haven’t figured this one out, although I knew how to do it with move_and_slide_with_snap in v3.x. I am pretty sure I am missing something obvious w/ v4.x:

In my player:

func _physics_process(_delta):

...

set_floor_snap_length(0)
	
	if Input.is_action_just_pressed("ui_jump") and is_on_floor() and not in_ladder_area:
		calc_velocity.y = JUMPFORCE
		$SoundJump.play()
	elif in_ladder_area:
		calc_velocity.y = 0
	else:
		calc_velocity.y = calc_velocity.y + GRAVITY
		if is_on_floor():
			# snap setting, does not appear to work
			set_floor_snap_length(0.1)
			
	set_up_direction(Vector2.UP)
	velocity = calc_velocity
	move_and_slide()
	calc_velocity = velocity
:bust_in_silhouette: Reply From: keidav

After searching Stack Overflow, I found the solution:

My moving platform was using CharacterBody2D instead of the new recommended AnimatableBody2D. I changed the node type on the moving platform and made sure that the sync_to_physics property was set to true. Modified my _physics_process() function as follows (removing the calls to set_floor_snap_length):

if Input.is_action_just_pressed("ui_jump") and is_on_floor() and not in_ladder_area:
		calc_velocity.y = JUMPFORCE
		$SoundJump.play()
	elif in_ladder_area:
		calc_velocity.y = 0
	else:
		calc_velocity.y = calc_velocity.y + GRAVITY

Everything now works as expected!

BTW, I was fighting with this for a couple of days… exhausting!

keidav | 2023-03-26 20:44

Thanks for posting the answer!

codabase | 2023-03-27 01:46

Thanks for the solution <3

Tugay72 | 2023-04-26 10:06