Reputation: 1
So I am trying to make PONG in godot as a way to learn, but following the tutorial (PONG tutorial series from Godot Tutorials (https://www.youtube.com/watch?v=KrPz4KcsZ4M&t=1460s)) isn't working because it is from an older version
Here's my current code:
extends Node2D
var screen_size
var screen_height
var screen_width
var screen_half_height = screen_height / 2.0
var screen_half_width = screen_width / 2.0
var pos
#Paddle variables
var paddle_color = Color.WHITE
var paddle_size = Vector2(10.0, 100.0)
var paddle_half_height = paddle_size.y / 2.0
var paddle_padding = 10.0
func _ready():
screen_size = get_viewport().size
pass
func _physics_process(delta):
pass
func _draw():
screen_size = Vector2(get_viewport().size)
draw_circle(Vector2(screen_half_width, screen_half_height), 10.0, Color.WHITE)
draw_rect(Rect2(Vector2(paddle_padding, screen_half_height - paddle_half_height),
paddle_size), paddle_color)
pass
which doesn't work
i also tried (this part is the only change):
var screen_size
var screen_height = get_viewport().y
var screen_width = get_viewport().x
var screen_half_height = screen_height / 2.0
var screen_half_width = screen_width / 2.0
var pos
but it tells me "Invalid get index 'y' (on base: 'null instance')
Upvotes: 0
Views: 32
Reputation: 1729
The problem is in these lines:
var screen_half_height = screen_height / 2.0
var screen_half_width = screen_width / 2.0
you never initialize screen_width and screen_height so this will not work. get_viewport() is null before the script is ready so it makes sense to initialize all these variables in your _ready function:
func _ready():
screen_size = get_viewport().size
screen_height = screen_size.y
screen_width = screen_size.x
screen_half_height = screen_height / 2.0
screen_half_width = screen_width / 2.0
With all variables correctly initialized it should work as intended in your tutorial.
To update you complete script code:
extends Node2D
var screen_size
var screen_height
var screen_width
var screen_half_height
var screen_half_width
var pos
#Paddle variables
var paddle_color = Color.WHITE
var paddle_size = Vector2(10.0, 100.0)
var paddle_half_height = paddle_size.y / 2.0
var paddle_padding = 10.0
func _ready():
screen_size = get_viewport().size
screen_height = screen_size.y
screen_width = screen_size.x
screen_half_height = screen_height / 2.0
screen_half_width = screen_width / 2.0
func _physics_process(delta):
pass
func _draw():
draw_circle(Vector2(screen_half_width, screen_half_height), 10.0, Color.WHITE)
draw_rect(Rect2(Vector2(paddle_padding, screen_half_height - paddle_half_height),
paddle_size), paddle_color)
pass
This will draw the ball and the left paddle, so you can continue working with the tutorial. To fully answer the title of your question here is the code to draw the second paddle:
draw_rect(Rect2(Vector2(screen_width - paddle_padding - paddle_size.x, screen_half_height - paddle_half_height),
paddle_size), paddle_color)
Upvotes: 2