Custom CharacterBody2D class, non-working methods and properties

Godot Version

4.1.3 stable

Question

Script, extends CharacterBody2D is a custom class Player, containing player physics data (like max speed, acceleration) and some service functions like _ready() and _physics_process(). But also, there is vector() function, that returns player input vector:

func vector():
	input_direction = Input.get_vector("move_right", "move_left", "move_up", "move_down")
	return input_direction.normalized()

This function not affects parameters when called in other classes:

#from idle_state.gd

var player = Player.new()
var player_vector = player.vector()

func _prev_vector() -> Vector2:
	var last_vector := Vector2(0, 1)
	if player_vector != Vector2.ZERO:
		last_vector = player_vector
	return last_vector

func Update(_delta):
    if player:
		_animation_playback()

Output: Idle animation play (0, 1), because it don’t register any input keys. That means that it isn’t callable by this way, and this is confirmed if I put theirself vector() functions in each class:

func _player_vector() -> Vector2:
	var input_direction = Input.get_vector("move_left", "move_right", "move_up", "move_down")
	print("vector updated: " + str(input_direction))
	return input_direction.normalized()

image

What did I miss?

did you mean you didn’t add the input actions?

and this needs more information, there’s a

Idle animation play (0, 1)

output, but don’t know where did it come from.
and please make clear what did you do with these functions.

var player_vector = player.vector()

This is a copied value, so player_vector is not updated, forever it’s starting value.

There could be two incorrect assumptions here, the less likely one is to assume the function is called every time a variable is accessed; it is only executing .vector() once.

The other assumption may be of copies and references. Most classes are referenced, you can tell if they inherit from “RefCounted”. Everything else creates a copy when assigned to a variable. RefCounted values can be passed to functions or other classes and still point to the same single object, where copies do not and will be edited independently.


In this case I would recommend only ever using player.vector() directly, and not storing it in a variable unless it’s being used within the same frame of gameplay.