So I've been beating my head against this for a while. I used to do this in godot 3.x but I'm having a lot of trouble with it now.

I'm trying to get the velocity of another CharacterBody2D, so I needed to reference the node in order to get it's properties, right?
It took me a while to even print the node that I wanted to get, but now that I have it, using "Player.velocity" doesn't work.

here's the code:

extends CharacterBody2D

class_name Enemy

@onready var player = get_node("%Player")
var playerVel = player.velocity

const SPEED = 300.0
const JUMP_VELOCITY = -400.0

@export_range(0.0, 1.0) var friction = 0.15
@export_range(0.0, 1.0) var acceleration = 0.2

var gravity = ProjectSettings.get_setting("physics/2d/default_gravity")

func _ready():
	print(playerVel)

#smash as in Super Smash Bros
func smash():
	#velocity = playerVel * -1
	pass

#Death
func death():
	queue_free()
	print("enemy")
  • This line here is your problem: var playerVel = player.velocity

    First the variable is initialised when the script is initialised. But the player variable is only initialised on ready. That happens much later. So at the time that player.velocity is executed, player is still null.

    Second, is that really what you want? Even with the issue above resolved playerVel will only contain the initial velocity (probably 0) and then never change again (unless you assign a new value to it). IMO the best solution would be to just ditch the playerVel variable and use player.velocity explicitly instead

This line here is your problem: var playerVel = player.velocity

First the variable is initialised when the script is initialised. But the player variable is only initialised on ready. That happens much later. So at the time that player.velocity is executed, player is still null.

Second, is that really what you want? Even with the issue above resolved playerVel will only contain the initial velocity (probably 0) and then never change again (unless you assign a new value to it). IMO the best solution would be to just ditch the playerVel variable and use player.velocity explicitly instead

    Zini Thank you, man, I didn't know that's how onready worked. Also, I'm aware it won't work as is, I just wanted to know I could get the velocity and then would figure out how to implement it in the system I'm trying to create, but thank you for the warning.