Actions

SPG:Slope Physics

From Sonic Retro

Revision as of 08:24, 16 July 2023 by LapperDev (talk | contribs) (When Going Upward: New ceiling landing example image)
Sonic Physics Guide
Collision
Physics
Gameplay
Presentation
Special

Notes:

  • The research applies to all four of the Sega Mega Drive games and Sonic CD.
  • This guide relies on information about tiles and sensors discussed in Solid Tiles.
  • This page is essentially part 2 of 2. This details Player physics when on slopes and specific methods of collision with steep slopes such as walls and ceilings. For part 1, describing specifics & basics of Player and Solid Tile collision, go to Slope Collision.

Introduction

Once you have the Player object able to collide with solid tiles, they need to move correctly over the terrain surface with momentum and physics. Knowing how sensors work will allow the Player move smoothly over terrain with different heights, and knowing how the Player's ground speed is affected by inputs to walk will allow them to move left and right, but that is not all there is to the engine. This guide will explain how the Player reacts to certain angles, and how 360 degree movement with momentum is achieved.

Slope Momentum

The Player's movement across the stage has to be influenced by angled ground in order to feel realistic.

Moving Along Slopes

Constant Value
acceleration_speed 0.046875 (12 subpixels)
deceleration_speed 0.5 (128 subpixels)
friction_speed 0.046875 (12 subpixels)
top_speed 6
gravity_force 0.21875 (56 subpixels)

In order for angled movement to be accurate, we need to make sure that the Player does not traverse an incline slope in the same amount of time as walking over flat ground of an equal width.

If Sonic were a simple "slope-less" platformer that required nothing but flat blocks, you would only need two speed variables: X Speed and Y Speed, the horizontal and vertical components of the Player's velocity. acceleration_speed, deceleration_speed, and friction_speed are added to X Speed; jump/bounce velocity and gravity_force are added to Y Speed (when the Player is in the air).

But when slopes are involved, while the Player moves along a slope, they're moving both horizontally and vertically. This means that both X Speed and Y Speed have a non-zero value. Simply adding acceleration_speed, deceleration_speed, or friction_speed to X Speed no longer works; imagine the Player was trying to run up a wall - adding to their horizontal speed would be useless because they need to move upward.

The trick is to employ a third speed variable (as the original engine does), Ground Speed. This is the speed of the Player along the ground, disregarding Ground Angle altogether. acceleration_speed, deceleration_speed, and friction_speed are applied to Ground Speed, not X Speed or Y Speed.

While on the ground, X Speed and Y Speed are entirely derived from Ground Speed every step before the Player is moved. Perhaps a code example is in order:

// Calculate X and Y Speed from Ground Speed
X Speed = Ground Speed * cos(Ground Angle)
Y Speed = Ground Speed * -sin(Ground Angle)

// Actually move via X Speed and Y Speed
X Position += X Speed;
Y Position += Y Speed;

No matter what happens to the Ground Angle, Ground Speed is preserved, so the game always knows what speed the Player is "really" moving at.

What's more, is that the position the Player is moved to with X Speed and Y Speed are where the player will next check for collision with the floor, so it is vital that the next position the player moves to for the next frame's checks aligns as much with the current slope direction as possible.

Slowing Down Uphill And Speeding Up Downhill

By this point, the Player should be able to handle any basic hills with an accurate angular motion, however they still need to slow down when going uphill and to speed up when going downhill. This is essentially a "gravity" being applied while on the ground, and is what makes slopes hard to climb but easy to run down. Fortunately, this is simple to achieve - with something called the Slope Factor.

While the player moves along slopes, a value called Slope Factor is used to modify the Player's Ground Speed. Just subtract Slope Factor * sin(Ground Angle) from Ground Speed at the beginning of every step. This only happens if the Player is not in Ceiling mode.

What is the value of Slope Factor?

Constant Value
slope_factor_normal 0.125 (32 subpixels)
slope_factor_rollup 0.078125 (20 subpixels)
slope_factor_rolldown 0.3125 (80 subpixels)

The value of Slope Factor is always slope_factor_normal when running, but not so when rolling. When the Player is rolling uphill (the sign of Ground Speed is equal to the sign of sin(Ground Angle)), Slope Factor is slope_factor_rollup. When the Player is rolling downhill (the sign of Ground Speed is not equal to the sign of sin(Ground Angle)), Slope Factor is slope_factor_rolldown.

