How gravity works?

im make character in godot but i dont understand how make the gravity works, the gravity can move but move constan.can you all help me?



@export var kecepatan = 400
var grafitasi = 10
var pemberat = 50
var accel = 100
var direct : Vector2 = Vector2.ZERO

func _physics_process(delta):
	var arah = direksi()
	if arah != Vector2.DOWN:
		velocity = velocity.move_toward(arah*kecepatan,accel)
	else:
		velocity = velocity.move_toward(Vector2.ZERO,pemberat)
	if is_on_floor():
		velocity.y = 0
	else:
		velocity.y += 10
	print(velocity.y)
	move_and_slide()
	aktif_animasi()

func direksi() -> Vector2:
	direct.x = Input.get_axis("left","right")
	direct = direct.normalized()
	return direct

There’s a few issues here…

Firstly, if arah != Vector2.DOWN: will always return false as your function direksi() is only setting the x value of the Vector2 and the y is always 0. If you change this to if arah != Vector2.ZERO: that should fix that problem as I’m assuming this is meant to be checking if there is any input.

Secondly, your velocity calculation is inherently flawed. move_towards() will move the entire velocity vector towards the to vector. Assuming a starting velocity of (0, 0), no input and is_on_floor() == false, at the end of the first frame, the velocity will be (0, 10). The second frame starting velocity is now (0, 10) with the same conditions. This time else: velocity = velocity.move_toward(Vector2.ZERO,pemberat) triggers. since velocity is (0, 10) and delta for move_towards() (i.e. pemberat) is 50, this will set velocity back to (0, 0) (as 50 is greater than the length of velocity which is 10). The result of this is that each frame velocity is always set to (0, 10) as pemberat is greater than the gravity.

The fix for this in 2D is fairly straightforward as you would simply only alter the x value of velocity in this section:

if arah != Vector2.DOWN:
		velocity = velocity.move_toward(arah*kecepatan,accel)
	else:
		velocity = velocity.move_toward(Vector2.ZERO,pemberat)

This way, vertical movement is independent of your input, and your character will always fall if they’re not on the ground. I would also suggest multiplying all your acceleration values (e.g. accel, pemberat, and grafitasi) by delta before applying them to velocity so your acceleration is framerate-independent. This way your values can be in proper acceleration units which will make it easier to tweak the values to your liking.

1 Like

You should also be multiplying any of this stuff by delta as well, otherwise its frame dependant.

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.