When I start the game, I get this error, please help

Godot Version

4.6.1

Question

extends Area2D

@export var speed = 400 # How fast the player will move (pixels/sec).
var screen_size # Size of the game window.

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

func _ready() → void:
screen_size = get_viewport_rect().size
pass # Replace with function body.

func _process(delta):
var velocity = Vector2.ZERO # The player’s movement vector.
if Input.is_action_pressed(“move_right”):
velocity.x += 1
if Input.is_action_pressed(“move_left”):
velocity.x += 1
if Input.is_action_pressed(“jump”):
velocity.y += 1
if Input.is_action_pressed(“push”):
velocity.x += 1
if Input.is_action_pressed(“run”):
velocity.y += 1
if velocity.length() > 0:
velocity = velocity.normalized() * speed
$AnimatedSprite2D.play()
else:
$AnimatedSprite2D.stop()
	position = velocity * delta
	position = position.clamp(Vector2.ZERO, screen_size)
	delta=16
	screen_size=1
	screen_size = DisplayServer.screen_get_size(1)
	
if velocity.x != 0:
	$AnimatedSprite2D.animation = "stand"
	$AnimatedSprite2D.flip_v = false
# See the note below about the following boolean assignment.
	$AnimatedSprite2D.flip_h = velocity.x < 0

Please do not create duplicate posts. As I already told you in your previous post, screen_size is null. You need to figure out why it’s null.

3 Likes

@ try utilise print() to find out what is going on :+1:

well, and how?

The error message is telling you that it cannot use ‘screen_size’ in that ‘clamp’ operation, as it’s either the wrong type, or simply ‘null’. It would appear from your postings that you are trying to run before you can walk. No problem with that, except that it’s the slowest way to progress. A far faster method would be to learn the very basics of programming, and Godot, from tutorials and/or videos. The usage of ‘print’ statements for following code results would be a part of that learning, and is a very basic skill to have. It’s not difficult at all, but it needs humility and patience to do what all programmers do : start from the modest beginnings and advance slowly but surely. Hope this helps; peace.

In Godot 4, the most reliable way to capture the screen size is to use the @onready keyword. This ensures the variable is set the moment the node enters the scene tree, before _process ever runs.

Replace your variable declaration at the top with this:

GDScript

@onready var screen_size = get_viewport_rect().size

Then, you can remove the screen_size assignment inside your _ready() function entirely.

Closed as duplicate of

Please continue the discussion there.