How to Implement " Jump " In KinematicBody 3D using GDScript ?

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

Hi all, Harshdeep here,
I’m totally new in game development side. I followed BornCG in Youtube and made exactly same 3D game. But, now I want to implement some jumping function with disable on gravity. ( means user can’t jump while in the air. ). I tried but, failed to implement it.

My controller code.

extends KinematicBody

var velocity = Vector3(0,0,0)

const SPEED = 5
const ROTATE = 5

func _ready():
	#Game Background Music
	var BackgroundMusic = get_node("BackgroundMusic/AudioStreamPlayer3D")
	BackgroundMusic.play()
	#pass
	
func _physics_process(delta):
	
	
	#RollerBall(Player) Control.
	if Input.is_action_pressed("ui_right") and Input.is_action_pressed("ui_left"):
		velocity.x = 0
	elif Input.is_action_pressed("ui_right"):
		velocity.x = SPEED
		$MeshInstance.rotate_z(deg2rad(-ROTATE))
	elif Input.is_action_pressed("ui_left"):
		velocity.x = -SPEED
		$MeshInstance.rotate_z(deg2rad(ROTATE))
	else:
		velocity.x = lerp(velocity.x,0,0.1)

	if Input.is_action_pressed("ui_up") and Input.is_action_pressed("ui_down"):
		velocity.z = 0
	elif Input.is_action_pressed("ui_up"):
		velocity.z = -SPEED
		$MeshInstance.rotate_x(deg2rad(-ROTATE))
	elif Input.is_action_pressed("ui_down"):
		velocity.z = SPEED
		$MeshInstance.rotate_x(deg2rad(ROTATE))
	else:
		velocity.z = lerp(velocity.z,0,0.1)

	move_and_slide(velocity)
:bust_in_silhouette: Reply From: kidscancode

If you pass move_and_slide() a floor_normal value, you can use is_on_floor() to determine if you’re standing on the ground or not, and allow a jump. You should never disable gravity - it’s a constant force pulling downward. To jump, set your body’s y velocity to the desired value.

For an example, see: Using CharacterBody2D/3D — Godot Engine (latest) documentation in English

(It’s 2D, but the concept is the same in 3D)

More information can be found in the KinematicBody documentation.

thanks brother. Just explored your YT channel. and changed entire code.
thanks a lot. you got one more subscriber. :slight_smile:

Harshdeep Patel | 2019-08-06 07:56

:bust_in_silhouette: Reply From: Nikhil Sonar

const Jump_gravity = 9.8
const jump_power = 12

#“ui_jumping” is created from (project setting>input map>Action>You can create keys )

if is_on_wall() and Input.is_action_just_pressed("ui_jump"):#for Jumping "space".
	velocity.y = jump_power*Jump_gravity
elif is_on_wall()==false or Input.is_action_just_released("ui_jump"):
	velocity.y = -(Jump_gravity*jump_power*delta*2)

#delta is used for increasing the speed in asending order.