If I try running your code, I get an error message and the game doesn’t run:
Invalid type in function ‘look_at’ in base ‘CharacterBody2D (character_body_2d.gd)’. Cannot convert argument 1 from int to Vector2.
If I remove the last line, and then try to run it again and press forward, I get a different error:
Error setting property ‘velocity’ with value of type float.
Generally, if your code doesn’t work, and you are getting error messages, it’s a good idea to read those, and if you don’t understand them, at least include them when you post your question here.
With that out of the way: Both of these errors occur because you’re trying to use a float instead of a vector. I’m not entirely sure what you’re trying to do with the direction
variable - if it’s rotation, then a simpler way to achieve that would be:
if Input.is_action_just_pressed("left"):
rotate(deg_to_rad(-10))
if Input.is_action_just_pressed("right"):
rotate(deg_to_rad(10))
Or, for smoother rotation while the buttons are held down:
if Input.is_action_pressed("left"):
rotate(deg_to_rad(-50) * delta)
if Input.is_action_pressed("right"):
rotate(deg_to_rad(50) * delta)
Then, in order to move in the direction the character is pointing, you take its global_transform.y
or global_transform.x
and multiply with the speed. Which one you use depends on which way the character sprite is pointing. Here’s moving along the y axis (only while the forward button is held down):
if Input.is_action_pressed("forward"):
velocity = global_transform.y * SPEED
else:
velocity = Vector2.ZERO
move_and_slide()