Actions

Difference between revisions of "SPG:Solid Tiles"

From Sonic Retro

m (Slope factor should be subtracted)
m
Line 1: Line 1:
 
'''Notes:'''
 
'''Notes:'''
 +
The research applies to all four of the [[Sega Mega Drive]] games and ''[[Sonic CD]]''.
  
Research applies to all four of the [[Sega Mega Drive]] games, and ''[[Sonic CD]]''.
+
Following only describes how [[Sonic the Hedgehog|Sonic]] collides and interacts with solid tiles. Solid objects, such as [[Monitor|Monitors]], Moving Platforms, and Blocks each have their own collision routines with Sonic and don't necessarily behave exactly the same as the tiles do.
  
The following only describes how [[Sonic the Hedgehog|Sonic]] collides and interacts with solid tiles. Solid objects, such as [[Monitor|Monitors]], Moving Platforms, and Blocks each have their own collision routines with Sonic, and don't necessarily behave exactly the same as the tiles do.
+
Degree angles are counterclockwise with 0 facing right (flat floor).
 
 
Degree angles are counter clockwise with 0 facing right (flat floor).
 
  
 
[[Image:SPGAngles2.png]]
 
[[Image:SPGAngles2.png]]
Line 17: Line 16:
  
 
  <nowiki>//Variables
 
  <nowiki>//Variables
xpos: the x coordinate of sonic's centre
+
xpos: The X-coordinate of Sonic's center.
ypos: the y coordinate of sonic's centre
+
ypos: The Y-coordinate of Sonic's center.
xsp: the speed in which sonic is moving horizontally
+
xsp: The speed at which Sonic is moving horizontally.
ysp: the speed in which sonic is moving vertically
+
ysp: The speed at which Sonic is moving vertically.
gsp: the speed in which sonic is moving on the ground
+
gsp: The speed at which Sonic is moving on the ground.
slope: the current slope factor (slp) value being used
+
slope: The current slope factor (slp) value being used.
ang: sonic's angle on the ground
+
ang: Sonic's angle on the ground.
 
 
 
//Constants
 
//Constants
Line 30: Line 29:
 
frc: 0.046875 (same as acc)
 
frc: 0.046875 (same as acc)
 
top: 6
 
top: 6
jmp: 6.5 (6 for knuckles)
+
jmp: 6.5 (6 for Knuckles)
 
slp: 0.125
 
slp: 0.125
 
slprollup: 0.078125
 
slprollup: 0.078125
Line 38: Line 37:
  
 
==Sensors==
 
==Sensors==
Collision is handled using 'sensor lines' that surround Sonic. They will be explained and referenced throughout this section.
+
The collision is handled using 'sensor lines' that surround Sonic. They will be explained and referenced throughout this section.
  
 
[[Image:SPGSensors.png]]
 
[[Image:SPGSensors.png]]
Line 44: Line 43:
  
 
   A & B - Floor collision
 
   A & B - Floor collision
   C & D - Ceiling collision (in air only)
+
   C & D - Ceiling collision (only used mid-air)
   E & F - Wall collision (shift by 8px depending on certain factors, which will be explained)
+
   E & F - Wall collision (shifting by 8px depending on certain factors, which will be explained)
 
   XY - Sonic's xpos and ypos
 
   XY - Sonic's xpos and ypos
  
 
==Introduction==
 
==Introduction==
  
What are solid tiles? While there are often solid objects in Sonic zones, the zone itself would require far too much object memory if the environment were constructed entirely of solid objects, each with their own 64 bytes of RAM. A clever short-cut is used - the zone is constructed out of tiles, anyway, so all that needs be done is have each tile know whether or not it is solid.
+
What are solid tiles? While there are often solid objects in Sonic zones, the zone itself would require far too much object memory if the environment were constructed entirely of solid objects, each with their own 64 bytes of RAM. A clever short-cut is used - the zone is constructed out of tiles anyway, so all that needs be done is have each tile know whether or not it is solid.
  
You may know that zones are broken down into 128x128 pixel chunks (or 256x256 pixel chunks in ''[[Sonic 1]]'' and ''[[Sonic CD]]''), which are in turn broken into 16x16 pixels tiles, which are again in turn broken into even smaller 8x8 pixel tiles. All of the solidity magic happens with the 16x16 tiles, so those are the only ones we'll be interested in throughout this guide.
+
You may know that zones are broken down into 128x128 pixel chunks (or 256x256 pixel chunks in ''[[Sonic 1]]'' and ''[[Sonic CD]]''), which are in turn broken into 16x16 pixels tiles, which are again in turn broken into even smaller 8x8 pixel tiles. All of the solidity magic happens with the 16x16 tiles, so those are the only ones we will be interested in throughout this guide.
  
It's Sonic's collisions and interactions with these solid tiles that makes up his basic engine. They dictate how he handles floors, walls, ceilings, slopes, and loops. Because this is such a large subject, and so complex, this guide is more proximate than other Sonic Physics Guides, but I've kept speculation to a minimum.
+
Sonic's collisions and interactions with these solid tiles are what make up his basic engine. They dictate how he handles floors, walls, ceilings, slopes, and loops. Because this is such a large subject, and so complex, this guide is more proximate than other Sonic Physics Guides, but I have kept speculation to a minimum.
  
Note: While solidity tiles are used in the original games, these basic collision methods & sensor layouts will still work (with adjustments) with sprite masks, or line intersections, etc, in your own engine.
+
Note: While solidity tiles are used in the original games, these basic collision methods and sensor layouts will still work (with adjustments) with sprite masks, or line intersections, etc, in your own engine.
  
 
==Standing==
 
==Standing==
  
Sonic has to check to check for Solid tiles beneath him. This can be achieved with two sensor lines, pointing downward. One (A) should be on Sonic's left side, at ''xpos''-9. The other (B) should be on his right, at ''xpos''+9. They should start at ''ypos'' and extend to his feet at ''ypos''+20. They should also check at least 16 pixels below his feet at ground level while not in the air (but not too far, or he'll pop down when descending low steps and stairs, which you don't want). This extra space checked is to keep him attached to the ground even if it slopes away from him as he moves horizontally.
+
Sonic has to check to check for solid tiles beneath him. This can be achieved with two sensor lines, pointing downward. One (A) should be on Sonic's left side, at ''xpos''-9. The other (B) should be on his right, at ''xpos''+9. They should start at ''ypos'' and extend to his feet at ''ypos''+20. They should also check at least 16 pixels below his feet at ground level while not in the air (but not too far, or he will pop down when descending low steps and stairs, which you do not want). This extra space checked is to keep him attached to the ground even if it slopes away from him as he moves horizontally.
  
When Sonic is rolling or jumping, the A B C and D sensors are at ''xpos''-7 and ''xpos''+7 rather than ''xpos''-9 and ''xpos''+9. However, his horizontal sensor line remains the same whether curled up or not.
+
When Sonic is rolling or jumping, sensor A, B, C, and D are at ''xpos''-7 and ''xpos''+7 rather than ''xpos''-9 and ''xpos''+9. However, his horizontal sensor line remains the same whether curled up or not.
  
 
[[Image:SPGStanding.PNG|128px]]
 
[[Image:SPGStanding.PNG|128px]]
  
Assuming the ground level to be at a Y position of 736 ($02E0), Sonic stands atop it at a ''ypos'' of 716 ($02CC). That's 20 pixels above ground level.
+
Assuming the ground level to be at a Y position of 736 ($02E0), Sonic stands atop it at a ''ypos'' of 716 ($02CC), which are 20 pixels above ground level.
  
 
===Falling Off===
 
===Falling Off===
  
Sonic has to be able to run off of ledges. It wouldn't do to just keep walking like Wile E. Coyote, not noticing that there's nothing beneath him.
+
Sonic has to be able to run off of ledges. It would not do to just keep walking like Wile E. Coyote, not noticing that there is nothing beneath him.
  
If both the A and B sensors detect no solid tiles, Sonic will "fall" - a flag will be set telling the engine he's now in the air.
+
If both sensor A and B detect no solid tiles, Sonic will "fall" - a flag will be set telling the engine he is now in the air.
  
 
===Balancing On Edges===
 
===Balancing On Edges===
  
