gdscript 2d platformer mopvement code example

Example 1: godot platformer movement

extends KinematicBody2D # The player is a kinematic body, hence extends Kine..

# Adjustable variables of the player
# export is used to allow to edit the values outside the script
export var speed = 500 # The speed of the character
export var gravity = 32 # The gravity of the character
export var jumpforce = 800 # The jump force of the character

var motion = Vector2.ZERO 

func _physics_process(delta): 
	
	# Player movement functions:
	if Input.is_action_pressed("ui_right"): # If the player enters the right arrow
		motion.x = speed # then the x coordinates of the vector be positive
	elif Input.is_action_pressed("ui_left"): # If the player enters the left arrow
		motion.x = -speed # then the x coordinates of the vector be negative
	else: # If none of these are pressed
		motion.x = lerp(motion.x, 0, 0.25) # set the x to 0 by smoothly transitioning by 0.25
	
	if is_on_floor(): # If the ground checker is colliding with the ground
		if Input.is_action_pressed("ui_up"): # And the player hits the up arrow key
			JumpSound.play() # Play the jump sound
			motion.y = -jumpforce # then jump by jumpforce
	
	motion.y += gravity + delta # Always make the player fall down
	
	motion = move_and_slide(motion, Vector2.UP)
	# Move and slide is a function which allows the kinematic body to detect
	# collisions and move accordingly

Example 2: simple platformer movement in godot

# simple platoformer movement for godot with friction and acceleration
# "move_right", "move_left" and "move_up" are defined in project setting/input map

# the node that we'll use is kinematic body 2d
extends KinematicBody2D

# the movement variables (mess around with them to make the movement the way you like)
export (int) var speed = 300
export (int) var jump_speed = -600
export (int) var gravity = 1000
export (float, 0, 1.0) var friction = 0.25
export (float, 0, 1.0) var acceleration = 0.25

var velocity = Vector2.ZERO

# geting player input with our own function
func get_input():
	var dir = 0
	if Input.is_action_pressed("move_right"):
		dir += 1
	if Input.is_action_pressed("move_left"):
		dir -= 1
	if dir != 0:
		velocity.x = lerp(velocity.x, dir * speed, acceleration)
	else:
		velocity.x = lerp(velocity.x, 0, friction)

# and finaly calculating the movement
func _physics_process(delta):
	get_input()
	velocity.y += gravity * delta
	velocity = move_and_slide(velocity, Vector2.UP)
	if Input.is_action_pressed("move_up"):
		if is_on_floor():
			velocity.y = jump_speed
	if Input.is_action_just_released("move_up"): # this will check to see if are jump key is released and stop the player jumping
		if sign(velocity.y) != 1:
			velocity.y = 0

Tags:

Misc Example