Skip to content

Commit 8373936

Browse files
committed
Removing need for sqrts when mass is the same
1 parent d59617a commit 8373936

1 file changed

Lines changed: 32 additions & 11 deletions

File tree

src/physics/arcade/SeparateY.js

Lines changed: 32 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -70,25 +70,45 @@ var SeparateY = function (body1, body2, overlapOnly, bias)
7070
// At this point, the velocity from gravity, world rebounds, etc has been factored in.
7171
// The body is moving the direction it wants to, but may be blocked and rebound.
7272

73-
if (!body1Immovable && !body2Immovable)
73+
var move1 = (!body1Immovable && (v1 >= 0 && !worldBlocked1.down) || (v1 < 0 && !worldBlocked1.up));
74+
var move2 = (!body2Immovable && (v2 >= 0 && !worldBlocked2.down) || (v2 < 0 && !worldBlocked2.up));
75+
76+
if (move1 && move2)
7477
{
7578
// Neither body is immovable, so they get a new velocity based on mass
7679
var mass1 = body1.mass;
7780
var mass2 = body2.mass;
7881

79-
var bnv1 = Math.sqrt((v2 * v2 * mass2) / mass1) * ((v2 > 0) ? 1 : -1);
80-
var bnv2 = Math.sqrt((v1 * v1 * mass1) / mass2) * ((v1 > 0) ? 1 : -1);
82+
// We don't need costly sqrts if both masses are the same
83+
if (mass1 === mass2)
84+
{
85+
var bnv1 = (v2 > 0) ? v2 : v2 * -1;
86+
var bnv2 = (v1 > 0) ? v1 : v1 * -1;
8187

82-
var avg = (bnv1 + bnv2) * 0.5;
88+
var avg = (bnv1 + bnv2) * 0.5;
8389

84-
var nv1 = bnv1;
85-
var nv2 = bnv2;
90+
var nv1 = bnv1 - avg;
91+
var nv2 = bnv2 - avg;
92+
93+
ny1 = avg + nv1 * bounce1.y;
94+
ny2 = avg + nv2 * bounce2.y;
95+
}
96+
else
97+
{
98+
var bnv1 = Math.sqrt((v2 * v2 * mass2) / mass1) * ((v2 > 0) ? 1 : -1);
99+
var bnv2 = Math.sqrt((v1 * v1 * mass1) / mass2) * ((v1 > 0) ? 1 : -1);
86100

87-
nv1 -= avg;
88-
nv2 -= avg;
101+
var avg = (bnv1 + bnv2) * 0.5;
89102

90-
ny1 = avg + nv1 * bounce1.y;
91-
ny2 = avg + nv2 * bounce2.y;
103+
var nv1 = bnv1;
104+
var nv2 = bnv2;
105+
106+
nv1 -= avg;
107+
nv2 -= avg;
108+
109+
ny1 = avg + nv1 * bounce1.y;
110+
ny2 = avg + nv2 * bounce2.y;
111+
}
92112

93113
// var total = v1 - v2;
94114
// ny1 = (((mass1 - mass2) * v1 + 2 * mass1 * v1) / (mass1 + mass2)) * bounce1.y;
@@ -97,6 +117,7 @@ var SeparateY = function (body1, body2, overlapOnly, bias)
97117

98118
console.log('resolution');
99119
console.log('body1', ny1, 'body2', ny2);
120+
console.log('speed', body1.speed, body2.speed);
100121
console.log('v1', v1, 'v2', v2);
101122
console.log('avg', avg);
102123
console.log('nv', nv1, nv2);
@@ -123,7 +144,7 @@ var SeparateY = function (body1, body2, overlapOnly, bias)
123144
// Velocities calculated, time to work out what moves where
124145
if (overlap !== 0)
125146
{
126-
// Try and give 50% separation to each body
147+
// Try and give 50% separation to each body (this could be improved to give a speed ratio amount to each body)
127148
var share = overlap * 0.5;
128149

129150
if (topFace)

0 commit comments

Comments
 (0)