Godot 4 movement fix
Criado em: 5 de janeiro de 2025
Criado em: 5 de janeiro de 2025
extends CharacterBody2D
var max_speed = 100
func _ready():
pass # Replace with function body.
func _proccess(delta):
var direction = get_direction_to_player()
velocity = max_speed * direction
move_and_slide()
func get_direction_to_player():
var player = get_tree().get_first_node_in_group("player") as Node2D
if player != null:
return (player.global_position - global_position).nornalized()
return Vector2(0,0)
Below is a cleaned-up version of your script with the most common fixes applied. The main issues in the snippet you posted are:
func _process(delta):
or func _physics_process(delta):
.nornalized()
.CharacterBody2D
has its own built-in velocity
property and typically uses move_and_slide()
.KinematicBody2D
with a manually defined velocity
and call move_and_slide(velocity * delta)
inside _physics_process
.Below is an example corrected for Godot 4. If you are still using Godot 3, see the notes at the bottom for how to adapt it.
gdscriptextends CharacterBody2D var max_speed = 100 func _ready(): # You can initialize things here if needed pass func _physics_process(delta): var direction = get_direction_to_player() # Scale the direction to max_speed velocity = max_speed * direction # Move using Godot 4's CharacterBody2D API velocity = move_and_slide() func get_direction_to_player() -> Vector2: # Finds the first node in the group "player" var player = get_tree().get_first_node_in_group("player") as Node2D if player != null: # Use 'normalized()' (with a 'd') return (player.global_position - global_position).normalized() return Vector2.ZERO
CharacterBody2D
with KinematicBody2D
.gdscriptfunc _physics_process(delta): var direction = get_direction_to_player() velocity = max_speed * direction velocity = move_and_slide(velocity * delta)
normalized()
, _physics_process
or _process
) as shown above.Choosing _process(delta)
vs _physics_process(delta)
_process(delta)
for purely visual/logic updates._physics_process(delta)
if you are dealing with physics-related movement every frame (this ensures it runs in sync with the physics step).Using groups:
"player"
via the Godot editor (or via add_to_group("player")
in code). Otherwise, get_tree().get_first_node_in_group("player")
will be null
.Movement details:
move_and_slide()
uses the velocity
property of CharacterBody2D
automatically. You can optionally add parameters like “up direction” if you need advanced features such as floor detection or gravity.move_and_slide(velocity * delta, Vector2.UP)
is more common for 2D platformers (with gravity).With these corrections, your script should properly chase the Player node in your scene.