Skip to main content

khora_data/ecs/components/physics/
collider.rs

1// Copyright 2025 eraflo
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use khora_core::math::Vec3;
16use khora_core::physics::{ColliderHandle, ColliderShape};
17use khora_macros::Component;
18use serde::{Deserialize, Serialize};
19
20/// Component representing a collider attached to an entity.
21#[derive(Debug, Clone, Component, Serialize, Deserialize)]
22#[component(domain = Physics)]
23pub struct Collider {
24    /// Opaque handle used by the physics provider.
25    #[component(skip)]
26    pub handle: Option<ColliderHandle>,
27    /// Shape of the collider.
28    pub shape: ColliderShape,
29    /// Friction coefficient.
30    pub friction: f32,
31    /// Restitution (bounciness) coefficient.
32    pub restitution: f32,
33    /// Whether this collider is a sensor (does not respond to forces).
34    pub is_sensor: bool,
35}
36
37impl Default for Collider {
38    fn default() -> Self {
39        Self {
40            handle: None,
41            shape: ColliderShape::Sphere(0.5),
42            friction: 0.5,
43            restitution: 0.0,
44            is_sensor: false,
45        }
46    }
47}
48
49impl Collider {
50    /// Creates a new box collider.
51    pub fn new_box(half_extents: Vec3) -> Self {
52        Self {
53            handle: None,
54            shape: ColliderShape::Box(half_extents),
55            friction: 0.5,
56            restitution: 0.0,
57            is_sensor: false,
58        }
59    }
60
61    /// Creates a new sphere collider.
62    pub fn new_sphere(radius: f32) -> Self {
63        Self {
64            handle: None,
65            shape: ColliderShape::Sphere(radius),
66            friction: 0.5,
67            restitution: 0.0,
68            is_sensor: false,
69        }
70    }
71}