when i change direction, the character moves faster for a few seconds. please tell how to avoid this.
extends AnimatedSprite2D
var x := 0
var y := 488
var vel : int
var jump = 0
var direction := “right”
var anim := “idle”
func _input(event):
if event.is_action_pressed(“space”) and jump == 0:
jump = 15
func _process(delta):
var right = Input.is_action_pressed(“right”)
var left = Input.is_action_pressed(“left”)
if (right and left and jump == 0) or (not(right or left) and jump == 0):
anim = “idle”
vel = 0
elif jump > 0:
anim = “jump”
elif jump < 0:
anim = “fall”
elif right:
$“.”.flip_h = false
vel = 140
anim = “run”
elif left:
$“.”.flip_h = true
vel = -140
anim = “run”
x += vel * delta
y -= jump * delta * 50
jump -= 50 * delta
if y >= 488:
y = 488
jump = 0
$“.”.play(anim)
$“.”.position = Vector2(x,y)
If you put this in backticks:
```gdscript
code code code
```
It formats as code and preserves the highlighting. I’ve done that below, and added some comments…
extends AnimatedSprite2D
var x := 0 # x and y here could be a Vector2
var y := 488 # You might want to do a `const FLOOR_Y = 488` or something.
var vel : int
var jump = 0
var direction := "right" # This never gets set in _process()...
var anim := "idle"
func _input(event):
if event.is_action_pressed("space") and jump == 0:
jump = 15
func _process(delta):
# Consider using Input.get_axis() here. It will simplify your logic,
# and may fix some or all of your input problem.
var right = Input.is_action_pressed("right")
var left = Input.is_action_pressed("left")
if (right and left and jump == 0) or (not(right or left) and jump == 0):
anim = "idle"
vel = 0
elif jump > 0:
anim = "jump"
elif jump < 0:
anim = "fall"
# If you're mid-jump and both left and right are set, with your current code
# you'll wind up going into `elif right:` below.
elif right:
$".".flip_h = false # You can replace this with: flip.h = false
vel = 140
anim = "run"
elif left:
$".".flip_h = true # You can replace this with: flip.h = true
vel = -140
anim = "run"
x += vel * delta
y -= jump * delta * 50
jump -= 50 * delta
if y >= 488:
y = 488
jump = 0
$".".play(anim) # You can replace this with: play(anim)
$".".position = Vector2(x,y) # And this with: position = Vector2(x, y)