One nice touch is that Sonic goes into a balancing animation when near to the edge of a ledge. This only happens when he's stopped (his ground speed is 0).
+
One nice touch is that Sonic goes into a balancing animation when near to the edge of a ledge. This only happens when he is stopped (his ground speed is 0).
  
How does the engine know? It's simple - any time only one of the ground sensors is activated, Sonic must be near a ledge. If A is active and B is not, the ledge is to his right. If vice versa, the ledge is to his left.
+
How does the engine know? It is simple - any time only one of the ground sensors is activated, Sonic must be near a ledge. If A is active and B is not the ledge is to his right and vice versa.
  
But if Sonic began balancing the instant one of the sensors found nothing, he'd do it too "early", and it would look silly. So it only happens when only one sensor is active, and ''xpos'' is greater than the edge of the solid tile found by the active sensor.
+
But if Sonic began balancing the instant one of the sensors found nothing, he would do it too "early", and it would look silly. So it only happens when only one sensor is active, and ''xpos'' is greater than the edge of the solid tile found by the active sensor.
  
 
[[Image:SPGBalancing.PNG|384px]]
 
[[Image:SPGBalancing.PNG|384px]]
  
Assuming the right edge of the ledge to be an x of 2655 ($0A5F), Sonic will only start to balance at an ''xpos'' of 2656 ($0A60) (edge pixel+1). He'll fall off at an ''xpos'' of 2665 ($0A69) (edge pixel+10), when both sensors find nothing.
+
Assuming the right edge of the ledge to be an x of 2655 ($0A5F), Sonic will only start to balance at an ''xpos'' of 2656 ($0A60) (edge pixel+1). He'll fall off at an ''xpos'' of 2665 ($0A69) (edge pixel+10) when both sensors find nothing.
  
 
In ''[[Sonic 2]]'' and ''[[Sonic CD]]'', if the ledge is the opposite direction than he is facing, he has a second balancing animation.
 
In ''[[Sonic 2]]'' and ''[[Sonic CD]]'', if the ledge is the opposite direction than he is facing, he has a second balancing animation.
  
In ''[[Sonic 2]]'', ''[[Sonic 3]]'', and ''[[Sonic & Knuckles]]'', Sonic has yet a ''third'' balancing animation, for when he's even further out on the ledge. Assuming the same values as above, this would start when he's at an ''xpos'' of 2662 ($0A66).
+
In ''[[Sonic 2]]'', ''[[Sonic 3]]'', and ''[[Sonic & Knuckles]]'', Sonic has yet a ''third'' balancing animation, for when he's even further out on the ledge. Assuming the same values as above, this would start when he is at an ''xpos'' of 2662 ($0A66).
  
'''Note:''' While balancing, certain abilities are not allowed (ducking, looking up, spindashing, etc). In Sonic 3 & Knuckles, the player is still allowed to duck and spindash (but not to look up) when balancing on ground, but not when balancing on an object.
+
'''Note:''' While balancing, certain abilities are not allowed (ducking, looking up, spindashing, etc). In Sonic 3 & Knuckles, the player is still allowed to duck and spindash (not to look up, though) when balancing on the ground but not when balancing on an object.
  
 
==Pushing==
 
==Pushing==
Line 100: Line 99:
 
[[Image:SPGPushing.PNG|256px]]
 
[[Image:SPGPushing.PNG|256px]]
  
Assuming the wall's left side to be at an X position of 704 ($02C0), Sonic can't get closer than an ''xpos'' of 693 ($02B5). Assuming the wall's right side to be at an X position of 831 ($033F), Sonic can't get closer than an ''xpos'' of 842 ($034A). That's 11 pixels difference, in either direction.
+
Assuming the wall's left side to be at an X position of 704 ($02C0), Sonic cannot get closer than an ''xpos'' of 693 ($02B5). Assuming the wall's right side to be at an X position of 831 ($033F), Sonic cannot get closer than an ''xpos'' of 842 ($034A). That's 11 pixels difference, in either direction.
  
Thus the sensor line should be 20 pixels wide, stretching from Sonic's ''xpos''-10 to ''xpos''+10. Any time it detects a solid tile, Sonic should be "popped out", set to the edge of the tile minus (or plus) 11, and his ground speed set to 0. (He can't be popped out by only 10, because then a point at ''xpos''+10 would still lie within the edge pixel of the tile. This would register a continuous collision, and he'd stick to the wall.)  
+
Thus the sensor line should be 20 pixels wide, stretching from Sonic's ''xpos''-10 to ''xpos''+10. Any time it detects a solid tile, Sonic should be "popped out", set to the edge of the tile minus (or plus) 11, and his ground speed set to 0. (He cannot be popped out by only 10, because then a point at ''xpos''+10 would still lie within the edge pixel of the tile. This would register a continuous collision, and he would stick to the wall.)  
  
 
Though the tile's edge minus Sonic's ''xpos'' might be 11, there are only 10 free pixels between Sonic's ''xpos'' and the tile's edge. The eleventh pixel away is the tile's edge itself. So Sonic is effectively only 20 pixels wide.
 
Though the tile's edge minus Sonic's ''xpos'' might be 11, there are only 10 free pixels between Sonic's ''xpos'' and the tile's edge. The eleventh pixel away is the tile's edge itself. So Sonic is effectively only 20 pixels wide.
  
You may remember that the A & B ground sensors are only 18 pixels apart, but Sonic is 20 pixels wide when pushing into walls. So Sonic is skinnier by 2 pixels when running off of ledges than when bumping into walls.
+
You may remember that sensors A and B are only 18 pixels apart but Sonic is 20 pixels wide when pushing into walls. This means that Sonic is skinnier by 2 pixels when running off of ledges than when bumping into walls.
  
 
==Slopes And Curves==
 
==Slopes And Curves==
  
''Sonic the Hedgehog'' was one of the first games to use curved surfaces and even entire 360 degree loops. Most other games of the era composed their environments entirely of blocks (and the occasional ramp).
+
''Sonic the Hedgehog'' was one of the first games to use curved surfaces and even entire 360-degree loops. Most other games of the era composed their environments entirely of blocks (and the occasional ramp).
  
 
The ability to cope with smoothly shaped environments is one of the fundamental aspects of the Sonic games' novelty and appeal. Unfortunately, it is also perhaps the most difficult and complex aspect to recreate in a fan game.
 
The ability to cope with smoothly shaped environments is one of the fundamental aspects of the Sonic games' novelty and appeal. Unfortunately, it is also perhaps the most difficult and complex aspect to recreate in a fan game.
Line 118: Line 117:
 
===Height Masks===
 
===Height Masks===
  
Any time the A or B sensors find a solid tile, they return the height of that tile.
+
Any time Sensor A or B find a solid tile, they return the height of that tile.  
  
 
How is the height of the tile found?
 
How is the height of the tile found?
  
Each tile has a value associated with it that references a mask stored in memory. Each mask is simply an array of 16 height values that range from $00 to $10, and an angle value.
+
Each tile has a value associated with it that references a mask stored in memory. Each mask is simply an array of 16 height values that range from $00 to $10 and an angle value.
  
 
[[Image:SPGHeightMask.PNG]]
 
[[Image:SPGHeightMask.PNG]]
Line 140: Line 139:
 
Unfortunately, there are a couple of annoying bugs in the original engine because of this method.
 
Unfortunately, there are a couple of annoying bugs in the original engine because of this method.
  
If Sonic stands on a slanted ledge, one sensor will find no tile, and return a height of foot level. This causes Sonic to be set to the wrong position.
+
If Sonic stands on a slanted ledge, one sensor will find no tile and return a height of foot level. This causes Sonic to be set to the wrong position.
  
 
[[Image:SPGSlopeBug1.PNG|384px]]
 
[[Image:SPGSlopeBug1.PNG|384px]]
  
Sonic raises up with the B sensor as he moves right. When B drops off the ledge, Sonic defaults to the level of the A sensor. Then he raises up with the A sensor as he moves further right. So he'll move up, drop down, and move up again as he runs off the ledge.
+
Sonic raises up with sensor B sensor as he moves right. When B drops off the ledge, Sonic defaults to the level of sensor A. Then he raises up with sensor A as he moves further right. So he will move up, drop down, and move up again as he runs off the ledge.
  
There are few areas where this is noticeable, but it's true in all the Mega Drive titles, and it's pretty tacky.
+
There are only a few areas where this is noticeable, but it applies to all Mega Drive titles and is pretty tacky.
  