Note:

  • In Sonic 1 and 2, walking/running Slope Factor doesn't get subtracted if the Player is stopped (Ground Speed is 0). But in Sonic 3 & Knuckles, if Ground Speed is 0, the game will still subtract Slope Factor if the value of it is greater than or equal to 0.05078125 (13 subpixels). So that the Player can't stand on steep slopes - it will force them to walk down. Rolling slope factor, however, has no check for if Ground Speed is 0 in any of the games.

360 Degree Movement

So the Player can run over basic hills and ramps and ledges, and all that is great. But it is still not enough. They cannot make their way from the flat ground, up a steeper and steeper slope, to walls and ceilings without more work.

Why not? Well, because in a typical platformer, any ground sensors check straight downward, finding the height of the ground. There is just no way they can handle the transition to walls when everything is built for moving snapping the Player up and down on the Y-axis.

How can we solve this? By using four different modes of movement. This will take a little explaining.

The Four Modes

Each mode is an entire "basic" platform engine. There are 2 modes that align the Player vertically on the Y Axis (Floor mode and Ceiling mode), and 2 modes that align the Player horizontally on the X Axis (Left Wall mode and Right Wall mode).

To better understand, imagine a simpler platformer without full loops, just a few low hills and ramps. To stay aligned with the floor after moving horizontally, all the character would need to do is move up or down until they met the level of the ground. The angle of the floor would then be measured. The angle would be used to attenuate Ground Speed, but nothing more is needed. The character can just horizontally and then be moved straight up and down to adhere to floor level.

Well, this is exactly how the Sonic games do things. These basic platformers are essentially always in "Floor mode". However in Sonic games, when Ground Angle gets too steep, the Player switches mode, moving from Floor mode to Right Wall mode (to Ceiling mode, to Left Wall mode, and back around to Floor mode, etc). At any one time, in any one mode, the Player behaves like a simpler platformer on different axis. The magic happens by combining all four modes, and seamlessly switching between them.

Determining The Mode

The Player's current mode is derived entirely from the current Ground Angle. For example, when walking to the right up a quarter pipe, if Ground Angle is shallower than 46° (223), the player will be in Floor mode. Floor mode behaves more or less like any other kind of platformer, with the ground below the Player, and the Player aligns to the ground vertically.

Then, when Ground Angle reaches a point steeper than 45° (224), the Player will be in Right Wall mode. Here everything is basically the same, only rotated 90 degrees. The ground is to the right of the Player, and the Player aligns to the ground horizontally instead of vertically.

And of course, if Ground Angle then became shallower than 46° (223), the Player would be back in Floor mode.

The other transitions work in exactly the same way. When the mode is being calculated, it simply checks which quadrant the Player's Ground Angle is currently in, which will place the Player in the correct mode (ranges are inclusive):

Mode Angle Range
Floor Mode (start of rotation) 0° (255) to 45° (224)
Right Wall Mode 46° (223) to 134° (161)
Ceiling Mode 135° (160) to 225° (96)
Left Wall Mode 226° (95) to 314° (33)
Floor Mode (end of rotation) 315° (32) to 360° (0)

Mode Collision Changes

Where are the ground sensors when in modes other then Floor mode? Simply put, they change axis to point in the new direction of the ground.

For example, in Right Wall mode they're in exactly the same place, only rotated 90 degrees. Sensor A is now at Y Position + Width Radius instead of X Position - Width Radius. Sensor B is now at Y Position - Width Radius, instead of X Position + Width Radius. Instead of downward vertical sensor, they are now horizontal facing left, at his foot level (which is now "below" them, at X Position + Width Radius). They move and rotate in the same way for the other modes.

Because the sensors move so far, it is possible for the Player to be "popped" out to a new position in the step in which he switches mode. However, this is hardly ever more than a few pixels and really isn't noticeable during normal play.

With these four modes, the Player can go over all sorts of shapes. Inner curves, outer curves, you name them. Here are some approximate example images with their angle values to help give you some idea of what this results in:

SPGInnerCurve.PNG SPGInnerCurveChart.PNG

You can observe Sonic's mode changing after his floor angle (Ground Angle) exceeds 45°. Sonic's position shifts a bit when the mode change occurs, due to the totally new collision angle and position.

