How make my character fall(Gravity) in Kinematic body 3d

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By StarX1709

Hello!
I created a 3D character using kinematic body(3D) . Now i want to make my character jump and then fall on the ground(gravity). See the code

extends KinematicBody

var velocity = Vector3.ZERO
var gravity = 100
func _physics_process(delta):
	if Input.is_action_ just_pressed("jump"):
		velocity.y = 10
		velocity.y += gravity *delta
		move_and_slide(velocity)

with this code my player jumps but it does not fall back instead it gets stucked in the middle.Now i want to know how to add gravity -

:bust_in_silhouette: Reply From: p7f

What you see happens because you are only adding gravity when you jumped, so the gravity is not added when already on air. Also, move and slide is only being called inside the if where you jump… try something like this:

extends KinematicBody

var velocity = Vector3.ZERO
var gravity = 100
func _physics_process(delta):
    if Input.is_action_ just_pressed("jump") and is_on_floor():
        velocity.y = 10

    velocity.y += gravity *delta
    velocity = move_and_slide(velocity, Vector3.UP)

Note that i moved the last two lines outside the if, and also, added a check to see if the body is on floor before jumping, to avoid jumping in middle air. Also, you should update velocity with move_and_slide so gravity doesnt sum up while on floor.

Edited as people in comments noted it was missing up direction

hello!
thanks for your answer but now it is going upward without any Input press and it is not stopping.

StarX1709 | 2020-08-20 06:17

Thanks!
I have figured out this problem . Thank you for solution

StarX1709 | 2020-08-20 07:34

Yiu are welcome! If the answer worked for you, you may select it so others can see its solved!

p7f | 2020-08-20 11:30

you forgot to add:

velocity = move_and_slide(velocity, Vector3.UP)

is_on_floor() will always return false if the up direction isnt specified

Chevon | 2020-08-21 04:43

p7f
your answer was incomplete but the technique gave me an idea

StarX1709 | 2020-08-21 05:45

chevon
yes i applied this code and it worked

StarX1709 | 2020-08-21 05:47

Oh, yeah, i forgot that. I just modified the original code in the original question.

p7f | 2020-08-21 11:30

your answer was incomplete but the technique gave me an idea

Ok, glad to help! So it would be nice for you to post your solution, and select that answer, so others can see its solved!

p7f | 2020-08-21 11:33

i am trying to learn godot and had the same question.
the only thing i changed from your code was instead of += i used -=

so the final code looks like this.

thank you.

extends KinematicBody

var velocity = Vector3.ZERO
var gravity = 30

func _ready():
	pass

func _physics_process(delta):
	velocity.y -= gravity * delta
	velocity = move_and_slide(velocity,Vector3.UP)

semih | 2022-08-24 00:58