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
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.