SPGOuterCurve.PNG SPGOuterCurveChart.PNG

You may notice the Sonic's mode switches erratically on the convex curve, this is because his floor angle (Ground Angle) will suddenly decrease when switching to wall mode, causing it to switch back and forth until he is far enough down the curve to stabilise. This isn't usually noticeable, and happens less the faster you are moving.

When to Change Mode

If you've checked the guide regarding the Main Game Loop you may notice the mode switching isn't mentioned at all, that's because the game doesn't actually ever "switch" or "update" the Player's mode. The Player's current "mode" is decided right before a collision occurs. It will measure their Ground Angle as described above, and decide which mode of collision to use right there and then. There is no "mode" state stored in memory. So effectively, the Player's mode updates whenever their angle (Ground Angle) does.

Since a new Ground Angle is only calculated as a result of ground collision, the Player's mode for the current frame's ground collision has to use the previous frames angle, even though the Player has moved to a new part of the slope since then. This results in the Player's mode effectively changing 1 frame after the Player reaches one of the diagonal angle thresholds, as seen above.

Falling and Slipping Down Slopes

At this point, slope movement will work rather well, but it's not enough just to slow the Player down on steep slopes. They need to slip down when it gets too steep and you are moving too slowly.

The angle range of slopes for slipping is when your Ground Angle is steeper than 45 degrees:

Range Values
Slipping and Falling

46° (223) to 315° (32)

In addition, the game will check if absolute Ground Speed falls below 2.5 (2 pixels, 128 subpixels).

So, when these conditions are met, what happens? Well, the Player will slip. This achieved by detaching the Player from the floor (clearing the grounded state), setting Ground Speed to 0, and employing the control lock timer.

SPGSlopeSlip.gif Next to Sonic you can see the control lock timer.

Here, when he gets too steep, Sonic detaches from the floor, Ground Speed is set to 0, and control lock timer is set.

But wait, why does Sonic not stop dead in his tracks if he become airbone and Ground Speed was set to 0? Well, if the floor isn't steep enough to freely fall from, the Player will immediately land back onto the floor and the Ground Speed will be restored from X/Y Speed as normal. Landing on the floor and speed conversion is further detailed up ahead in Landing On The Ground)

Okay, what about if the Player is on an even steeper floor?

SPGSlopeFall.gif

You can notice he detaches from the floor and control lock is set. It doesn't tick down until he lands, and even after the timer has begun, when he crosses the gap the timer pauses. The code for both the control lock timer and the slipping are only ran when grounded.