A second form of it occurs when two opposing ramp tiles abut each other, as in some of the low hills in [[Green Hill Zone]] and [[Marble Zone]].
+
The second form of it occurs when two opposing ramp tiles abut each other, as in some of the low hills in [[Green Hill Zone]] and [[Marble Zone]].
  
 
[[Image:SPGSlopeBug2.PNG|384px]]
 
[[Image:SPGSlopeBug2.PNG|384px]]
  
The B sensor starts climbing down the ramp on the right, but Sonic still defaults to the level of the previous ramp found by the A sensor. Because these ramps are usually shallow, this only causes him to dip down in the middle by about 1 pixel.
+
Sensor B starts climbing down the ramp on the right, but Sonic still defaults to the level of the previous ramp found by sensor A. Because these ramps are usually shallow, this only causes him to dip down in the middle by about 1 pixel.
  
But that's not all. Because the highest sensor is the one Sonic gets the angle from, even though it looks like he should be considered to be at the angle of the ramp on the right (because he's closer to it), he'll still have the angle of the ramp on the left. When you jump, he'll jump at that angle, moving backward, not forward like you'd expect.
+
But that is not all. Because the highest sensor is the one Sonic gets the angle from, even though it looks like he should be considered to be at the angle of the ramp on the right (because he is closer to it), he will still have the angle of the ramp on the left. When you jump, he will jump at that angle, moving backward, not forward like you would expect.
  
 
===Moving At Angles===
 
===Moving At Angles===
  
Well, that's all very well and good for having Sonic move smoothly over terrain with different heights. But's that's not all there is to the engine. Sonic's speed has to be attenuated by angled ground in order to be realistic.
+
Well, that is all very well and good for having Sonic move smoothly over terrain with different heights, but that is not all there is to the engine. Sonic's speed has to be attenuated by angled ground in order to be realistic.
  
There are two ways in which Sonic's speed is affected on angles. The first makes sure that he doesn't traverse a hill in the same amount of time as walking over flat ground of an equal width. The second slows him when going uphill, and speeds him up when going downhill. Let's look at each of these in turn.
+
There are two ways in which Sonic's speed is affected on angles. The first will make sure that he does not traverse a hill in the same amount of time as walking over flat ground of an equal width. The second will slow him down when going uphill and speed him up when going downhill. Let's look at each of these in turn.
  
 
====The Three Speed Variables====
 
====The Three Speed Variables====
Line 166: Line 165:
 
If Sonic were a simple platformer that required nothing but blocks, you would only need two speed variables: X speed (''xsp'') and Y speed (''xsp''), the horizontal and vertical components of Sonic's velocity. Acceleration (''acc''), deceleration (''dec''), and friction (''frc'') are added to ''xsp''; jump/bounce velocity and gravity (''grv'') are added to ''ysp'' (when Sonic is in the air).
 
If Sonic were a simple platformer that required nothing but blocks, you would only need two speed variables: X speed (''xsp'') and Y speed (''xsp''), the horizontal and vertical components of Sonic's velocity. Acceleration (''acc''), deceleration (''dec''), and friction (''frc'') are added to ''xsp''; jump/bounce velocity and gravity (''grv'') are added to ''ysp'' (when Sonic is in the air).
  
But when slopes are involved, while Sonic moves along a slope, he's moving both horizontally and vertically. This means that both ''xsp'' and ''xsp'' have a non-zero value. Simply adding ''acc'', ''dec'', or ''frc'' to ''xsp'' no longer works; imagine Sonic was trying to run up a wall - adding to his horizontal speed would be useless, because he needs to move upward.
+
But when slopes are involved, while Sonic moves along a slope, he's moving both horizontally and vertically. This means that both ''xsp'' and ''xsp'' have a non-zero value. Simply adding ''acc'', ''dec'', or ''frc'' to ''xsp'' no longer works; imagine Sonic was trying to run up a wall - adding to his horizontal speed would be useless because he needs to move upward.
  
 
The trick is to employ a third speed variable (as the original engine does), so let's call it Ground speed (''gsp''). This is the speed of Sonic along the ground, disregarding ''ang'' altogether. ''acc'', ''dec'', and ''frc'' are applied to ''gsp'', not ''xsp'' or ''ysp''.
 
The trick is to employ a third speed variable (as the original engine does), so let's call it Ground speed (''gsp''). This is the speed of Sonic along the ground, disregarding ''ang'' altogether. ''acc'', ''dec'', and ''frc'' are applied to ''gsp'', not ''xsp'' or ''ysp''.
Line 182: Line 181:
 
====Slope Factor====
 
====Slope Factor====
  
By this point, Sonic ought to be able to handle any hills with an accurate velocity. But he still needs to be slowed when going uphill, and sped up when up going downhill.
+
By this point, Sonic should be able to handle any hills with an accurate velocity but he still needs to slow down when going uphill and speed up when going downhill.
  
 
Fortunately, this is simple to achieve - with something called the Slope Factor (''slope''). Just subtract ''slope''*sin(''ang'') from ''gsp'' at the beginning of every step.  
 
Fortunately, this is simple to achieve - with something called the Slope Factor (''slope''). Just subtract ''slope''*sin(''ang'') from ''gsp'' at the beginning of every step.  
Line 188: Line 187:
 
   gsp -= slope*sin(ang);
 
   gsp -= slope*sin(ang);
  
The value of ''slope'' is always ''slp'' when running, but not so when rolling. When Sonic is rolling uphill (the sign of ''gsp'' is equal to the sign of sin(''ang'')), ''slope'' is ''slprollup'' ($001E). When Sonic is rolling downhill (the sign of ''gsp'' is '''not''' equal to the sign of sin(''ang'')), ''slope'' is ''slprolldown'' ($0050).
+
The value of ''slope'' is always ''slp'' when running, but not so when rolling. When Sonic is rolling uphill (the sign of ''gsp'' is equal to the sign of sin(''ang'')), ''slope'' is ''slprollup'' ($001E). When Sonic is rolling downhill (the sign of ''gsp'' is '''not''' equal to the sign of sin(''ang'')), ''slope'' is ''slprolldown'' ($0050).
  
'''Note:''' In Sonic 1, it appears that ''slope'' doesn't get added if Sonic is stopped, and in his standing/waiting cycle. But in Sonic 3 & Knuckles, ''slope'' seems to be added even then, so that Sonic can't stand on steep slopes - they'll force him to walk backward down them.
+
'''Note:''' In Sonic 1, it appears that ''slope'' doesn't get added if Sonic is stopped and in his standing/waiting cycle. But in Sonic 3 & Knuckles, ''slope'' seems to be added even then, so that Sonic can't stand on steep slopes - they will force him to walk them down.
  
 
===Jumping At Angles===
 
===Jumping At Angles===
Line 205: Line 204:
 
==Switching Mode==
 
==Switching Mode==
  
So Sonic can run over hills and ramps and ledges, and all that's great. But it's ''still'' not enough. He can't make his way from the ground to walls and ceilings without more work.
+
So Sonic can run over hills and ramps and ledges, and all that is great. But it is ''still'' not enough. He cannot make his way from the ground to walls and ceilings without more work.
  
Why not? Well, because the A and B ground sensors check straight downward, finding the height of the ground. There's just no way they can handle the transition to walls when everything is built for moving straight up and down on the Y axis.
+
Why not? Well, because sensor A and B 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 straight 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.
 
How can we solve this? By using four different modes of movement. This will take a little explaining.
Line 215: Line 214:
 
It seems pretty reasonable to assume that, because Sonic can traverse ground in 360 degrees, the engine handles all 360 degrees in much the same way. But, in fact, the engine splits the angles into four quadrants, greatly simplifying things.
 
It seems pretty reasonable to assume that, because Sonic can traverse ground in 360 degrees, the engine handles all 360 degrees in much the same way. But, in fact, the engine splits the angles into four quadrants, greatly simplifying things.
  
