Skip to content

Instantly share code, notes, and snippets.

@Shilo
Created March 23, 2024 16:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Shilo/42b6818a5b3178bbbb3b794fd1bc8593 to your computer and use it in GitHub Desktop.
Save Shilo/42b6818a5b3178bbbb3b794fd1bc8593 to your computer and use it in GitHub Desktop.
Godot Rigidbody2D that allows for movement and jump input. Input is relative the gravity direction. Useful for "Super Mario Galaxy" type planet game.
class_name SpacePlayer extends RigidBody2D
const JUMP_STRENGTH: float = 200
const MOVE_SPEED: float = 200
func _process(_delta: float) -> void:
update_input()
func update_input() -> void:
if !_is_on_ground():
return
var gravity_direction: Vector2 = get_gravity().normalized()
_update_jump(gravity_direction)
_update_move(gravity_direction)
func _update_jump(gravity_direction: Vector2) -> void:
if !Input.is_action_just_pressed("ui_accept"):
return
apply_central_impulse(JUMP_STRENGTH * -gravity_direction)
func _update_move(gravity_direction: Vector2) -> void:
var input_direction = Input.get_axis("ui_left", "ui_right")
if !input_direction:
return
var input_direction_normalized = 1 if input_direction > 0 else -1
var input_direction_strength = abs(input_direction)
var direction = gravity_direction.rotated(PI / 2 * -input_direction_normalized)
apply_central_force(MOVE_SPEED * direction * input_direction_strength)
func _is_on_ground() -> bool:
return get_colliding_bodies().size() > 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment