How to only follow the "y" of a moving object?

Godot Version

4.3

Question

I’m trying to make an opponent paddle (CharacterBody2D) follow the “y” of a moving object, specifically, a ball (CharacterBody2D). That ball is for now bouncing around the screen. I want a paddle to follow it. I was able to do that by doing self.global_position.y = ball.global_position.y. The problem is, it exactly follows it. I want some kind of a delay, some kind of speed implemented on the paddle so that it won’t exactly follow the ball.

This is the code for the opponent paddle:

extends CharacterBody2D


class_name Opponent


@onready var ball_node: CharacterBody2D = get_node("/root/Game/Ball")

var _speed: float = 100.0


func _ready() -> void:
	pass


func _physics_process(delta: float) -> void:
	self.global_position.y = ball_node.global_position.y
	self.global_position.y = lerp(ball_node.global_position.y, self.global_position.y, _speed)
	
	move_and_slide()

You can bufferize the position of the ball and position your paddle at one of the previously bufferized position.

Thank you for the reply.

I somehow found a way to do this. Here is the code:

extends CharacterBody2D


class_name Opponent


@onready var ball_node: CharacterBody2D = get_node("/root/Game/Ball")

var _speed: float = 150.0
var target: Vector2 = position


func _ready() -> void:
	pass


func _physics_process(delta: float) -> void:
	target.y = ball_node.global_position.y
	velocity.y = (target.y - position.y) * _speed * delta
	
	move_and_slide()

Now, depending on the speed, the opponent paddle may or may not catch the ball. This is like a Pong Game, actually. The opponent’s difficulty will be determined by the speed the opponent’s paddle can follow the ball.