Skip to main content

nightshade_api/
physics.rs

1//! Forces, raycasts, and collision events for entities spawned with a
2//! [`Body`](crate::prelude::Body).
3
4use nightshade::ecs::physics::joints::{
5    FixedJoint, JointAxisDirection, JointHandle, RevoluteJoint, RopeJoint, SpringJoint,
6    create_fixed_joint, create_revolute_joint, create_rope_joint, create_spring_joint,
7};
8use nightshade::prelude::*;
9
10/// Applies an instantaneous impulse to a dynamic entity. Good for jumps,
11/// knockback, and explosions.
12#[inline]
13pub fn push(world: &mut World, entity: Entity, impulse: Vec3) {
14    physics_world_apply_impulse(&mut world.resources.physics, entity, impulse);
15}
16
17/// Sets a dynamic entity's linear velocity directly. Good for launching
18/// projectiles.
19#[inline]
20pub fn set_velocity(world: &mut World, entity: Entity, velocity: Vec3) {
21    physics_world_set_linear_velocity(&mut world.resources.physics, entity, velocity);
22}
23
24/// Casts a ray against all physics colliders and returns the closest hit.
25#[inline]
26pub fn raycast(
27    world: &World,
28    origin: Vec3,
29    direction: Vec3,
30    max_distance: f32,
31) -> Option<RaycastHit> {
32    physics_world_cast_ray(
33        &world.resources.physics,
34        origin,
35        direction,
36        max_distance,
37        None,
38    )
39}
40
41/// The collision events from the last physics step.
42#[inline]
43pub fn collisions(world: &World) -> &[CollisionEvent] {
44    physics_world_collision_events(&world.resources.physics)
45}
46
47/// Welds two bodies together rigidly.
48#[inline]
49pub fn attach_fixed(world: &mut World, parent: Entity, child: Entity) -> Option<JointHandle> {
50    create_fixed_joint(world, parent, child, FixedJoint::new())
51}
52
53/// Hinges two bodies around an axis. Doors, levers, wheels.
54#[inline]
55pub fn attach_hinge(
56    world: &mut World,
57    parent: Entity,
58    child: Entity,
59    axis: JointAxisDirection,
60) -> Option<JointHandle> {
61    create_revolute_joint(world, parent, child, RevoluteJoint::new(axis))
62}
63
64/// Connects two bodies with a spring. Suspension, bouncy attachments.
65#[inline]
66pub fn attach_spring(
67    world: &mut World,
68    parent: Entity,
69    child: Entity,
70    rest_length: f32,
71    stiffness: f32,
72    damping: f32,
73) -> Option<JointHandle> {
74    create_spring_joint(
75        world,
76        parent,
77        child,
78        SpringJoint::new(rest_length, stiffness, damping),
79    )
80}
81
82/// Tethers two bodies with a maximum separation. Chains, leashes, pendulums.
83#[inline]
84pub fn attach_rope(
85    world: &mut World,
86    parent: Entity,
87    child: Entity,
88    max_distance: f32,
89) -> Option<JointHandle> {
90    create_rope_joint(world, parent, child, RopeJoint::new(max_distance))
91}