character_body_3d.cpp 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944
  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. #include "character_body_3d.h"
  31. //so, if you pass 45 as limit, avoid numerical precision errors when angle is 45.
  32. #define FLOOR_ANGLE_THRESHOLD 0.01
  33. bool CharacterBody3D::move_and_slide() {
  34. // Hack in order to work with calling from _process as well as from _physics_process; calling from thread is risky
  35. double delta = Engine::get_singleton()->is_in_physics_frame() ? get_physics_process_delta_time() : get_process_delta_time();
  36. for (int i = 0; i < 3; i++) {
  37. if (locked_axis & (1 << i)) {
  38. velocity[i] = 0.0;
  39. }
  40. }
  41. Transform3D gt = get_global_transform();
  42. previous_position = gt.origin;
  43. Vector3 current_platform_velocity = platform_velocity;
  44. if ((collision_state.floor || collision_state.wall) && platform_rid.is_valid()) {
  45. bool excluded = false;
  46. if (collision_state.floor) {
  47. excluded = (platform_floor_layers & platform_layer) == 0;
  48. } else if (collision_state.wall) {
  49. excluded = (platform_wall_layers & platform_layer) == 0;
  50. }
  51. if (!excluded) {
  52. PhysicsDirectBodyState3D *bs = nullptr;
  53. // We need to check the platform_rid object still exists before accessing.
  54. // A valid RID is no guarantee that the object has not been deleted.
  55. // We can only perform the ObjectDB lifetime check on Object derived objects.
  56. // Note that physics also creates RIDs for non-Object derived objects, these cannot
  57. // be lifetime checked through ObjectDB, and therefore there is a still a vulnerability
  58. // to dangling RIDs (access after free) in this scenario.
  59. if (platform_object_id.is_null() || ObjectDB::get_instance(platform_object_id)) {
  60. // This approach makes sure there is less delay between the actual body velocity and the one we saved.
  61. bs = PhysicsServer3D::get_singleton()->body_get_direct_state(platform_rid);
  62. }
  63. if (bs) {
  64. Vector3 local_position = gt.origin - bs->get_transform().origin;
  65. current_platform_velocity = bs->get_velocity_at_local_position(local_position);
  66. } else {
  67. // Body is removed or destroyed, invalidate floor.
  68. current_platform_velocity = Vector3();
  69. platform_rid = RID();
  70. }
  71. } else {
  72. current_platform_velocity = Vector3();
  73. }
  74. }
  75. motion_results.clear();
  76. bool was_on_floor = collision_state.floor;
  77. collision_state.state = 0;
  78. last_motion = Vector3();
  79. if (!current_platform_velocity.is_zero_approx()) {
  80. PhysicsServer3D::MotionParameters parameters(get_global_transform(), current_platform_velocity * delta, margin);
  81. parameters.recovery_as_collision = true; // Also report collisions generated only from recovery.
  82. parameters.exclude_bodies.insert(platform_rid);
  83. if (platform_object_id.is_valid()) {
  84. parameters.exclude_objects.insert(platform_object_id);
  85. }
  86. PhysicsServer3D::MotionResult floor_result;
  87. if (move_and_collide(parameters, floor_result, false, false)) {
  88. motion_results.push_back(floor_result);
  89. CollisionState result_state;
  90. _set_collision_direction(floor_result, result_state);
  91. }
  92. }
  93. if (motion_mode == MOTION_MODE_GROUNDED) {
  94. _move_and_slide_grounded(delta, was_on_floor);
  95. } else {
  96. _move_and_slide_floating(delta);
  97. }
  98. // Compute real velocity.
  99. real_velocity = get_position_delta() / delta;
  100. if (platform_on_leave != PLATFORM_ON_LEAVE_DO_NOTHING) {
  101. // Add last platform velocity when just left a moving platform.
  102. if (!collision_state.floor && !collision_state.wall) {
  103. if (platform_on_leave == PLATFORM_ON_LEAVE_ADD_UPWARD_VELOCITY && current_platform_velocity.dot(up_direction) < 0) {
  104. current_platform_velocity = current_platform_velocity.slide(up_direction);
  105. }
  106. velocity += current_platform_velocity;
  107. }
  108. }
  109. return motion_results.size() > 0;
  110. }
  111. void CharacterBody3D::_move_and_slide_grounded(double p_delta, bool p_was_on_floor) {
  112. Vector3 motion = velocity * p_delta;
  113. Vector3 motion_slide_up = motion.slide(up_direction);
  114. Vector3 prev_floor_normal = floor_normal;
  115. platform_rid = RID();
  116. platform_object_id = ObjectID();
  117. platform_velocity = Vector3();
  118. platform_angular_velocity = Vector3();
  119. platform_ceiling_velocity = Vector3();
  120. floor_normal = Vector3();
  121. wall_normal = Vector3();
  122. ceiling_normal = Vector3();
  123. // No sliding on first attempt to keep floor motion stable when possible,
  124. // When stop on slope is enabled or when there is no up direction.
  125. bool sliding_enabled = !floor_stop_on_slope;
  126. // Constant speed can be applied only the first time sliding is enabled.
  127. bool can_apply_constant_speed = sliding_enabled;
  128. // If the platform's ceiling push down the body.
  129. bool apply_ceiling_velocity = false;
  130. bool first_slide = true;
  131. bool vel_dir_facing_up = velocity.dot(up_direction) > 0;
  132. Vector3 total_travel;
  133. for (int iteration = 0; iteration < max_slides; ++iteration) {
  134. PhysicsServer3D::MotionParameters parameters(get_global_transform(), motion, margin);
  135. parameters.max_collisions = 6; // There can be 4 collisions between 2 walls + 2 more for the floor.
  136. parameters.recovery_as_collision = true; // Also report collisions generated only from recovery.
  137. PhysicsServer3D::MotionResult result;
  138. bool collided = move_and_collide(parameters, result, false, !sliding_enabled);
  139. last_motion = result.travel;
  140. if (collided) {
  141. motion_results.push_back(result);
  142. CollisionState previous_state = collision_state;
  143. CollisionState result_state;
  144. _set_collision_direction(result, result_state);
  145. // If we hit a ceiling platform, we set the vertical velocity to at least the platform one.
  146. if (collision_state.ceiling && platform_ceiling_velocity != Vector3() && platform_ceiling_velocity.dot(up_direction) < 0) {
  147. // If ceiling sliding is on, only apply when the ceiling is flat or when the motion is upward.
  148. if (!slide_on_ceiling || motion.dot(up_direction) < 0 || (ceiling_normal + up_direction).length() < 0.01) {
  149. apply_ceiling_velocity = true;
  150. Vector3 ceiling_vertical_velocity = up_direction * up_direction.dot(platform_ceiling_velocity);
  151. Vector3 motion_vertical_velocity = up_direction * up_direction.dot(velocity);
  152. if (motion_vertical_velocity.dot(up_direction) > 0 || ceiling_vertical_velocity.length_squared() > motion_vertical_velocity.length_squared()) {
  153. velocity = ceiling_vertical_velocity + velocity.slide(up_direction);
  154. }
  155. }
  156. }
  157. if (collision_state.floor && floor_stop_on_slope && (velocity.normalized() + up_direction).length() < 0.01) {
  158. Transform3D gt = get_global_transform();
  159. if (result.travel.length() <= margin + CMP_EPSILON) {
  160. gt.origin -= result.travel;
  161. }
  162. set_global_transform(gt);
  163. velocity = Vector3();
  164. motion = Vector3();
  165. last_motion = Vector3();
  166. break;
  167. }
  168. if (result.remainder.is_zero_approx()) {
  169. motion = Vector3();
  170. break;
  171. }
  172. // Apply regular sliding by default.
  173. bool apply_default_sliding = true;
  174. // Wall collision checks.
  175. if (result_state.wall && (motion_slide_up.dot(wall_normal) <= 0)) {
  176. // Move on floor only checks.
  177. if (floor_block_on_wall) {
  178. // Needs horizontal motion from current motion instead of motion_slide_up
  179. // to properly test the angle and avoid standing on slopes
  180. Vector3 horizontal_motion = motion.slide(up_direction);
  181. Vector3 horizontal_normal = wall_normal.slide(up_direction).normalized();
  182. real_t motion_angle = Math::abs(Math::acos(-horizontal_normal.dot(horizontal_motion.normalized())));
  183. // Avoid to move forward on a wall if floor_block_on_wall is true.
  184. // Applies only when the motion angle is under 90 degrees,
  185. // in order to avoid blocking lateral motion along a wall.
  186. if (motion_angle < .5 * Math_PI) {
  187. apply_default_sliding = false;
  188. if (p_was_on_floor && !vel_dir_facing_up) {
  189. // Cancel the motion.
  190. Transform3D gt = get_global_transform();
  191. real_t travel_total = result.travel.length();
  192. real_t cancel_dist_max = MIN(0.1, margin * 20);
  193. if (travel_total <= margin + CMP_EPSILON) {
  194. gt.origin -= result.travel;
  195. result.travel = Vector3(); // Cancel for constant speed computation.
  196. } else if (travel_total < cancel_dist_max) { // If the movement is large the body can be prevented from reaching the walls.
  197. gt.origin -= result.travel.slide(up_direction);
  198. // Keep remaining motion in sync with amount canceled.
  199. motion = motion.slide(up_direction);
  200. result.travel = Vector3();
  201. } else {
  202. // Travel is too high to be safely canceled, we take it into account.
  203. result.travel = result.travel.slide(up_direction);
  204. motion = result.remainder;
  205. }
  206. set_global_transform(gt);
  207. // Determines if you are on the ground, and limits the possibility of climbing on the walls because of the approximations.
  208. _snap_on_floor(true, false);
  209. } else {
  210. // If the movement is not canceled we only keep the remaining.
  211. motion = result.remainder;
  212. }
  213. // Apply slide on forward in order to allow only lateral motion on next step.
  214. Vector3 forward = wall_normal.slide(up_direction).normalized();
  215. motion = motion.slide(forward);
  216. // Scales the horizontal velocity according to the wall slope.
  217. if (vel_dir_facing_up) {
  218. Vector3 slide_motion = velocity.slide(result.collisions[0].normal);
  219. // Keeps the vertical motion from velocity and add the horizontal motion of the projection.
  220. velocity = up_direction * up_direction.dot(velocity) + slide_motion.slide(up_direction);
  221. } else {
  222. velocity = velocity.slide(forward);
  223. }
  224. // Allow only lateral motion along previous floor when already on floor.
  225. // Fixes slowing down when moving in diagonal against an inclined wall.
  226. if (p_was_on_floor && !vel_dir_facing_up && (motion.dot(up_direction) > 0.0)) {
  227. // Slide along the corner between the wall and previous floor.
  228. Vector3 floor_side = prev_floor_normal.cross(wall_normal);
  229. if (floor_side != Vector3()) {
  230. motion = floor_side * motion.dot(floor_side);
  231. }
  232. }
  233. // Stop all motion when a second wall is hit (unless sliding down or jumping),
  234. // in order to avoid jittering in corner cases.
  235. bool stop_all_motion = previous_state.wall && !vel_dir_facing_up;
  236. // Allow sliding when the body falls.
  237. if (!collision_state.floor && motion.dot(up_direction) < 0) {
  238. Vector3 slide_motion = motion.slide(wall_normal);
  239. // Test again to allow sliding only if the result goes downwards.
  240. // Fixes jittering issues at the bottom of inclined walls.
  241. if (slide_motion.dot(up_direction) < 0) {
  242. stop_all_motion = false;
  243. motion = slide_motion;
  244. }
  245. }
  246. if (stop_all_motion) {
  247. motion = Vector3();
  248. velocity = Vector3();
  249. }
  250. }
  251. }
  252. // Stop horizontal motion when under wall slide threshold.
  253. if (p_was_on_floor && (wall_min_slide_angle > 0.0) && result_state.wall) {
  254. Vector3 horizontal_normal = wall_normal.slide(up_direction).normalized();
  255. real_t motion_angle = Math::abs(Math::acos(-horizontal_normal.dot(motion_slide_up.normalized())));
  256. if (motion_angle < wall_min_slide_angle) {
  257. motion = up_direction * motion.dot(up_direction);
  258. velocity = up_direction * velocity.dot(up_direction);
  259. apply_default_sliding = false;
  260. }
  261. }
  262. }
  263. if (apply_default_sliding) {
  264. // Regular sliding, the last part of the test handle the case when you don't want to slide on the ceiling.
  265. if ((sliding_enabled || !collision_state.floor) && (!collision_state.ceiling || slide_on_ceiling || !vel_dir_facing_up) && !apply_ceiling_velocity) {
  266. const PhysicsServer3D::MotionCollision &collision = result.collisions[0];
  267. Vector3 slide_motion = result.remainder.slide(collision.normal);
  268. if (collision_state.floor && !collision_state.wall && !motion_slide_up.is_zero_approx()) {
  269. // Slide using the intersection between the motion plane and the floor plane,
  270. // in order to keep the direction intact.
  271. real_t motion_length = slide_motion.length();
  272. slide_motion = up_direction.cross(result.remainder).cross(floor_normal);
  273. // Keep the length from default slide to change speed in slopes by default,
  274. // when constant speed is not enabled.
  275. slide_motion.normalize();
  276. slide_motion *= motion_length;
  277. }
  278. if (slide_motion.dot(velocity) > 0.0) {
  279. motion = slide_motion;
  280. } else {
  281. motion = Vector3();
  282. }
  283. if (slide_on_ceiling && result_state.ceiling) {
  284. // Apply slide only in the direction of the input motion, otherwise just stop to avoid jittering when moving against a wall.
  285. if (vel_dir_facing_up) {
  286. velocity = velocity.slide(collision.normal);
  287. } else {
  288. // Avoid acceleration in slope when falling.
  289. velocity = up_direction * up_direction.dot(velocity);
  290. }
  291. }
  292. }
  293. // No sliding on first attempt to keep floor motion stable when possible.
  294. else {
  295. motion = result.remainder;
  296. if (result_state.ceiling && !slide_on_ceiling && vel_dir_facing_up) {
  297. velocity = velocity.slide(up_direction);
  298. motion = motion.slide(up_direction);
  299. }
  300. }
  301. }
  302. total_travel += result.travel;
  303. // Apply Constant Speed.
  304. if (p_was_on_floor && floor_constant_speed && can_apply_constant_speed && collision_state.floor && !motion.is_zero_approx()) {
  305. Vector3 travel_slide_up = total_travel.slide(up_direction);
  306. motion = motion.normalized() * MAX(0, (motion_slide_up.length() - travel_slide_up.length()));
  307. }
  308. }
  309. // When you move forward in a downward slope you don’t collide because you will be in the air.
  310. // This test ensures that constant speed is applied, only if the player is still on the ground after the snap is applied.
  311. else if (floor_constant_speed && first_slide && _on_floor_if_snapped(p_was_on_floor, vel_dir_facing_up)) {
  312. can_apply_constant_speed = false;
  313. sliding_enabled = true;
  314. Transform3D gt = get_global_transform();
  315. gt.origin = gt.origin - result.travel;
  316. set_global_transform(gt);
  317. // Slide using the intersection between the motion plane and the floor plane,
  318. // in order to keep the direction intact.
  319. Vector3 motion_slide_norm = up_direction.cross(motion).cross(prev_floor_normal);
  320. motion_slide_norm.normalize();
  321. motion = motion_slide_norm * (motion_slide_up.length());
  322. collided = true;
  323. }
  324. if (!collided || motion.is_zero_approx()) {
  325. break;
  326. }
  327. can_apply_constant_speed = !can_apply_constant_speed && !sliding_enabled;
  328. sliding_enabled = true;
  329. first_slide = false;
  330. }
  331. _snap_on_floor(p_was_on_floor, vel_dir_facing_up);
  332. // Reset the gravity accumulation when touching the ground.
  333. if (collision_state.floor && !vel_dir_facing_up) {
  334. velocity = velocity.slide(up_direction);
  335. }
  336. }
  337. void CharacterBody3D::_move_and_slide_floating(double p_delta) {
  338. Vector3 motion = velocity * p_delta;
  339. platform_rid = RID();
  340. platform_object_id = ObjectID();
  341. floor_normal = Vector3();
  342. platform_velocity = Vector3();
  343. platform_angular_velocity = Vector3();
  344. bool first_slide = true;
  345. for (int iteration = 0; iteration < max_slides; ++iteration) {
  346. PhysicsServer3D::MotionParameters parameters(get_global_transform(), motion, margin);
  347. parameters.recovery_as_collision = true; // Also report collisions generated only from recovery.
  348. PhysicsServer3D::MotionResult result;
  349. bool collided = move_and_collide(parameters, result, false, false);
  350. last_motion = result.travel;
  351. if (collided) {
  352. motion_results.push_back(result);
  353. CollisionState result_state;
  354. _set_collision_direction(result, result_state);
  355. if (result.remainder.is_zero_approx()) {
  356. motion = Vector3();
  357. break;
  358. }
  359. if (wall_min_slide_angle != 0 && Math::acos(wall_normal.dot(-velocity.normalized())) < wall_min_slide_angle + FLOOR_ANGLE_THRESHOLD) {
  360. motion = Vector3();
  361. if (result.travel.length() < margin + CMP_EPSILON) {
  362. Transform3D gt = get_global_transform();
  363. gt.origin -= result.travel;
  364. set_global_transform(gt);
  365. }
  366. } else if (first_slide) {
  367. Vector3 motion_slide_norm = result.remainder.slide(wall_normal).normalized();
  368. motion = motion_slide_norm * (motion.length() - result.travel.length());
  369. } else {
  370. motion = result.remainder.slide(wall_normal);
  371. }
  372. if (motion.dot(velocity) <= 0.0) {
  373. motion = Vector3();
  374. }
  375. }
  376. if (!collided || motion.is_zero_approx()) {
  377. break;
  378. }
  379. first_slide = false;
  380. }
  381. }
  382. void CharacterBody3D::apply_floor_snap() {
  383. if (collision_state.floor) {
  384. return;
  385. }
  386. // Snap by at least collision margin to keep floor state consistent.
  387. real_t length = MAX(floor_snap_length, margin);
  388. PhysicsServer3D::MotionParameters parameters(get_global_transform(), -up_direction * length, margin);
  389. parameters.max_collisions = 4;
  390. parameters.recovery_as_collision = true; // Also report collisions generated only from recovery.
  391. parameters.collide_separation_ray = true;
  392. PhysicsServer3D::MotionResult result;
  393. if (move_and_collide(parameters, result, true, false)) {
  394. CollisionState result_state;
  395. // Apply direction for floor only.
  396. _set_collision_direction(result, result_state, CollisionState(true, false, false));
  397. if (result_state.floor) {
  398. // Ensure that we only move the body along the up axis, because
  399. // move_and_collide may stray the object a bit when getting it unstuck.
  400. // Canceling this motion should not affect move_and_slide, as previous
  401. // calls to move_and_collide already took care of freeing the body.
  402. if (result.travel.length() > margin) {
  403. result.travel = up_direction * up_direction.dot(result.travel);
  404. } else {
  405. result.travel = Vector3();
  406. }
  407. parameters.from.origin += result.travel;
  408. set_global_transform(parameters.from);
  409. }
  410. }
  411. }
  412. void CharacterBody3D::_snap_on_floor(bool p_was_on_floor, bool p_vel_dir_facing_up) {
  413. if (collision_state.floor || !p_was_on_floor || p_vel_dir_facing_up) {
  414. return;
  415. }
  416. apply_floor_snap();
  417. }
  418. bool CharacterBody3D::_on_floor_if_snapped(bool p_was_on_floor, bool p_vel_dir_facing_up) {
  419. if (up_direction == Vector3() || collision_state.floor || !p_was_on_floor || p_vel_dir_facing_up) {
  420. return false;
  421. }
  422. // Snap by at least collision margin to keep floor state consistent.
  423. real_t length = MAX(floor_snap_length, margin);
  424. PhysicsServer3D::MotionParameters parameters(get_global_transform(), -up_direction * length, margin);
  425. parameters.max_collisions = 4;
  426. parameters.recovery_as_collision = true; // Also report collisions generated only from recovery.
  427. parameters.collide_separation_ray = true;
  428. PhysicsServer3D::MotionResult result;
  429. if (move_and_collide(parameters, result, true, false)) {
  430. CollisionState result_state;
  431. // Don't apply direction for any type.
  432. _set_collision_direction(result, result_state, CollisionState());
  433. return result_state.floor;
  434. }
  435. return false;
  436. }
  437. void CharacterBody3D::_set_collision_direction(const PhysicsServer3D::MotionResult &p_result, CollisionState &r_state, CollisionState p_apply_state) {
  438. r_state.state = 0;
  439. real_t wall_depth = -1.0;
  440. real_t floor_depth = -1.0;
  441. bool was_on_wall = collision_state.wall;
  442. Vector3 prev_wall_normal = wall_normal;
  443. int wall_collision_count = 0;
  444. Vector3 combined_wall_normal;
  445. Vector3 tmp_wall_col; // Avoid duplicate on average calculation.
  446. for (int i = p_result.collision_count - 1; i >= 0; i--) {
  447. const PhysicsServer3D::MotionCollision &collision = p_result.collisions[i];
  448. if (motion_mode == MOTION_MODE_GROUNDED) {
  449. // Check if any collision is floor.
  450. real_t floor_angle = collision.get_angle(up_direction);
  451. if (floor_angle <= floor_max_angle + FLOOR_ANGLE_THRESHOLD) {
  452. r_state.floor = true;
  453. if (p_apply_state.floor && collision.depth > floor_depth) {
  454. collision_state.floor = true;
  455. floor_normal = collision.normal;
  456. floor_depth = collision.depth;
  457. _set_platform_data(collision);
  458. }
  459. continue;
  460. }
  461. // Check if any collision is ceiling.
  462. real_t ceiling_angle = collision.get_angle(-up_direction);
  463. if (ceiling_angle <= floor_max_angle + FLOOR_ANGLE_THRESHOLD) {
  464. r_state.ceiling = true;
  465. if (p_apply_state.ceiling) {
  466. platform_ceiling_velocity = collision.collider_velocity;
  467. ceiling_normal = collision.normal;
  468. collision_state.ceiling = true;
  469. }
  470. continue;
  471. }
  472. }
  473. // Collision is wall by default.
  474. r_state.wall = true;
  475. if (p_apply_state.wall && collision.depth > wall_depth) {
  476. collision_state.wall = true;
  477. wall_depth = collision.depth;
  478. wall_normal = collision.normal;
  479. // Don't apply wall velocity when the collider is a CharacterBody3D.
  480. if (Object::cast_to<CharacterBody3D>(ObjectDB::get_instance(collision.collider_id)) == nullptr) {
  481. _set_platform_data(collision);
  482. }
  483. }
  484. // Collect normal for calculating average.
  485. if (!collision.normal.is_equal_approx(tmp_wall_col)) {
  486. tmp_wall_col = collision.normal;
  487. combined_wall_normal += collision.normal;
  488. wall_collision_count++;
  489. }
  490. }
  491. if (r_state.wall) {
  492. if (wall_collision_count > 1 && !r_state.floor) {
  493. // Check if wall normals cancel out to floor support.
  494. if (!r_state.floor && motion_mode == MOTION_MODE_GROUNDED) {
  495. combined_wall_normal.normalize();
  496. real_t floor_angle = Math::acos(combined_wall_normal.dot(up_direction));
  497. if (floor_angle <= floor_max_angle + FLOOR_ANGLE_THRESHOLD) {
  498. r_state.floor = true;
  499. r_state.wall = false;
  500. if (p_apply_state.floor) {
  501. collision_state.floor = true;
  502. floor_normal = combined_wall_normal;
  503. }
  504. if (p_apply_state.wall) {
  505. collision_state.wall = was_on_wall;
  506. wall_normal = prev_wall_normal;
  507. }
  508. return;
  509. }
  510. }
  511. }
  512. }
  513. }
  514. void CharacterBody3D::_set_platform_data(const PhysicsServer3D::MotionCollision &p_collision) {
  515. platform_rid = p_collision.collider;
  516. platform_object_id = p_collision.collider_id;
  517. platform_velocity = p_collision.collider_velocity;
  518. platform_angular_velocity = p_collision.collider_angular_velocity;
  519. platform_layer = PhysicsServer3D::get_singleton()->body_get_collision_layer(platform_rid);
  520. }
  521. void CharacterBody3D::set_safe_margin(real_t p_margin) {
  522. margin = p_margin;
  523. }
  524. real_t CharacterBody3D::get_safe_margin() const {
  525. return margin;
  526. }
  527. const Vector3 &CharacterBody3D::get_velocity() const {
  528. return velocity;
  529. }
  530. void CharacterBody3D::set_velocity(const Vector3 &p_velocity) {
  531. velocity = p_velocity;
  532. }
  533. bool CharacterBody3D::is_on_floor() const {
  534. return collision_state.floor;
  535. }
  536. bool CharacterBody3D::is_on_floor_only() const {
  537. return collision_state.floor && !collision_state.wall && !collision_state.ceiling;
  538. }
  539. bool CharacterBody3D::is_on_wall() const {
  540. return collision_state.wall;
  541. }
  542. bool CharacterBody3D::is_on_wall_only() const {
  543. return collision_state.wall && !collision_state.floor && !collision_state.ceiling;
  544. }
  545. bool CharacterBody3D::is_on_ceiling() const {
  546. return collision_state.ceiling;
  547. }
  548. bool CharacterBody3D::is_on_ceiling_only() const {
  549. return collision_state.ceiling && !collision_state.floor && !collision_state.wall;
  550. }
  551. const Vector3 &CharacterBody3D::get_floor_normal() const {
  552. return floor_normal;
  553. }
  554. const Vector3 &CharacterBody3D::get_wall_normal() const {
  555. return wall_normal;
  556. }
  557. const Vector3 &CharacterBody3D::get_last_motion() const {
  558. return last_motion;
  559. }
  560. Vector3 CharacterBody3D::get_position_delta() const {
  561. return get_global_transform().origin - previous_position;
  562. }
  563. const Vector3 &CharacterBody3D::get_real_velocity() const {
  564. return real_velocity;
  565. }
  566. real_t CharacterBody3D::get_floor_angle(const Vector3 &p_up_direction) const {
  567. ERR_FAIL_COND_V(p_up_direction == Vector3(), 0);
  568. return Math::acos(floor_normal.dot(p_up_direction));
  569. }
  570. const Vector3 &CharacterBody3D::get_platform_velocity() const {
  571. return platform_velocity;
  572. }
  573. const Vector3 &CharacterBody3D::get_platform_angular_velocity() const {
  574. return platform_angular_velocity;
  575. }
  576. Vector3 CharacterBody3D::get_linear_velocity() const {
  577. return get_real_velocity();
  578. }
  579. int CharacterBody3D::get_slide_collision_count() const {
  580. return motion_results.size();
  581. }
  582. PhysicsServer3D::MotionResult CharacterBody3D::get_slide_collision(int p_bounce) const {
  583. ERR_FAIL_INDEX_V(p_bounce, motion_results.size(), PhysicsServer3D::MotionResult());
  584. return motion_results[p_bounce];
  585. }
  586. Ref<KinematicCollision3D> CharacterBody3D::_get_slide_collision(int p_bounce) {
  587. ERR_FAIL_INDEX_V(p_bounce, motion_results.size(), Ref<KinematicCollision3D>());
  588. if (p_bounce >= slide_colliders.size()) {
  589. slide_colliders.resize(p_bounce + 1);
  590. }
  591. // Create a new instance when the cached reference is invalid or still in use in script.
  592. if (slide_colliders[p_bounce].is_null() || slide_colliders[p_bounce]->get_reference_count() > 1) {
  593. slide_colliders.write[p_bounce].instantiate();
  594. slide_colliders.write[p_bounce]->owner_id = get_instance_id();
  595. }
  596. slide_colliders.write[p_bounce]->result = motion_results[p_bounce];
  597. return slide_colliders[p_bounce];
  598. }
  599. Ref<KinematicCollision3D> CharacterBody3D::_get_last_slide_collision() {
  600. if (motion_results.size() == 0) {
  601. return Ref<KinematicCollision3D>();
  602. }
  603. return _get_slide_collision(motion_results.size() - 1);
  604. }
  605. bool CharacterBody3D::is_floor_stop_on_slope_enabled() const {
  606. return floor_stop_on_slope;
  607. }
  608. void CharacterBody3D::set_floor_stop_on_slope_enabled(bool p_enabled) {
  609. floor_stop_on_slope = p_enabled;
  610. }
  611. bool CharacterBody3D::is_floor_constant_speed_enabled() const {
  612. return floor_constant_speed;
  613. }
  614. void CharacterBody3D::set_floor_constant_speed_enabled(bool p_enabled) {
  615. floor_constant_speed = p_enabled;
  616. }
  617. bool CharacterBody3D::is_floor_block_on_wall_enabled() const {
  618. return floor_block_on_wall;
  619. }
  620. void CharacterBody3D::set_floor_block_on_wall_enabled(bool p_enabled) {
  621. floor_block_on_wall = p_enabled;
  622. }
  623. bool CharacterBody3D::is_slide_on_ceiling_enabled() const {
  624. return slide_on_ceiling;
  625. }
  626. void CharacterBody3D::set_slide_on_ceiling_enabled(bool p_enabled) {
  627. slide_on_ceiling = p_enabled;
  628. }
  629. uint32_t CharacterBody3D::get_platform_floor_layers() const {
  630. return platform_floor_layers;
  631. }
  632. void CharacterBody3D::set_platform_floor_layers(uint32_t p_exclude_layers) {
  633. platform_floor_layers = p_exclude_layers;
  634. }
  635. uint32_t CharacterBody3D::get_platform_wall_layers() const {
  636. return platform_wall_layers;
  637. }
  638. void CharacterBody3D::set_platform_wall_layers(uint32_t p_exclude_layers) {
  639. platform_wall_layers = p_exclude_layers;
  640. }
  641. void CharacterBody3D::set_motion_mode(MotionMode p_mode) {
  642. motion_mode = p_mode;
  643. }
  644. CharacterBody3D::MotionMode CharacterBody3D::get_motion_mode() const {
  645. return motion_mode;
  646. }
  647. void CharacterBody3D::set_platform_on_leave(PlatformOnLeave p_on_leave_apply_velocity) {
  648. platform_on_leave = p_on_leave_apply_velocity;
  649. }
  650. CharacterBody3D::PlatformOnLeave CharacterBody3D::get_platform_on_leave() const {
  651. return platform_on_leave;
  652. }
  653. int CharacterBody3D::get_max_slides() const {
  654. return max_slides;
  655. }
  656. void CharacterBody3D::set_max_slides(int p_max_slides) {
  657. ERR_FAIL_COND(p_max_slides < 1);
  658. max_slides = p_max_slides;
  659. }
  660. real_t CharacterBody3D::get_floor_max_angle() const {
  661. return floor_max_angle;
  662. }
  663. void CharacterBody3D::set_floor_max_angle(real_t p_radians) {
  664. floor_max_angle = p_radians;
  665. }
  666. real_t CharacterBody3D::get_floor_snap_length() {
  667. return floor_snap_length;
  668. }
  669. void CharacterBody3D::set_floor_snap_length(real_t p_floor_snap_length) {
  670. ERR_FAIL_COND(p_floor_snap_length < 0);
  671. floor_snap_length = p_floor_snap_length;
  672. }
  673. real_t CharacterBody3D::get_wall_min_slide_angle() const {
  674. return wall_min_slide_angle;
  675. }
  676. void CharacterBody3D::set_wall_min_slide_angle(real_t p_radians) {
  677. wall_min_slide_angle = p_radians;
  678. }
  679. const Vector3 &CharacterBody3D::get_up_direction() const {
  680. return up_direction;
  681. }
  682. void CharacterBody3D::set_up_direction(const Vector3 &p_up_direction) {
  683. ERR_FAIL_COND_MSG(p_up_direction == Vector3(), "up_direction can't be equal to Vector3.ZERO, consider using Floating motion mode instead.");
  684. up_direction = p_up_direction.normalized();
  685. }
  686. void CharacterBody3D::_notification(int p_what) {
  687. switch (p_what) {
  688. case NOTIFICATION_ENTER_TREE: {
  689. // Reset move_and_slide() data.
  690. collision_state.state = 0;
  691. platform_rid = RID();
  692. platform_object_id = ObjectID();
  693. motion_results.clear();
  694. platform_velocity = Vector3();
  695. platform_angular_velocity = Vector3();
  696. } break;
  697. }
  698. }
  699. void CharacterBody3D::_bind_methods() {
  700. ClassDB::bind_method(D_METHOD("move_and_slide"), &CharacterBody3D::move_and_slide);
  701. ClassDB::bind_method(D_METHOD("apply_floor_snap"), &CharacterBody3D::apply_floor_snap);
  702. ClassDB::bind_method(D_METHOD("set_velocity", "velocity"), &CharacterBody3D::set_velocity);
  703. ClassDB::bind_method(D_METHOD("get_velocity"), &CharacterBody3D::get_velocity);
  704. ClassDB::bind_method(D_METHOD("set_safe_margin", "margin"), &CharacterBody3D::set_safe_margin);
  705. ClassDB::bind_method(D_METHOD("get_safe_margin"), &CharacterBody3D::get_safe_margin);
  706. ClassDB::bind_method(D_METHOD("is_floor_stop_on_slope_enabled"), &CharacterBody3D::is_floor_stop_on_slope_enabled);
  707. ClassDB::bind_method(D_METHOD("set_floor_stop_on_slope_enabled", "enabled"), &CharacterBody3D::set_floor_stop_on_slope_enabled);
  708. ClassDB::bind_method(D_METHOD("set_floor_constant_speed_enabled", "enabled"), &CharacterBody3D::set_floor_constant_speed_enabled);
  709. ClassDB::bind_method(D_METHOD("is_floor_constant_speed_enabled"), &CharacterBody3D::is_floor_constant_speed_enabled);
  710. ClassDB::bind_method(D_METHOD("set_floor_block_on_wall_enabled", "enabled"), &CharacterBody3D::set_floor_block_on_wall_enabled);
  711. ClassDB::bind_method(D_METHOD("is_floor_block_on_wall_enabled"), &CharacterBody3D::is_floor_block_on_wall_enabled);
  712. ClassDB::bind_method(D_METHOD("set_slide_on_ceiling_enabled", "enabled"), &CharacterBody3D::set_slide_on_ceiling_enabled);
  713. ClassDB::bind_method(D_METHOD("is_slide_on_ceiling_enabled"), &CharacterBody3D::is_slide_on_ceiling_enabled);
  714. ClassDB::bind_method(D_METHOD("set_platform_floor_layers", "exclude_layer"), &CharacterBody3D::set_platform_floor_layers);
  715. ClassDB::bind_method(D_METHOD("get_platform_floor_layers"), &CharacterBody3D::get_platform_floor_layers);
  716. ClassDB::bind_method(D_METHOD("set_platform_wall_layers", "exclude_layer"), &CharacterBody3D::set_platform_wall_layers);
  717. ClassDB::bind_method(D_METHOD("get_platform_wall_layers"), &CharacterBody3D::get_platform_wall_layers);
  718. ClassDB::bind_method(D_METHOD("get_max_slides"), &CharacterBody3D::get_max_slides);
  719. ClassDB::bind_method(D_METHOD("set_max_slides", "max_slides"), &CharacterBody3D::set_max_slides);
  720. ClassDB::bind_method(D_METHOD("get_floor_max_angle"), &CharacterBody3D::get_floor_max_angle);
  721. ClassDB::bind_method(D_METHOD("set_floor_max_angle", "radians"), &CharacterBody3D::set_floor_max_angle);
  722. ClassDB::bind_method(D_METHOD("get_floor_snap_length"), &CharacterBody3D::get_floor_snap_length);
  723. ClassDB::bind_method(D_METHOD("set_floor_snap_length", "floor_snap_length"), &CharacterBody3D::set_floor_snap_length);
  724. ClassDB::bind_method(D_METHOD("get_wall_min_slide_angle"), &CharacterBody3D::get_wall_min_slide_angle);
  725. ClassDB::bind_method(D_METHOD("set_wall_min_slide_angle", "radians"), &CharacterBody3D::set_wall_min_slide_angle);
  726. ClassDB::bind_method(D_METHOD("get_up_direction"), &CharacterBody3D::get_up_direction);
  727. ClassDB::bind_method(D_METHOD("set_up_direction", "up_direction"), &CharacterBody3D::set_up_direction);
  728. ClassDB::bind_method(D_METHOD("set_motion_mode", "mode"), &CharacterBody3D::set_motion_mode);
  729. ClassDB::bind_method(D_METHOD("get_motion_mode"), &CharacterBody3D::get_motion_mode);
  730. ClassDB::bind_method(D_METHOD("set_platform_on_leave", "on_leave_apply_velocity"), &CharacterBody3D::set_platform_on_leave);
  731. ClassDB::bind_method(D_METHOD("get_platform_on_leave"), &CharacterBody3D::get_platform_on_leave);
  732. ClassDB::bind_method(D_METHOD("is_on_floor"), &CharacterBody3D::is_on_floor);
  733. ClassDB::bind_method(D_METHOD("is_on_floor_only"), &CharacterBody3D::is_on_floor_only);
  734. ClassDB::bind_method(D_METHOD("is_on_ceiling"), &CharacterBody3D::is_on_ceiling);
  735. ClassDB::bind_method(D_METHOD("is_on_ceiling_only"), &CharacterBody3D::is_on_ceiling_only);
  736. ClassDB::bind_method(D_METHOD("is_on_wall"), &CharacterBody3D::is_on_wall);
  737. ClassDB::bind_method(D_METHOD("is_on_wall_only"), &CharacterBody3D::is_on_wall_only);
  738. ClassDB::bind_method(D_METHOD("get_floor_normal"), &CharacterBody3D::get_floor_normal);
  739. ClassDB::bind_method(D_METHOD("get_wall_normal"), &CharacterBody3D::get_wall_normal);
  740. ClassDB::bind_method(D_METHOD("get_last_motion"), &CharacterBody3D::get_last_motion);
  741. ClassDB::bind_method(D_METHOD("get_position_delta"), &CharacterBody3D::get_position_delta);
  742. ClassDB::bind_method(D_METHOD("get_real_velocity"), &CharacterBody3D::get_real_velocity);
  743. ClassDB::bind_method(D_METHOD("get_floor_angle", "up_direction"), &CharacterBody3D::get_floor_angle, DEFVAL(Vector3(0.0, 1.0, 0.0)));
  744. ClassDB::bind_method(D_METHOD("get_platform_velocity"), &CharacterBody3D::get_platform_velocity);
  745. ClassDB::bind_method(D_METHOD("get_platform_angular_velocity"), &CharacterBody3D::get_platform_angular_velocity);
  746. ClassDB::bind_method(D_METHOD("get_slide_collision_count"), &CharacterBody3D::get_slide_collision_count);
  747. ClassDB::bind_method(D_METHOD("get_slide_collision", "slide_idx"), &CharacterBody3D::_get_slide_collision);
  748. ClassDB::bind_method(D_METHOD("get_last_slide_collision"), &CharacterBody3D::_get_last_slide_collision);
  749. 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");
  750. ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "up_direction"), "set_up_direction", "get_up_direction");
  751. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "slide_on_ceiling"), "set_slide_on_ceiling_enabled", "is_slide_on_ceiling_enabled");
  752. ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "velocity", PROPERTY_HINT_NONE, "suffix:m/s", PROPERTY_USAGE_NO_EDITOR), "set_velocity", "get_velocity");
  753. ADD_PROPERTY(PropertyInfo(Variant::INT, "max_slides", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR), "set_max_slides", "get_max_slides");
  754. 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");
  755. ADD_GROUP("Floor", "floor_");
  756. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "floor_stop_on_slope"), "set_floor_stop_on_slope_enabled", "is_floor_stop_on_slope_enabled");
  757. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "floor_constant_speed"), "set_floor_constant_speed_enabled", "is_floor_constant_speed_enabled");
  758. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "floor_block_on_wall"), "set_floor_block_on_wall_enabled", "is_floor_block_on_wall_enabled");
  759. 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");
  760. 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");
  761. ADD_GROUP("Moving Platform", "platform_");
  762. 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");
  763. ADD_PROPERTY(PropertyInfo(Variant::INT, "platform_floor_layers", PROPERTY_HINT_LAYERS_3D_PHYSICS), "set_platform_floor_layers", "get_platform_floor_layers");
  764. ADD_PROPERTY(PropertyInfo(Variant::INT, "platform_wall_layers", PROPERTY_HINT_LAYERS_3D_PHYSICS), "set_platform_wall_layers", "get_platform_wall_layers");
  765. ADD_GROUP("Collision", "");
  766. ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "safe_margin", PROPERTY_HINT_RANGE, "0.001,256,0.001,suffix:m"), "set_safe_margin", "get_safe_margin");
  767. BIND_ENUM_CONSTANT(MOTION_MODE_GROUNDED);
  768. BIND_ENUM_CONSTANT(MOTION_MODE_FLOATING);
  769. BIND_ENUM_CONSTANT(PLATFORM_ON_LEAVE_ADD_VELOCITY);
  770. BIND_ENUM_CONSTANT(PLATFORM_ON_LEAVE_ADD_UPWARD_VELOCITY);
  771. BIND_ENUM_CONSTANT(PLATFORM_ON_LEAVE_DO_NOTHING);
  772. }
  773. void CharacterBody3D::_validate_property(PropertyInfo &p_property) const {
  774. if (motion_mode == MOTION_MODE_FLOATING) {
  775. if (p_property.name.begins_with("floor_") || p_property.name == "up_direction" || p_property.name == "slide_on_ceiling") {
  776. p_property.usage = PROPERTY_USAGE_NO_EDITOR;
  777. }
  778. }
  779. }
  780. CharacterBody3D::CharacterBody3D() :
  781. PhysicsBody3D(PhysicsServer3D::BODY_MODE_KINEMATIC) {
  782. }