Recreating gravity in games is harder than you’d think

Share on facebook
Facebook
Share on twitter
Twitter
Share on linkedin
LinkedIn
Share on reddit
Reddit
Share on telegram
Telegram
Share on email
Email

Gravity is one of the simplest and most complicated things in existence. It’s both as straightforward as jumping, and a source of cosmic machinations and monsters that defy the imagination. The entity holding you to the ground right now is the same principle of attraction that leads to black holes – exhausted stars that have collapsed under their own mass, growing denser and denser until, at last, they form a vortex so absolute that time deforms and not even light can escape the pull. 

Videogames have been wrestling with gravity since the medium’s birth, from the geometric landslides of Tetris to the Jenga-esque launch vehicle physics of full-blown 3D space sims. These games can be a useful means of visualising equations and phenomena you’d otherwise need a PhD to understand, but most games compromise with reality out of necessity or simply in the name of fun. They are their own little bespoke universes – and even those that adhere sternly to the science struggle to portray the ideas put forward in Albert Einstein’s theory of general relativity. 

Upwardly mobile

Before we get to Einstein, however, let’s talk Mario. Working out how to make a character fall in a platformer is one of game development’s bread-and-butter challenges. It sounds simple enough: you subtract a certain vertical distance from the character every frame unless there’s something in the way. But getting a leaping character to ‘feel’ right can take months of work, because everyday gravity is generally more inconvenient than enjoyable. To make it sing in a videogame, you have to figure out how and when to break the rules.

“If you apply gravity on top of a normal jump, you’re going to get this parabola shape,” explains Frying Jelly’s Eric Stryczek, one of the minds behind the dreamy yet ferocious 99 Fails. “It’s perfect. [But] it actually feels really terrible as a jump. So what Mario did all the way back on the Nintendo Entertainment System was have this sort of extra behaviour – when you’re falling, velocity gets exponential. So you sort of go up, stay in the air for a while, and then you get sucked right back down really quickly.”

(Image credit: Giant Army)

The equation for how fast objects fall on Earth is minus 9.81 metres per second squared – many third-party game engines like Unity treat this as the rough default for their physics systems. But as Stryczek goes on, “It feels really floaty to have a value like that. Because in platformers, we tend to jump really high. What a lot of beginners get wrong is that they don’t mess with this value – you really need to have that snappy feeling.”

In 99 Fails, things are complicated by the protagonist Zeebo’s habit of changing shape. “Zeebo has this recurring nightmare, where he’s transforming in weird and grotesque ways,” says Frying Jelly’s founder Pawel Pachniewski. “And each time, there’s a different mechanic that the player uses – he’ll be a cart, he’ll have long legs, he’ll be a grasshopper jumping onto broken pillars, he’ll have clones.” As such, Frying Jelly sometimes switches off gravity entirely when it wants to add a specific movement trajectory.

Squaring the circle

Expand the playable space to encompass an actual planet, and gravity becomes even more of a riddle. “The definition of down isn’t down anymore,” says Felipe Falanghe, creator of Kerbal Space Program. “You can’t just move things towards the bottom of the screen or the horizon, you have to figure out where you are in relation to the planet and apply force towards the centre.”

As to how much force you should apply, most developers and astrophysicists follow Isaac Newton’s inverse square law of gravity, which dictates that an object’s gravity is strong up close and drops off rapidly as you move away, then shallows out. Understanding this formula is key to playing Kerbal Space Program, in which you send little green men to visit other planets in a kooky yet unforgiving approximation of our solar system. “It’s the thing that makes orbits work,” Falanghe says. “If you don’t add that orbits will look like… well, they won’t look like circles.” Indeed, most Kerbal spaceflights look like craters.

(Image credit: PanGuoJun)

If Kerbal sticks to the textbooks on this count, it ‘cheats’ on other fronts. In particular, it sidesteps the so-called ‘n-body’ problem, whereby every planetary mass in a group exerts a gravitational pull on every other body simultaneously. “KSP does something that is not entirely realistic which is sometimes called patched conic approximation, which is just a fancy way of saying that we switch gravity sources whenever you get close enough to another one. When you cross into the ‘sphere of influence’ of the moon, the sources switch, and now you’re only affected by gravity from the moon.”

