Update the object physics, called automatically by engine once each frame. Can be overridden to stop or change how physics works for an object.
()
| 153 | |
| 154 | /** Update the object physics, called automatically by engine once each frame. Can be overridden to stop or change how physics works for an object. */ |
| 155 | updatePhysics() |
| 156 | { |
| 157 | // child objects do not have physics |
| 158 | ASSERT(!this.parent); |
| 159 | |
| 160 | // bail if a collision callback destroyed us mid-frame |
| 161 | if (this.destroyed) return; |
| 162 | |
| 163 | if (this.clampSpeed) |
| 164 | { |
| 165 | // limit max speed to prevent missing collisions |
| 166 | this.velocity.x = clamp(this.velocity.x, -objectMaxSpeed, objectMaxSpeed); |
| 167 | this.velocity.y = clamp(this.velocity.y, -objectMaxSpeed, objectMaxSpeed); |
| 168 | } |
| 169 | |
| 170 | // apply physics |
| 171 | const oldPos = this.pos.copy(); |
| 172 | this.velocity.x *= this.damping; |
| 173 | this.velocity.y *= this.damping; |
| 174 | if (this.mass) |
| 175 | { |
| 176 | // apply gravity only if it has mass |
| 177 | this.velocity.x += gravity.x * this.gravityScale; |
| 178 | this.velocity.y += gravity.y * this.gravityScale; |
| 179 | } |
| 180 | this.pos.x += this.velocity.x; |
| 181 | this.pos.y += this.velocity.y; |
| 182 | this.angle += this.angleVelocity *= this.angleDamping; |
| 183 | |
| 184 | // physics sanity checks |
| 185 | ASSERT(this.angleDamping >= 0 && this.angleDamping <= 1); |
| 186 | ASSERT(this.damping >= 0 && this.damping <= 1); |
| 187 | |
| 188 | // don't do collision for static objects or if solver disabled |
| 189 | if (!enablePhysicsSolver || !this.mass) return; |
| 190 | |
| 191 | const wasFalling = this.velocity.y < 0 && gravity.y < 0 || this.velocity.y > 0 && gravity.y > 0; |
| 192 | if (this.groundObject) |
| 193 | { |
| 194 | // apply friction in local space of ground object |
| 195 | const friction = max(this.friction, this.groundObject.friction); |
| 196 | const groundSpeed = this.groundObject.velocity.x; |
| 197 | this.velocity.x = groundSpeed + (this.velocity.x - groundSpeed) * friction; |
| 198 | this.groundObject = undefined; |
| 199 | } |
| 200 | |
| 201 | if (this.collideSolidObjects) |
| 202 | { |
| 203 | // check collisions against solid objects |
| 204 | const epsilon = .001; // necessary to push slightly outside of the collision |
| 205 | for (const o of engineObjectsCollide) |
| 206 | { |
| 207 | // skip destroyed, child objects, or self collision |
| 208 | if (o.destroyed || o.parent || o === this) continue; |
| 209 | |
| 210 | // non solid objects don't collide with each other |
| 211 | if (!this.isSolid && !o.isSolid) continue; |
| 212 |
no test coverage detected