Godot Version
4.2.1
Question
I’m trying to access a CharacterBody2D’s velocity in a “Tracker” nodes script. I’m attempting to make the Tracker node match the position of the character body, but then offset it by the character body’s velocity.
For some reason, the character body’s velocity is always (0,0).
Here’s the code for thew character body…
@tool
extends CharacterBody2D
@onready var collision_shape = $CharacterBody2D/CollisionShape2D
var radius: float = 64.0:
set(v):
radius = v
collision_shape.shape.radius = radius
queue_redraw()
var drag: Vector2 = Vector2(0.1, 0.2);
var vel: = Vector2(100, -1000);
var speed: = 3.0;
var gravity: = 198.0
var frame_count = 0;
var has_started = false
func _draw():
draw_circle(Vector2.ZERO, radius, Color.FIREBRICK)
# I'm using the Godot State Charts add-on
func _on_play_state_physics_processing(delta):
if !Engine.is_editor_hint():
vel.y += (gravity * speed) * delta
vel -= drag if vel.length() > 0 else Vector2.ZERO
var collision = move_and_collide(vel*delta)
if collision:
if (collision.get_collider() as Node2D).is_in_group('world_collider'):
vel = vel.bounce(collision.get_normal())
queue_redraw()
and here’s the code for the Tracker node
extends Node2D
@export var debug: bool = false
@export var body: CharacterBody2D
# Called when the node enters the scene tree for the first time.
func _ready():
pass # Replace with function body.
func _draw():
if(debug):
draw_circle(Vector2.ZERO, 20, Color.RED)
# set the node's position to the body's position
# offset the node's position by the body's velocity
func _physics_process(_delta):
position = body.position
position += body.velocity
I assumed move_and_collide was setting the velocity, but I guess I must be wrong about that. Any help greatly appreciated.
Also, I’m newish to Godot and GDScript, so I’d also welcome any advice if you see anything strange in the way I’m trying to code this.