Debian Codegraph @

scene/3d/physics/character_body_3d.cpp

raw symbols SCIP
1 /**************************************************************************/
2 /* character_body_3d.cpp */
3 /**************************************************************************/
4 /* This file is part of: */
5 /* GODOT ENGINE */
6 /* https://godotengine.org */
7 /**************************************************************************/
8 /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
9 /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
10 /* */
11 /* Permission is hereby granted, free of charge, to any person obtaining */
12 /* a copy of this software and associated documentation files (the */
13 /* "Software"), to deal in the Software without restriction, including */
14 /* without limitation the rights to use, copy, modify, merge, publish, */
15 /* distribute, sublicense, and/or sell copies of the Software, and to */
16 /* permit persons to whom the Software is furnished to do so, subject to */
17 /* the following conditions: */
18 /* */
19 /* The above copyright notice and this permission notice shall be */
20 /* included in all copies or substantial portions of the Software. */
21 /* */
22 /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
23 /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
24 /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
25 /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
26 /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
27 /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
28 /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
29 /**************************************************************************/
30
31 #include "character_body_3d.h"
32
33 #ifndef DISABLE_DEPRECATED
34 #include "servers/physics_3d/physics_server_3d_extension.h"
35 #endif
36
37 //so, if you pass 45 as limit, avoid numerical precision errors when angle is 45.
38 #define FLOOR_ANGLE_THRESHOLD 0.01
39
40 bool CharacterBody3D::move_and_slide() {
41 // Hack in order to work with calling from _process as well as from _physics_process; calling from thread is risky
42 double delta = Engine::get_singleton()->is_in_physics_frame() ? get_physics_process_delta_time() : get_process_delta_time();
43
44 for (int i = 0; i < 3; i++) {
45 if (locked_axis & (1 << i)) {
46 velocity[i] = 0.0;
47 }
48 }
49
50 Transform3D gt = get_global_transform();
51 previous_position = gt.origin;
52
53 Vector3 current_platform_velocity = platform_velocity;
54
55 if ((collision_state.floor || collision_state.wall) && platform_rid.is_valid()) {
56 bool excluded = false;
57 if (collision_state.floor) {
58 excluded = (platform_floor_layers & platform_layer) == 0;
59 } else if (collision_state.wall) {
60 excluded = (platform_wall_layers & platform_layer) == 0;
61 }
62 if (!excluded) {
63 PhysicsDirectBodyState3D *bs = nullptr;
64
65 // We need to check the platform_rid object still exists before accessing.
66 // A valid RID is no guarantee that the object has not been deleted.
67
68 // We can only perform the ObjectDB lifetime check on Object derived objects.
69 // Note that physics also creates RIDs for non-Object derived objects, these cannot
70 // be lifetime checked through ObjectDB, and therefore there is a still a vulnerability
71 // to dangling RIDs (access after free) in this scenario.
72 if (platform_object_id.is_null() || ObjectDB::get_instance(platform_object_id)) {
73 // This approach makes sure there is less delay between the actual body velocity and the one we saved.
74 bs = PhysicsServer3D::get_singleton()->body_get_direct_state(platform_rid);
75 }
76
77 if (bs) {
78 Vector3 local_position = gt.origin - bs->get_transform().origin;
79 current_platform_velocity = bs->get_velocity_at_local_position(local_position);
80 } else {
81 // Body is removed or destroyed, invalidate floor.
82 current_platform_velocity = Vector3();
83 platform_rid = RID();
84 }
85 } else {
86 current_platform_velocity = Vector3();
87 }
88 }
89
90 motion_results.clear();
91
92 bool was_on_floor = collision_state.floor;
93 collision_state.state = 0;
94
95 last_motion = Vector3();
96
97 if (!current_platform_velocity.is_zero_approx()) {
98 PhysicsServer3D::MotionParameters parameters(get_global_transform(), current_platform_velocity * delta, margin);
99 parameters.recovery_as_collision = true; // Also report collisions generated only from recovery.
100
101 parameters.exclude_bodies.insert(platform_rid);
102 if (platform_object_id.is_valid()) {
103 parameters.exclude_objects.insert(platform_object_id);
104 }
105
106 PhysicsServer3D::MotionResult floor_result;
107 if (move_and_collide(parameters, floor_result, false, false)) {
108 motion_results.push_back(floor_result);
109
110 CollisionState result_state;
111 _set_collision_direction(floor_result, result_state);
112 }
113 }
114
115 if (motion_mode == MOTION_MODE_GROUNDED) {
116 _move_and_slide_grounded(delta, was_on_floor);
117 } else {
118 _move_and_slide_floating(delta);
119 }
120
121 // Compute real velocity.
122 real_velocity = get_position_delta() / delta;
123
124 if (platform_on_leave != PLATFORM_ON_LEAVE_DO_NOTHING) {
125 // Add last platform velocity when just left a moving platform.
126 if (!collision_state.floor && !collision_state.wall) {
127 if (platform_on_leave == PLATFORM_ON_LEAVE_ADD_UPWARD_VELOCITY && current_platform_velocity.dot(up_direction) < 0) {
128 current_platform_velocity = current_platform_velocity.slide(up_direction);
129 }
130 velocity += current_platform_velocity;
131 }
132 }
133
134 return motion_results.size() > 0;
135 }
136
137 void CharacterBody3D::_move_and_slide_grounded(double p_delta, bool p_was_on_floor) {
138 Vector3 motion = velocity * p_delta;
139 Vector3 motion_slide_up = motion.slide(up_direction);
140 Vector3 prev_floor_normal = floor_normal;
141
142 platform_rid = RID();
143 platform_object_id = ObjectID();
144 platform_velocity = Vector3();
145 platform_angular_velocity = Vector3();
146 platform_ceiling_velocity = Vector3();
147 floor_normal = Vector3();
148 wall_normal = Vector3();
149 ceiling_normal = Vector3();
150
151 // No sliding on first attempt to keep floor motion stable when possible,
152 // When stop on slope is enabled or when there is no up direction.
153 bool sliding_enabled = !floor_stop_on_slope;
154 // Constant speed can be applied only the first time sliding is enabled.
155 bool can_apply_constant_speed = sliding_enabled;
156 // If the platform's ceiling push down the body.
157 bool apply_ceiling_velocity = false;
158 bool first_slide = true;
159 bool vel_dir_facing_up = velocity.dot(up_direction) > 0;
160 Vector3 total_travel;
161
162 for (int iteration = 0; iteration < max_slides; ++iteration) {
163 PhysicsServer3D::MotionParameters parameters(get_global_transform(), motion, margin);
164 parameters.max_collisions = 6; // There can be 4 collisions between 2 walls + 2 more for the floor.
165 parameters.recovery_as_collision = true; // Also report collisions generated only from recovery.
166
167 PhysicsServer3D::MotionResult result;
168 bool collided = move_and_collide(parameters, result, false, !sliding_enabled);
169
170 last_motion = result.travel;
171
172 if (collided) {
173 motion_results.push_back(result);
174
175 CollisionState previous_state = collision_state;
176
177 CollisionState result_state;
178 _set_collision_direction(result, result_state);
179
180 // If we hit a ceiling platform, we set the vertical velocity to at least the platform one.
181 if (collision_state.ceiling && platform_ceiling_velocity != Vector3() && platform_ceiling_velocity.dot(up_direction) < 0) {
182 // If ceiling sliding is on, only apply when the ceiling is flat or when the motion is upward.
183 if (!slide_on_ceiling || motion.dot(up_direction) < 0 || (ceiling_normal + up_direction).length() < 0.01) {
184 apply_ceiling_velocity = true;
185 Vector3 ceiling_vertical_velocity = up_direction * up_direction.dot(platform_ceiling_velocity);
186 Vector3 motion_vertical_velocity = up_direction * up_direction.dot(velocity);
187 if (motion_vertical_velocity.dot(up_direction) > 0 || ceiling_vertical_velocity.length_squared() > motion_vertical_velocity.length_squared()) {
188 velocity = ceiling_vertical_velocity + velocity.slide(up_direction);
189 }
190 }
191 }
192
193 if (collision_state.floor && floor_stop_on_slope && (velocity.normalized() + up_direction).length() < 0.01) {
194 Transform3D gt = get_global_transform();
195 if (result.travel.length() <= margin + CMP_EPSILON) {
196 gt.origin -= result.travel;
197 }
198 set_global_transform(gt);
199 velocity = Vector3();
200 motion = Vector3();
201 last_motion = Vector3();
202 break;
203 }
204
205 if (result.remainder.is_zero_approx()) {
206 motion = Vector3();
207 break;
208 }
209
210 // Apply regular sliding by default.
211 bool apply_default_sliding = true;
212
213 // Wall collision checks.
214 if (result_state.wall && (motion_slide_up.dot(wall_normal) <= 0)) {
215 // Move on floor only checks.
216 if (floor_block_on_wall) {
217 // Needs horizontal motion from current motion instead of motion_slide_up
218 // to properly test the angle and avoid standing on slopes
219 Vector3 horizontal_motion = motion.slide(up_direction);
220 Vector3 horizontal_normal = wall_normal.slide(up_direction).normalized();
221 real_t motion_angle = Math::abs(Math::acos(-horizontal_normal.dot(horizontal_motion.normalized())));
222
223 // Avoid to move forward on a wall if floor_block_on_wall is true.
224 // Applies only when the motion angle is under 90 degrees,
225 // in order to avoid blocking lateral motion along a wall.
226 if (motion_angle < .5 * Math::PI) {
227 apply_default_sliding = false;
228 if (p_was_on_floor && !vel_dir_facing_up) {
229 // Cancel the motion.
230 Transform3D gt = get_global_transform();
231 real_t travel_total = result.travel.length();
232 real_t cancel_dist_max = MIN(0.1, margin * 20);
233 if (travel_total <= margin + CMP_EPSILON) {
234 gt.origin -= result.travel;
235 result.travel = Vector3(); // Cancel for constant speed computation.
236 } else if (travel_total < cancel_dist_max) { // If the movement is large the body can be prevented from reaching the walls.
237 gt.origin -= result.travel.slide(up_direction);
238 // Keep remaining motion in sync with amount canceled.
239 motion = motion.slide(up_direction);
240 result.travel = Vector3();
241 } else {
242 // Travel is too high to be safely canceled, we take it into account.
243 result.travel = result.travel.slide(up_direction);
244 motion = result.remainder;
245 }
246 set_global_transform(gt);
247 // Determines if you are on the ground, and limits the possibility of climbing on the walls because of the approximations.
248 _snap_on_floor(true, false);
249 } else {
250 // If the movement is not canceled we only keep the remaining.
251 motion = result.remainder;
252 }
253
254 // Apply slide on forward in order to allow only lateral motion on next step.
255 Vector3 forward = wall_normal.slide(up_direction).normalized();
256 motion = motion.slide(forward);
257
258 // Scales the horizontal velocity according to the wall slope.
259 if (vel_dir_facing_up) {
260 Vector3 slide_motion = velocity.slide(result.collisions[0].normal);
261 // Keeps the vertical motion from velocity and add the horizontal motion of the projection.
262 velocity = up_direction * up_direction.dot(velocity) + slide_motion.slide(up_direction);
263 } else {
264 velocity = velocity.slide(forward);
265 }
266
267 // Allow only lateral motion along previous floor when already on floor.
268 // Fixes slowing down when moving in diagonal against an inclined wall.
269 if (p_was_on_floor && !vel_dir_facing_up && (motion.dot(up_direction) > 0.0)) {
270 // Slide along the corner between the wall and previous floor.
271 Vector3 floor_side = prev_floor_normal.cross(wall_normal);
272 if (floor_side != Vector3()) {
273 motion = floor_side * motion.dot(floor_side);
274 }
275 }
276
277 // Stop all motion when a second wall is hit (unless sliding down or jumping),
278 // in order to avoid jittering in corner cases.
279 bool stop_all_motion = previous_state.wall && !vel_dir_facing_up;
280
281 // Allow sliding when the body falls.
282 if (!collision_state.floor && motion.dot(up_direction) < 0) {
283 Vector3 slide_motion = motion.slide(wall_normal);
284 // Test again to allow sliding only if the result goes downwards.
285 // Fixes jittering issues at the bottom of inclined walls.
286 if (slide_motion.dot(up_direction) < 0) {
287 stop_all_motion = false;
288 motion = slide_motion;
289 }
290 }
291
292 if (stop_all_motion) {
293 motion = Vector3();
294 velocity = Vector3();
295 }
296 }
297 }
298
299 // Stop horizontal motion when under wall slide threshold.
300 if (p_was_on_floor && (wall_min_slide_angle > 0.0) && result_state.wall) {
301 Vector3 horizontal_normal = wall_normal.slide(up_direction).normalized();
302 real_t motion_angle = Math::abs(Math::acos(-horizontal_normal.dot(motion_slide_up.normalized())));
303 if (motion_angle < wall_min_slide_angle) {
304 motion = up_direction * motion.dot(up_direction);
305 velocity = up_direction * velocity.dot(up_direction);
306
307 apply_default_sliding = false;
308 }
309 }
310 }
311
312 if (apply_default_sliding) {
313 // Regular sliding, the last part of the test handle the case when you don't want to slide on the ceiling.
314 if ((sliding_enabled || !collision_state.floor) && (!collision_state.ceiling || slide_on_ceiling || !vel_dir_facing_up) && !apply_ceiling_velocity) {
315 const PhysicsServer3D::MotionCollision &collision = result.collisions[0];
316
317 Vector3 slide_motion = result.remainder.slide(collision.normal);
318 if (collision_state.floor && !collision_state.wall && !motion_slide_up.is_zero_approx()) {
319 // Slide using the intersection between the motion plane and the floor plane,
320 // in order to keep the direction intact.
321 real_t motion_length = slide_motion.length();
322 slide_motion = up_direction.cross(result.remainder).cross(floor_normal);
323
324 // Keep the length from default slide to change speed in slopes by default,
325 // when constant speed is not enabled.
326 slide_motion.normalize();
327 slide_motion *= motion_length;
328 }
329
330 if (slide_motion.dot(velocity) > 0.0) {
331 motion = slide_motion;
332 } else {
333 motion = Vector3();
334 }
335
336 if (slide_on_ceiling && result_state.ceiling) {
337 // Apply slide only in the direction of the input motion, otherwise just stop to avoid jittering when moving against a wall.
338 if (vel_dir_facing_up) {
339 velocity = velocity.slide(collision.normal);
340 } else {
341 // Avoid acceleration in slope when falling.
342 velocity = up_direction * up_direction.dot(velocity);
343 }
344 }
345 }
346 // No sliding on first attempt to keep floor motion stable when possible.
347 else {
348 motion = result.remainder;
349 if (result_state.ceiling && !slide_on_ceiling && vel_dir_facing_up) {
350 velocity = velocity.slide(up_direction);
351 motion = motion.slide(up_direction);
352 }
353 }
354 }
355
356 total_travel += result.travel;
357
358 // Apply Constant Speed.
359 if (p_was_on_floor && floor_constant_speed && can_apply_constant_speed && collision_state.floor && !motion.is_zero_approx()) {
360 Vector3 travel_slide_up = total_travel.slide(up_direction);
361 motion = motion.normalized() * MAX(0, (motion_slide_up.length() - travel_slide_up.length()));
362 }
363 }
364 // When you move forward in a downward slope you don’t collide because you will be in the air.
365 // This test ensures that constant speed is applied, only if the player is still on the ground after the snap is applied.
366 else if (floor_constant_speed && first_slide && _on_floor_if_snapped(p_was_on_floor, vel_dir_facing_up)) {
367 can_apply_constant_speed = false;
368 sliding_enabled = true;
369 Transform3D gt = get_global_transform();
370 gt.origin = gt.origin - result.travel;
371 set_global_transform(gt);
372
373 // Slide using the intersection between the motion plane and the floor plane,
374 // in order to keep the direction intact.
375 Vector3 motion_slide_norm = up_direction.cross(motion).cross(prev_floor_normal);
376 motion_slide_norm.normalize();
377
378 motion = motion_slide_norm * (motion_slide_up.length());
379 collided = true;
380 }
381
382 if (!collided || motion.is_zero_approx()) {
383 break;
384 }
385
386 can_apply_constant_speed = !can_apply_constant_speed && !sliding_enabled;
387 sliding_enabled = true;
388 first_slide = false;
389 }
390
391 _snap_on_floor(p_was_on_floor, vel_dir_facing_up);
392
393 // Reset the gravity accumulation when touching the ground.
394 if (collision_state.floor && !vel_dir_facing_up) {
395 velocity = velocity.slide(up_direction);
396 }
397 }
398
399 void CharacterBody3D::_move_and_slide_floating(double p_delta) {
400 Vector3 motion = velocity * p_delta;
401
402 platform_rid = RID();
403 platform_object_id = ObjectID();
404 floor_normal = Vector3();
405 platform_velocity = Vector3();
406 platform_angular_velocity = Vector3();
407
408 bool first_slide = true;
409 for (int iteration = 0; iteration < max_slides; ++iteration) {
410 PhysicsServer3D::MotionParameters parameters(get_global_transform(), motion, margin);
411 parameters.recovery_as_collision = true; // Also report collisions generated only from recovery.
412
413 PhysicsServer3D::MotionResult result;
414 bool collided = move_and_collide(parameters, result, false, false);
415
416 last_motion = result.travel;
417
418 if (collided) {
419 motion_results.push_back(result);
420
421 CollisionState result_state;
422 _set_collision_direction(result, result_state);
423
424 if (result.remainder.is_zero_approx()) {
425 motion = Vector3();
426 break;
427 }
428
429 if (wall_min_slide_angle != 0 && Math::acos(wall_normal.dot(-velocity.normalized())) < wall_min_slide_angle + FLOOR_ANGLE_THRESHOLD) {
430 motion = Vector3();
431 if (result.travel.length() < margin + CMP_EPSILON) {
432 Transform3D gt = get_global_transform();
433 gt.origin -= result.travel;
434 set_global_transform(gt);
435 }
436 } else if (first_slide) {
437 Vector3 motion_slide_norm = result.remainder.slide(wall_normal).normalized();
438 motion = motion_slide_norm * (motion.length() - result.travel.length());
439 } else {
440 motion = result.remainder.slide(wall_normal);
441 }
442
443 if (motion.dot(velocity) <= 0.0) {
444 motion = Vector3();
445 }
446 }
447
448 if (!collided || motion.is_zero_approx()) {
449 break;
450 }
451
452 first_slide = false;
453 }
454 }
455
456 void CharacterBody3D::apply_floor_snap() {
457 if (collision_state.floor) {
458 return;
459 }
460
461 // Snap by at least collision margin to keep floor state consistent.
462 real_t length = MAX(floor_snap_length, margin);
463
464 PhysicsServer3D::MotionParameters parameters(get_global_transform(), -up_direction * length, margin);
465 parameters.max_collisions = 4;
466 parameters.recovery_as_collision = true; // Also report collisions generated only from recovery.
467 parameters.collide_separation_ray = true;
468
469 PhysicsServer3D::MotionResult result;
470 if (move_and_collide(parameters, result, true, false)) {
471 CollisionState result_state;
472 // Apply direction for floor only.
473 _set_collision_direction(result, result_state, CollisionState(true, false, false));
474
475 if (result_state.floor) {
476 // Ensure that we only move the body along the up axis, because
477 // move_and_collide may stray the object a bit when getting it unstuck.
478 // Canceling this motion should not affect move_and_slide, as previous
479 // calls to move_and_collide already took care of freeing the body.
480 if (result.travel.length() > margin) {
481 result.travel = up_direction * up_direction.dot(result.travel);
482 } else {
483 result.travel = Vector3();
484 }
485
486 parameters.from.origin += result.travel;
487 set_global_transform(parameters.from);
488 }
489 }
490 }
491
492 void CharacterBody3D::_snap_on_floor(bool p_was_on_floor, bool p_vel_dir_facing_up) {
493 if (collision_state.floor || !p_was_on_floor || p_vel_dir_facing_up) {
494 return;
495 }
496
497 apply_floor_snap();
498 }
499
500 bool CharacterBody3D::_on_floor_if_snapped(bool p_was_on_floor, bool p_vel_dir_facing_up) {
501 if (up_direction == Vector3() || collision_state.floor || !p_was_on_floor || p_vel_dir_facing_up) {
502 return false;
503 }
504
505 // Snap by at least collision margin to keep floor state consistent.
506 real_t length = MAX(floor_snap_length, margin);
507
508 PhysicsServer3D::MotionParameters parameters(get_global_transform(), -up_direction * length, margin);
509 parameters.max_collisions = 4;
510 parameters.recovery_as_collision = true; // Also report collisions generated only from recovery.
511 parameters.collide_separation_ray = true;
512
513 PhysicsServer3D::MotionResult result;
514 if (move_and_collide(parameters, result, true, false)) {
515 CollisionState result_state;
516 // Don't apply direction for any type.
517 _set_collision_direction(result, result_state, CollisionState());
518
519 return result_state.floor;
520 }
521
522 return false;
523 }
524
525 void CharacterBody3D::_set_collision_direction(const PhysicsServer3D::MotionResult &p_result, CollisionState &r_state, CollisionState p_apply_state) {
526 r_state.state = 0;
527
528 real_t wall_depth = -1.0;
529 real_t floor_depth = -1.0;
530
531 bool was_on_wall = collision_state.wall;
532 Vector3 prev_wall_normal = wall_normal;
533 int wall_collision_count = 0;
534 Vector3 combined_wall_normal;
535 Vector3 tmp_wall_col; // Avoid duplicate on average calculation.
536
537 for (int i = p_result.collision_count - 1; i >= 0; i--) {
538 const PhysicsServer3D::MotionCollision &collision = p_result.collisions[i];
539
540 if (motion_mode == MOTION_MODE_GROUNDED) {
541 // Check if any collision is floor.
542 real_t floor_angle = collision.get_angle(up_direction);
543 if (floor_angle <= floor_max_angle + FLOOR_ANGLE_THRESHOLD) {
544 r_state.floor = true;
545 if (p_apply_state.floor && collision.depth > floor_depth) {
546 collision_state.floor = true;
547 floor_normal = collision.normal;
548 floor_depth = collision.depth;
549 _set_platform_data(collision);
550 }
551 continue;
552 }
553
554 // Check if any collision is ceiling.
555 real_t ceiling_angle = collision.get_angle(-up_direction);
556 if (ceiling_angle <= floor_max_angle + FLOOR_ANGLE_THRESHOLD) {
557 r_state.ceiling = true;
558 if (p_apply_state.ceiling) {
559 platform_ceiling_velocity = collision.collider_velocity;
560 ceiling_normal = collision.normal;
561 collision_state.ceiling = true;
562 }
563 continue;
564 }
565 }
566
567 // Collision is wall by default.
568 r_state.wall = true;
569
570 if (p_apply_state.wall && collision.depth > wall_depth) {
571 collision_state.wall = true;
572 wall_depth = collision.depth;
573 wall_normal = collision.normal;
574
575 // Don't apply wall velocity when the collider is a CharacterBody3D.
576 if (ObjectDB::get_instance<CharacterBody3D>(collision.collider_id) == nullptr) {
577 _set_platform_data(collision);
578 }
579 }
580
581 // Collect normal for calculating average.
582 if (!collision.normal.is_equal_approx(tmp_wall_col)) {
583 tmp_wall_col = collision.normal;
584 combined_wall_normal += collision.normal;
585 wall_collision_count++;
586 }
587 }
588
589 if (r_state.wall) {
590 if (wall_collision_count > 1 && !r_state.floor) {
591 // Check if wall normals cancel out to floor support.
592 if (!r_state.floor && motion_mode == MOTION_MODE_GROUNDED) {
593 combined_wall_normal.normalize();
594 real_t floor_angle = Math::acos(combined_wall_normal.dot(up_direction));
595 if (floor_angle <= floor_max_angle + FLOOR_ANGLE_THRESHOLD) {
596 r_state.floor = true;
597 r_state.wall = false;
598 if (p_apply_state.floor) {
599 collision_state.floor = true;
600 floor_normal = combined_wall_normal;
601 }
602 if (p_apply_state.wall) {
603 collision_state.wall = was_on_wall;
604 wall_normal = prev_wall_normal;
605 }
606 return;
607 }
608 }
609 }
610 }
611 }
612
613 void CharacterBody3D::_set_platform_data(const PhysicsServer3D::MotionCollision &p_collision) {
614 PhysicsDirectBodyState3D *bs = PhysicsServer3D::get_singleton()->body_get_direct_state(p_collision.collider);
615 if (bs == nullptr) {
616 return;
617 }
618
619 platform_rid = p_collision.collider;
620 platform_object_id = p_collision.collider_id;
621 platform_velocity = p_collision.collider_velocity;
622 platform_angular_velocity = p_collision.collider_angular_velocity;
623
624 #ifndef DISABLE_DEPRECATED
625 // Try to accommodate for any physics extensions that have yet to implement `PhysicsDirectBodyState3D::get_collision_layer`.
626 PhysicsDirectBodyState3DExtension *bs_ext = Object::cast_to<PhysicsDirectBodyState3DExtension>(bs);
627 if (bs_ext != nullptr && !GDVIRTUAL_IS_OVERRIDDEN_PTR(bs_ext, _get_collision_layer)) {
628 platform_layer = PhysicsServer3D::get_singleton()->body_get_collision_layer(p_collision.collider);
629 } else
630 #endif
631 {
632 platform_layer = bs->get_collision_layer();
633 }
634 }
635
636 void CharacterBody3D::set_safe_margin(real_t p_margin) {
637 margin = p_margin;
638 }
639
640 real_t CharacterBody3D::get_safe_margin() const {
641 return margin;
642 }
643
644 const Vector3 &CharacterBody3D::get_velocity() const {
645 return velocity;
646 }
647
648 void CharacterBody3D::set_velocity(const Vector3 &p_velocity) {
649 velocity = p_velocity;
650 }
651
652 bool CharacterBody3D::is_on_floor() const {
653 return collision_state.floor;
654 }
655
656 bool CharacterBody3D::is_on_floor_only() const {
657 return collision_state.floor && !collision_state.wall && !collision_state.ceiling;
658 }
659
660 bool CharacterBody3D::is_on_wall() const {
661 return collision_state.wall;
662 }
663
664 bool CharacterBody3D::is_on_wall_only() const {
665 return collision_state.wall && !collision_state.floor && !collision_state.ceiling;
666 }
667
668 bool CharacterBody3D::is_on_ceiling() const {
669 return collision_state.ceiling;
670 }
671
672 bool CharacterBody3D::is_on_ceiling_only() const {
673 return collision_state.ceiling && !collision_state.floor && !collision_state.wall;
674 }
675
676 const Vector3 &CharacterBody3D::get_floor_normal() const {
677 return floor_normal;
678 }
679
680 const Vector3 &CharacterBody3D::get_wall_normal() const {
681 return wall_normal;
682 }
683
684 const Vector3 &CharacterBody3D::get_last_motion() const {
685 return last_motion;
686 }
687
688 Vector3 CharacterBody3D::get_position_delta() const {
689 return get_global_transform().origin - previous_position;
690 }
691
692 const Vector3 &CharacterBody3D::get_real_velocity() const {
693 return real_velocity;
694 }
695
696 real_t CharacterBody3D::get_floor_angle(const Vector3 &p_up_direction) const {
697 ERR_FAIL_COND_V(p_up_direction == Vector3(), 0);
698 return Math::acos(floor_normal.dot(p_up_direction));
699 }
700
701 const Vector3 &CharacterBody3D::get_platform_velocity() const {
702 return platform_velocity;
703 }
704
705 const Vector3 &CharacterBody3D::get_platform_angular_velocity() const {
706 return platform_angular_velocity;
707 }
708
709 Vector3 CharacterBody3D::get_linear_velocity() const {
710 return get_real_velocity();
711 }
712
713 int CharacterBody3D::get_slide_collision_count() const {
714 return motion_results.size();
715 }
716
717 PhysicsServer3D::MotionResult CharacterBody3D::get_slide_collision(int p_bounce) const {
718 ERR_FAIL_INDEX_V(p_bounce, motion_results.size(), PhysicsServer3D::MotionResult());
719 return motion_results[p_bounce];
720 }
721
722 Ref<KinematicCollision3D> CharacterBody3D::_get_slide_collision(int p_bounce) {
723 ERR_FAIL_INDEX_V(p_bounce, motion_results.size(), Ref<KinematicCollision3D>());
724 if (p_bounce >= slide_colliders.size()) {
725 slide_colliders.resize(p_bounce + 1);
726 }
727
728 // Create a new instance when the cached reference is invalid or still in use in script.
729 if (slide_colliders[p_bounce].is_null() || slide_colliders[p_bounce]->get_reference_count() > 1) {
730 slide_colliders.write[p_bounce].instantiate();
731 slide_colliders.write[p_bounce]->owner_id = get_instance_id();
732 }
733
734 slide_colliders.write[p_bounce]->result = motion_results[p_bounce];
735 return slide_colliders[p_bounce];
736 }
737
738 Ref<KinematicCollision3D> CharacterBody3D::_get_last_slide_collision() {
739 if (motion_results.is_empty()) {
740 return Ref<KinematicCollision3D>();
741 }
742 return _get_slide_collision(motion_results.size() - 1);
743 }
744
745 bool CharacterBody3D::is_floor_stop_on_slope_enabled() const {
746 return floor_stop_on_slope;
747 }
748
749 void CharacterBody3D::set_floor_stop_on_slope_enabled(bool p_enabled) {
750 floor_stop_on_slope = p_enabled;
751 }
752
753 bool CharacterBody3D::is_floor_constant_speed_enabled() const {
754 return floor_constant_speed;
755 }
756
757 void CharacterBody3D::set_floor_constant_speed_enabled(bool p_enabled) {
758 floor_constant_speed = p_enabled;
759 }
760
761 bool CharacterBody3D::is_floor_block_on_wall_enabled() const {
762 return floor_block_on_wall;
763 }
764
765 void CharacterBody3D::set_floor_block_on_wall_enabled(bool p_enabled) {
766 floor_block_on_wall = p_enabled;
767 }
768
769 bool CharacterBody3D::is_slide_on_ceiling_enabled() const {
770 return slide_on_ceiling;
771 }
772
773 void CharacterBody3D::set_slide_on_ceiling_enabled(bool p_enabled) {
774 slide_on_ceiling = p_enabled;
775 }
776
777 uint32_t CharacterBody3D::get_platform_floor_layers() const {
778 return platform_floor_layers;
779 }
780
781 void CharacterBody3D::set_platform_floor_layers(uint32_t p_exclude_layers) {
782 platform_floor_layers = p_exclude_layers;
783 }
784
785 uint32_t CharacterBody3D::get_platform_wall_layers() const {
786 return platform_wall_layers;
787 }
788
789 void CharacterBody3D::set_platform_wall_layers(uint32_t p_exclude_layers) {
790 platform_wall_layers = p_exclude_layers;
791 }
792
793 void CharacterBody3D::set_motion_mode(MotionMode p_mode) {
794 motion_mode = p_mode;
795 }
796
797 CharacterBody3D::MotionMode CharacterBody3D::get_motion_mode() const {
798 return motion_mode;
799 }
800
801 void CharacterBody3D::set_platform_on_leave(PlatformOnLeave p_on_leave_apply_velocity) {
802 platform_on_leave = p_on_leave_apply_velocity;
803 }
804
805 CharacterBody3D::PlatformOnLeave CharacterBody3D::get_platform_on_leave() const {
806 return platform_on_leave;
807 }
808
809 int CharacterBody3D::get_max_slides() const {
810 return max_slides;
811 }
812
813 void CharacterBody3D::set_max_slides(int p_max_slides) {
814 ERR_FAIL_COND(p_max_slides < 1);
815 max_slides = p_max_slides;
816 }
817
818 real_t CharacterBody3D::get_floor_max_angle() const {
819 return floor_max_angle;
820 }
821
822 void CharacterBody3D::set_floor_max_angle(real_t p_radians) {
823 floor_max_angle = p_radians;
824 }
825
826 real_t CharacterBody3D::get_floor_snap_length() {
827 return floor_snap_length;
828 }
829
830 void CharacterBody3D::set_floor_snap_length(real_t p_floor_snap_length) {
831 ERR_FAIL_COND(p_floor_snap_length < 0);
832 floor_snap_length = p_floor_snap_length;
833 }
834
835 real_t CharacterBody3D::get_wall_min_slide_angle() const {
836 return wall_min_slide_angle;
837 }
838
839 void CharacterBody3D::set_wall_min_slide_angle(real_t p_radians) {
840 wall_min_slide_angle = p_radians;
841 }
842
843 const Vector3 &CharacterBody3D::get_up_direction() const {
844 return up_direction;
845 }
846
847 void CharacterBody3D::set_up_direction(const Vector3 &p_up_direction) {
848 ERR_FAIL_COND_MSG(p_up_direction == Vector3(), "up_direction can't be equal to Vector3.ZERO, consider using Floating motion mode instead.");
849 up_direction = p_up_direction.normalized();
850 }
851
852 void CharacterBody3D::_notification(int p_what) {
853 switch (p_what) {
854 case NOTIFICATION_ENTER_TREE: {
855 // Reset move_and_slide() data.
856 collision_state.state = 0;
857 platform_rid = RID();
858 platform_object_id = ObjectID();
859 motion_results.clear();
860 platform_velocity = Vector3();
861 platform_angular_velocity = Vector3();
862 } break;
863 }
864 }
865
866 void CharacterBody3D::_bind_methods() {
867 ClassDB::bind_method(D_METHOD("move_and_slide"), &CharacterBody3D::move_and_slide);
868 ClassDB::bind_method(D_METHOD("apply_floor_snap"), &CharacterBody3D::apply_floor_snap);
869
870 ClassDB::bind_method(D_METHOD("set_velocity", "velocity"), &CharacterBody3D::set_velocity);
871 ClassDB::bind_method(D_METHOD("get_velocity"), &CharacterBody3D::get_velocity);
872
873 ClassDB::bind_method(D_METHOD("set_safe_margin", "margin"), &CharacterBody3D::set_safe_margin);
874 ClassDB::bind_method(D_METHOD("get_safe_margin"), &CharacterBody3D::get_safe_margin);
875 ClassDB::bind_method(D_METHOD("is_floor_stop_on_slope_enabled"), &CharacterBody3D::is_floor_stop_on_slope_enabled);
876 ClassDB::bind_method(D_METHOD("set_floor_stop_on_slope_enabled", "enabled"), &CharacterBody3D::set_floor_stop_on_slope_enabled);
877 ClassDB::bind_method(D_METHOD("set_floor_constant_speed_enabled", "enabled"), &CharacterBody3D::set_floor_constant_speed_enabled);
878 ClassDB::bind_method(D_METHOD("is_floor_constant_speed_enabled"), &CharacterBody3D::is_floor_constant_speed_enabled);
879 ClassDB::bind_method(D_METHOD("set_floor_block_on_wall_enabled", "enabled"), &CharacterBody3D::set_floor_block_on_wall_enabled);
880 ClassDB::bind_method(D_METHOD("is_floor_block_on_wall_enabled"), &CharacterBody3D::is_floor_block_on_wall_enabled);
881 ClassDB::bind_method(D_METHOD("set_slide_on_ceiling_enabled", "enabled"), &CharacterBody3D::set_slide_on_ceiling_enabled);
882 ClassDB::bind_method(D_METHOD("is_slide_on_ceiling_enabled"), &CharacterBody3D::is_slide_on_ceiling_enabled);
883
884 ClassDB::bind_method(D_METHOD("set_platform_floor_layers", "exclude_layer"), &CharacterBody3D::set_platform_floor_layers);
885 ClassDB::bind_method(D_METHOD("get_platform_floor_layers"), &CharacterBody3D::get_platform_floor_layers);
886 ClassDB::bind_method(D_METHOD("set_platform_wall_layers", "exclude_layer"), &CharacterBody3D::set_platform_wall_layers);
887 ClassDB::bind_method(D_METHOD("get_platform_wall_layers"), &CharacterBody3D::get_platform_wall_layers);
888
889 ClassDB::bind_method(D_METHOD("get_max_slides"), &CharacterBody3D::get_max_slides);
890 ClassDB::bind_method(D_METHOD("set_max_slides", "max_slides"), &CharacterBody3D::set_max_slides);
891 ClassDB::bind_method(D_METHOD("get_floor_max_angle"), &CharacterBody3D::get_floor_max_angle);
892 ClassDB::bind_method(D_METHOD("set_floor_max_angle", "radians"), &CharacterBody3D::set_floor_max_angle);
893 ClassDB::bind_method(D_METHOD("get_floor_snap_length"), &CharacterBody3D::get_floor_snap_length);
894 ClassDB::bind_method(D_METHOD("set_floor_snap_length", "floor_snap_length"), &CharacterBody3D::set_floor_snap_length);
895 ClassDB::bind_method(D_METHOD("get_wall_min_slide_angle"), &CharacterBody3D::get_wall_min_slide_angle);
896 ClassDB::bind_method(D_METHOD("set_wall_min_slide_angle", "radians"), &CharacterBody3D::set_wall_min_slide_angle);
897 ClassDB::bind_method(D_METHOD("get_up_direction"), &CharacterBody3D::get_up_direction);
898 ClassDB::bind_method(D_METHOD("set_up_direction", "up_direction"), &CharacterBody3D::set_up_direction);
899 ClassDB::bind_method(D_METHOD("set_motion_mode", "mode"), &CharacterBody3D::set_motion_mode);
900 ClassDB::bind_method(D_METHOD("get_motion_mode"), &CharacterBody3D::get_motion_mode);
901 ClassDB::bind_method(D_METHOD("set_platform_on_leave", "on_leave_apply_velocity"), &CharacterBody3D::set_platform_on_leave);
902 ClassDB::bind_method(D_METHOD("get_platform_on_leave"), &CharacterBody3D::get_platform_on_leave);
903
904 ClassDB::bind_method(D_METHOD("is_on_floor"), &CharacterBody3D::is_on_floor);
905 ClassDB::bind_method(D_METHOD("is_on_floor_only"), &CharacterBody3D::is_on_floor_only);
906 ClassDB::bind_method(D_METHOD("is_on_ceiling"), &CharacterBody3D::is_on_ceiling);
907 ClassDB::bind_method(D_METHOD("is_on_ceiling_only"), &CharacterBody3D::is_on_ceiling_only);
908 ClassDB::bind_method(D_METHOD("is_on_wall"), &CharacterBody3D::is_on_wall);
909 ClassDB::bind_method(D_METHOD("is_on_wall_only"), &CharacterBody3D::is_on_wall_only);
910 ClassDB::bind_method(D_METHOD("get_floor_normal"), &CharacterBody3D::get_floor_normal);
911 ClassDB::bind_method(D_METHOD("get_wall_normal"), &CharacterBody3D::get_wall_normal);
912 ClassDB::bind_method(D_METHOD("get_last_motion"), &CharacterBody3D::get_last_motion);
913 ClassDB::bind_method(D_METHOD("get_position_delta"), &CharacterBody3D::get_position_delta);
914 ClassDB::bind_method(D_METHOD("get_real_velocity"), &CharacterBody3D::get_real_velocity);
915 ClassDB::bind_method(D_METHOD("get_floor_angle", "up_direction"), &CharacterBody3D::get_floor_angle, DEFVAL(Vector3(0.0, 1.0, 0.0)));
916 ClassDB::bind_method(D_METHOD("get_platform_velocity"), &CharacterBody3D::get_platform_velocity);
917 ClassDB::bind_method(D_METHOD("get_platform_angular_velocity"), &CharacterBody3D::get_platform_angular_velocity);
918 ClassDB::bind_method(D_METHOD("get_slide_collision_count"), &CharacterBody3D::get_slide_collision_count);
919 ClassDB::bind_method(D_METHOD("get_slide_collision", "slide_idx"), &CharacterBody3D::_get_slide_collision);
920 ClassDB::bind_method(D_METHOD("get_last_slide_collision"), &CharacterBody3D::_get_last_slide_collision);
921
922 ADD_PROPERTY(PropertyInfo(Variant::INT, "motion_mode", PROPERTY_HINT_ENUM, "Grounded,Floating", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), "set_motion_mode", "get_motion_mode");
923 ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "up_direction"), "set_up_direction", "get_up_direction");
924 ADD_PROPERTY(PropertyInfo(Variant::BOOL, "slide_on_ceiling"), "set_slide_on_ceiling_enabled", "is_slide_on_ceiling_enabled");
925 ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "velocity", PROPERTY_HINT_NONE, "suffix:m/s", PROPERTY_USAGE_NO_EDITOR), "set_velocity", "get_velocity");
926 ADD_PROPERTY(PropertyInfo(Variant::INT, "max_slides", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR), "set_max_slides", "get_max_slides");
927 ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "wall_min_slide_angle", PROPERTY_HINT_RANGE, "0,180,0.1,radians_as_degrees", PROPERTY_USAGE_DEFAULT), "set_wall_min_slide_angle", "get_wall_min_slide_angle");
928
929 ADD_GROUP("Floor", "floor_");
930 ADD_PROPERTY(PropertyInfo(Variant::BOOL, "floor_stop_on_slope"), "set_floor_stop_on_slope_enabled", "is_floor_stop_on_slope_enabled");
931 ADD_PROPERTY(PropertyInfo(Variant::BOOL, "floor_constant_speed"), "set_floor_constant_speed_enabled", "is_floor_constant_speed_enabled");
932 ADD_PROPERTY(PropertyInfo(Variant::BOOL, "floor_block_on_wall"), "set_floor_block_on_wall_enabled", "is_floor_block_on_wall_enabled");
933 ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "floor_max_angle", PROPERTY_HINT_RANGE, "0,180,0.1,radians_as_degrees"), "set_floor_max_angle", "get_floor_max_angle");
934 ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "floor_snap_length", PROPERTY_HINT_RANGE, "0,1,0.01,or_greater,suffix:m"), "set_floor_snap_length", "get_floor_snap_length");
935
936 ADD_GROUP("Moving Platform", "platform_");
937 ADD_PROPERTY(PropertyInfo(Variant::INT, "platform_on_leave", PROPERTY_HINT_ENUM, "Add Velocity,Add Upward Velocity,Do Nothing", PROPERTY_USAGE_DEFAULT), "set_platform_on_leave", "get_platform_on_leave");
938 ADD_PROPERTY(PropertyInfo(Variant::INT, "platform_floor_layers", PROPERTY_HINT_LAYERS_3D_PHYSICS), "set_platform_floor_layers", "get_platform_floor_layers");
939 ADD_PROPERTY(PropertyInfo(Variant::INT, "platform_wall_layers", PROPERTY_HINT_LAYERS_3D_PHYSICS), "set_platform_wall_layers", "get_platform_wall_layers");
940
941 ADD_GROUP("Collision", "");
942 ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "safe_margin", PROPERTY_HINT_RANGE, "0.001,256,0.001,suffix:m"), "set_safe_margin", "get_safe_margin");
943
944 BIND_ENUM_CONSTANT(MOTION_MODE_GROUNDED);
945 BIND_ENUM_CONSTANT(MOTION_MODE_FLOATING);
946
947 BIND_ENUM_CONSTANT(PLATFORM_ON_LEAVE_ADD_VELOCITY);
948 BIND_ENUM_CONSTANT(PLATFORM_ON_LEAVE_ADD_UPWARD_VELOCITY);
949 BIND_ENUM_CONSTANT(PLATFORM_ON_LEAVE_DO_NOTHING);
950 }
951
952 void CharacterBody3D::_validate_property(PropertyInfo &p_property) const {
953 if (!Engine::get_singleton()->is_editor_hint()) {
954 return;
955 }
956 if (motion_mode == MOTION_MODE_FLOATING) {
957 if (p_property.name.begins_with("floor_") || p_property.name == "up_direction" || p_property.name == "slide_on_ceiling") {
958 p_property.usage = PROPERTY_USAGE_NO_EDITOR;
959 }
960 }
961 }
962
963 CharacterBody3D::CharacterBody3D() :
964 PhysicsBody3D(PhysicsServer3D::BODY_MODE_KINEMATIC) {
965 }