How to make sprite slowly follow mouse cursors x?

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

So the code below does not work since velocity gets set to 0 when you are on the left side of the paddle, and I would like to know how to make it so it will still have a smooth transition but still follow the mouse. Thanks.

extends Control

var velocity : float = 1

func _ready():
pass

func _process(delta):
print(velocity)
if $Paddle.position.x < get_viewport().get_mouse_position().x:
if velocity == 0:
velocity += 1
if velocity > 3:
velocity = 3
$Paddle.position.x += velocity
$Paddle.position.x += velocity
velocity += velocity / 30
elif $Paddle.position.x > get_viewport().get_mouse_position().x:
if velocity == 0:
velocity -= 1
if velocity < -3:
velocity = -3
$Paddle.position.x += velocity
velocity -= velocity / 30

Also sorry for it not being formatted, every time I pasted it kept not putting it in the code block and instead making it normal text

MrBucket | 2022-08-21 23:36

:bust_in_silhouette: Reply From: estebanmolca

to limit the speed:

var max_speed : float = 300

func _process(delta):
	#move paddle to mouse at max_speed:
	var pos = move_toward($Paddle.position.x,get_global_mouse_position().x, delta * max_speed)
	#limit the lef and right position of the paddle: 
	$Paddle.position.x = clamp(pos,50,600)

Another way is using a linear interpolation, the movement is smoother but decreases as the object reaches its target:

var speed : float = 2

func _process(delta):
	$Paddle.position.x = $Paddle.position.linear_interpolate(get_global_mouse_position(),delta * speed).x

If I understood your question correctly, this should help.