my pong AI movement is very clunky

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

i’m new to godot and am making a pong game to practice, i tried making an AI and it works but the movement is extremely clunky when the ball gets near to the paddle
here’s my code:

var speed: = Vector2(0.0 , 100.0)
var direction: = Vector2(0.0,0.0)
var velocity:= Vector2(0.0,0.0)

Called when the node enters the scene tree for the first time.

func _ready() → void:

Called every frame. ‘delta’ is the elapsed time since the previous frame.

func _physics_process(delta: float) → void:
position.x = 135
var ball = get_parent().get_node(“ball”).position
if ball.y < position.y:
direction.y = -1
velocity = speed * direction
elif ball.y > position.y:
direction.y = 1
velocity = speed * direction

What do you mean by “extremely clunky”? What is the problem you’re trying to solve here?

njamster | 2020-02-20 17:21

the platform won’t stop moving up and down really quickly instead of just adjusting cleanly

ROBOTOO007 | 2020-02-20 17:34

:bust_in_silhouette: Reply From: Mitcha47

Perhaps decrease your speed variable as the ball gets closer?
Otherwise the paddle tries to make fine grain adjustments but is going too fast and that makes it jump around.

:bust_in_silhouette: Reply From: njamster

Unless the y-position of the ball and your paddle are exactly the same, the paddle will move. Try adding an offset, like this:

onready var ball = get_node("../ball")

func _ready():
	position.x = 135

func _physics_process(delta):
	var y_dist = sqrt(pow(ball.position.y - position.y, 2)) 

	if y_dist < (speed.y * delta):
	 	# not  far enough away to move
	 	direction = Vector2.ZERO
	elif ball.position.y > position.y:
	 	# far enough to move and ball below the paddle
		direction = Vector2.DOWN
	elif ball.position.y < position.y:
	 	# far enough to move and ball above the paddle
		direction = Vector2.UP

	velocity = speed * direction

I chose speed.y * delta as an offset, because that’s the distance your paddle will move in one frame. So the paddle will only move if the ball is at least one full move away. This prevents the tremor you observed without slowing down the paddle.

thanks a lot

ROBOTOO007 | 2020-02-21 10:32