Howdy folks (I’m new to Unity c:), I am trying to have some movement working properly for both slopes and grounded movement!
I have tried setting current speed as a separate variable that is then applied to the movement input, slope angle, and gravity.
However it’s causing deceleration to not function, as there is a sudden stop, when it should be stopping gradually. And another situation such as when the player is on a slope will slowly climb up as if current speed is still building up, when it should be seamlessly carrying the momentum without hitches.
https://gdl.space/odajorabag.cs
private void CalculateSpeed()
{
//General acceleration before anything else.
#region Calculate Acceleration and Deceleration
if (Mathf.Abs(moveInput.x) > 0f)
{
if (currentSpeed < maxSpeed)
{
currentSpeed += walkAcceleration * Time.deltaTime;//walkAcceleration is your adjustment for walk acceleration.
}
}
else
{
currentSpeed -= walkDeceleration * Time.deltaTime; //walkDeceleration slows the player down.
currentSpeed = Mathf.Max(currentSpeed, 0f);
currentSpeed = Mathf.Clamp(currentSpeed, -maxSpeed, maxSpeed);
}
#endregion
if (IsGrounded && !_onSlope)
{
Debug.Log("Grounded, but not on slope!");
//is Player not moving?
if (Mathf.Approximately(moveInput.x, 0))
{
newPlayerVelocity.Set(walkSpeed * moveInput.x * currentSpeed, playerRB.velocity.y);
//stateManager.CurrentState = PlayerStateManager.PlayerState.Idle;
}
else
{
newPlayerVelocity.Set(walkSpeed * moveInput.x * currentSpeed, playerRB.velocity.y);
}
newPlayerVelocity.x = Mathf.Clamp(newPlayerVelocity.x, -maxSpeed, maxSpeed);
playerRB.velocity = new Vector2(newPlayerVelocity.x, newPlayerVelocity.y - gravityScale);
}
//Should move with kinematic assistance on slopes by detecting if slope is approximately 45 or 315.
else if (IsGrounded && _onSlope) //Checks if is grounded and is on a slope.
{
Debug.Log("Grounded on slope!");
//is Player not moving?
if (Mathf.Approximately(moveInput.x, 0))
{
newPlayerVelocity.Set(_slopePerp.x * -moveInput.x * currentSpeed,_slopePerp.y * -moveInput.x * currentSpeed);
//stateManager.CurrentState = PlayerStateManager.PlayerState.Idle;
}
else
{
newPlayerVelocity.Set(_slopePerp.x * -moveInput.x * currentSpeed,_slopePerp.y * -moveInput.x * currentSpeed);
}
newPlayerVelocity.x = Mathf.Clamp(newPlayerVelocity.x, -maxSpeed, maxSpeed);
playerRB.velocity = new Vector2(newPlayerVelocity.x, newPlayerVelocity.y - gravityScale);
}
// Airborne movement behavior.
else if (!IsGrounded)
{
Debug.Log("Airborne!");
//is Player not moving?
if (Mathf.Approximately(moveInput.x, 0))
{
//stateManager.CurrentState = PlayerStateManager.PlayerState.Idle;
}
else
{
if (_onSlope)
{
newPlayerVelocity.Set(_slopePerp.x * -moveInput.x * walkAcceleration, walkSpeed * _slopePerp.y * -moveInput.x * walkAcceleration);
}
newPlayerVelocity.Set(moveInput.x, playerRB.velocity.y);
}
playerRB.velocity = new Vector2(newPlayerVelocity.x, playerRB.velocity.y - gravityScale);
}
}