Rubbley · game/gravity · ADRs 0003, 0006, 0012, 0017, 0018

How Rubbley's gravity works

Newtonian physics, the few game tweaks laid on top of it, and the strategy behind the moves. Each idea comes with a diagram and the code that implements it. The numbers are the shipped tuning: G = 8, Rubbley starts at mass 10, a movable planet's mass is 250, softening is 1 m and max range is 35 m.

01One physics tick

Every body is a 3D Jolt rigid body locked to the Play Plane (y = 0). It can move only in X and Z and can turn only around Y, so the physics is really 2D. The project's default gravity is zero. A body feels only the forces our code adds, plus the point gravity of any Anchored Body's Area.

RubbleyMoves reads input, sets multipliers / Wells GravitySystem._physics_process priority 100 · gather arrays GravitySolver · Newton pairs CaptureAssist · steer toward a circle Drift · carry along the stage Σ apply_central_ force(F) Jolt v += F/m·dt damp v cap |v| x += v·dt semi-implicit Euler GravityWell pushes its bodies itself AnchoredPull (Area3D) Godot point gravity
Each tick, forces from three independent contributors are summed and applied once per body. Gravity Wells and Anchored Bodies feed the same integrator from outside the system.

Why the integration method matters. Jolt updates velocity first and then moves the body using the new velocity. This is semi-implicit (symplectic) Euler. In plain Euler, energy creeps upward and every orbit slowly spirals outward. In symplectic Euler, energy wobbles but doesn't drift, so a real, physics-driven orbit stays stable for minutes.

damping: dv/dt = −c·v ⇒ v(t) = v₀·e^(−c·t)

Damping removes a fraction c of a body's speed each second. Drift and the capture assist both have to pay this back.

game/bodies/play_plane_body.gd
func _ready() -> void:
	axis_lock_linear_y = true       # can't leave the plane
	axis_lock_angular_x = true      # spins only around Y
	axis_lock_angular_z = true
	linear_damp_mode = RigidBody3D.DAMP_MODE_REPLACE
	linear_damp = tuning.linear_damp_per_second

func _integrate_forces(state: PhysicsDirectBodyState3D) -> void:
	state.linear_velocity = state.linear_velocity.limit_length(tuning.speed_cap_m_per_s)

02Newton and the mass rule

Two masses pull on each other with equal and opposite forces. The acceleration each one feels is that force divided by its own mass.

F = G · m₁ · m₂ / d² a₁ = F / m₁ a₂ = F / m₂
d = 16 m Rubbleym = 10 Planetm = 250 F ≈ 77.7 N F ≈ 77.7 N a = 7.77 m/s² a = 0.31 m/s²
The forces are equal (amber); the accelerations (blue) differ by the mass ratio, 25×. The GDD's rule that "the heavier body is the centre point" follows from this. No line of code checks which body is heavier.

03Softening and range

As d → 0, 1/d² goes to infinity, and two bodies grazing each other would shoot apart. Plummer softening adds a small length ε so the pull peaks and then falls back to zero at contact. Far away it's ordinary Newton.

F = G·m₁·m₂ · d / (d² + ε²)^1.5 d ≫ ε : (d² + ε²)^1.5 ≈ d³ ⇒ F ≈ G·m₁·m₂ / d² d → 0 : F → 0 peak at d = ε/√2
Pure Newton, GM/d²Softened, ε = 1 m
Acceleration toward a 250-mass planet (GM = 2000 m³/s²) over the first 6 m. Past about 3 m the two curves match. Beyond the 35 m max range the pull is cut to zero.
game/gravity/gravity_solver.gd
for i in count:
	if roles[i] != GravityBody.Role.CELESTIAL:
		continue                                   # only Celestial bodies pull
	for j in count:
		var mutual := roles[j] == GravityBody.Role.CELESTIAL
		# A Celestial pair is computed once, from its lower index.
		if j == i or (mutual and j < i) or roles[j] == GravityBody.Role.ANCHORED:
			continue
		var offset := positions[j] - positions[i]  # vector i → j, length d
		var distance_squared := offset.length_squared()
		if distance_squared > max_range_squared or distance_squared == 0.0:
			continue
		var softened := distance_squared + softening_squared
		var pair_multiplier: float = (
			multipliers[i] * multipliers[j]
			* pair_multipliers.get(Vector2i(mini(i, j), maxi(i, j)), 1.0)
		)
		# offset supplies both the direction and the extra factor of d
		var force := (
			offset * (_tuning.gravitational_constant * masses[i] * masses[j] * pair_multiplier)
			/ (softened * sqrt(softened))
		)
		result[j] -= force        # j is pulled toward i
		if mutual:
			result[i] += force    # and i toward j: Newton's third law

