Small optimizaton

It’s been a long while since I’ve opened up Godot. Would it be better to have the screenSize variable global instead of local. That way it’s only calculated once in the _ready function?

extends CharacterBody2D

var speed = 250
var screenSize

func _ready():
	screenSize = get_viewport_rect().size

func _physics_process(delta):
	velocity = Vector2(0,0)
	if Input.is_action_pressed("move_right"):
		velocity.x = speed
	if Input.is_action_pressed("move_left"):
		velocity.x = -speed
	if Input.is_action_pressed("move_up"):
		velocity.y = -speed
	if Input.is_action_pressed("move_down"):
		velocity.y = speed

	global_position = global_position.clamp(Vector2(0,0), screenSize)


Most of the time, it is better to keep variables local whenever possible, however in the case of the screenSize variable, making to global is a reasonable choice.

This is because this variable is unlikely going to change during the runtime, calculating it once in the _ready function and storing it in a global variable can help improve performance.

Also, making the screenSize variable global allows you access it from other functions in the script without having to use parameters

So all and all making the screenSize variable global is reasonableas long as you ensure that the value is only calculated once and remains accurate throughout the lifespan of the script.

Hope this helps a bit.

This topic was automatically closed 20 days after the last reply. New replies are no longer allowed.

Privacy & Terms