Skip to content

Commit ef4b3cf

Browse files
committed
Improved update handler to cut down on body iteration and stepping without an update due. Fix phaserjs#4529
1 parent 96298cf commit ef4b3cf

1 file changed

Lines changed: 47 additions & 17 deletions

File tree

src/physics/arcade/World.js

Lines changed: 47 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -913,39 +913,63 @@ var World = new Class({
913913
return;
914914
}
915915

916+
var i;
917+
var fixedDelta = this._frameTime;
918+
var msPerFrame = this._frameTimeMS * this.timeScale;
919+
920+
this._elapsed += delta;
921+
916922
// Update all active bodies
917923
var body;
918924
var bodies = this.bodies.entries;
919925

920-
for (var i = 0; i < bodies.length; i++)
926+
// Will a step happen this frame?
927+
var willStep = (this._elapsed >= msPerFrame);
928+
929+
for (i = 0; i < bodies.length; i++)
921930
{
922931
body = bodies[i];
923932

924933
if (body.enable)
925934
{
926-
body.preUpdate();
935+
body.preUpdate(willStep, fixedDelta);
927936
}
928937
}
929938

930-
var stepsThisFrame = 1;
931-
var fixedDelta = this._frameTime;
932-
var msPerFrame = this._frameTimeMS * this.timeScale;
939+
// We know that a step will happen this frame, so let's bundle it all together to save branching and iteration costs
940+
if (willStep)
941+
{
942+
this._elapsed -= msPerFrame;
943+
this.stepsLastFrame = 1;
933944

934-
this._elapsed += delta - msPerFrame;
945+
// Optionally populate our dynamic collision tree
946+
if (this.useTree)
947+
{
948+
this.tree.clear();
949+
this.tree.load(bodies);
950+
}
951+
952+
// Process any colliders
953+
var colliders = this.colliders.update();
954+
955+
for (i = 0; i < colliders.length; i++)
956+
{
957+
var collider = colliders[i];
935958

936-
// Always step once, no matter what
937-
this.step(fixedDelta);
959+
if (collider.active)
960+
{
961+
collider.update();
962+
}
963+
}
964+
}
938965

966+
// Process any additional steps this frame
939967
while (this._elapsed >= msPerFrame)
940968
{
941969
this._elapsed -= msPerFrame;
942970

943-
stepsThisFrame++;
944-
945971
this.step(fixedDelta);
946972
}
947-
948-
this.stepsLastFrame = stepsThisFrame;
949973
},
950974

951975
/**
@@ -993,6 +1017,8 @@ var World = new Class({
9931017
collider.update();
9941018
}
9951019
}
1020+
1021+
this.stepsLastFrame++;
9961022
},
9971023

9981024
/**
@@ -1011,13 +1037,17 @@ var World = new Class({
10111037
var dynamic = this.bodies;
10121038
var staticBodies = this.staticBodies;
10131039

1014-
for (i = 0; i < len; i++)
1040+
// We don't need to postUpdate if there wasn't a step this frame
1041+
if (this.stepsLastFrame)
10151042
{
1016-
body = bodies[i];
1017-
1018-
if (body.enable)
1043+
for (i = 0; i < len; i++)
10191044
{
1020-
body.postUpdate();
1045+
body = bodies[i];
1046+
1047+
if (body.enable)
1048+
{
1049+
body.postUpdate();
1050+
}
10211051
}
10221052
}
10231053

0 commit comments

Comments
 (0)