grunk/src/player/rigid_body_physics.gd

32 lines
1022 B
GDScript

extends Node
## Component to simulate rigid body interactions with a CharacterBody3D.
## Base collision force (will scale with impact velocity)
@export_range(0.0, 500.0, 0.1) var force := 50.0
## Lower bound for collision speed scaling.
@export var min_speed := 1.0
## Upper bound for collision speed scaling.
@export var max_speed := 10.0
## Toggle rigid body interactions.
@export var enabled := true
@onready var controller := owner as CharacterBody3D
func _physics_process(_delta: float) -> void:
if not enabled:
return
for i: int in controller.get_slide_collision_count():
var collision := controller.get_slide_collision(i)
for j: int in collision.get_collision_count():
var collider := collision.get_collider(j) as RigidBody3D
if collider:
var direction := -collision.get_normal()
var speed := clampf(controller.velocity.length(), min_speed, max_speed)
var offset := collision.get_position(j) - collider.global_position
collider.apply_impulse(direction * speed * force, offset)