Treating gravity as a strictly two-way affair makes for a more stable and predictable simulation, which is vital given that missions in Kerbal can take several in-game years. It means that the simulation doesn’t have to recalculate gravity ‘step by step’; indeed, the game can switch mid-spaceflight to a “deterministic” means of calculating movement without causing discrepancies. “We used to call it the rails system because the spacecraft was on rails, and it basically meant that we could freeze all physics, and just carry things through space.” The trade-off is that Kerbal can’t simulate certain fancier astrophysical ‘terrain variables’, such as Lagrangian points – tactically advantageous locations in space between masses, where the pull from each mass is equal.

Sum of all spheres

Mobius Digital’s planet-hopping timeloop adventure Outer Wilds is similarly selective in its simulation. For one thing, Newton’s inverse square law only applies to one mass – the sun. The reason is simply that Outer Wilds’ solar system is tiny, with planets the size of islands separated by tens of kilometres – as such, the pull of gravity drops away too quickly. “Early on, I tried the inverse square law on planets,” says Alex Beachum, creative director. “But because they’re so small, it just becomes too easy to achieve escape velocity – it doesn’t feel right.” Instead, gravity decreases in a more ‘linear’ fashion, and the developer can set alignment fields so that players orient towards masses automatically.

Outer Wilds also exercises a bit of licence with regard to interactions between planets, adds tech artist and programmer Logan Ver Hoef. “We have this sphere of influence for the sun and we’ve got spheres of influence for each planet. But because planets end up passing so close by each other, if they actually affected each other at that scale, they’d form these wild patterns and probably just escape orbit.” The game’s equivalent of our Moon, the Attlerock, responds only to the gravity of one planet, but with extra acceleration dolloped on top to reflect that planet’s orbit – otherwise, says Beachum, the Attlerock might be left behind or dragged into the sun.

(Image credit: Annapurna Interactive)

Elsewhere, however, the simulation is more stringent. Your spacecraft may tumble off the back of a comet when it nears the sun, for example, because in keeping with Newton’s law, the star’s gravity acts differently on the ship’s mass versus the comet. Moments like these were often discovered during play, and left in for kicks. For all its resemblance to a cosmic stage production, with planets shape-shifting on schedule, Outer Wilds is on some level a ‘pure simulation’ with plenty of potential for chaos.

It’s possible to wreak havoc simply by venturing too far. “If you disable autopilot and fly away from the solar system, and open your star map, everything’s lost its mind,” Beachum says. “Because floating point errors build up, and the planets are too far away. You can actually break the simulation if you try hard enough, because they’re not on rails.” The game’s 22 minute timeloop was introduced partly as a kind of safety valve. “We wanted the solar system to change in ways that aren’t easily reversible, like Brittle Hollow falling apart, and having everything reset is an easy way to handle that,” Ver Hoef says. “But also, the 20-ish minute mark was originally our limit for stability.”

PLAYING WITH STARS

Way out at the deep end of videogame simulations of gravity is Giant Army’s Universe Sandbox 2. Created initially by Dan Dixon, who wrote his first gravity simulator in high school, it’s been in development for ten years and has swollen to the point that the current iteration can recreate the motions of entire galaxies, each with its central supermassive black hole. Unlike Outer Wilds and Kerbal, Universe Sandbox 2 is a ‘true’ n-body physics simulation. It calculates the effects of hundreds of bodies on each other’s movements, though it economises in places by, for instance, treating close-knit asteroids as a single mass. “It can become very, very slow,” Dixon acknowledges. “But in many ways, gravity is the simplest thing we do now.”

Giant Army has even looked at recreating dark matter, the mysterious and invisible substance that fills our universe, adding to its gravity and keeping apparently ‘underweight’ galaxies in shape. “Part of the problem with dark matter is that it doesn’t really come in chunks,” says Erika Nesvold, Giant Army’s in-house astrophysicist. “There was a theory that it was big, compact objects, but it seems more likely now that it’s sort of spread throughout a galaxy. And that’s just really hard to handle in an n-body simulation. And it’s also hard, of course, to show dark matter to a user. But we’d love to get back into it someday.”

(Image credit: Giant Army)

As a sim with no objectives besides meddling with the cosmos, Universe Sandbox 2 doesn’t have to worry as much about the design and playability pressures that shape gravity in Kerbal and Outer Wilds. But in adopting n-body physics, it has to wrangle with the question of mounting errors dependent on the speed at which the simulation progresses.