To better understand what I'm talking about, imagine a simpler platformer without full loops, just a few low hills and ramps. All the character would need to do is, after moving horizontally, move up or down until they met the level of the floor. The angle of the floor would then be measured. The angle would be used to attenuate ''Gsp'', but nothing more. The character would still always move horizontally, and move straight up and down to adhere to floor level.
+
To better understand what I am talking about, imagine a simpler platformer without full loops, just a few low hills and ramps. All the character would need to do is, after moving horizontally, move up or down until they met the level of the floor. The angle of the floor would then be measured. The angle would be used to attenuate ''gsp'', but nothing more. The character would still always move horizontally and move straight up and down to adhere to floor level.
  
 
This is much like how Sonic does things. Only, when ''ang'' gets too steep, Sonic switches "quadrant", 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, Sonic behaves like a simpler platformer. The magic happens by combining all four modes, and cleverly switching between them smoothly.
 
This is much like how Sonic does things. Only, when ''ang'' gets too steep, Sonic switches "quadrant", 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, Sonic behaves like a simpler platformer. The magic happens by combining all four modes, and cleverly switching between them smoothly.
Line 236: Line 235:
 
You might rightly ask where the ground sensors are when in Right Wall mode. They're in exactly the same place, only rotated 90 degrees. Sensor A is now at Sonic's ''ypos''+9 instead of ''xpos''-9. Sensor B is now at Sonic's ''ypos''-9, instead of ''xpos''+9. Instead of vertical sensor lines, they are now horizontal, stretching 16 pixels beyond his foot level (which is now 20 pixels "below" him, at ''xpos''+20).
 
You might rightly ask where the ground sensors are when in Right Wall mode. They're in exactly the same place, only rotated 90 degrees. Sensor A is now at Sonic's ''ypos''+9 instead of ''xpos''-9. Sensor B is now at Sonic's ''ypos''-9, instead of ''xpos''+9. Instead of vertical sensor lines, they are now horizontal, stretching 16 pixels beyond his foot level (which is now 20 pixels "below" him, at ''xpos''+20).
  
Yes, because the sensors move so far, it is possible for Sonic 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 at all during normal play. To adjust for this in a new engine, an alternative method to switch mode would be to check for solid ground using a 90 degree rotated mask. For example, standing upright on flat ground, the left side would check rotated 90 degrees for steep slopes to switch to Left Wall Mode, and the right would check rotated -90 degrees for steep slopes to switch to Right Wall Mode. Only the lower ground sensor of the rotated mask would need to check for ground. This would have to exclude walls so Sonic doesn't begin walking on a wall when he gets near one, but would mean Sonic switched mode sooner on a slope meaning less "popping".
+
Yes, because the sensors move so far, it is possible for Sonic 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 at all during normal play. To adjust for this in a new engine, an alternative method to switch mode would be to check for solid ground using a 90 degree rotated mask. For example, standing upright on flat ground, the left side would check rotated 90 degrees for steep slopes to switch to Left Wall Mode, and the right would check rotated -90 degrees for steep slopes to switch to Right Wall Mode. Only the lower ground sensor of the rotated mask would need to check for ground. This would have to exclude walls so Sonic doesn't begin walking on a wall when he gets near one, but would mean Sonic switched mode sooner on a slope which means less "popping".
  
 
One more thing: I said that solid tiles were made of height arrays. Operative word: ''height''. How do they work when in Right Wall mode? Well, rather gobsmackingly, it turns out that in the original engine, each solid tile has ''two'' complementary height arrays, one used for when moving horizontally, the other for when moving vertically.
 
One more thing: I said that solid tiles were made of height arrays. Operative word: ''height''. How do they work when in Right Wall mode? Well, rather gobsmackingly, it turns out that in the original engine, each solid tile has ''two'' complementary height arrays, one used for when moving horizontally, the other for when moving vertically.
Line 250: Line 249:
 
===Falling and Sliding Off Of Walls And Ceilings===
 
===Falling and Sliding Off Of Walls And Ceilings===
  
When in Right Wall, Left Wall, or Ceiling mode and Sonic's ''ang'' is between 90 and 270, Sonic will fall any time absolute ''gsp'' falls below ''fall'' ($0280) (''gsp'' is set to 0 at this time, but ''xsp'' and ''ysp'' are unaffected, so Sonic will continue his trajectory through the air). This happens even if there is ground beneath him. If Sonic is in Right Wall, Left Wall, or Ceiling Mode but Sonic's ''ang'' is not between 90 and 270 then the horizontal control lock timer described below will still be set to 30 but Sonic will not enter a fall state remaining in his current state.
+
When in Right Wall, Left Wall, or Ceiling mode and Sonic's ''ang'' is between 90 and 270, Sonic will fall any time absolute ''gsp'' falls below ''fall'' ($0280) (''gsp'' is set to 0 at this time, but ''xsp'' and ''ysp'' are unaffected, so Sonic will continue his trajectory through the air). This happens even if there is ground beneath him. If Sonic is in Right Wall, Left Wall, or Ceiling Mode but Sonic's ''ang'' is not between 90 and 270 then the horizontal control lock timer described below will still be set to 30 but Sonic will not enter a falling state remaining in his current state.
  
 
====Horizontal Control Lock====
 
====Horizontal Control Lock====
  
