Personally, I would just define the variables I need outside of the _ready
function and then set their values in _ready
. Like this:
extends Area2D
var screensize
var gun_size
var gun_x
func _ready():
# Assign the class variables so they can be used throughout the script:
screensize = get_viewport().size
gun_w = $CollisionShape2D.shape.extents * 2
gun_x = position.x
# Do whatever is needed in _ready below:
position.x = screensize.x / 2.0
position.y = (screensize.y / 2.0) - gun_h
Func _process(delta):
if (Input.is_key_pressed(KEY_LEFT)):
if (gun_x > gunsize.x/2):
gun_x-= 5
else:
gun_x=gunsize.x/2
if (Input.is_key_pressed(KEY_RIGHT)):
if (gun_x < gunsize.x/2):
gun_x += 5
else:
gun_x = screensize.x - gunsize.x / 2
The code above has not been tested. However, the code should, in theory, work just fine.
The important part is that the variables are defined outside of any functions, making them class variables, and then these variables are populated in the _ready
function. Because _ready
is called before any of the other functions, when you access the class variables in functions like _process
the variables will be populated with the values we assigned in _ready
.
Another thing you can do is use the onready
keyword when defining the class variables. Personally I don’t use onready
, but if you want to use onready
then you can write the class variables like this:
extends Area2D
onready var screensize = get_viewport().size
onready var gun_size = $CollisionShape2D.shape.extents * 2
onready var gun_x = position.x
Like before, the code above has not been tested.
Hopefully this helps!