-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathikcc.gd
2086 lines (1650 loc) · 84.1 KB
/
ikcc.gd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
## Implements a kinematic/virtual character body.
class_name IKCC
extends PhysicsBody3D
#==================================================================================================
# -----------------------
# | CONSTANTS AND ENUMS |
# -----------------------
## The maximum slide iterations allowed.
const MAX_SLIDES : int = 5 # Default: 5
## The maximum collision reports per slide iteration.
const MAX_SLIDE_COLLISIONS : int = 6 # Default: 6
## The maximum collision reports per floor snaps.
const MAX_SNAP_COLLISIONS : int = 4 # Default: 4
## The maximum collision reports for motionless collision checks.
const MAX_REST_COLLISIONS : int = 4 # Default: 4
## The maximum number of constraint iterations
const MAX_CONSTRAINT_ITERATIONS : int = 7 # Default: 7 (Jolt's CharacterVirtual's is 15)
## General epsilon used to compare floats.
const CMP_EPSILON : float = 0.00001 # Default: 0.00001
## Epsilon used when checking if given planes are equal to each other.
const PLANES_CMP_EPSILON : float = 0.00001 # Default: 0.00001
## Epsilon used when classifying collisions by the angle of their normals.
const ANGLE_CMP_EPSILON : float = 0.01 # Default: 0.01
## Offset length used when offsetting raycasts.
const RAYCAST_OFFSET_LENGTH : float = 0.001 # Default: 0.001
## The length of a recovery can approximately be no more than safe margin times this number.
const RECOVERY_FACTOR : float = 2.0 # Default: 2.0
## The factor used to increase the safe margin for the final touch collision check.
const TOUCH_SAFE_MARGIN_FACTOR : float = 2.0 # Default: 2.0
## Different modes for sliding collision response.
enum MotionMode {
## Suitable for moving along the ground.
GROUNDED,
## Suitable for flying or swimming movement.
FLOATING
}
## Defines how to modify the velocity when leaving a moving platform.
enum PlatformLeaveAction {
## Does nothing when leaving a platform.
DO_NOTHING,
## Adds the last platform velocity to [member velocity] when leaving a platform.
ADD_VELOCITY,
## Adds the last platform velocity without the downward component to [member velocity].
ADD_VELOCITY_NO_DOWNWARDS
}
#==================================================================================================
# --------------
# | PROPERTIES |
# --------------
## Sets the motion mode which defines the behavior of [method move_and_slide].
## See [enum MotionMode] constants for available modes.
@export var motion_mode := MotionMode.GROUNDED
## Vector pointing upwards, used to determine what is a wall and what is a floor (or a ceiling)
## when calling [method move_and_slide].
@export var up_direction : Vector3 = Vector3.UP :
set(value) : up_direction = value.normalized()
@export_group("Assign me a reference!")
## Reference to the collider belonging to the character body.
@export var collider : CollisionShape3D
@export_group("Floor")
## Maximum angle where a slope is still considered a floor (or a ceiling), rather than a wall.
@export_range(0.0, 180.0, 0.1, "degrees")
var floor_max_angle_degrees : float = 45.0 :
set (value) :
floor_max_angle = value * (PI/180.0) # Set radian variable
floor_max_angle_degrees = value # Set degree variable
## If [code]true[/code], removes the sliding caused by the downward component of [member velocity]
## when landing from air onto a sloped floor. Additionally, [member velocity] will keep it's horizontal
## direction when solving a floor constraint. (The horizontal plane is defined by
## [member up_direction].) [br]
## It's [b]important[/b] to note that if you want gravity and other downwards and towards the floor
## accelerations to drag the body down on floor slopes, you should set this to [code]false[/code],
## (because keeping horizontal direction is undesired in that scenario)!
@export var floor_stop_on_slope : bool = true
## If [code]true[/code], [member velocity] will keep it's original magnitude when solving a floor
## constraint.
@export var floor_constant_speed : bool = false
## Sets a maximum snapping distance. When set to a value different from [code]0.0[/code], the body is
## kept attached to slopes when calling [method move_and_slide]. The snapping vector is determined by
## the given distance along the opposite direction of the [member up_direction]. If the body snaps
## to the floor, [member velocity] will be modified so that it parallels the floor plane.
@export_range(0.0, 1.0, 0.01, "suffix:m") var max_snap_length : float = 0.26 :
set(value) : max_snap_length = absf(value)
## If [member velocity] has a magnitude of at least [floor_detach_threshold] in the opposite
## direction of a floor, the body will not snap to it, otherwise it won't.
@export var floor_detach_threshold : float = 2.0
@export_group("Wall")
## If [code]true[/code], the body will not slide up wall slopes when colliding with them on floor.
@export var floor_block_on_wall : bool = true
## If the angle of a wall collision is smaller than this angle, the body will stop
## instead of sliding along it.
@export_range(0.0, 180.0, 0.1, "degrees")
var wall_min_slide_angle_degrees : float = 15.0 :
set (value) :
wall_min_slide_angle = value * (PI/180.0) # Set radian variable
wall_min_slide_angle_degrees = value # Set degree variable
## If [code]true[/code], [member velocity] will keep it's original magnitude when solving a wall
## constraint.
@export var wall_constant_speed : bool = false
@export_group("Ceiling")
## If [code]false[/code], the body will not slide up ceilings.
@export var slide_up_ceilings : bool = true
## If [code]true[/code], [member velocity] will keep it's original magnitude when solving a ceiling
## constraint.
@export var ceiling_constant_speed : bool = false
@export_group("Moving Platforms")
## If [code]true[/code], the applied motion from [member platform_velocity] will also follow the sliding behaviour,
## instead of stopping on collisions.
@export var slide_platform_motion : bool = true
## Sets the behavior to apply when you leave a moving platform. By default, to be physically accurate,
## when you leave the last platform velocity is applied. See [enum PlatformLeaveAction] constants for available behavior.
@export var platform_leave_action := PlatformLeaveAction.ADD_VELOCITY
## If the vertical platform velocity change is larger than this threshold, the body will detach
## from the platform. Note that this only works if the leave velocity large enough to bypass
## the floor snap. (See [member floor_detach_threshold].)
@export var platform_detach_treshold : float = 1.0
## Collision layers that will be included for detecting floor bodies that will act as moving platforms
## to be followed by the body.
@export_flags_3d_physics var moving_platform_layers : int = 1
@export_group("Stepping")
## Sets the maximum height of the walls the character can step on.
@export_range(0.0, 1.0, 0.01, "suffix:m") var max_step_height : float = 0.26 :
set(value) : max_step_height = absf(value)
## Sets the mimimum distance the character will move towards a wall when attempting to step on it.
@export_range(0.0, 0.01, 0.001) var min_step_forward_distance : float = 0.001
## If stepping will not result in the body landing on a floor, an additional test will be made to
## see if there is floor further along the step direction, the distance to travel forward in this
## test is [member step_floor_check_distance]. If a floor is found, the step move will be succesful.
@export_range(0.0, 0.5, 0.01) var step_floor_check_distance : float = 0.3
@export_group("Rigid Body Interactions")
## If [code]false[/code], rigid bodies collisions will be treated as collisions with static bodies. [br]
## If [code]true[/code], contact impulses and weight force will be simulated when colliding with
## rigid bodies. In this case, it's [b]important[/b] that the collision mask of the rigid bodies that
## will be interacted with has the character's collision layer excluded!
@export var interact_with_rigid_bodies : bool = true
## The mass of the character body.
@export_range(0.001, 1000.0, 0.001, "suffix:kg") var mass : float = 1.0 :
set(value) :
mass = maxf(CMP_EPSILON, value)
inverse_mass = 1.0 / mass
@export_group("Collision")
## Extra margin used for recovery and during slide collisons. [br] [br]
## If the body is at least this close to another body, it will consider them to be colliding
## and will be pushed away before performing the actual motion. [br]
## A higher value means it's more flexible for detecting collision, which helps with consistently
## detecting walls and floors. [br]
## A lower value forces the collision algorithm to use more exact detection, so it can be used in
## cases that specifically require precision, e.g at very low scale to avoid visible jittering,
## or for stability with a stack of character bodies.
@export_range(0.001, 0.010, 0.001, "suffix:m") var safe_margin : float = 0.001 :
set(value) : safe_margin = absf(value)
#==================================================================================================
# --------------
# | VARIABLES |
# --------------
## [code]true[/code] if the body is touching a floor. [br]
## Set during [method move_and_slide].
var is_on_floor : bool
## [code]true[/code] if the body is touching a wall. [br]
## Set during [method move_and_slide].
var is_on_wall : bool
## [code]true[/code] if the body is touching a ceiling. [br]
## Set during [method move_and_slide].
var is_on_ceiling : bool
## [code]true[/code] if the body collided with a floor. [br]
## Set during [method move_and_slide].
var collided_with_floor : bool
## [code]true[/code] if the body collided with a wall. [br]
## Set during [method move_and_slide].
var collided_with_wall : bool
## [code]true[/code] if the body collided with a ceiling. [br]
## Set during [method move_and_slide].
var collided_with_ceiling : bool
## [code]true[/code] if the body is touching a floor surface. [br]
## Set during [method move_and_slide].
var is_on_floor_surface : bool
## [code]true[/code] if the body performed a step move. [br]
## Set during [method move_and_slide].
var has_stepped : bool
## [code]true[/code] if the body is touched a floor in the previous call to [method move_and_slide]. [br]
## Set during [method move_and_slide].
var prev_on_floor : bool
## [code]true[/code] if the body is touched a floor surface in the previous call to [method move_and_slide]. [br]
## Set during [method move_and_slide].
var prev_on_floor_surface : bool
## [code]true[/code] if platform velocity was valid in the previous call to [method move_and_slide]. [br]
## Set during [method move_and_slide].
var prev_platform_velocity_valid : bool
## The linear velocity of the body.
var velocity : Vector3
## The position delta divided by delta time. [br]
## Set during [method move_and_slide].
var real_velocity : Vector3
## The travel vector from the last call to [method move_and_slide].
var delta_position : Vector3
## The normal of the deepest active floor collision. If the body is not touching a floor, it's a zero vector. [br]
## Set during [method move_and_slide].
var current_floor_normal : Vector3
## The normal of the deepest active wall collision. If the body is not touching a wall, it's a zero vector. [br]
## Set during [method move_and_slide].
var current_wall_normal : Vector3
## The normal of the deepest active ceiling collision. If the body is not touching a ceiling, it's a zero vector. [br]
## Set during [method move_and_slide].
var current_ceiling_normal : Vector3
## The normal of the latest floor collision. If the body did not collide with a floor, it's a zero vector. [br]
## Set during [method move_and_slide].
var last_floor_normal : Vector3
## The normal of the latest wall collision. If the body did not collide with a wall, it's a zero vector. [br]
## Set during [method move_and_slide].
var last_wall_normal : Vector3
## The normal of the latest ceiling collision. If the body did not collide with a ceiling, it's a zero vector. [br]
## Set during [method move_and_slide].
var last_ceiling_normal : Vector3
## The velocity of the floor collider at the position of the character body. If the body is not on
## a floor, it's a zero vector. [br]
## Set during [method move_and_slide].
var platform_velocity : Vector3
## The velocity the body hit the ground with arriving from air. If that didn't happen, it's a zero vector. [br]
## Set during [method move_and_slide].
var floor_impact_velocity : Vector3
## The global position of the body before the latest call to [method move_and_slide]. [br]
## Set during [method move_and_slide].
var previous_position : Vector3
## Stores the id of the current floor collider the body is touching. [br]
## Set during [method move_and_slide].
var current_floor_collider_encoded : EncodedObjectAsID
## The RID of the current floor collider the body is touching. [br]
## Set during [method move_and_slide].
var current_floor_collider_rid : RID
## An array of data objects that holds collision data sorted by colliders. [br]
## Set during [method move_and_slide].
var collider_datas : Array[ColliderData]
## An array of data objects that stores information about the collisions that happened
## during the latest call to [method move_and_slide]. [br]
## Does not include collision data of the final touch collision check and floor snaps.
var collision_states : Array[CollisionState]
## ## The collision data of the latest floor snap. [br]
## Set during [method move_and_slide] and [method snap_to_floor]. [br]
## [b]Note:[/b] Wall and ceiling collisions are not registered by floor snapping.
var snap_collision_state : CollisionState
## The collision data of the last collision check at the final position of the body. [br]
## Set during [method move_and_slide]. [br]
## [b]Note:[/b] Floor collisions are not registered in this object, because floor status
## at the final position is detected exclusively by floor snapping.
## Check [member snap_collision_state] for the final registered floor data.
var touch_collision_state : CollisionState
# Translate angle properties to radian when initialising
## The minimum wall slide angle in radians.
@onready var wall_min_slide_angle : float = wall_min_slide_angle_degrees * (PI/180.0)
## The maximum wall angle in radians.
@onready var floor_max_angle : float = floor_max_angle_degrees * (PI/180.0)
# Precalculate inverse mass
## The inverse mass of the body.
@onready var inverse_mass : float = 1.0 / mass
#==================================================================================================
# ------------------
# | PUBLIC METHODS |
# ------------------
## Call this in '_physics_process' to simulate body movement.
## Returns true if collision happened.
func move_and_slide() -> bool :
# "Hack in order to work with calling from _process as well as from _physics_process; calling from thread is risky"
var delta_t : float = get_physics_process_delta_time() if Engine.is_in_physics_frame() else get_process_delta_time()
previous_position = global_position
# Take axis lock into account
if axis_lock_linear_x :
velocity.x = 0.0
if axis_lock_linear_y :
velocity.y = 0.0
if axis_lock_linear_z :
velocity.z = 0.0
# Save previous states
prev_on_floor = is_on_floor
prev_on_floor_surface = is_on_floor_surface
# Reset state variables
collided_with_floor = false
collided_with_wall = false
collided_with_ceiling = false
is_on_floor = false
is_on_wall = false
is_on_ceiling = false
is_on_floor_surface = false
has_stepped = false
#last_floor_normal = Vector3.ZERO <-- We will read this later in grounded move, so don't clear it yet
last_wall_normal = Vector3.ZERO
last_ceiling_normal = Vector3.ZERO
current_floor_normal = Vector3.ZERO
current_wall_normal = Vector3.ZERO
current_ceiling_normal = Vector3.ZERO
floor_impact_velocity = Vector3.ZERO
collision_states.clear()
collider_datas.clear()
snap_collision_state = null
touch_collision_state = null
# Handle contacts before moving, and get their constraints
var pre_move_constraints : Array[KinematicConstraint] = handle_pre_move_contacts()
# Move with requested motion mode
if motion_mode == MotionMode.GROUNDED :
grounded_move(delta_t, pre_move_constraints)
else :
last_floor_normal = Vector3.ZERO
floating_move(delta_t, pre_move_constraints)
# Add platform velocity if left floor
if platform_leave_action != PlatformLeaveAction.DO_NOTHING and not platform_velocity.is_zero_approx() and not current_floor_collider_encoded :
if platform_leave_action == PlatformLeaveAction.ADD_VELOCITY_NO_DOWNWARDS :
platform_velocity -= minf(0.0, platform_velocity.dot(up_direction)) * up_direction
velocity += platform_velocity
platform_velocity = Vector3.ZERO
# Compute delta position and de facto velocity
delta_position = global_position - previous_position
real_velocity = delta_position / delta_t
# Handle contacts at final position
handle_contacts_at_final_position()
if collision_states.is_empty() and not touch_collision_state and not snap_collision_state :
return false
return true
## Snaps the character to the floor, if there is floor below within 'p_snap_length' meters away.
func snap_to_floor(p_snap_length : float) -> bool :
# Snap by at least safe margin to keep floor state consistent
var snap_length : float = maxf(safe_margin, p_snap_length)
var collided : bool
var snap_motion := -up_direction * snap_length
var motion_result := PhysicsTestMotionResult3D.new()
var motion_params := PhysicsTestMotionParameters3D.new()
motion_params.from = global_transform
motion_params.motion = snap_motion
motion_params.margin = safe_margin
motion_params.recovery_as_collision = true
motion_params.max_collisions = MAX_SNAP_COLLISIONS
# NOTE: Test only, because we only move the body if a floor collision happened
collided = _move_and_collide(motion_result, motion_params, true)
if not collided :
return false
var travel : Vector3 = motion_result.get_meta("travel", motion_result.get_travel()) as Vector3
var result_state := CollisionState.new()
set_collision_state(motion_result, result_state)
if not (result_state.s_floor or result_state.s_wall_floor) :
# Check surface normal, if it's floor, allow another snap attempt on next frame
# Fixes case when walking down step and reported collision normal is wall
# NOTE : This triggers the snap method more often, but makes snapping more reliable.
var snap_position : Vector3 = global_position + travel
if collided_with_floor_surface(result_state, snap_position) :
is_on_floor_surface = true
return false
# Determine constraints for velocity, in order to make it parallel to floors,
# as to not move away from them
var kinematic_constraints : Array[KinematicConstraint]
for i : int in result_state.floor_collision_indexes :
var floor_normal : Vector3 = motion_result.get_collision_normal(i)
# Filter out floors we are detaching from
var d : float = velocity.dot(floor_normal)
if d > floor_detach_threshold :
continue
# Constant speed is applied, so only direction will be adjusted
# NOTE: This will redirect vertical velocity towards floor direction!
append_kinematic_constraint_if_unique_approx(
kinematic_constraints,
KinematicConstraint.new(-floor_normal, Vector3.ZERO, 0.0, true, true)
)
# Handle wall floors
if result_state.s_wall_floor :
var d : float = velocity.dot(result_state.wall_floor_normal)
if d < floor_detach_threshold :
append_kinematic_constraint_if_unique_approx(
kinematic_constraints,
KinematicConstraint.new(-result_state.wall_floor_normal, Vector3.ZERO, 0.0, true, true)
)
var is_travel_significant : bool = travel.length_squared() > safe_margin**2
var detaching_from_floor : bool = kinematic_constraints.size() == 0
# Update overall state
# NOTE: If floor is within safe margin, floor state is applied even if
# velocity is not facing the floor. We need this since floor snapping acts
# as the floor detector.
if not detaching_from_floor or (detaching_from_floor and not is_travel_significant) :
update_overall_state(result_state, true, false, false, true)
snap_collision_state = result_state
# If we are detaching from all floors, don't snap to floor
if detaching_from_floor :
return false
# Only move the body if we are not close enough already.
# INFO: This helps avoid sliding caused by recovery.
if is_travel_significant :
global_position += travel
velocity = solve_kinematic_constraints(kinematic_constraints, velocity, up_direction)
return true
## Applies an impulse to the character body.
func apply_impulse(p_impulse : Vector3) -> void :
velocity += p_impulse * inverse_mass
#==================================================================================================
# -------------------
# | PRIVATE METHODS |
# -------------------
## Called before moving the body. Handles contacts at the starting position,
## returns the constraints from these contacts.
func handle_pre_move_contacts() -> Array[KinematicConstraint] :
# TODO: A better method is needed for checking shape intersections. Replace
# this collision check for that one, once available.
# Get current collisions before moving
# NOTE: Currently only the 'body_test_motion' (called inside _move_and_collide)
# is suitable for collision checks, since it's the only way to retrieve the necessary data of all contacts.
var pre_move_motion_result := PhysicsTestMotionResult3D.new()
var motion_params := PhysicsTestMotionParameters3D.new()
motion_params.from = global_transform
motion_params.motion = Vector3.ZERO
motion_params.margin = safe_margin
motion_params.recovery_as_collision = true
motion_params.max_collisions = MAX_REST_COLLISIONS
# Disable slide cancelling, because we are not moving the body
_move_and_collide(pre_move_motion_result, motion_params, true, false)
# Determine collision state with collisions from character motion ignored,
# only collisions resulting from motion of other bodies are registered.
var incoming_collision_state := CollisionState.new()
set_collision_state(pre_move_motion_result, incoming_collision_state, true)
collision_states.push_back(incoming_collision_state)
# Update overall state with incoming collisions
if motion_mode == MotionMode.FLOATING :
update_overall_state(incoming_collision_state, false, true, false)
else :
update_overall_state(incoming_collision_state, true, true, true)
# Determine constraints from this state
var kinematic_constraints : Array[KinematicConstraint]
var dynamic_constraints : Array[DynamicConstraint]
if motion_mode == MotionMode.FLOATING :
determine_floating_move_constraints(
incoming_collision_state, kinematic_constraints, dynamic_constraints
)
else :
determine_grounded_move_constraints(
incoming_collision_state, kinematic_constraints, dynamic_constraints
)
# Solve velocity for these constraints
velocity = solve_dynamic_constraints(dynamic_constraints, velocity, inverse_mass)
velocity = solve_kinematic_constraints(kinematic_constraints, velocity, up_direction)
# Determine collision state with all current contacts before moving
var pre_move_collision_state := CollisionState.new()
set_collision_state(pre_move_motion_result, pre_move_collision_state, false)
# NOTE: The overall state is not updated with collisions that are not the
# result of motion from either the character, or other bodies. We register
# touching collision only at the final position.
# Determine constraints from this state
# NOTE: The incoming collisions are a subset of the current contacts, so
# we can safely clear the array of constraints.
kinematic_constraints.clear()
if motion_mode == MotionMode.FLOATING :
determine_floating_move_constraints(
pre_move_collision_state, kinematic_constraints, dynamic_constraints
)
else :
determine_grounded_move_constraints(
pre_move_collision_state, kinematic_constraints, dynamic_constraints
)
return kinematic_constraints
## Called when done moving, handles contacts at the final position.
func handle_contacts_at_final_position() -> void :
# TODO: A better method is needed for checking shape intersections. Replace
# this collision check for that one, once available.
# Check for all current contacts at the final position
var touch_motion_result := PhysicsTestMotionResult3D.new()
var motion_params := PhysicsTestMotionParameters3D.new()
# NOTE: When getting touch collisions we need an inflated safe margin, because the character is
# pushed away from collisions, so it will no longer collide if we use the unaltered safe margin.
var touch_safe_margin : float = safe_margin * TOUCH_SAFE_MARGIN_FACTOR
motion_params.from = global_transform
motion_params.motion = Vector3.ZERO
motion_params.margin = touch_safe_margin
motion_params.recovery_as_collision = true
motion_params.max_collisions = MAX_REST_COLLISIONS
# Disable slide cancelling, because we are not moving the body
_move_and_collide(touch_motion_result, motion_params, true, false)
# Determine collision state with these contacts
touch_collision_state = CollisionState.new()
set_collision_state(touch_motion_result, touch_collision_state)
# Update overall state and also set current state properties
if motion_mode == MotionMode.FLOATING :
update_overall_state(touch_collision_state, false, true, false, true)
else : # Grounded move
# We don't want to set the floor status here, because floor snapping
# already determined the floor status
# FIXME: This does mean certain wall floors don't get detected...
update_overall_state(touch_collision_state, false, true, true, true)
## Performs a grounded movement.
func grounded_move(p_delta_t : float, p_pre_move_constraints : Array[KinematicConstraint]) -> void :
# Determine platform velocity
var prev_platform_velocity : Vector3 = platform_velocity
var floor_collider_valid : bool = false
platform_velocity = Vector3.ZERO
if current_floor_collider_rid.is_valid() :
var platform_layer : int = PhysicsServer3D.body_get_collision_layer(current_floor_collider_rid)
var excluded : bool = (moving_platform_layers & platform_layer) == 0
if not excluded :
var body_state : PhysicsDirectBodyState3D = PhysicsServer3D.body_get_direct_state(current_floor_collider_rid)
var local_position : Vector3 = global_position - body_state.transform.origin
platform_velocity = body_state.get_velocity_at_local_position(local_position)
if prev_platform_velocity_valid :
var platform_vertical_velocity_change_length : float = (prev_platform_velocity - platform_velocity).dot(last_floor_normal)
if platform_vertical_velocity_change_length > platform_detach_treshold and prev_platform_velocity.dot(last_floor_normal) > floor_detach_threshold :
velocity += prev_platform_velocity
platform_velocity = Vector3.ZERO
floor_collider_valid = true
prev_platform_velocity_valid = floor_collider_valid
# Now we can clear last_floor_normal
last_floor_normal = Vector3.ZERO
# Move with platform velocity
if not platform_velocity.is_zero_approx() :
if slide_platform_motion :
# Perform a sliding move with platform velocity
var platform_move_io := MoveShapeIO.new(global_transform, platform_velocity, p_delta_t)
move_shape(platform_move_io, prev_on_floor, p_pre_move_constraints,[current_floor_collider_rid])
# Update position
global_transform = platform_move_io.transform
# Update overall state with collisions
for collision_state : CollisionState in platform_move_io.collision_states :
collision_states.push_back(collision_state)
update_overall_state(collision_state, true, true, true)
else :
# Move with platform velocity until collision
var motion_result : = PhysicsTestMotionResult3D.new()
var motion_params : = PhysicsTestMotionParameters3D.new()
motion_params.from = global_transform
motion_params.motion = platform_velocity * p_delta_t
motion_params.margin = safe_margin
motion_params.recovery_as_collision = true
motion_params.max_collisions = MAX_SLIDE_COLLISIONS
motion_params.exclude_bodies = [current_floor_collider_rid]
var collided : bool = _move_and_collide(motion_result, motion_params)
if collided :
var result_state := CollisionState.new()
set_collision_state(motion_result, result_state)
update_overall_state(result_state, true, true, true)
collision_states.push_back(result_state)
# Clear pre move constraints, since we have moved
p_pre_move_constraints.clear()
# Clear floor collider data
current_floor_collider_encoded = null
current_floor_collider_rid = RID()
# Move with velocity
var move_io := MoveShapeIO.new(global_transform, velocity, p_delta_t)
move_shape(move_io, prev_on_floor, p_pre_move_constraints)
# Update position and velocity
global_transform = move_io.transform
velocity = move_io.velocity
# Update overall state with collisions
for collision_state : CollisionState in move_io.collision_states :
collision_states.push_back(collision_state)
update_overall_state(collision_state, true, true, true)
# Set step status flag and floor impact velocity
has_stepped = move_io.has_stepped
floor_impact_velocity = move_io.floor_impact_velocity
# Snap to floor if character was on the floor in the previous frame, or has
# touched floor during movement.
if prev_on_floor or move_io.touched_floor or prev_on_floor_surface :
snap_to_floor(max_snap_length)
# Apply gravity force to floor collider
if interact_with_rigid_bodies :
apply_gravity_force_to_floor(p_delta_t)
## Applies gravity force to the floor collider.
func apply_gravity_force_to_floor(p_delta_t : float) -> void :
if not (current_floor_collider_encoded and is_body_dynamic(current_floor_collider_rid)) :
return
# Create dynamic constraints
var index : int = ColliderData.find_by_collider_id(collider_datas, current_floor_collider_encoded.object_id)
var floor_collider_data : ColliderData = collider_datas[index]
var dynamic_constraints : Array[DynamicConstraint]
for i : int in floor_collider_data.collision_count :
dynamic_constraints.push_back(
DynamicConstraint.new(
floor_collider_data.collider_rid,
floor_collider_data.collision_normals[i],
floor_collider_data.collision_points[i]
)
)
# Calculate velocity from gravity acceleraation
var gravity_velocity : Vector3 = get_gravity() * p_delta_t
# We have to take platform velocity into account
gravity_velocity += platform_velocity * (
# If the floor platform is "pulling", reverse the added velocity
-1.0 if platform_velocity.dot(up_direction) < 0.0 else 1.0
)
# Apply the impulses
solve_dynamic_constraints(dynamic_constraints, gravity_velocity, inverse_mass)
## Performs a floating movement.
func floating_move(p_delta_t : float, p_pre_move_constraints : Array[KinematicConstraint]) -> void :
# Clear floor collider data
current_floor_collider_encoded = null
current_floor_collider_rid = RID()
# Move with velocity
var move_io := MoveShapeIO.new(global_transform, velocity, p_delta_t)
move_shape(move_io, prev_on_floor, p_pre_move_constraints)
# Update position and velocity
global_transform = move_io.transform
velocity = move_io.velocity
# Update overall state with collisions
for collision_state : CollisionState in move_io.collision_states :
collision_states.push_back(collision_state)
update_overall_state(collision_state, false, true, false)
## Simulates body movement using collision checks.
func move_shape(
p_io : MoveShapeIO,
p_prev_on_floor : bool,
p_prev_kinematic_constraints : Array[KinematicConstraint] = [],
p_excluded_bodies : Array[RID] = [],
p_step_move_enabled : bool = true
) -> void :
# Check if done maximum allowed amount of iterations
if p_io.iteration_count > MAX_SLIDES :
# NOTE : this shouldn't happen
printerr("IKCC: Max slides surpassed! (%d)" % MAX_SLIDES)
return
# If simulation time provided is zero (or less), treat it as an error and bail
if is_zero_approx(p_io.time_remaining) or p_io.time_remaining <= 0.0 :
printerr("IKCC: Simulation time provided to 'move_shape' is zero!")
return
# Increase iteration counter
p_io.iteration_count += 1
# Perform recovery, move body along motion, stop if collided
var motion : Vector3 = p_io.velocity * p_io.time_remaining
var motion_result : = PhysicsTestMotionResult3D.new()
var motion_params : = PhysicsTestMotionParameters3D.new()
motion_params.from = p_io.transform
motion_params.motion = motion
motion_params.margin = safe_margin
motion_params.recovery_as_collision = true
motion_params.max_collisions = MAX_SLIDE_COLLISIONS
motion_params.exclude_bodies = p_excluded_bodies
var collided : bool = _move_and_collide(motion_result, motion_params, true)
# Modify output position by adding the safe fraction of the motion
var travel : Vector3 = motion_result.get_meta("travel", motion_result.get_travel()) as Vector3
p_io.transform.origin += travel
# Reduce remaining time by time spent moving
p_io.time_remaining -= p_io.time_remaining * motion_result.get_collision_safe_fraction()
if not collided :
return # Moved all the way, no collision to respond to
# Calculate collision info
var result_state := CollisionState.new()
set_collision_state(motion_result, result_state)
# Store collision info
p_io.collision_states.push_back(result_state)
if motion.is_zero_approx() :
return # Motion was zero, no need to slide
# Determine constraints
var kinematic_constraints : Array[KinematicConstraint] = []
var dynamic_constraints : Array[DynamicConstraint] = []
# Only add previous constraints if we haven't moved a significant amount
# NOTE: Recovery can be more than the safe margin, we have to take it into account.
var is_travel_significant : bool = travel.length_squared() > (safe_margin * RECOVERY_FACTOR)**2
if not is_travel_significant :
kinematic_constraints += p_prev_kinematic_constraints
# Remember floor stauts of this iteration (Only used for grounded movement.)
# If collision includes floor, we can set this to true and skip the floor collision check.
var touching_floor : bool = result_state.s_floor or result_state.s_wall_floor
if motion_mode == MotionMode.FLOATING :
determine_floating_move_constraints(result_state, kinematic_constraints, dynamic_constraints)
else : # Grounded motion mode
var floor_below : bool = result_state.s_floor
var floor_surface_below : bool = false
var floor_check_travel := Vector3.ZERO
# If no floor collision is reported, we need an extra collision check at our current position.
if not touching_floor :
var floor_state := CollisionState.new()
if check_floor_status(p_io.transform, max_step_height, floor_state, true) :
floor_below = floor_state.s_floor or floor_state.s_wall_floor
floor_surface_below = floor_state.s_floor_surface_only
floor_check_travel = floor_state.motion_result.get_meta("travel", floor_state.motion_result.get_travel()) as Vector3
# NOTE: Recovery can be more than the safe margin, we have to take it into account.
touching_floor = floor_below and floor_check_travel.length_squared() <= (safe_margin * RECOVERY_FACTOR)**2
# Set flag if we are touching the floor
p_io.touched_floor = p_io.touched_floor or touching_floor
# Check if we collided with a step
if p_step_move_enabled and not is_zero_approx(max_step_height) and (floor_below or floor_surface_below) and result_state.s_wall :
# Retrieve IO objects of forward move, in case step move fails
var step_forward_ios : Array[MoveShapeIO]
if step_move(p_io, result_state, p_excluded_bodies, step_forward_ios) :
# The character succesfully stepped with remaning time, so we are out of it.
return
# If the step move failed, cancel any impulse applied to bodies during the forward move
for move_shape_io : MoveShapeIO in step_forward_ios :
move_shape_io.restore_body_states()
# Determine if we want to block horizontal movement on steep slopes
var slide_up_steep_slopes : bool = not (floor_block_on_wall and touching_floor and result_state.s_wall)
# If floor check distance is not too much, we apply it to the body's position,
# in order to make floor status more reliable when sliding along steep slopes
if not slide_up_steep_slopes and touching_floor :
p_io.transform.origin += floor_check_travel
determine_grounded_move_constraints(
result_state, kinematic_constraints, dynamic_constraints, slide_up_steep_slopes, slide_up_ceilings
)
# The user may wish to know the velocity the character hit the ground with, so save it
var landed_from_air : bool = not p_prev_on_floor and result_state.s_floor
if landed_from_air and p_io.floor_impact_velocity.is_zero_approx() :
p_io.floor_impact_velocity = p_io.velocity
# Determine new velocity
var new_velocity : Vector3 = p_io.velocity
# This feature prevents sliding caused by accumulated velocity from gravity
# when landing on sloped floors.
# NOTE: Disabling gravity when on floor is the user's responsibility!
# When the character lands on the floor from air...
if floor_stop_on_slope and landed_from_air :
# and vertical component would cause sliding down the slope...
if p_io.velocity.dot(up_direction) < 0.0 :
# First remove downward vertical (gravity) component...
new_velocity = p_io.velocity.slide(up_direction)
# ... then adjust current velocity so that it parallels the floor planes, by
# solving the constraints defined below.
var floor_dir_constraints : Array[KinematicConstraint]
for i : int in result_state.floor_collision_indexes :
var floor_normal : Vector3 = motion_result.get_collision_normal(i)
# Constant speed is applied, so only direction will be adjusted.
append_kinematic_constraint_if_unique_approx(
floor_dir_constraints,
KinematicConstraint.new(-floor_normal, Vector3.ZERO, 0.0, true, true)
)
new_velocity = solve_kinematic_constraints(floor_dir_constraints, new_velocity, up_direction)
# Solve constraints
new_velocity = solve_dynamic_constraints(dynamic_constraints, new_velocity, inverse_mass, p_io)
new_velocity = solve_kinematic_constraints(kinematic_constraints, new_velocity, up_direction)
# Set new output velocity
p_io.velocity = new_velocity
# Cancel motion caused by recovery, when needed
if not is_travel_significant :
var cancelled_travel := Vector3.ZERO
for constraint : KinematicConstraint in kinematic_constraints :
if constraint.is_slide_cancelled :
var travel_horizontal_to_plane : Vector3 = travel.slide(constraint.plane_normal)
cancelled_travel += travel_horizontal_to_plane
travel -= travel_horizontal_to_plane
constraint.is_slide_cancelled = false # reset flag
# Modify output position
p_io.transform.origin -= cancelled_travel
if new_velocity.is_zero_approx() :
return # There's not enough velocity left
# Stop simulating if new velocity still faces a constraint plane
for constraint : Constraint in (kinematic_constraints + dynamic_constraints) as Array[Constraint] :
if new_velocity.dot(constraint.plane_normal) <= -CMP_EPSILON :
return
if is_zero_approx(p_io.time_remaining) :
return # Not enough time left to be simulated, bail
# Iterate
move_shape(
p_io,
touching_floor,
kinematic_constraints,
p_excluded_bodies,
p_step_move_enabled
)
## Determines constraints for floating movement according to input collision state.
func determine_floating_move_constraints(
p_collision_state : CollisionState,
p_kinematic_constraints : Array[KinematicConstraint],
p_dynamic_constraints : Array[DynamicConstraint]
) -> void :
# NOTE: All collisions are walls if motion mode is floating.
for i : int in p_collision_state.wall_collision_indexes :
var wall_normal : Vector3 = p_collision_state.motion_result.get_collision_normal(i)
var wall_velocity : Vector3 = p_collision_state.motion_result.get_collider_velocity(i)
var collider_rid : RID = p_collision_state.motion_result.get_collider_rid(i)
if interact_with_rigid_bodies and is_body_dynamic(collider_rid) :
var collision_point : Vector3 = p_collision_state.motion_result.get_collision_point(i)
p_dynamic_constraints.push_back(DynamicConstraint.new(collider_rid, wall_normal, collision_point))
continue
append_kinematic_constraint_if_unique_approx(
p_kinematic_constraints,
KinematicConstraint.new(wall_normal, wall_velocity, wall_min_slide_angle, wall_constant_speed)
)
## Determines constraints for grounded movement according to input collision state.
func determine_grounded_move_constraints(
p_collision_state : CollisionState,
p_kinematic_constraints : Array[KinematicConstraint],
p_dynamic_constraints : Array[DynamicConstraint] = [],
p_slide_up_steep_slopes : bool = true,
p_slide_up_ceilings : bool = true,
) -> void :
# Floor collisions
for i : int in p_collision_state.floor_collision_indexes :
var floor_normal : Vector3 = p_collision_state.motion_result.get_collision_normal(i)
# We don't add the collider velocity to the floor constraint,
# since floor movement is handled through platform_velocity.
# We also treat all floor constraints as kinematic.
append_kinematic_constraint_if_unique_approx(
p_kinematic_constraints,
KinematicConstraint.new(floor_normal, Vector3.ZERO, 0.0, floor_constant_speed, floor_stop_on_slope)
)
# Wall collisions
for i : int in p_collision_state.wall_collision_indexes :
var wall_normal : Vector3 = p_collision_state.motion_result.get_collision_normal(i)
var wall_velocity : Vector3 = p_collision_state.motion_result.get_collider_velocity(i)
var collider_rid : RID = p_collision_state.motion_result.get_collider_rid(i)
if interact_with_rigid_bodies and is_body_dynamic(collider_rid) :
var collision_point : Vector3 = p_collision_state.motion_result.get_collision_point(i)
p_dynamic_constraints.push_back(DynamicConstraint.new(collider_rid, wall_normal, collision_point))
continue
# Convert to constraint
var wall_constraint := KinematicConstraint.new(wall_normal, wall_velocity, wall_min_slide_angle, wall_constant_speed)
# If not allowed to slide up slopes, add an additional constraint that
# holds the character back
if not p_slide_up_steep_slopes :
# Jolt: "Only take planes that point up."
var dot : float = wall_normal.dot(up_direction)
if dot > CMP_EPSILON :
# Jolt: "Make horizontal normal"
var horizontal_normal : Vector3 = (wall_normal - dot * up_direction).normalized()
# Jolt: "Project the contact velocity on the new normal so that both planes push at an equal rate"
var projected_velocity : Vector3 = wall_velocity.dot(horizontal_normal) * horizontal_normal
# Jolt: "Create a secondary constraint that blocks horizontal movement"
append_kinematic_constraint_if_unique_approx(
p_kinematic_constraints,
KinematicConstraint.new(horizontal_normal, projected_velocity, wall_min_slide_angle, wall_constant_speed)
)
append_kinematic_constraint_if_unique_approx(p_kinematic_constraints,wall_constraint)
# Ceiling collisions
for i : int in p_collision_state.ceiling_collision_indexes :
var ceiling_normal : Vector3 = p_collision_state.motion_result.get_collision_normal(i)
var ceiling_velocity : Vector3 = p_collision_state.motion_result.get_collider_velocity(i)
var collider_rid : RID = p_collision_state.motion_result.get_collider_rid(i)
if interact_with_rigid_bodies and is_body_dynamic(collider_rid) :
var collision_point : Vector3 = p_collision_state.motion_result.get_collision_point(i)
p_dynamic_constraints.push_back(DynamicConstraint.new(collider_rid, ceiling_normal, collision_point))