Skip to content

Commit

Permalink
Don't override KinematicCollision reference when still in use in script
Browse files Browse the repository at this point in the history
In case the reference is stored in script, create a new instance to
avoid overriding the previous values.
Otherwise, re-use the reference as before to avoid extra allocations.
  • Loading branch information
pouleyKetchoupp committed Sep 23, 2021
1 parent c1e6c2c commit 9269952
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 4 deletions.
6 changes: 4 additions & 2 deletions scene/2d/physics_body_2d.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,8 @@ Ref<KinematicCollision2D> PhysicsBody2D::_move(const Vector2 &p_motion, bool p_t
PhysicsServer2D::MotionResult result;

if (move_and_collide(p_motion, result, p_margin, p_test_only)) {
if (motion_cache.is_null()) {
// Create a new instance when the cached reference is invalid or still in use in script.
if (motion_cache.is_null() || motion_cache->reference_get_count() > 1) {
motion_cache.instantiate();
motion_cache->owner = this;
}
Expand Down Expand Up @@ -1369,7 +1370,8 @@ Ref<KinematicCollision2D> CharacterBody2D::_get_slide_collision(int p_bounce) {
slide_colliders.resize(p_bounce + 1);
}

if (slide_colliders[p_bounce].is_null()) {
// Create a new instance when the cached reference is invalid or still in use in script.
if (slide_colliders[p_bounce].is_null() || slide_colliders[p_bounce]->reference_get_count() > 1) {
slide_colliders.write[p_bounce].instantiate();
slide_colliders.write[p_bounce]->owner = this;
}
Expand Down
6 changes: 4 additions & 2 deletions scene/3d/physics_body_3d.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,8 @@ void PhysicsBody3D::remove_collision_exception_with(Node *p_node) {
Ref<KinematicCollision3D> PhysicsBody3D::_move(const Vector3 &p_motion, bool p_test_only, real_t p_margin, int p_max_collisions) {
PhysicsServer3D::MotionResult result;
if (move_and_collide(p_motion, result, p_margin, p_test_only, p_max_collisions)) {
if (motion_cache.is_null()) {
// Create a new instance when the cached reference is invalid or still in use in script.
if (motion_cache.is_null() || motion_cache->reference_get_count() > 1) {
motion_cache.instantiate();
motion_cache->owner = this;
}
Expand Down Expand Up @@ -1590,7 +1591,8 @@ Ref<KinematicCollision3D> CharacterBody3D::_get_slide_collision(int p_bounce) {
slide_colliders.resize(p_bounce + 1);
}

if (slide_colliders[p_bounce].is_null()) {
// Create a new instance when the cached reference is invalid or still in use in script.
if (slide_colliders[p_bounce].is_null() || slide_colliders[p_bounce]->reference_get_count() > 1) {
slide_colliders.write[p_bounce].instantiate();
slide_colliders.write[p_bounce]->owner = this;
}
Expand Down

0 comments on commit 9269952

Please sign in to comment.