The formula has d / (d²+ε²)^1.5 rather than 1/d² because offset is not a unit vector. Its length is already d, so multiplying by it gives the direction and the extra d together, and the code never needs a normalized() call.

04Who pulls whom

In real physics every pair of masses attracts, so the work grows with the square of the body count. Rubbley's phone budget can't afford that, so each body has one of three roles.

Rubbley Planet mutual (Celestial ↔ Celestial) Debris one-way (Passive) Anchored Area point gravity, never moves
RolePullsIs pulledExamples
Celestialyes, mutuallyyesRubbley, planets, asteroids, large enemies
Passivenoyesdebris, materials, small enemies
Anchoredyes, via its Areano (frozen)big level planets

The cost becomes Ncelestial × Ntotal. A hundred debris pieces with three Celestial Bodies cost about 300 pair evaluations, not about 5,000.

05Gravega multipliers: how Attract works

Attract never pushes a body directly. It raises a multiplier, and the solver turns that into force on the next tick. A pair's pull is scaled by both bodies' own multipliers and by any multiplier set on that particular pair.

F_pair = G·m₁·m₂ · (mult₁ · mult₂ · pair_mult) / (d² + ε²)^1.5
MoveWhat it setsShipped valueEffect
Attract on selfgravega_multiplier× 3.0every pair Rubbley is in pulls 3× harder
Targeted Attractpair_multipliers[target]× 2.0only the Rubbley↔target pair

The force stays mutual, so the mass rule still applies. Attracting a planet mostly pulls Rubbley to the planet. Attracting a Passive piece of debris pulls only the debris, because Passive bodies pull nothing back.

game/bodies/rubbley/rubbley_moves.gd
match target.kind:
	AimTarget.Kind.RUBBLEY:
		_attracting_self = true
		gravity_body.gravega_multiplier = stats.attract_self_multiplier
	AimTarget.Kind.CELESTIAL_BODY:
		_attract_target = targetables[target.body_index]
		gravity_body.pair_multipliers[_attract_target.gravity_body] = (
			stats.attract_celestial_multiplier
		)
	AimTarget.Kind.EMPTY_SPACE:
		_place_gravity_well(aim)

The target is locked when the button goes down, nothing changes while it's held, and the multiplier is reset on release. RubbleyMoves runs before the GravitySystem (which uses PHYSICS_PRIORITY = 100), so a press takes effect on the same tick.

06Anchored bodies

A big level planet is frozen in place. It still has to pull, and Godot's Area3D point gravity does that cheaply. With a unit distance of 1 m, Godot computes g = strength / d²: exact inverse-square, with no softening. The system sets the strength every tick to G × mass × multiplier.

game/gravity/anchored_pull.gd
gravity_space_override = Area3D.SPACE_OVERRIDE_COMBINE
gravity_point = true
gravity_point_unit_distance = 1.0   # g(d) = strength / d²

func pull(strength: float, range_m: float) -> void:
	gravity = strength               # G × M × multiplier, set by GravitySystem each tick

When a Targeted Attract multiplies a pair that includes an Anchored Body, the Area already supplies the ×1 share. The solver's _add_anchored_pair_pull adds only the extra (pair_multiplier − 1) part on the moving body.

07Orbits from first principles

No orbit is scripted. A body moving sideways fast enough keeps falling toward the planet and keeps missing it. For a circle, gravity has to supply exactly the centripetal acceleration:

v² / r = a(r) ⇒ v_circ = √(a · r) pure Newton: √(GM / r) Rubbley at 16 m from a 250-mass planet: a ≈ 7.77 m/s² v_circ ≈ 11.1 m/s one lap ≈ 2π·16 / 11.1 ≈ 9 s
Launch sideways from the dot at k × circular speed. Below 1 the launch point is the farthest point of an ellipse. Above 1 it's the closest point. At √2 ≈ 1.41 and above, the body has more kinetic energy than the planet's binding energy (½v² ≥ GM/r) and escapes. The shaded disc is the planet's 8 m radius: the k = 0.75 ellipse dips to 7.2 m and would hit it.
game/gravity/orbit_launch.gd
var on_plane := Vector3(offset.x, 0.0, offset.z)
var radius := on_plane.length()
var across := Vector3.UP.cross(on_plane) / radius   # offset turned 90° in the plane
if not anticlockwise:
	across = -across
