My attempt at smooth 2d platformer character doesn't work as iintended

Godot Version

godot 4.3

Question

I found few tutorials and the move_toward() method seemed fine, velocity = velocity.move_toward(speed * direction, acceleration) it takes two argument (maybe more) and here changes the velocity from what it was to 'speed * direction' by increments of 'acceleration' I'm having trouble with jumping as when pressing required input the player gains in altitude but falls very slowly, whenever I tried changing things a bit it went wrong some other way like only falling when moving or not fallin at all

extends CharacterBody2D


var speed = 200.0
var jump = -400.0
var acceleration = 40
var deceleration = 80
var direction = Vector2.ZERO
var gravity = 800

func input():
	var direction: Vector2 = Vector2.ZERO
	direction.x = Input.get_axis("ui_left", "ui_right")
	direction = direction.normalized()
	return direction 

func _physics_process(delta):
	# Add the gravity.
	velocity.y += gravity * delta
	# Movement
	var direction: Vector2 = input()
	if direction != Vector2.ZERO:
		velocity = velocity.move_toward(speed * direction, acceleration)
	else:
		velocity = velocity.move_toward(Vector2.ZERO, deceleration)
	# Handle jump.
	velocity.y += gravity * delta
	if Input.is_action_just_pressed("ui_up"):
			velocity.y = jump
	move_and_slide()

I am desperate to understand this problem but another method to implement “smooth” movement for a 2d platformeris appreciated.

I’m pretty sure physics_process is called 60 times per second. So if gravity is 800, you’ll apply +13.333 gravity per frame. This means at a jump height of 400, you should be taking ~7-8 seconds to fall? You might just need to change your gravity value to match how fast you want to be falling.

1 Like

It might help to use the same units in gravity (pixels per second) as you do for horizontal movement (pixels per frame)

If you multiply your acceleration/deceleration by delta it will be per-second, you will need to increase this value by about 60 to 2400; which will reach full speed in ~1/10th of a second.

velocity = velocity.move_toward(speed * direction, acceleration * delta)

Now maybe your gravity makes more sense, but the jump is a velocity/force impulse so it’s still using a different unit, it should feel similar to tweaking acceleration though.

Thank you for replying.
I tampered with the values many times and that seems not to be the case I am sure it’s bad code somewhere or maybe the whole approach is flawed.

thanks for replying.
wow that worked, I was initially skeptical of your solution as I attributed the errors to my code relating to the y axis of velocity and misunderstood those lines to affect only horizental movement but it worked, thanks.