Reputation: 45
I just started learning Godot and don't understand why the player would not move? here is the script attached to the player
extends CharacterBody2D
var velocity = Vector2.ZERO
func _physics_process(delta):
if Input.is_action_pressed("ui_right"):
velocity.x = 4
elif Input.is_action_pressed("ui_left"):
velocity.x = -4
else:
velocity = 0
move_and_collide(velocity)
Upvotes: 0
Views: 2116
Reputation: 101
There are multiple small errors in your code that prevent your Character from moving.
First: the move_and_collide()
function is outside of the _physics_process()
function. To fix this, you simply have to indent move_and_collide()
. It will look something like this:
func _physics_process(delta):
if Input.is_action_pressed("ui_right"):
velocity.x = 4
elif Input.is_action_pressed("ui_left"):
velocity.x = -4
else:
velocity = 0
move_and_collide(velocity)
Now move_and_collide()
will be inside of the _physics_process()
loop.
Second: for a CharacterBody2D, the variable
velocity already exists (This is new to Godot 4 I believe).
In line 2:
var velocity = Vector2.ZERO
You are trying to redefine the variable. To fix this all you have to do is remove the var
and make it velocity = Vector2.ZERO
. You could also simply remove this line completely, which I would suggest.
Third: This is a small mistake, but on line 9, you are trying to assign the value 0
to the variable velocity
, which is a Vector2
and not an Integer
. To fix this simply change velocity
to velocity.x
The final code would look like this:
extends CharacterBody2D
func _physics_process(delta):
if Input.is_action_pressed("ui_right"):
velocity.x = 4
elif Input.is_action_pressed("ui_left"):
velocity.x = -4
else:
velocity.x = 0
move_and_collide(velocity)
Upvotes: 0