simple platformer movement in godot code example
Example 1: godot platformer movement
extends KinematicBody2D
export var speed = 500
export var gravity = 32
export var jumpforce = 800
var motion = Vector2.ZERO
func _physics_process(delta):
if Input.is_action_pressed("ui_right"):
motion.x = speed
elif Input.is_action_pressed("ui_left"):
motion.x = -speed
else:
motion.x = lerp(motion.x, 0, 0.25)
if is_on_floor():
if Input.is_action_pressed("ui_up"):
JumpSound.play()
motion.y = -jumpforce
motion.y += gravity + delta
motion = move_and_slide(motion, Vector2.UP)
Example 2: simple platformer movement in godot
extends KinematicBody2D
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
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)
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"):
if sign(velocity.y) != 1:
velocity.y = 0