The bigger the ‘step’ between each set of n-body calculations, the less precise things become. “As a rule of thumb, picking a time step that’s bigger than the time it takes something to orbit in a circle is a bad idea,” Nesvold says. The game performs additional ‘sub-step’ calculations for finesse in the event of objects making sharp turns, but “there’s only so many you can do”. Increase the time interval too much, and whole star systems may disappear. “Some users thought, ‘Oh, in the future, everything’s gonna fly away from the sun,'” says Dixon. “No, no, no, what’s happened is you sped up time so much that it’s become inaccurate, which is [a problem] inherent to simulations.”

Distant relatives

While Outer Wilds, Kerbal and Universe Sandbox 2 are fundamentally grounded in ‘classical’ Newtonian physics, their creators have all flirted with the more recent, and transformative theories of gravity introduced by Albert Einstein. To crudely summarise their differences, Newton’s physics holds that space is full of masses and forces act on them in linear time. According to Einstein, however, space and time are actually a single, fluctuating entity – a ‘spacetime’ which is woven together and distorted by mass, and this distortion is what we call gravity.

Einstein’s theory dictates that planets and stars don’t just reel in other masses, but ‘dilate’ time nearby relative to the passage of time for an observer further afield. This obliges a fascinating, but not very intuitive rethinking of the act of falling. “The idea is that it’s not a force pulling you down, it’s the future leading you towards the ground,” Falanghe explains. “Spacetime bends, so that when your straight-line trajectory turns towards the ground it’s not just space that bends but time. The future bends your trajectory.”

As fascinated as he is by this prospect, Falanghe decided early on not to apply Einsteinian physics to Kerbal Space Program, partly because the ramifications are negligible at solar system scale, and partly because time dilation is tricky to portray in a management game where solid scheduling is key. “In Kerbal, we have the orbit map that shows your trajectory, and you can plan manoeuvres and see how your trajectory would intersect with another celestial body, turn around and things like that. But if you said, ‘Oh, by the way, your ship clock will desynchronise with your home clock by like, 0.2 seconds, by the time you get here,’ that’s much harder to communicate to the player.”

Giant Army has thought more earnestly about introducing relativistic effects. As Nesvold and Dixon point out, these can be observed ‘close at hand’ in the elusive behaviour of Mercury, which orbits close enough to our sun to experience time dilation from its mass. The problem is that simulating general relativity requires the player to actually be relative to things – to occupy a vantage point within the universe, so as to, for example, witness the effects of gravity on light. This would somewhat interfere with the usual running of a god sim. “If you deleted the sun, it would take a certain amount of time for it to disappear off your screen.”

Heart of Darkness

(Image credit: Annapurna Interactive)

Both Kerbal and Universe Sandbox 2 are checked from exploring Einstein because they’re born of genres that are steeped in concepts from Newton. Thanks to its sci-fi story, Outer Wilds is able to forge a little further. It hints at relativistic effects in the form of alien time travel experiments, connected to a miniature black hole that lurks beneath the crust of one unfortunate planet. During the game’s alpha, Mobius also added an island area that turned time dilation into a performance issue. “When you got close to this antenna, I just made the framerate worse,” Beachum reflects. “But it was really bad, and if anything, I think it should have been the reverse. It should have been that everything around you speeds up.”

The aforesaid black hole distorts light believably – it recreates the deflection of photons by gravitational lensing, though as Ver Hoef acknowledges, “It’s super fudged – [an actual photon] would follow a curved path and ours just go: boink!” But there’s no time dilation, and as with the sun and planets, the object’s gravity is carefully contained. “A black hole the size of Brittle Hollow should have a distortion radius larger than our real-world solar system.”

It’s easy to forget amid talk of refraction and dilation that what motivates all these projects is a sense of wonder – not just at the operations of gravity, but at the mingled elegance and eccentricity of the models describing it. “You have simple formulas and equations that give you this approximation of the universe,” enthuses Falanghe. Among Giant Army’s goals is teaching players to embrace the imperfections of sims at large – from videogames to the supercomputer-powered, yet no less flawed models used by NASA.

As Dixon concludes, “What a cool way to be able to learn about the amazing reality that we find ourselves in, and that the universe is weirder than anyone ever imagined.” It remains difficult to conceive of a gravity sim wholly based around Einstein’s theories, but if the above projects are any indication, it’s only a matter of time before somebody takes the plunge.

Article source: PCGamer

You might also enjoy