Godot Version
Godot_v4.2.2
Question
I am making a simple 2D platformer and I have a problem with slopes. If I ascend the slope, it works fine. But if I am descending the slope, the player is constantly “jumping” on it (imagine hopping down the hill). Is there any way to stick player to the ground whenever he is on slope? (or any way that could stop that jumping)
Here is my code:
using Godot;
using System;
public partial class player : CharacterBody2D
{
public const float Speed = 100.0f;
public const float JumpVelocity = -300.0f;
public float gravity = ProjectSettings.GetSetting("physics/2d/default_gravity").AsSingle();
float Acceleration;
public float defAccel = 0.25f;
public float airAccel = 0.20f;
private float lastDirectionX = 1;
private float JumpCount = 0;
public Sprite2D sprite;
public AnimationPlayer animations;
public override void _Ready()
{
sprite = GetNode<Sprite2D>("sprite");
animations = GetNode<AnimationPlayer>("sprite/animations");
Acceleration = defAccel;
}
public override void _PhysicsProcess(double delta)
{
Vector2 velocity = Velocity;
#region JUMP & FALL
if (!IsOnFloor())
{
velocity.Y += gravity * (float)delta;
Acceleration = airAccel;
if(!IsOnFloor() && velocity.Y < 0) // JUMPING STATE
{
animations.Play("jump");
GD.Print("jump");
}
else if(!IsOnFloor() && velocity.Y > 0) // FALLING STATE
{
animations.Play("fall");
}
}
if(IsOnFloor())
{
Acceleration = defAccel;
JumpCount = 0;
}
// Handle Jump.
if (Input.IsActionJustPressed("jump") && IsOnFloor() && JumpCount == 0)
{
velocity.Y = JumpVelocity;
JumpCount = 1;
}
else if (Input.IsActionJustPressed("jump") && JumpCount == 1)
{
velocity.Y = JumpVelocity * 0.9f;
JumpCount = 0;
}
#endregion
#region MOVEMENT
Vector2 direction = new Vector2(Input.GetActionStrength("right") - Input.GetActionStrength("left"), 0);
if (direction != Vector2.Zero) // MOVING STATE
{
velocity.X = Mathf.Lerp(Velocity.X, direction.X * Speed, Acceleration);
if(IsOnFloor())
animations.Play("move");
if (direction.X != 0)
lastDirectionX = direction.X;
}
else // IDLE STATE
{
velocity.X = Mathf.Lerp(Velocity.X, 0, Acceleration);
if(IsOnFloor())
animations.Play("idle");
}
#endregion
#region LAST DIRECTION
if(lastDirectionX > 0)
{
sprite.FlipH = false;
}
else
{
sprite.FlipH = true;
}
#endregion
Velocity = velocity;
MoveAndSlide();
}
}