Created
March 23, 2024 16:26
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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