67 lines
2.3 KiB
GDScript
67 lines
2.3 KiB
GDScript
@tool
|
|
class_name Module
|
|
extends RigidBody2D
|
|
|
|
@onready var structural_container: Node2D = $StructuralContainer
|
|
@onready var hull_volume_container: Node2D = $HullVolumeContainer
|
|
|
|
func _recalculate_physics_properties():
|
|
print("Recalculating physics properties...")
|
|
|
|
# 1. Sum masses and find a weighted center of mass
|
|
var total_mass: float = 0.0
|
|
var total_mass_pos = Vector2.ZERO
|
|
var all_structural_pieces = structural_container.get_children()
|
|
|
|
for piece in all_structural_pieces:
|
|
if piece is StructuralPiece:
|
|
total_mass += piece.piece_mass
|
|
# The position is relative to the structural_container.
|
|
total_mass_pos += piece.position * piece.piece_mass
|
|
|
|
if total_mass > 0:
|
|
var new_center_of_mass = total_mass_pos / total_mass
|
|
# We set the center of mass in the RigidBody2D.
|
|
self.set_center_of_mass(new_center_of_mass)
|
|
self.mass = total_mass
|
|
|
|
# --- Combine all collision shapes into one for the RigidBody ---
|
|
# This is a key part of your design, allowing for efficient physics calculations.
|
|
# Note: This is an expensive operation and should only be done on demand.
|
|
|
|
# Remove any existing collision shapes from this RigidBody2D
|
|
for child in get_children():
|
|
if child is CollisionShape2D or child is CollisionPolygon2D:
|
|
child.queue_free()
|
|
|
|
var shape = ConcavePolygonShape2D.new()
|
|
var all_points: PackedVector2Array = []
|
|
|
|
# Iterate through all structural pieces to get their collision polygons
|
|
for piece in all_structural_pieces:
|
|
if piece is StructuralPiece:
|
|
for child in piece.get_children():
|
|
if child is CollisionPolygon2D:
|
|
# Get the points in the structural piece's local space
|
|
var piece_points = child.polygon
|
|
var piece_xform = piece.transform
|
|
|
|
# Transform the points to the module's local space
|
|
for p in piece_points:
|
|
all_points.append(piece_xform.xform(p))
|
|
|
|
shape.set_segments(all_points)
|
|
|
|
var new_collision_shape = CollisionShape2D.new()
|
|
new_collision_shape.shape = shape
|
|
add_child(new_collision_shape)
|
|
|
|
print("Physics Recalculated: Total Mass: %.2f kg" % total_mass)
|
|
else:
|
|
print("No structural pieces found. Physics properties not updated.")
|
|
|
|
func clear_module():
|
|
for piece in structural_container.get_children():
|
|
piece.queue_free()
|
|
_recalculate_physics_properties()
|