extends CharacterBody2D
@onready var sprite = $AnimatedSprite2D
@export var SPEED = 320.0
@export var JUMP_HEIGHT = -450.0
@export var attacking = false
func _physics_process(_delta):
if Input.is_action_pressed(“right”):
sprite.scale.x = abs(sprite.scale.x) * -1
if Input.is_action_pressed(“left”):
sprite.scale.x = abs(sprite.scale.x) * +1
#$AnimatedSprite.flip_h = true
Add the gravity.
if not is_on_floor():
velocity += get_gravity() * _delta
if Input.is_action_just_pressed("jump") and is_on_floor():
velocity.y = JUMP_HEIGHT
Get the input direction and handle the movement/deceleration.
As good practice, you should replace UI actions with custom gameplay actions.
var direction := Input.get_axis("right", "left")
if direction:
velocity.x = direction * SPEED
velocity.x = move_toward(velocity.x, 0, SPEED)
move_and_slide()
update_sprite()
func update_sprite():
if velocity.x !=0:
sprite.play("run")
else:
sprite.play("idle")
if velocity.y < 0:
sprite.play("jump")
if velocity.y > 0:
sprite.play("fall")
can yall just point out whats wrong and to also give the solution to said problem
I think you have mis-remembered move_toward. You currently move toward 0 at a rate of SPEED.
velocity.x = move_toward(velocity.x, 0, SPEED)
So lets say direction is 1, your SPEED is 320, you have
# set from input
velocity.x = direction * SPEED
# then slow down
velocity.x = move_toward(velocity.x, 0, SPEED)
# which is actually this:
velocity.x = move_toward(320, 0, 320)
Which is instantly 0.
I think you meant to do:
velocity.x = move_toward(velocity.x, 0, SPEED * delta)
Not sure this is the only thing you have wrong. And this rate of decrease seems like a lot anyway. If you comment out this slowing down does your char move? Also I cannot tell if this is in _process or not. It does not help that you have not put your code properly into a code block, it makes it very hard to read/follow.
that kinda worked but now my character would slide instead of coming to a stop when i let go of the key
Ok that is good. Now you can re-introduce the slowing but this time start with just delta.
I would also create a new variable called something like “DECELERATE” so you can then have DECELERATE * delta if the delta alone is still too slidy for your character. In this way, if you change you chars speed it wont change the slow down when a key is lifted.
1 Like