183 lines
6.8 KiB
GDScript
183 lines
6.8 KiB
GDScript
extends Node2D
|
|
class_name OrbitalBody2D
|
|
|
|
# Defines the physical behavior of this body.
|
|
enum PhysicsMode {
|
|
INDEPENDENT, # An independent body with its own physics simulation (planets, characters in EVA).
|
|
COMPOSITE, # A body that aggregates mass and forces from ANCHORED children (ships, modules).
|
|
ANCHORED # A component that is "bolted on" and defers physics to a COMPOSITE parent.
|
|
}
|
|
|
|
@export var physics_mode: PhysicsMode = PhysicsMode.INDEPENDENT
|
|
|
|
var current_grid_authority: OrbitalBody2D = null
|
|
|
|
# Mass of this individual component
|
|
@export var base_mass: float = 1.0
|
|
@export var mass: float = 0.0 # Aggregated mass of this body and all its OrbitalBody2D children
|
|
@export var linear_velocity: Vector2 = Vector2.ZERO
|
|
@export var angular_velocity: float = 0.0
|
|
|
|
# Variables to accumulate forces applied during the current physics frame
|
|
var accumulated_force: Vector2 = Vector2.ZERO
|
|
var accumulated_torque: float = 0.0
|
|
|
|
# Placeholder for Moment of Inertia.
|
|
@export var inertia: float = 1.0
|
|
|
|
func _ready():
|
|
# Ensure mass update runs immediately before the first _physics_process.
|
|
recalculate_physical_properties()
|
|
|
|
set_physics_process(not Engine.is_editor_hint())
|
|
physics_interpolation_mode = Node.PHYSICS_INTERPOLATION_MODE_OFF
|
|
|
|
# --- PUBLIC FORCE APPLICATION METHODS ---
|
|
# This method is called by a component (like Thruster) at its global position.
|
|
func apply_force(force: Vector2, pos: Vector2 = self.global_position):
|
|
# This is the force routing logic.
|
|
match physics_mode:
|
|
PhysicsMode.INDEPENDENT:
|
|
_add_forces(force, pos)
|
|
PhysicsMode.COMPOSITE:
|
|
_add_forces(force, pos)
|
|
## If we are the root, accumulate the force and calculate torque on the total body.
|
|
#accumulated_force += force
|
|
#
|
|
## Calculate torque (2D cross product: T = r x F = r.x * F.y - r.y * F.x)
|
|
## 'r' is the vector from the center of mass (global_position) to the point of force application (position).
|
|
#var r = position - global_position
|
|
#var torque = r.x * force.y - r.y * force.x
|
|
#accumulated_torque += torque
|
|
PhysicsMode.ANCHORED:
|
|
# If we are not the root, we must route the force to the next OrbitalBody2D parent.
|
|
var p = get_parent()
|
|
while p:
|
|
if p is OrbitalBody2D:
|
|
# Recursively call the parent's apply_force method.
|
|
# This sends the force (and its original global position) up the chain.
|
|
p.apply_force(force, pos)
|
|
return # Stop at the first OrbitalBody2D parent
|
|
p = p.get_parent()
|
|
|
|
push_error("Anchored OrbitalBody2D has become dislodged and is now Composite.")
|
|
physics_mode = PhysicsMode.COMPOSITE
|
|
apply_force(force, position)
|
|
|
|
func _add_forces(force: Vector2, pos: Vector2 = Vector2.ZERO):
|
|
# If we are the root, accumulate the force and calculate torque on the total body.
|
|
accumulated_force += force
|
|
|
|
# Calculate torque (2D cross product: T = r x F = r.x * F.y - r.y * F.x)
|
|
# 'r' is the vector from the center of mass (global_position) to the point of force application (position).
|
|
var r = pos - global_position
|
|
var torque = r.x * force.y - r.y * force.x
|
|
accumulated_torque += torque
|
|
|
|
func _update_mass_and_inertia():
|
|
mass = base_mass
|
|
for child in get_children():
|
|
if child is OrbitalBody2D:
|
|
child._update_mass_and_inertia() # Recurse into children
|
|
mass += child.mass
|
|
|
|
print("Node: %s, Mass: %f" % [self, mass])
|
|
|
|
func _physics_process(delta):
|
|
if not Engine.is_editor_hint():
|
|
# Note: We're not integrating forces for anchored bodies
|
|
# anchored bodies add forces to their parents and
|
|
match physics_mode:
|
|
PhysicsMode.INDEPENDENT:
|
|
_integrate_forces(delta)
|
|
PhysicsMode.COMPOSITE:
|
|
_integrate_forces(delta)
|
|
|
|
func _integrate_forces(delta):
|
|
# Safety Check for Division by Zero
|
|
var sim_mass = mass
|
|
if sim_mass <= 0.0:
|
|
# If mass is zero, stop all physics to prevent NaN explosion.
|
|
accumulated_force = Vector2.ZERO
|
|
accumulated_torque = 0.0
|
|
return
|
|
|
|
## 1. Calculate and accumulate gravitational force (F_g)
|
|
#var total_gravity_force = OrbitalMechanics.calculate_n_body_gravity_forces(self)
|
|
#
|
|
## 2. Total all forces: F_total = F_g + F_accumulated_from_thrusters
|
|
#var total_force = total_gravity_force +
|
|
|
|
# 3. Apply Linear Physics (F = ma)
|
|
var linear_acceleration = accumulated_force / sim_mass # Division is now safe
|
|
linear_velocity += linear_acceleration * delta
|
|
global_position += linear_velocity * delta
|
|
|
|
# 4. Apply Rotational Physics (T = I * angular_acceleration)
|
|
var angular_acceleration = accumulated_torque / inertia
|
|
angular_velocity += angular_acceleration * delta
|
|
rotation += angular_velocity * delta
|
|
|
|
# 5. Reset accumulated forces for the next frame
|
|
accumulated_force = Vector2.ZERO
|
|
accumulated_torque = 0.0
|
|
|
|
# This is the new, corrected function.
|
|
func recalculate_physical_properties():
|
|
# For non-composite bodies, the calculation is simple.
|
|
if physics_mode != PhysicsMode.COMPOSITE:
|
|
mass = base_mass
|
|
# --- THE FIX ---
|
|
# An independent body doesn't calculate inertia from parts.
|
|
# We ensure it has a non-zero default value to prevent division by zero.
|
|
if inertia <= 0.0:
|
|
inertia = 1.0
|
|
return
|
|
|
|
var all_parts: Array[OrbitalBody2D] = []
|
|
_collect_anchored_parts(all_parts)
|
|
|
|
if all_parts.is_empty():
|
|
mass = base_mass
|
|
inertia = 1.0
|
|
return
|
|
|
|
# --- Step 1: Calculate Total Mass and LOCAL Center of Mass ---
|
|
var total_mass = 0.0
|
|
var weighted_local_pos_sum = Vector2.ZERO
|
|
for part in all_parts:
|
|
total_mass += part.base_mass
|
|
# We get the part's position *relative to the root module*
|
|
var local_pos = part.global_position - self.global_position
|
|
weighted_local_pos_sum += local_pos * part.base_mass
|
|
|
|
var local_center_of_mass = Vector2.ZERO
|
|
if total_mass > 0:
|
|
local_center_of_mass = weighted_local_pos_sum / total_mass
|
|
|
|
# --- Step 2: Calculate Total Moment of Inertia around the LOCAL CoM ---
|
|
var total_inertia = 0.0
|
|
for part in all_parts:
|
|
# Get the part's position relative to the root module again
|
|
var local_pos = part.global_position - self.global_position
|
|
# The radius is the distance from the part's local position to the ship's local center of mass
|
|
var r_squared = (local_pos - local_center_of_mass).length_squared()
|
|
total_inertia += part.base_mass * r_squared
|
|
|
|
# --- Step 3: Assign the final values ---
|
|
self.mass = total_mass
|
|
# We apply a scaling factor here because our "units" are pixels.
|
|
# This brings the final value into a range that feels good for gameplay.
|
|
# You can tune this factor to make ships feel heavier or lighter.
|
|
self.inertia = total_inertia * 0.01
|
|
|
|
#print("Physics Recalculated: Mass=%.2f kg, Inertia=%.2f" % [mass, inertia])
|
|
|
|
# A recursive helper function to get an array of all OrbitalBody2D children
|
|
func _collect_anchored_parts(parts_array: Array):
|
|
parts_array.append(self)
|
|
for child in get_children():
|
|
# TODO: this assumes that all OrbitalBody2D that are attached are done in a clean chain without breaks, which may not be the case
|
|
if child is OrbitalBody2D and child.physics_mode == PhysicsMode.ANCHORED:
|
|
child._collect_anchored_parts(parts_array)
|