So, what about the timer? When the Player falls or slips off in the manner described above, the control lock timer is set to 30 (it won't begin to count down until the Player lands back on the ground). While this timer is non-zero and the Player is on the ground, it prevents directional input from adjusting the Player's speed with the left or right buttons. The timer counts down by one every step when grounded, so the lock lasts about half a second. During this time only slope_factor_normal and the speed the Player fell back on the ground with is in effect, so the Player will slip back down the slope.

In the above first example gif, you may notice the control lock timer counts down twice, this is purely because Sonic happened to be too steep and too slow still when the timer ended initially, and he slipped once again, seamlessly.

So, with some example code, it works like the following:

// Is player grounded?
if player is grounded
{
    if control_lock_timer == 0
    {
        // Should player slip and fall?
        if abs(Ground Speed) < 2.5 and (Ground Angle is within the slipping and falling range)
        {
            // Detach (fall)
            grounded = false;
            
            // Lock controls (slip)
            Ground Speed = 0;
            control_lock_timer = 30;
        }
    }
    else
    {
        // Tick down timer
        control_lock_timer -= 1; 
    }
}


Sonic 3 Method

Sonic 3 works a little differently, where Sonic will slip down at angles even shallower than 45°, and only detach from the floor when at angles even steeper than 45°.

Range Values
Slipping Ground Angle is within the range 35° (231) to 326° (24) inclusive.
Falling Ground Angle is within the range 69° (207) to 293° (48) inclusive.

Not only are there these new ranges, Ground Speed is now modified by 0.5 instead of being set to 0.

Here's how it works:

// Is the Player grounded?
if player is grounded
{
    if control_lock_timer == 0
    {
        // Should player slip?
        if abs(Ground Speed) < 2.5 and (Ground Angle is within slip range)
        {
            // Lock controls (slip)
            control_lock_timer = 30;
            
            // Should player fall?
            if (Ground Angle is within fall range)
            {
                // Detach (fall)
                grounded = false;
            }
            else
            {
                // Depending on what side of the player the slope is, add or subtract 0.5 from Ground Speed to slide down it
                if Ground Angle < 180°
                {
                    Ground Speed -= 0.5;
                }
                else
                {
                    Ground Speed += 0.5;
                }
            }
        }
    }
    else
    {
        // Tick down timer
        control_lock_timer -= 1; 
    }
}

Landing On The Ground

While the Player is grounded, both X Speed and Y Speed are constantly derived from Ground Speed. When they fall or otherwise leave the ground, X Speed and Y Speed are already the correct values for them to continue their trajectory through the air. But when they land back on the ground, a new Ground Speed value must be calculated from the X Speed and Y Speed that they have upon impact.

While airborne moving downwards the moment your airborne Ground Sensors collide with the floor, a winning angle value is found by the airborne Ground Sensors, and the Player will land. In the same way, when you are moving upwards and your Ceiling Sensors collide with a ceiling, a winning angle value is found by the Ceiling Sensors, and the Player will attempt to land.

Notes:

  • This section describes physics during the moment the Player collides with floors and ceilings while airborne, and then transitions from being airborne to being grounded. For how the Player generally collides with the terrain while grounded, see Ground Sensors and 360 Degree Movement, and for slope physics & momentum while grounded, see Slope Momentum.
  • This section explains the physics side of things, for more information about the collision side of things, see Landing On A Floor and Landing On A Ceiling.
  • Some of the reactions described ahead are in part determined by what direction the Player was moving in the air, which is the same calculation as noted in Airborne Sensor Activation.

When Falling Downward

When the Player lands on a floor, they will become grounded, a winning angle will be found by the sensors, and based on this angle, Ground Speed will be set differently.

SPGLandFloor.png

The following ranges are inclusive.

Range Values Result

Shallow

0° (255) to 23° (240)

and mirrored: 339° (15) to 360° (0)

The floor landed on is very flat, so Ground Speed can just be set based on the Player's X Speed:

Ground Speed is set to the value of X Speed. Ground Angle is set to the angle found by the floor sensors.

Slope

24° (239) to 45° (224)

and mirrored: 316° (31) to 338° (16)

The slope landed on is slightly steep, so it will use X Speed if the Player was moving horizontally, but will calculate a new Ground Speed based on half of Y Speed if they were moving down:

When moving mostly left or mostly right, Ground Speed is set to X Speed. Otherwise, Ground Speed is set to Y Speed * 0.5 * -sign(sin(Ground Angle)). Ground Angle is set to the angle found by the floor sensors.

Steep Slope

46° (223) to 90° (192)

and mirrored: 271° (63) to 315° (32)

The slope landed on is very steep, so it will use X Speed if the Player was moving horizontally, but will calculate a new Ground Speed based on Y Speed if they were moving down:

When moving mostly left or mostly right, Ground Speed is set to X Speed. Otherwise, Ground Speed is set to Y Speed * -sign(sin(Ground Angle)). Ground Angle is set to the angle found by the floor sensors.

When Going Upward

When the Player lands on a ceiling, a winning angle will be found by the sensors, and based on this angle, the reaction will be different.

SPGCeilingLand.gif

When the Player contacts a steep slope above them, they will land and continue along it. Otherwise, they will simply bump their head.

SPGLandCeiling.png

The following ranges are inclusive.

Range Values Result

Slope

91° (191) to 135° (160)

and mirrored: 226° (95) to 270° (64)

The ceiling is quite steep and can be smoothly landed on:

The Player reattaches to the ceiling (becomes grounded) and Ground Speed is set to Y Speed * -sign(sin(Ground Angle)). Ground Angle is set to the angle found by the ceiling sensors.

Ceiling

136° (159) to 225° (96)

The ceiling is too flat to land on:

The Player simply bumps their head on the ceiling, and doesn't reattach to it. Y Speed is set to 0, and X Speed/Ground Speed/Ground Angle are unaffected.

Notes

  • This page is essentially part 2 of 2. This details Player physics when on slopes and specific methods of collision with steep slopes such as walls and ceilings. For part 1, describing specifics & basics of Player and Solid Tile collision, go to Slope Collision.