+1 vote

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:
pass

Called every frame. 'delta' is the elapsed time since the previous frame.

func physicsprocess(delta: float) -> void:
position.x = 135
var ball = getparent().getnode("ball").position
if ball.y < position.y:
direction.y = -1
velocity = speed * direction
moveandslide(velocity)
elif ball.y > position.y:
direction.y = 1
velocity = speed * direction
moveandslide(velocity)

in Engine by (120 points)

What do you mean by "extremely clunky"? What is the problem you're trying to solve here?

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

2 Answers

0 votes

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.

by (86 points)
+1 vote

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
    move_and_slide(velocity)

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.

by (10,221 points)

thanks a lot

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.