Skip to main content

nightshade_api/
character.rs

1//! The kinematic character controller behind [`first_person`](crate::prelude::first_person):
2//! read its grounded state and velocity, tune its movement, or drive it from
3//! your own code instead of the built in input.
4
5use nightshade::prelude::*;
6
7/// Whether the character controller entity is standing on the ground this frame.
8pub fn is_grounded(world: &World, entity: Entity) -> bool {
9    world
10        .get::<nightshade::plugins::physics::components::CharacterControllerComponent>(entity)
11        .map(|controller| controller.grounded)
12        .unwrap_or(false)
13}
14
15/// The character controller's current velocity, or zero if it has none.
16pub fn controller_velocity(world: &World, entity: Entity) -> Vec3 {
17    world
18        .get::<nightshade::plugins::physics::components::CharacterControllerComponent>(entity)
19        .map(|controller| controller.velocity)
20        .unwrap_or_else(Vec3::zeros)
21}
22
23/// Sets the character's maximum move speed in units per second.
24pub fn set_controller_speed(world: &mut World, entity: Entity, speed: f32) {
25    if let Some(controller) = world
26        .get_mut::<nightshade::plugins::physics::components::CharacterControllerComponent>(
27        entity,
28    ) {
29        controller.max_speed = speed;
30    }
31}
32
33/// Sets the character's jump strength.
34pub fn set_controller_jump(world: &mut World, entity: Entity, jump_impulse: f32) {
35    if let Some(controller) = world
36        .get_mut::<nightshade::plugins::physics::components::CharacterControllerComponent>(
37        entity,
38    ) {
39        controller.jump_impulse = jump_impulse;
40    }
41}
42
43/// Drives the character from your own code instead of the engine input:
44/// `movement` is the desired motion on the ground plane (x and z), and `jump`
45/// requests a jump this frame. Useful for AI agents and networked players.
46pub fn move_character(world: &mut World, entity: Entity, movement: Vec2, jump: bool) {
47    if let Some(controller) = world
48        .get_mut::<nightshade::plugins::physics::components::CharacterControllerComponent>(
49        entity,
50    ) {
51        controller.external_movement = movement;
52        controller.external_jump = jump;
53    }
54}