Created
November 16, 2024 14:55
-
-
Save lotus128/10d81967a518ee97b9b3b89518973f47 to your computer and use it in GitHub Desktop.
3D character controller in Bevy with Avian3D
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /// determine next linear velocity for a character. | |
| /// "with body" means veloicity is applied to the body. | |
| // TODO move to avian3d_lib | |
| pub fn determine_next_step_linear_velocity_for_rigidbody_with_body( | |
| spatial_query: &SpatialQuery, | |
| query_filter: SpatialQueryFilter, | |
| start_root_global_translation: Vec3, | |
| start_root_global_rotation: Quat, | |
| body_shape: SharedShape, | |
| body_local_translation: Vec3, | |
| linear_velocity: Vec3, | |
| angular_velocity: Vec3, | |
| ) -> Vec3 { | |
| let start_body_relative_global_translation = | |
| start_root_global_rotation * body_local_translation; | |
| let start_body_global_translation = | |
| start_root_global_translation + start_body_relative_global_translation; | |
| let cast_shape_collider = Collider::from(body_shape); | |
| let cast_shape_rotation = start_root_global_rotation; | |
| let cast_origin = start_body_global_translation; | |
| let cast_distance = linear_velocity.length(); | |
| let root_angular_velocity; | |
| let body_linear_velocity; | |
| if cast_distance == 0.0 { | |
| body_linear_velocity = Vec3::ZERO; | |
| root_angular_velocity = angular_velocity; | |
| } else { | |
| let cast_direction = Dir3::new_unchecked(linear_velocity / cast_distance); | |
| let cast_hit_option = spatial_query.cast_shape( | |
| &cast_shape_collider, | |
| cast_origin, | |
| cast_shape_rotation, | |
| cast_direction, | |
| cast_distance, | |
| true, | |
| query_filter, | |
| ); | |
| if let Some(cast_hit) = cast_hit_option { | |
| body_linear_velocity = cast_direction * cast_hit.time_of_impact; | |
| root_angular_velocity = angular_velocity; | |
| } else { | |
| body_linear_velocity = linear_velocity; | |
| root_angular_velocity = angular_velocity; | |
| }; | |
| }; | |
| let end_body_relative_global_translation = | |
| Quat::from_scaled_axis(root_angular_velocity) | |
| * start_root_global_rotation | |
| * body_local_translation; | |
| let next_step_linear_velocity = start_body_relative_global_translation | |
| + body_linear_velocity | |
| - end_body_relative_global_translation; | |
| return next_step_linear_velocity; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment