Godot member "velocity" redefined (original in native class 'CharacterBody2D')
- User
Godot member "velocity" redefined (original in native class 'CharacterBody2D')
- Assistant
The message you are seeing indicates that there is a member variable named
velocitythat has already been defined in the native classCharacterBody2Dand you are trying to redefine it in your script. This can lead to unexpected behavior and errors.In Godot 4,
CharacterBody2Dhas a built-invelocityproperty which you can use directly instead of redefining it. If you redefine it, you may shadow the original definition, which can cause conflicts.Here’s how you can work with the
velocityproperty in theCharacterBody2Dclass:First, ensure your script extends
CharacterBody2D. Then use the built-invelocityproperty directly.Example Usage
extends CharacterBody2D # Adding a constant for gravity const GRAVITY = 20.0 const SPEED = 100.0 # Using the built-in velocity func _physics_process(delta): # Adding gravity to the velocity.y velocity.y += GRAVITY * delta # Example of adding player control for moving left and right if Input.is_action_pressed("ui_right"): velocity.x = SPEED elif Input.is_action_pressed("ui_left"): velocity.x = -SPEED else: velocity.x = 0 # Move and slide with the velocity velocity = move_and_slide()Key Points
- As you can see, you don't need to redefine
velocitybecause it already exists within theCharacterBody2Dclass. - You can directly manipulate
velocityto reflect different states such as applying gravity, reacting to player input, etc. - The
move_and_slidemethod is typically used withvelocityfor handling movement in a way that considers sliding along surfaces.
Common Pitfalls
- Avoid using
var velocitydeclaration in your script when extendingCharacterBody2Das it may override or shadow the built-invelocityproperty leading to unpredictable behavior. - Be mindful of the type and usage of
velocity. It’s already a Vector2 type representing the 2D velocity of the character body.
By adhering to these practices, you should be able to properly use the
velocityproperty without redefinition conflicts. - As you can see, you don't need to redefine