Problems with Enemy AI in a Pong game

Godot 4.4.1

I am new to godot and have been trying to make a pong game to learn more. I have programmed most of the enemy AI but I have encountered a problem.

I want the enemy to check if it is in the trajectory of the ball and, if not, to move towards it. At the moment, the paddle is moving down even when the ball is predicted to go above it. Any advice on how to fix this issue would be greatly appreciated!

This is the code I have come up with (It is attached to the enemy paddle, which is a CharacterBody2D):

extends CharacterBody2D

var m: float = 0

var y: float = 0

func _physics_process(delta: float) -> void:
	move_and_slide()
	
	var x: float = $".".position.x
	
	var xforce = $"../Ball".xforce
	var yforce = $"../Ball".yforce
	
	var y1 = $"../Ball".position.y
	var x1 = $"../Ball".position.x
	
	m = yforce / xforce
	y = y1 + (m * (x - x1))
	
	if y < position.y - 6:
		velocity.y = -150
	elif y > position.y + 6:
		velocity.y = 150
	else:
		velocity.y = 0

Why are m and y global variables? And what are yforce and xforce?

I didn’t realise that m and y were global variables. I just needed to define them and didn’t want them being set to a certain value every frame. xforce and yforce are the ball’s velocity.x and velocity.y respectively.

Well, right now, the paddle moves regardless of if the ball is moving towards it, and if the ball is moving away, it moves in the wrong direction, because the signs will be flipped in some places. I don’t know if this is the problem you mean, but I don’t see anything else.

You could fix it by only moving the paddle when the ball is coming toward it

func _physics_process(delta: float) -> void:
	# ...
	var yforce = $"../Ball".yforce

	if sign(xforce) != sign(x - x1):
		return
	# ...
1 Like