return across * speed_multiple * sqrt(pull_strength / radius)

Vis-viva: the slowest safe launch

Debris is scattered with random launch speeds, and none of it may crash into the planet. Two conservation laws link the launch point (radius r, speed v = k·v_circ) to the closest point (rₚ, vₚ):

angular momentum: r · v = rₚ · vₚ energy: ½v² − GM/r = ½vₚ² − GM/rₚ ⇒ rₚ = r·k² / (2 − k²) ⇒ k = √( 2rₚ / (r + rₚ) )
static func slowest_speed_multiple(radius_m: float, lowest_m: float) -> float:
	return sqrt(2.0 * lowest_m / (radius_m + lowest_m))

DebrisField raises each piece's random speed multiple to at least this value, so every orbit stays clear of the surface.

08The capture assist

Players almost never arrive at exactly circular speed and exactly sideways. The capture assist is a proportional controller: inside a heavier body's Capture Radius (20 m for a planet), it adds a force that steers the body's velocity toward the ideal circular velocity at its current distance.

Capture Radius primary outward target v (relative) target − v Each tick v_circ = √(pull · d) skip if |v| > 1.3 · v_circ target ⟂ outward, same way round F = m·[k·(target − v) + c·(target + v_primary)] k = 2 /s closes the gap; the c·(…) term pays back damping so a circle holds.
The assist pushes along the amber error vector, toward the green circular velocity. It only adds force, so the body stays a normal dynamic body that a Repel or a collision can still knock out.
a = k · (v_target − v) ⇒ error(t) = error₀ · e^(−k·t) time constant 1/k = 0.5 s
How much of the velocity error is left after the assist takes over (ignoring gravity's own effect). About 37% remains after 0.5 s and about 5% after 1.5 s.
game/gravity/capture_assist.gd
var pull := _pull(primary, i, distance, masses, roles, multipliers) * pair_multiplier
var circular_speed := sqrt(pull * distance)
var relative := _on_plane(velocities[i] - velocities[primary])
if relative.length() > circular_speed * _tuning.capture_speed_multiple:
	continue                                    # a flyby, not a capture
var outward := offset / distance
# Keep the way the body already goes round; one falling straight in goes anticlockwise.
var way_round := -1.0 if outward.cross(relative).y < 0.0 else 1.0
var target := Vector3.UP.cross(outward) * way_round * circular_speed
# The body's own damping would slow even a circular Orbit, so the assist pays it back.
var damping_payback := (target + _on_plane(velocities[primary])) * linear_damps[i]
result[i] = (
	((target - relative) * _tuning.capture_assist_rate_per_second + damping_payback)
	* masses[i]
)

09Orbit lab

A small re-implementation of sections 03, 07 and 08 using the shipped numbers. Rubbley launches sideways from 16 m. Try 0.75 with the assist off (he hits the planet), then turn the assist on. The planet is held still here, and Drift is off.

time
0.0 s
distance
16.0 m
speed
0.0 m/s
v_circ here
0.0 m/s
swept
0°
tracking
Runs at 60 ticks per second with semi-implicit Euler, at 2× speed. Rubbley's damping is 0.03/s and his speed cap is 20 m/s. The rings show the 20 m Capture Radius and the 25 m Orbit limit (1.25×). The status chip uses the Orbit predicate from section 12.

10Drift

Drift carries Rubbley along the level at 4.09 m/s, on top of his own motion. Setting velocity directly would fight the physics engine, so Drift works out the force that produces the change it wants, using F = m·a in reverse.

F = m · [ (carry − carried_last_tick) / dt + c · carry ] ↑ change in carried velocity ↑ cancel damping on it
game/gravity/drift.gd
var on_plane := Vector3(direction.x, 0.0, direction.z).normalized()
var carry := on_plane * _tuning.drift_speed_m_per_s
result[drifting_index] = ((carry - _carried) / delta + carry * linear_damp) * mass
_carried = carry

On the first tick the whole 4.09 m/s is added in one go. After that the first term is zero unless the stage's direction turns. Tests check the result against the closed-form distance, where Rubbley's own starting speed fades under damping:

distance = drift_speed · (t₂ − t₁) + v₀ · (e^(−c·t₁) − e^(−c·t₂)) / c

11Gravity Wells: deliberately not Newtonian

An Attract on empty space places a Well. Its pull is linear: strongest at the centre and zero at the edge. It's multiplied by each body's mass, so every body gets the same acceleration whatever it weighs. The Well behaves like a pocket of bent space, not like a heavy object.

a(d) = S · (1 − d/R) S = 50 m/s², R = 24 m, no pull inside 0.36 m falling in from the edge: v² = 2∫₀ᴿ S(1 − d/R) dd = S·R = 1200 ⇒ v ≈ 34.6 m/s (cap: 20)
A Well's pull across its 24 m radius. Nothing damps it, so a falling body overshoots the centre and swings through. If the Well expires mid-swing (after 3 s), the body keeps that velocity. That's the "fling". In about one Well in five the fling nearly cancels Drift and leaves Rubbley almost stopped; ADR 0018 accepts this.
game/gravity/gravity_well.gd
func pull_on(point: Vector3) -> Vector3:
	var offset := global_position - point
	offset.y = 0.0
	var distance := offset.length()
	if distance <= CORE_M or distance >= radius_m:
		return Vector3.ZERO           # the core stops jitter at the exact centre
	return offset / distance * (1.0 - distance / radius_m)

# in _physics_process, for each overlapping body:
body.apply_central_force(pull_on(body.global_position) * strength * body.mass)

Point gravity wasn't an option here: Godot's Area gravity is either uniform or inverse-square, and a uniform pull strong enough to notice held Rubbley in place. Only one Well exists at a time. Placing a new one frees the old one immediately, so the old one doesn't pull for an extra tick.

12What counts as Orbit

Jolt isn't reproducible across platforms, so neither the game nor the tests compare exact positions. They check outcomes, and both use one shared predicate. A body is in Orbit when all three of these hold:

1 · Stay close within 1.25 × Capture Radius (red ring) 2 · Stay round farthest ≤ 1.3 × closest (green band) 3 · Go all the way round swept angle ≥ 360°; leaving the band restarts the count
game/gravity/orbit.gd
_closest_m = minf(_closest_m, distance)
_furthest_m = maxf(_furthest_m, distance)
if _furthest_m > _closest_m * _tuning.orbit_radius_band:
	_start(on_plane)                                  # broke the band: count again
	return
_travelled_rad += _last_offset.angle_to(on_plane)   # signed: going backwards subtracts
_last_offset = on_plane

Simulation tests run each scenario from 5 starting conditions: one canonical, plus four perturbed by ±5% speed, ±5° angle and ±5% distance. They assert bands of outcomes rather than exact positions. For example: released at 0.8 × Capture Radius at 0.9–1.1× circular speed, the body is in Orbit within 3 periods and stays in Orbit for 2 more.

13The aim decides the move

There are only three inputs. What's under the aim when the input starts decides which version of the move fires, and the target stays locked until release.

Under the aimAttract (held)Repel (one-shot)
RubbleyAttract on self, × 3 on all his pairsRepel Pulse (stuns)
Glowing Celestial BodyTargeted Attract, × 2 on one pairTargeted Repel
Empty spaceGravity WellGravity Ripple

The third input, Spin, ignores the aim. It fires whatever else is going on.

Rubbley checked first; wins ties aim d − r = −18 px centre negative = inside; most-inside body wins
game/bodies/rubbley/aim_target.gd
if on_plane.distance_to(_flat(rubbley_at)) <= rubbley_radius_m:
	target.kind = Kind.RUBBLEY            # Rubbley wins ties
	return target
var deepest := 0.0
for i in body_positions.size():
	# Signed distance to the edge: below 0 means the aim is inside the body.
	var past_edge := on_plane.distance_to(_flat(body_positions[i])) - body_radii[i]
	if past_edge <= deepest:
		deepest = past_edge
		target.kind = Kind.CELESTIAL_BODY
		target.body_index = i

Measuring to the edge rather than the centre keeps a big planet easy to hit, including one you're orbiting close to.

14Putting it together: orbital traversal

The design approach: build consistent physics first (Newton, mutual forces, orbits that come from the physics), then add small, separate assist forces that make it playable without putting anything on rails. Because everything stays dynamic, Repel, collisions and Wells always interact believably.

A orbital v Repel J/m exit = v + J/m B B's Capture Radius 1 · fall in, assist circles you 2 · time the Repel 3 · Targeted Attract on B pulls you across 4 · captured again, repeat
Exit velocity = orbital velocity + Repel impulse. Since the orbital part rotates as you go round, when you fire sets the direction you leave in. That timing is the traversal skill.

What's built now

All of this is in the game, in rubbley_moves.gd and the scripts around it: