Enemy movement in Pongonoid is jittery

I am making a hybrid of Pong and Breakout. The Main scene contains generated walls, borders, ball, player and the enemy. The player is controlled with arrow keys.

The Main scene.

The code for the Ball which starts moving in random direction.

extends CharacterBody2D

const SPEED = 16.0


func _ready() -> void:
	var x = randf_range(-1.0, 1.0)
	var y = randf_range(-0.5, 0.5)
	velocity = SPEED * Vector2(x, y)


func _physics_process(_delta: float) -> void:
	var collision = move_and_collide(velocity)

	if collision:
		var normal = collision.get_normal()
		velocity = velocity.bounce(normal)

The code for Enemy which tries to follow the ball. When I set the enemy’s speed to 512, its movement becomes extremely jittery.

extends CharacterBody2D

const SPEED = 512.0


# Called when the node enters the scene tree for the first time.
func _ready() -> void:
	pass # Replace with function body.


# Called every frame. 'delta' is the elapsed time since the previous frame.
func _physics_process(_delta: float) -> void:
	var ball_position = ($"../Ball" as CharacterBody2D).position
	
	if (position.y > ball_position.y):
		velocity.y = -1.0 * SPEED
	elif (position.y < ball_position.y):
		velocity.y = 1.0 * SPEED
	else:
		velocity.y = 0.0

	move_and_slide()

Try disabling (or enabling, depending on what it’s set to) physics interpolation

The speed is pretty fast and the code only detects if the positions are not equal then sends the Enemy at full speed towards it’s target, it’ probably over shooting every other frame and thus moving back and forth quickly.

Try using the difference

var difference: float = position.y - ball_position.y
velocity = clampf(difference, -1.0, 1.0) * SPEED
move_and_slide()

The ball makes the enemy move to the opposite direction and stick to the border.

Then I got my positions switched around, always take me two tries, like pluggin in a USB

var diff := ball_position.y - position.y

The movement of the enemy is still not smooth. The enemy also never misses.

That’s a very different issue, you’ll have to design a dumber AI

Probably due to something delta time related, move_and_slide() automatically takes frame time into account, you may have to undo that. Considering the other comment I’d bet you want some kind of acceleration value, using move_toward you can slowly increase the speed of objects per second.

var difference: float = position.y - ball_position.y
var target_velocity := clampf(difference / delta, -SPEED, SPEED)
velocity.y = move_toward(velocity.y, target_velocity, ACCELERATION * delta)
move_and_slide()
var difference: float = (position.y - ball_position.y) * delta
velocity.y = clampf(difference, -1.0, 1.0) * SPEED
move_and_slide()

Or a bit less confusing form:

var catchup_speed: float = (position.y - ball_position.y) / delta
velocity.y = clampf(catchup_speed, -SPEED, SPEED)
move_and_slide()