Vector2 Setters and Getters

Godot Version

4.5.1 Stable

Question

I am new to Godot and GDScript. I have a little bit of programming experience but not much. I am trying to understand why this piece of code I wrote works…

I have a first-person character controller script that I wrote. The horizontal look direction should wrap between 0 and TAU, and the vertical look direction should clamp between -90 and 90 degrees.

I had this successfully working in my “look_around()” function, but then I read in the Godot manual about setters and getters and figured I might be able to apply this so that it always works regardless where I set the look direction.

This is how I set it up.

var look_rotation: Vector2 = Vector2(0.0, 0.0):
	set(value):
		look_rotation = Vector2(clampf(value.x, deg_to_rad(look_down_limit),
				deg_to_rad(look_up_limit)), fposmod(value.y, TAU))

@onready var head: Node3D = $Head
func look_around(look_input: Vector2) -> void:
	look_rotation.y -= look_input.x * look_sensitivity
	look_rotation.x -= look_input.y * look_sensitivity
	
	# Rotate the whole player left and right
	transform.basis = Basis() # Reset rotation
	rotate_y(look_rotation.y)
	
	# Rotate the player's head up and down
	head.transform.basis = Basis() # Reset rotation
	head.rotate_x(look_rotation.x)

So this code works as expected, however I don’t understand exactly how. Since the set function takes a Vector2 argument, how is the set function working when I set the x and y vectors individually?

When you write look_rotation.x += 1.0, you basically say look_rotation = Vector2(look_rotation.x + 1.0, look_rotation.y), so you’re always pushing a Vector2 into the setter, even when you’re setting the components individually.

1 Like

Aha that makes sense thank you! I had a feeling it would be something along those lines. In that case it’s probably more efficient to just limit the values after I change them in the code rather than in a setter function. Or use two float variables rather than a vector2.

1 Like

It won’t impact the performance of your game if it’s just this simple calculation, so don’t bother optimizing it for performance. Try not to fall a victim of early optimization, optimize only when necessary.

1 Like