Combining clamp and lerp for draggable object

Godot Version

4.3

Question

hi! i currently have a card that i’m dragging across the screen. i’d like to use lerp to create a fun drag delay effect, and i’d like to use clamp to keep it within the bounds of the screen, so is there any way to combine these two lines of code?

func _physics_process(delta: float) -> void:
	if card_being_dragged:
		var mouse_pos = get_global_mouse_position()
		card_being_dragged.position = Vector2(clamp(mouse_pos.x, 0, screen_size.x), clamp(mouse_pos.y, 0, screen_size.y))
		card_being_dragged.position = card_being_dragged.position.lerp(mouse_pos, delta * follow_speed)```

You could clamp the value after the lerp, using it’s position instead of the mouse position

I think Vector2.clamp should work the same as your line, but shorter.

var mouse_pos = get_global_mouse_position()
card_being_dragged.position = card_being_dragged.position.lerp(mouse_pos, delta * follow_speed)
card_being_dragged.position = card_being_dragged.position.clamp(Vector2.ZERO, screen_size)
2 Likes

Thank you so much! Solved the problem!

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.