Skip to content

Instantly share code, notes, and snippets.

@Intrivus
Created July 30, 2024 16:50
Show Gist options
  • Save Intrivus/33d064008bb48cd41795e836d472f316 to your computer and use it in GitHub Desktop.
Save Intrivus/33d064008bb48cd41795e836d472f316 to your computer and use it in GitHub Desktop.
using Godot;
using System;
public partial class Character : CharacterBody2D
{
[Export] private float JumpHeight;
[Export] private float TimeToApex;
[Export] private float TimeToGround;
private Vector2 NewVelocity;
private Vector2 OldVelocity;
private Vector2 AppliedVelocity;
public bool CanJump;
private bool IsJumping;
private bool IsFalling;
private float ApexGravity => 2 * JumpHeight / (TimeToApex * TimeToApex);
private float FallGravity => 2 * JumpHeight / (TimeToGround * TimeToGround);
private float JumpForce => -2 * JumpHeight / TimeToApex;
private float JumpTimer;
void HandleJump()
{
void Jump() => NewVelocity.Y = JumpForce;
if (Input.IsActionPressed("Jump") && !IsJumping && CanJump && IsOnFloor())
{
Jump();
CanJump = false;
IsJumping = true;
}
else if (IsOnFloor())
{
CanJump = true;
IsJumping = false;
}
}
public override void _PhysicsProcess(double delta)
{
AppliedVelocity = Velocity;
Move();
HandleJump();
OldVelocity = NewVelocity;
NewVelocity.Y += Gravity() * (float)delta;
NewVelocity.Y = Mathf.Clamp(NewVelocity.Y, !IsOnCeiling() ? JumpForce : 0, !IsOnFloor() ? Mathf.Inf : 0);
AppliedVelocity.Y = (OldVelocity.Y + NewVelocity.Y) * .5f;
// if (IsFalling)
// {
// JumpTimer += (float)delta;
// }
// else if (!IsFalling && JumpTimer != 0)
// {
// GD.Print(JumpTimer);
// JumpTimer = 0;
// }
GD.Print(GlobalPosition.Y);
Velocity = AppliedVelocity;
MoveAndSlide();
}
void Move()
{
Vector2 direction = Vector2.Zero;
direction.X = Input.GetAxis("MoveLeft", "MoveRight");
AppliedVelocity.X = direction.X * 500;
}
float Gravity()
{
IsFalling = !IsOnFloor() && NewVelocity.Y >= 0;
return IsFalling ? FallGravity : ApexGravity;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment