How to read player character velocity from unconnected node?

Godot Version

4.1.1

Question

I am trying to create a first-person character controller in which weapons are stored as separate scenes loaded and instanced at runtime instead of directly as a child in the editor. My player character is represented by a CharacterBody3D node. I wish to have the weapon node read the velocity of the player character relative to the world in order to drive a procedural sway / bob animation, but nothing I try works.

If I call the CharacterBody3D in an @onready var, and then call get_real_velocity(), it errors out reporting that it can’t call that method on a string. I’m assuming I should be trying to read a vector3, but I can’t figure out how to do this.

I basically just need to get my CharacterBody3D’s real velocity as a vector3 and pass it to a different node. I would be really graetful for any guidance on how to do this!

I usually send data like this to a variable in a singleton (typically so an enemy knows where the player is in the world). You can then have the singleton signal other nodes or have the node script look at the variable in the singleton.

Edit: Sorry I’m tired. Is it possible to copy past the movement code in your character controller here so we can take a look at it. Also I think you can just convert the vector3 to a string by using str()

IE:

string_version_of_vec3_var = str(the_variable_that_has_vec3_info)

After some chatting with a friend, yeah, this was the solution I ended up going for as I realised I was massively overthinking what I was trying to do. I set up an autoload script called ‘Game.gd’, set a variable named ‘player’, and then set my actual player script up so my autoload would call back to it by using:

func _ready():
Game.player = self

Now I can just grab the velocity from basically anywhere by calling Game.player.velocity :slight_smile:

Thank you for the suggestion! I hadn’t realised that you could use autoloaded scripts like singletons in Godot.

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