I'm using a CharacterBody2D in Godot 4 and my movement is mostly working the way I want, but I'm still having difficulty with ascending slopes.
At first I thought it was just something related to my tile setup, but I still have issues even when creating a StaticBody2D with a rectangle collision shape.
Usually the player cannot ascend slopes at all in the game. They just get stuck running in place. When I introduced the rectangle shape to test, sometimes the player can ascend it, and then the next time I try it won't work, with the game still running, so no code change. You can see this in the video. Descending slopes seems to always work fine. When ascending slopes works at all, the speed still seems to be less than the constant speed that it should be based on the FloorConstantSpeed = true setting. The floor angle is also reported as being lower than the max angle I have configured even when I get stuck.
Here are all the relevant parts of the code I can think of.
Setup code that happens when the player is loaded:
body2D = GetParent<CharacterBody2D>();
body2D.FloorStopOnSlope = true;
body2D.FloorConstantSpeed = true;
body2D.FloorMaxAngle = (float)Mathf.DegToRad(75d);
body2D.FloorSnapLength = 3f;
body2D.FloorBlockOnWall = true;
body2D.MotionMode = CharacterBody2D.MotionModeEnum.Grounded;
Code to set Velocity's X component based on input
if (inputX == 0f)
{
inputX = -1f * Input.GetActionStrength(DefaultAction.Left);
}
// The player wants to move left or right. Let's see if they can do it.
if (Mathf.Abs(inputX) < LOW_INPUT_X_THRESHOLD)
{
// if we're moving very slowly, stop faster
Velocity.X = (float)Mathf.MoveToward(Velocity.X, 0, STOP_FORCE * GetPhysicsProcessDeltaTime());
}
else
{
Facing = inputX > 0f ? Directions.Right : Directions.Left;
Velocity.X = SPEED * movementScale * inputX;
return true;
}
Code in _PhysicsProcess() that calls MoveAndSlide
Velocity.X = Mathf.Clamp(Velocity.X, -MAX_X_SPEED, MAX_X_SPEED);
if (!body2D.IsOnFloor())
{
Velocity.Y = (float)Mathf.Min(CoreConstants.TERMINAL_VELOCITY, Velocity.Y+
(CoreConstants.DEFAULT_GRAVITY * GravityScale * delta * 2f));
}
// now apply the movement
body2D.Velocity = Velocity;
body2D.MoveAndSlide();
// pixel snap
body2D.GlobalPosition = body2D.GlobalPosition.Round();
I'm hoping this is just some setting or calculation I have wrong here. If I can use the debugger to confirm any theories out there let me know. Hope someone has a suggestion, thank you
Also may I please be verified so that my posts don't need mod approval?