When Sonic falls or slides off in the manner described above, the [[SPG:Springs and Things#Horizontal Control Lock|horizontal control lock]] timer is set to 30 ($1E) (it won't begin to count down until Sonic lands back on the ground). While this timer is non-zero and Sonic is on the ground, it prevents the player from adjusting Sonic's speed with the left or right buttons. The timer counts down by 1 every step, so the lock lasts about half a second. During this time only ''slp'' and the speed Sonic fell back on the ground with are in effect, so Sonic will slip back down the slope.
+
When Sonic falls or slides off in the manner described above, the [[SPG:Springs and Things#Horizontal Control Lock|horizontal control lock]] timer is set to 30 ($1E) (it won't begin to count down until Sonic lands back on the ground). While this timer is non-zero and Sonic is on the ground, it prevents the player from adjusting Sonic's speed with the left or right buttons. The timer counts down by one every step, so the lock lasts about half a second. During this time only ''slp'' and the speed Sonic fell back on the ground with is in effect, so Sonic will slip back down the slope.
  
 
   if (abs(gsp) < 2.5 && floor_mode != 0)  
 
   if (abs(gsp) < 2.5 && floor_mode != 0)  
Line 276: Line 275:
 
====Horizontal Sensor====
 
====Horizontal Sensor====
  
Sonic has to be able to bump into walls, just like when he's on the ground. So there's a horizontal sensor line, originating at his ''ypos'', and stretching from ''xpos''-10 to ''xpos''+10. Anytime it's colliding with a solid tile, Sonic's "popped" out to the edge of the tile plus/minus 11, just like on the ground.
+
Sonic has to be able to bump into walls, just like when he's on the ground. So there's a horizontal sensor line, originating at his ''ypos'', and stretching from ''xpos''-10 to ''xpos''+10. Anytime it is colliding with a solid tile, Sonic's "popped" out to the edge of the tile plus/minus 11, just like on the ground.
  
The thing is, this sensor line is wider than his vertical A and B sensors that detect the ground (we'll be getting to those in a minute). This means it's possible for the horizontal sensor line to detect a block that's Sonic is falling past, even if he has no ''xsp'' at all. This causes him to slip around solids by a pixel or two when he hits them at their extreme edges.
+
The thing is, this sensor line is wider than his vertical A and B sensors that detect the ground (we will be getting to those in a minute). This means it is possible for the horizontal sensor line to detect a block that Sonic is falling past, even if he has no ''xsp'' at all. This causes him to slip around solids by a pixel or two when he hits them at their extreme edges.
  
So when Sonic detects a collision with his horizontal sensor line, his ''xsp'' is only set to 0 if he moving in the direction of the wall, not away from it. If it were otherwise, he'd stick to walls as he fell past them.
+
So when Sonic detects a collision with his horizontal sensor line, his ''xsp'' is only set to 0 if he is moving in the direction of the wall, not away from it. If it were otherwise, he would stick to walls as he fell past them.
  
 
====Vertical Sensors====
 
====Vertical Sensors====
  
Sonic's A and B sensors are much the same in the air as they are on the ground. The difference is, when they detect a solid tile, Sonic isn't immediately set to the height found in the tile minus 20. Instead, he's only set to it if he's ''already'' lower than that height. Otherwise he'd suck to the floor when he got close to it.
+
Sensor A and B are very much the same in the air as they are on the ground. When they detect a solid tile, however, Sonic isn't immediately set to the height found in the tile minus 20. Instead, he is only set to it if he is ''already'' lower than that height. Otherwise, he would stick to the floor when he gets close to it.
  
Since the sensors stretch so far below his feet, what stops them from detecting the ground again in the step in which he jumps, never letting him leave the floor? Simple. He ignores them unless ''ysp'' is 0 or greater, so he'll only detect the ground while moving down.
+
Since the sensors stretch so far below his feet, what stops them from detecting the ground in the same step he jumps, preventing him from leaving the floor? Simple. He ignores them unless ''ysp'' is 0 or greater so that he will only detect the ground while moving down.
  
Because Sonic can move both up and down while in the air, there have to be two more sensors checking upward (C and D), so that he can bump into ceilings and curves that are above him. (C and D are perfect mirror images of A and B - they have the same X position and length, they just point up instead of down.) Sonic will detect ceilings and be pushed out of them whether he's moving up or down, unlike floors which are only detected when moving down. It ''is'' possible to hit a "ceiling" (which is just the bottom side of a block) while moving down - by pressing toward a wall with a gap in it, or jumping toward the side of an upper curve.
+
Because Sonic can move both up and down while in the air, there have to be two more sensors checking upward (Sensors C and D) so that he can bump into ceilings and curves that are above him. C and D mirror A and B perfectly - they have the same X position and length but are flipped upside down) Sonic will detect ceilings and be pushed out of them whether he is moving up or down, unlike floors which are only detected when moving down. It ''is'' possible to hit a "ceiling" (which is just the bottom side of a block) while moving down - by pressing toward a wall with a gap in it, or jumping toward the side of an upper curve.
  
 
===Jumping "Through" Floors===
 
===Jumping "Through" Floors===
  
There are some ledges that Sonic can jump up "through". These are often in the hilly, green zones such as [[Green Hill Zone]], [[Emerald Hill Zone]], [[Palmtree Panic Zone]], and so on. The solid tiles that make up these ledges are flagged by the engine as being a certain type that should only be detected by Sonic's A and B sensors. They're totally ignored by C and D, as well as the horizontal sensor line. Finally, the A & B sensors only detect the floor when Sonic is moving downwards (but always while on the ground). So with a slightly short jump you'll see Sonic 'pop' upwards onto a jump through surface once he begins to fall.
+
There are some ledges that Sonic can jump up "through". These are often in the hilly, green zones such as [[Green Hill Zone]], [[Emerald Hill Zone]], [[Palmtree Panic Zone]], and so on. The solid tiles that make up these ledges are flagged by the engine as being a certain type that should only be detected by Sonic's A and B sensors. They are ignored entirely by C and D as well as the horizontal sensor line. Finally, sensor A and B only detect the floor when Sonic is moving downwards (but always while on the ground). So with a slightly shorter jump, you will see Sonic 'pop' upwards onto a jump through surface once he begins to fall.
  
 
===Reacquisition Of The Ground===
 
===Reacquisition Of The Ground===
''xsp'' and ''ysp'' are derived from ''gsp'' when Sonic is on the ground. When he falls or otherwise leaves the ground, ''xsp'' and ''ysp'' are already the proper values for him to continue his trajectory through the air. But when Sonic lands back on the ground, ''gsp'' must be calculated from the ''xsp'' and ''ysp'' that he has when it happens.
+
Both ''xsp'' and ''ysp'' are derived from ''gsp'' while Sonic is on the ground. When he falls or otherwise leaves the ground, ''xsp'' and ''ysp'' are already the proper values for him to continue his trajectory through the air. But when Sonic lands back on the ground, ''gsp'' must be calculated from the ''xsp'' and ''ysp'' that he has when it happens.
You might think that they'd use cos() and sin() to get an accurate value, but not so. In fact, something much more basic happens, and it's different when hitting into a curved ceiling as opposed to landing on a curved floor, so I'll cover them separately.
+
You might think that they would use cos() and sin() to get an accurate value, but that is not the case. In fact, something much more basic happens, and it is different when hitting into a curved ceiling as opposed to landing on a curved floor, so I will cover them separately.
  
 
As you land the angle of the ground you touch is read (''ang'').
 
As you land the angle of the ground you touch is read (''ang'').
The following covers the angle (''ang'') of the ground (floor or ceiling) that Sonic touches as he lands, and only happens the frame when he lands, when changing from in air to grounded.
+
The following covers the angle (''ang'') of the ground (floor or ceiling) that Sonic touches as he lands, and only happens the frame when he lands when changing from in air to on ground.
  
 
====When Falling Downward====
 
====When Falling Downward====
Line 308: Line 307:
  
 
'''Half Steep:'''
 
'''Half Steep:'''
When ''ang'' is in the range of 22.5°~45° ($E0~$EF) (and mirrored 337.5°~315° ($10~$1F)), ''gsp'' is set to ''xsp'' but only if absolute ''xsp'' is greater than ''ysp''. Otherwise, ''gsp'' is set to ''ysp''*0.5*-sign(sin(''ang'')).  
+
When ''ang'' is in the range of 22.5°~45° ($E0~$EF) (and mirrored 337.5°~315° ($10~$1F)), ''gsp'' is set to ''xsp'' but only if the absolute of ''xsp'' is greater than ''ysp''. Otherwise, ''gsp'' is set to ''ysp''*0.5*-sign(sin(''ang'')).  
  
 
'''Full Steep:'''
 
'''Full Steep:'''
When ''ang'' is in the range of 45°~90° ($C0~$DF) (and mirrored 315°~270° ($20~$3F)), ''gsp'' is set ''xsp'' but only if absolute ''xsp'' is greater than ''ysp''. Otherwise, ''gsp'' is set to ''ysp''*-sign(sin(''ang'')).  
+
When ''ang'' is in the range of 45°~90° ($C0~$DF) (and mirrored 315°~270° ($20~$3F)), ''gsp'' is set to ''xsp'' but only if the absolute of ''xsp'' is greater than ''ysp''. Otherwise, ''gsp'' is set to ''ysp''*-sign(sin(''ang'')).
  
 
====When Going Upward====
 
====When Going Upward====
Line 317: Line 316:
  
 
'''Slope:'''
 
'''Slope:'''
When the ceiling ''ang'' detected is in the range of 135°~90° ($A0~$BF) (and mirrored 270°~225° ($40~$5F)), Sonic reattaches to the ceiling, and ''gsp'' is set to ''ysp''*-sign(sin(''ang'')).
+
When the ceiling ''ang'' detected is in the range of 135°~90° ($A0~$BF) (and mirrored 270°~225° ($40~$5F)), Sonic reattaches to the ceiling and ''gsp'' is set to ''ysp''*-sign(sin(''ang'')).
  
Note: This doesn't allow you to connect to an sloped ceiling and follow it downwards when you are moving horizontally in the air. One example of this is the secret route in CPZ act 2. In your engine, you may wish to use a method similar to when going downwards. If absolute ''xsp'' is greater than negative ''ysp'', set ''gsp'' to negative ''xsp''. Otherwise, use the calculation above.
+
Note: This does not allow you to connect to a sloped ceiling and follow it downwards when you are moving horizontally in the air. One example of this is the secret route in CPZ act 2. In your engine, you may wish to use a method similar to when going downwards. If absolute ''xsp'' is greater than negative ''ysp'', set ''gsp'' to negative ''xsp''. Otherwise, use the calculation above.
  
 
'''Ceiling:'''
 
'''Ceiling:'''
When the ceiling ''ang'' is in the range of 225°~135° ($60~$9F), Sonic hits his head like any ceiling, and doesn't reattach to it. ''ysp'' is set to 0, and ''xsp'' is unaffected.
+
When the ceiling ''ang'' is in the range of 225°~135° ($60~$9F), Sonic hits his head like with any ceiling, and doesn't reattach to it. ''ysp'' is set to 0, and ''xsp'' is unaffected.
  
 
==Reference: Converting Hex Angles==
 
==Reference: Converting Hex Angles==
Line 334: Line 333:
 
==Notes==
 
==Notes==
 
* Sonic can only brake ("screech to a halt") in Floor mode.
 
* Sonic can only brake ("screech to a halt") in Floor mode.
* Sonic can't jump when there is a low ceiling above him. If there is a collision detected with a sensor line stretching from Sonic's ''xpos''-9 to ''xpos''+9, at ''ypos''-25, Sonic won't bother jumping at all.
+
* Sonic cannot jump when there is a low ceiling above him. If there is a collision detected with a sensor line stretching from Sonic's ''xpos''-9 to ''xpos''+9, at ''ypos''-25, Sonic won't bother jumping at all.
* Sonic has a different height at different times. When he's standing, running, falling, or springing from a springboard, he's 40 pixels tall. His ''ypos'' is always his centre, so that's why he stands 20 pixels above the ground (and 20 pixels below ceilings when he hits into them, etc). However, when he's jumping or rolling, he's only 30 pixels tall, and he sets 15 pixels above the ground (and 15 pixels below ceiling, etc). In the step in which Sonic rolls or jumps, the engine adds 5 to his ''ypos'' so that even though he gets shorter and his centre changes position, his bottom point will remain unchanged. 5 also has to be subtracted from ''ypos'' when he unrolls, or lands from a jump. The camera system also has to keep this offset in mind, otherwise the view will jump when Sonic changes height.
+
* Sonic has a different height at different times. When he is standing, running, falling, or launched from a spring, he is 40 pixels tall. His ''ypos'' is always his center, which is why he stands 20 pixels above the ground (and 20 pixels below ceilings when he hits into them, etc). However, when he is jumping or rolling, he is only 30 pixels tall and he sets 15 pixels above the ground (and 15 pixels below the ceiling, etc). In the step in which Sonic rolls or jumps, the engine adds 5 to his ''ypos'' so that his bottom point will remain unchanged despite him getting shorter and his center changing position. 5 also has to be subtracted from ''ypos'' when he unrolls or lands from a jump. The camera system also has to keep this offset in mind, otherwise, the view will jump when Sonic changes height.
  
 
[[Category:Sonic Physics Guide]]
 
[[Category:Sonic Physics Guide]]

Revision as of 13:09, 25 November 2018

Notes: The research applies to all four of the Sega Mega Drive games and Sonic CD.

Following only describes how Sonic collides and interacts with solid tiles. Solid objects, such as Monitors, Moving Platforms, and Blocks each have their own collision routines with Sonic and don't necessarily behave exactly the same as the tiles do.

Degree angles are counterclockwise with 0 facing right (flat floor).

SPGAngles2.png Dark blue represents ground, light blue represents air.

Different calculations may be needed if using the hex angle values.

Variables

The following variables/constants will be referenced frequently in this section.

//Variables
xpos: The X-coordinate of Sonic's center.
ypos: The Y-coordinate of Sonic's center.
xsp: The speed at which Sonic is moving horizontally.
ysp: The speed at which Sonic is moving vertically.
gsp: The speed at which Sonic is moving on the ground.
slope: The current slope factor (slp) value being used.
ang: Sonic's angle on the ground.
	
//Constants
acc: 0.046875
dec: 0.5
frc: 0.046875 (same as acc)
top: 6
jmp: 6.5 (6 for Knuckles)
slp: 0.125
slprollup: 0.078125
slprolldown: 0.3125
fall: 2.5

Sensors

The collision is handled using 'sensor lines' that surround Sonic. They will be explained and referenced throughout this section.

SPGSensors.png An approximation of the sensors, though some might move positions or even not exist during certain states or character movements

 A & B - Floor collision
 C & D - Ceiling collision (only used mid-air)
 E & F - Wall collision (shifting by 8px depending on certain factors, which will be explained)
 XY - Sonic's xpos and ypos

Introduction

What are solid tiles? While there are often solid objects in Sonic zones, the zone itself would require far too much object memory if the environment were constructed entirely of solid objects, each with their own 64 bytes of RAM. A clever short-cut is used - the zone is constructed out of tiles anyway, so all that needs be done is have each tile know whether or not it is solid.

You may know that zones are broken down into 128x128 pixel chunks (or 256x256 pixel chunks in Sonic 1 and Sonic CD), which are in turn broken into 16x16 pixels tiles, which are again in turn broken into even smaller 8x8 pixel tiles. All of the solidity magic happens with the 16x16 tiles, so those are the only ones we will be interested in throughout this guide.

Sonic's collisions and interactions with these solid tiles are what make up his basic engine. They dictate how he handles floors, walls, ceilings, slopes, and loops. Because this is such a large subject, and so complex, this guide is more proximate than other Sonic Physics Guides, but I have kept speculation to a minimum.

Note: While solidity tiles are used in the original games, these basic collision methods and sensor layouts will still work (with adjustments) with sprite masks, or line intersections, etc, in your own engine.

Standing

Sonic has to check to check for solid tiles beneath him. This can be achieved with two sensor lines, pointing downward. One (A) should be on Sonic's left side, at xpos-9. The other (B) should be on his right, at xpos+9. They should start at ypos and extend to his feet at ypos+20. They should also check at least 16 pixels below his feet at ground level while not in the air (but not too far, or he will pop down when descending low steps and stairs, which you do not want). This extra space checked is to keep him attached to the ground even if it slopes away from him as he moves horizontally.

When Sonic is rolling or jumping, sensor A, B, C, and D are at xpos-7 and xpos+7 rather than xpos-9 and xpos+9. However, his horizontal sensor line remains the same whether curled up or not.

SPGStanding.PNG

Assuming the ground level to be at a Y position of 736 ($02E0), Sonic stands atop it at a ypos of 716 ($02CC), which are 20 pixels above ground level.

Falling Off

Sonic has to be able to run off of ledges. It would not do to just keep walking like Wile E. Coyote, not noticing that there is nothing beneath him.

If both sensor A and B detect no solid tiles, Sonic will "fall" - a flag will be set telling the engine he is now in the air.

Balancing On Edges

One nice touch is that Sonic goes into a balancing animation when near to the edge of a ledge. This only happens when he is stopped (his ground speed is 0).

How does the engine know? It is simple - any time only one of the ground sensors is activated, Sonic must be near a ledge. If A is active and B is not the ledge is to his right and vice versa.

But if Sonic began balancing the instant one of the sensors found nothing, he would do it too "early", and it would look silly. So it only happens when only one sensor is active, and xpos is greater than the edge of the solid tile found by the active sensor.

SPGBalancing.PNG

Assuming the right edge of the ledge to be an x of 2655 ($0A5F), Sonic will only start to balance at an xpos of 2656 ($0A60) (edge pixel+1). He'll fall off at an xpos of 2665 ($0A69) (edge pixel+10) when both sensors find nothing.

In Sonic 2 and Sonic CD, if the ledge is the opposite direction than he is facing, he has a second balancing animation.

In Sonic 2, Sonic 3, and Sonic & Knuckles, Sonic has yet a third balancing animation, for when he's even further out on the ledge. Assuming the same values as above, this would start when he is at an xpos of 2662 ($0A66).

Note: While balancing, certain abilities are not allowed (ducking, looking up, spindashing, etc). In Sonic 3 & Knuckles, the player is still allowed to duck and spindash (not to look up, though) when balancing on the ground but not when balancing on an object.

Pushing

Sonic has to stop when he bumps into walls. This can be achieved by checking for a collision with a line (E/F). The sensor line is at his ypos while on sloped ground, but at Sonic's ypos+8 while he is on flat ground (to push against low obstacles, since there are no slopes to avoid pushing against).

How wide should the sensor line be?

SPGPushing.PNG

Assuming the wall's left side to be at an X position of 704 ($02C0), Sonic cannot get closer than an xpos of 693 ($02B5). Assuming the wall's right side to be at an X position of 831 ($033F), Sonic cannot get closer than an xpos of 842 ($034A). That's 11 pixels difference, in either direction.

Thus the sensor line should be 20 pixels wide, stretching from Sonic's xpos-10 to xpos+10. Any time it detects a solid tile, Sonic should be "popped out", set to the edge of the tile minus (or plus) 11, and his ground speed set to 0. (He cannot be popped out by only 10, because then a point at xpos+10 would still lie within the edge pixel of the tile. This would register a continuous collision, and he would stick to the wall.)

Though the tile's edge minus Sonic's xpos might be 11, there are only 10 free pixels between Sonic's xpos and the tile's edge. The eleventh pixel away is the tile's edge itself. So Sonic is effectively only 20 pixels wide.

You may remember that sensors A and B are only 18 pixels apart but Sonic is 20 pixels wide when pushing into walls. This means that Sonic is skinnier by 2 pixels when running off of ledges than when bumping into walls.

Slopes And Curves

Sonic the Hedgehog was one of the first games to use curved surfaces and even entire 360-degree loops. Most other games of the era composed their environments entirely of blocks (and the occasional ramp).

The ability to cope with smoothly shaped environments is one of the fundamental aspects of the Sonic games' novelty and appeal. Unfortunately, it is also perhaps the most difficult and complex aspect to recreate in a fan game.

So how does it work?

Height Masks

Any time Sensor A or B find a solid tile, they return the height of that tile.

How is the height of the tile found?

Each tile has a value associated with it that references a mask stored in memory. Each mask is simply an array of 16 height values that range from $00 to $10 and an angle value.

SPGHeightMask.PNG

This height mask, for example, has the height array $00 00 01 02 02 03 04 05 05 06 06 07 08 09 09 09, and the angle $E8.

Which value of the height array is used? Subtract the tile's X position from the sensor's X position. The result is the index of the height array to use.

If the height value found is $10, then the sensor has to check for another tile above the first one found, and search for that one's height value.

Whichever sensor finds the highest height, Sonic's ypos is set to that height minus 20 pixels. His ang is also set to the angle of the solid tile that returned the highest height.

When no solid tile is found by a sensor, foot level (ypos+20) is returned by default.

Bugs Using This Method

Unfortunately, there are a couple of annoying bugs in the original engine because of this method.

If Sonic stands on a slanted ledge, one sensor will find no tile and return a height of foot level. This causes Sonic to be set to the wrong position.

SPGSlopeBug1.PNG

Sonic raises up with sensor B sensor as he moves right. When B drops off the ledge, Sonic defaults to the level of sensor A. Then he raises up with sensor A as he moves further right. So he will move up, drop down, and move up again as he runs off the ledge.

There are only a few areas where this is noticeable, but it applies to all Mega Drive titles and is pretty tacky.

The second form of it occurs when two opposing ramp tiles abut each other, as in some of the low hills in Green Hill Zone and Marble Zone.

SPGSlopeBug2.PNG

Sensor B starts climbing down the ramp on the right, but Sonic still defaults to the level of the previous ramp found by sensor A. Because these ramps are usually shallow, this only causes him to dip down in the middle by about 1 pixel.

But that is not all. Because the highest sensor is the one Sonic gets the angle from, even though it looks like he should be considered to be at the angle of the ramp on the right (because he is closer to it), he will still have the angle of the ramp on the left. When you jump, he will jump at that angle, moving backward, not forward like you would expect.

Moving At Angles

Well, that is all very well and good for having Sonic move smoothly over terrain with different heights, but that is not all there is to the engine. Sonic's speed has to be attenuated by angled ground in order to be realistic.

There are two ways in which Sonic's speed is affected on angles. The first will make sure that he does not traverse a hill in the same amount of time as walking over flat ground of an equal width. The second will slow him down when going uphill and speed him up when going downhill. Let's look at each of these in turn.

The Three Speed Variables

If Sonic were a simple platformer that required nothing but blocks, you would only need two speed variables: X speed (xsp) and Y speed (xsp), the horizontal and vertical components of Sonic's velocity. Acceleration (acc), deceleration (dec), and friction (frc) are added to xsp; jump/bounce velocity and gravity (grv) are added to ysp (when Sonic is in the air).

But when slopes are involved, while Sonic moves along a slope, he's moving both horizontally and vertically. This means that both xsp and xsp have a non-zero value. Simply adding acc, dec, or frc to xsp no longer works; imagine Sonic was trying to run up a wall - adding to his horizontal speed would be useless because he needs to move upward.

The trick is to employ a third speed variable (as the original engine does), so let's call it Ground speed (gsp). This is the speed of Sonic along the ground, disregarding ang altogether. acc, dec, and frc are applied to gsp, not xsp or ysp.

While on the ground, xsp and xsp are derived from gsp every step before Sonic is moved. Perhaps a pseudo-code example is in order:

 xsp = gsp*cos(angle);
 ysp = gsp*-sin(angle);
 
 xpos += xsp;
 ypos += ysp;

No matter what happens to the ang, gsp is preserved, so the engine always knows what speed Sonic is "really" moving at.

Slope Factor

By this point, Sonic should be able to handle any hills with an accurate velocity but he still needs to slow down when going uphill and speed up when going downhill.

Fortunately, this is simple to achieve - with something called the Slope Factor (slope). Just subtract slope*sin(ang) from gsp at the beginning of every step.

 gsp -= slope*sin(ang);

The value of slope is always slp when running, but not so when rolling. When Sonic is rolling uphill (the sign of gsp is equal to the sign of sin(ang)), slope is slprollup ($001E). When Sonic is rolling downhill (the sign of gsp is not equal to the sign of sin(ang)), slope is slprolldown ($0050).

Note: In Sonic 1, it appears that slope doesn't get added if Sonic is stopped and in his standing/waiting cycle. But in Sonic 3 & Knuckles, slope seems to be added even then, so that Sonic can't stand on steep slopes - they will force him to walk them down.

Jumping At Angles

Jumping is also affected by the angle Sonic is at when he does it. He can't simply set ysp to negative jmp - he needs to jump away from the angle he's standing on. Instead, both xsp and ysp must have jmp subtracted from them, using cos() and sin() to get the right values.

More pseudo-code:

 xsp -= jmp*sin(angle);
 ysp -= jmp*cos(angle);

Notice how the jump values are subtracted from the xsp and ysp. This means his speeds on the ground are preserved, meaning running up fast on a steep hill and jumping gives you the jump speeds and the speeds you had on the hill, resulting in a very high jump.

Switching Mode

So Sonic can run over hills and ramps and ledges, and all that is great. But it is still not enough. He cannot make his way from the ground to walls and ceilings without more work.

Why not? Well, because sensor A and B 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 straight 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

It seems pretty reasonable to assume that, because Sonic can traverse ground in 360 degrees, the engine handles all 360 degrees in much the same way. But, in fact, the engine splits the angles into four quadrants, greatly simplifying things.

To better understand what I am talking about, imagine a simpler platformer without full loops, just a few low hills and ramps. All the character would need to do is, after moving horizontally, move up or down until they met the level of the floor. The angle of the floor would then be measured. The angle would be used to attenuate gsp, but nothing more. The character would still always move horizontally and move straight up and down to adhere to floor level.

This is much like how Sonic does things. Only, when ang gets too steep, Sonic switches "quadrant", 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, Sonic behaves like a simpler platformer. The magic happens by combining all four modes, and cleverly switching between them smoothly.

So how and when does Sonic switch mode?

When in Floor mode, and ang is steeper than 45° ($E0), the engine switches into Right Wall mode. Everything is basically the same, only the sensors check to the right instead of downward, and Sonic is moved to "floor" level horizontally instead of vertically.

Now that he's in Right Wall mode, if ang is shallower than 45° ($E0), the engine switches back into Floor mode.

The other transitions work in exactly the same way, with the switch angles relative to the current mode.

A quick calculation can be made using ang of the floor, which will place Sonic in the correct mode:

 mode = round(angle/90) % 4;


This would return Sonic's Floor mode at 0, Right Wall at 1, Ceiling at 2, and Left Wall at 3.

You might rightly ask where the ground sensors are when in Right Wall mode. They're in exactly the same place, only rotated 90 degrees. Sensor A is now at Sonic's ypos+9 instead of xpos-9. Sensor B is now at Sonic's ypos-9, instead of xpos+9. Instead of vertical sensor lines, they are now horizontal, stretching 16 pixels beyond his foot level (which is now 20 pixels "below" him, at xpos+20).

Yes, because the sensors move so far, it is possible for Sonic 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 at all during normal play. To adjust for this in a new engine, an alternative method to switch mode would be to check for solid ground using a 90 degree rotated mask. For example, standing upright on flat ground, the left side would check rotated 90 degrees for steep slopes to switch to Left Wall Mode, and the right would check rotated -90 degrees for steep slopes to switch to Right Wall Mode. Only the lower ground sensor of the rotated mask would need to check for ground. This would have to exclude walls so Sonic doesn't begin walking on a wall when he gets near one, but would mean Sonic switched mode sooner on a slope which means less "popping".

One more thing: I said that solid tiles were made of height arrays. Operative word: height. How do they work when in Right Wall mode? Well, rather gobsmackingly, it turns out that in the original engine, each solid tile has two complementary height arrays, one used for when moving horizontally, the other for when moving vertically.

What about Left Wall and Ceiling mode? Wouldn't there need to be four height arrays? No, because tiles of those shapes simply use normal height arrays, just inverted. When in Ceiling mode, Sonic knows that the height value found should be used to move him down and not up.

With these four modes, Sonic can go over all sorts of shapes. Inner curves, outer curves, you name them. Here are some example images with their angle values to help give you some idea of what I've been talking about:

SPGInnerCurve.PNG SPGInnerCurveChart.PNG

SPGOuterCurve.PNG SPGOuterCurveChart.PNG

Falling and Sliding Off Of Walls And Ceilings

When in Right Wall, Left Wall, or Ceiling mode and Sonic's ang is between 90 and 270, Sonic will fall any time absolute gsp falls below fall ($0280) (gsp is set to 0 at this time, but xsp and ysp are unaffected, so Sonic will continue his trajectory through the air). This happens even if there is ground beneath him. If Sonic is in Right Wall, Left Wall, or Ceiling Mode but Sonic's ang is not between 90 and 270 then the horizontal control lock timer described below will still be set to 30 but Sonic will not enter a falling state remaining in his current state.

Horizontal Control Lock

When Sonic falls or slides off in the manner described above, the horizontal control lock timer is set to 30 ($1E) (it won't begin to count down until Sonic lands back on the ground). While this timer is non-zero and Sonic is on the ground, it prevents the player from adjusting Sonic's speed with the left or right buttons. The timer counts down by one every step, so the lock lasts about half a second. During this time only slp and the speed Sonic fell back on the ground with is in effect, so Sonic will slip back down the slope.

 if (abs(gsp) < 2.5 && floor_mode != 0) 
 {
   if (angle >= 90 && angle <= 270) 
   {
     floor_mode = 0;
     gsp = 0;
   }
   horizontal_lock_timer = 30;
 }

The Air State

Any time Sonic is in the air, he doesn't have to worry about angles, gsp, slp, or any of that jazz. All he has to do is move using xsp and ysp until he detects the ground, at which point he re-enters the ground state.

But Sonic does have an unusual set of collision sensors while moving through the air, and it's worth going over them in detail.

Air Sensors

Horizontal Sensor

Sonic has to be able to bump into walls, just like when he's on the ground. So there's a horizontal sensor line, originating at his ypos, and stretching from xpos-10 to xpos+10. Anytime it is colliding with a solid tile, Sonic's "popped" out to the edge of the tile plus/minus 11, just like on the ground.

The thing is, this sensor line is wider than his vertical A and B sensors that detect the ground (we will be getting to those in a minute). This means it is possible for the horizontal sensor line to detect a block that Sonic is falling past, even if he has no xsp at all. This causes him to slip around solids by a pixel or two when he hits them at their extreme edges.

So when Sonic detects a collision with his horizontal sensor line, his xsp is only set to 0 if he is moving in the direction of the wall, not away from it. If it were otherwise, he would stick to walls as he fell past them.

Vertical Sensors

Sensor A and B are very much the same in the air as they are on the ground. When they detect a solid tile, however, Sonic isn't immediately set to the height found in the tile minus 20. Instead, he is only set to it if he is already lower than that height. Otherwise, he would stick to the floor when he gets close to it.

Since the sensors stretch so far below his feet, what stops them from detecting the ground in the same step he jumps, preventing him from leaving the floor? Simple. He ignores them unless ysp is 0 or greater so that he will only detect the ground while moving down.

Because Sonic can move both up and down while in the air, there have to be two more sensors checking upward (Sensors C and D) so that he can bump into ceilings and curves that are above him. C and D mirror A and B perfectly - they have the same X position and length but are flipped upside down) Sonic will detect ceilings and be pushed out of them whether he is moving up or down, unlike floors which are only detected when moving down. It is possible to hit a "ceiling" (which is just the bottom side of a block) while moving down - by pressing toward a wall with a gap in it, or jumping toward the side of an upper curve.

Jumping "Through" Floors

There are some ledges that Sonic can jump up "through". These are often in the hilly, green zones such as Green Hill Zone, Emerald Hill Zone, Palmtree Panic Zone, and so on. The solid tiles that make up these ledges are flagged by the engine as being a certain type that should only be detected by Sonic's A and B sensors. They are ignored entirely by C and D as well as the horizontal sensor line. Finally, sensor A and B only detect the floor when Sonic is moving downwards (but always while on the ground). So with a slightly shorter jump, you will see Sonic 'pop' upwards onto a jump through surface once he begins to fall.

Reacquisition Of The Ground

Both xsp and ysp are derived from gsp while Sonic is on the ground. When he falls or otherwise leaves the ground, xsp and ysp are already the proper values for him to continue his trajectory through the air. But when Sonic lands back on the ground, gsp must be calculated from the xsp and ysp that he has when it happens. You might think that they would use cos() and sin() to get an accurate value, but that is not the case. In fact, something much more basic happens, and it is different when hitting into a curved ceiling as opposed to landing on a curved floor, so I will cover them separately.

As you land the angle of the ground you touch is read (ang). The following covers the angle (ang) of the ground (floor or ceiling) that Sonic touches as he lands, and only happens the frame when he lands when changing from in air to on ground.

When Falling Downward

SPGLandFloor.png

Shallow: When ang is in the range of 22.5°~0° ($F0~$FF) (and their mirror images, 360°~337.5° ($00~$0F)), gsp is set to the value of xsp.

Half Steep: When ang is in the range of 22.5°~45° ($E0~$EF) (and mirrored 337.5°~315° ($10~$1F)), gsp is set to xsp but only if the absolute of xsp is greater than ysp. Otherwise, gsp is set to ysp*0.5*-sign(sin(ang)).

Full Steep: When ang is in the range of 45°~90° ($C0~$DF) (and mirrored 315°~270° ($20~$3F)), gsp is set to xsp but only if the absolute of xsp is greater than ysp. Otherwise, gsp is set to ysp*-sign(sin(ang)).

When Going Upward

SPGLandCeiling.png

Slope: When the ceiling ang detected is in the range of 135°~90° ($A0~$BF) (and mirrored 270°~225° ($40~$5F)), Sonic reattaches to the ceiling and gsp is set to ysp*-sign(sin(ang)).

Note: This does not allow you to connect to a sloped ceiling and follow it downwards when you are moving horizontally in the air. One example of this is the secret route in CPZ act 2. In your engine, you may wish to use a method similar to when going downwards. If absolute xsp is greater than negative ysp, set gsp to negative xsp. Otherwise, use the calculation above.

Ceiling: When the ceiling ang is in the range of 225°~135° ($60~$9F), Sonic hits his head like with any ceiling, and doesn't reattach to it. ysp is set to 0, and xsp is unaffected.

Reference: Converting Hex Angles

The Mega Drive games use angles in hex, $00 through $FF, meaning that there are only 256 divisions of a circle, not 360 like we're used to. Worse, the direction is anti-clockwise compared to other languages like GML, so $20 isn't 45° like it should be - it's 315°.

In order to convert the original hex angles into angles you can use in GML, use this calculation (rendered here in pseudo-code):

 return (256-hex_angle)*1.40625;

Notes

  • Sonic can only brake ("screech to a halt") in Floor mode.
  • Sonic cannot jump when there is a low ceiling above him. If there is a collision detected with a sensor line stretching from Sonic's xpos-9 to xpos+9, at ypos-25, Sonic won't bother jumping at all.
  • Sonic has a different height at different times. When he is standing, running, falling, or launched from a spring, he is 40 pixels tall. His ypos is always his center, which is why he stands 20 pixels above the ground (and 20 pixels below ceilings when he hits into them, etc). However, when he is jumping or rolling, he is only 30 pixels tall and he sets 15 pixels above the ground (and 15 pixels below the ceiling, etc). In the step in which Sonic rolls or jumps, the engine adds 5 to his ypos so that his bottom point will remain unchanged despite him getting shorter and his center changing position. 5 also has to be subtracted from ypos when he unrolls or lands from a jump. The camera system also has to keep this offset in mind, otherwise, the view will jump when Sonic changes height.