Attention | Topic was automatically imported from the old Question2Answer platform. | |
Asked By | abecus |
I am new to Godot and am following a pong tutorial, but the timer in initialize_positions() function does not work. I don’t know why also there is no error in code because the game runs well the only problem is with the timer.
Thanks in advance.
extends Node2D
var screen_size
var pad_size
var pad_speed
var ball_speed
var direction
signal updated
func _ready() -> void:
screen_size = get_viewport().size
# incresing the y dim. of pad beacuse, i have scaled the pad by factor 1.5
pad_size = Vector2($Left.texture.get_size().x, $Left.texture.get_size().y*1.5)
initialize_positions()
yield(self,"updated")
set_process(true)
func _process(delta: float) -> void:
# get all position of the sprits (balls, left_pad, right_pad).
var ball_pos = $Ball.get_position()+ ball_speed*delta*direction
var left_rect = Rect2($Left.get_position()- pad_size*0.5, pad_size)
var right_rect = Rect2($Right.get_position()- pad_size*0.5, pad_size)
# checks for if ball is at roof or floor and changing it's direction
if not (0<ball_pos.y and ball_pos.y<screen_size.y):
direction.y = -direction.y
# checks is ball is on a pad and changes the x direction and
# randomizes the y direction of the ball
if left_rect.has_point(ball_pos) or right_rect.has_point(ball_pos):
direction.x = -direction.x
direction.y = randf()*2 -1 # randf -> float in range[0,1]
direction = direction.normalized()
ball_speed *= 1.1
# update the ball's position
$Ball.set_position(ball_pos)
if not (0<ball_pos.x and ball_pos.x<screen_size.x):
initialize_positions()
yield(self, "updated")
# Move left pad
var left_pos = $Left.get_position()
if left_pos.y>0+pad_size.y/2 and Input.is_key_pressed(KEY_W):
left_pos.y += -pad_speed*delta
if left_pos.y<screen_size.y-pad_size.y/2 and Input.is_key_pressed(KEY_S):
left_pos.y += pad_speed*delta
$Left.set_position(left_pos)
# Move right pad
var right_pos = $Right.get_position()
if right_pos.y>0+pad_size.y/2 and Input.is_key_pressed(KEY_UP):
right_pos.y += -pad_speed*delta
if right_pos.y<screen_size.y-pad_size.y/2 and Input.is_key_pressed(KEY_DOWN):
right_pos.y += pad_speed*delta
$Right.set_position(right_pos)
func initialize_positions():
pad_speed = 300
ball_speed = 150
direction = Vector2(-1,0)
$Ball.set_position(screen_size/2)
$Left.set_position(Vector2(10, screen_size.y/2))
$Right.set_position(Vector2(screen_size.x-10, screen_size.y/2))
yield(get_tree().create_timer(3.0), "timeout")
emit_signal("updated")