Skip to content

Instantly share code, notes, and snippets.

@lamarmarshall
Created January 22, 2024 03:20
Show Gist options
  • Save lamarmarshall/a5adc9e07a063c56b2caecee5643dd0f to your computer and use it in GitHub Desktop.
Save lamarmarshall/a5adc9e07a063c56b2caecee5643dd0f to your computer and use it in GitHub Desktop.
godot 4, player movement hop
extends Area2D
func _on_body_entered(body: Node2D) -> void:
if body is Player:
if body.velocity.y > 0:
body.jump()
extends CharacterBody2D
class_name Player
var speed = 300.0
var viewport_size
var gravity = 15
var max_fall_velocity = 1000.0
var jump_velocity = -800
@onready var animator = $AnimationPlayer
func jump() -> void:
velocity.y = jump_velocity
func _ready() -> void:
viewport_size = get_viewport_rect().size
func _process(delta: float) -> void:
if velocity.y > 0:
if animator.current_animation != "fall":
animator.play("fall")
elif velocity.y < 0:
if animator.current_animation != "jump":
animator.play("jump")
func _physics_process(delta: float) -> void:
velocity.y += gravity
if velocity.y > max_fall_velocity:
velocity.y = max_fall_velocity
var direction = Input.get_axis("move_left", "move_right")
#print(direction)
if direction:
velocity.x = direction * speed
else:
velocity.x = move_toward(velocity.x, 0, speed)
move_and_slide()
var margin = 20
if global_position.x > viewport_size.x + margin:
global_position.x = -margin
if global_position.x < 0 - margin:
global_position.x = viewport_size.x + margin
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment