simple platformer movement in godot

Solutions on MaxInterview for simple platformer movement in godot by the best coders in the world

showing results for - "simple platformer movement in godot"
Elyes
07 Jul 2016
1extends KinematicBody2D # The player is a kinematic body, hence extends Kine..
2
3# Adjustable variables of the player
4# export is used to allow to edit the values outside the script
5export var speed = 500 # The speed of the character
6export var gravity = 32 # The gravity of the character
7export var jumpforce = 800 # The jump force of the character
8
9var motion = Vector2.ZERO 
10
11func _physics_process(delta): 
12	
13	# Player movement functions:
14	if Input.is_action_pressed("ui_right"): # If the player enters the right arrow
15		motion.x = speed # then the x coordinates of the vector be positive
16	elif Input.is_action_pressed("ui_left"): # If the player enters the left arrow
17		motion.x = -speed # then the x coordinates of the vector be negative
18	else: # If none of these are pressed
19		motion.x = lerp(motion.x, 0, 0.25) # set the x to 0 by smoothly transitioning by 0.25
20	
21	if is_on_floor(): # If the ground checker is colliding with the ground
22		if Input.is_action_pressed("ui_up"): # And the player hits the up arrow key
23			JumpSound.play() # Play the jump sound
24			motion.y = -jumpforce # then jump by jumpforce
25	
26	motion.y += gravity + delta # Always make the player fall down
27	
28	motion = move_and_slide(motion, Vector2.UP)
29	# Move and slide is a function which allows the kinematic body to detect
30	# collisions and move accordingly
31		
32	
33
34
35
Bastien
28 Aug 2019
1# simple platoformer movement for godot with friction and acceleration
2# "move_right", "move_left" and "move_up" are defined in project setting/input map
3
4# the node that we'll use is kinematic body 2d
5extends KinematicBody2D
6
7# the movement variables (mess around with them to make the movement the way you like)
8export (int) var speed = 300
9export (int) var jump_speed = -600
10export (int) var gravity = 1000
11export (float, 0, 1.0) var friction = 0.25
12export (float, 0, 1.0) var acceleration = 0.25
13
14var velocity = Vector2.ZERO
15
16# geting player input with our own function
17func get_input():
18	var dir = 0
19	if Input.is_action_pressed("move_right"):
20		dir += 1
21	if Input.is_action_pressed("move_left"):
22		dir -= 1
23	if dir != 0:
24		velocity.x = lerp(velocity.x, dir * speed, acceleration)
25	else:
26		velocity.x = lerp(velocity.x, 0, friction)
27
28# and finaly calculating the movement
29func _physics_process(delta):
30	get_input()
31	velocity.y += gravity * delta
32	velocity = move_and_slide(velocity, Vector2.UP)
33	if Input.is_action_pressed("move_up"):
34		if is_on_floor():
35			velocity.y = jump_speed
36	if Input.is_action_just_released("move_up"): # this will check to see if are jump key is released and stop the player jumping
37		if sign(velocity.y) != 1:
38			velocity.y = 0