diff --git a/Gruntfile.js b/Gruntfile.js index 34754257..abe8ec56 100644 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -136,6 +136,7 @@ module.exports = function (grunt) { 'src/physics/World.js', 'src/physics/PointProxy.js', 'src/physics/Body.js', + 'src/physics/Spring.js', 'src/particles/Particles.js', 'src/particles/arcade/ArcadeParticles.js', diff --git a/build/config.php b/build/config.php index 47a2e714..5f775995 100644 --- a/build/config.php +++ b/build/config.php @@ -182,6 +182,7 @@ + diff --git a/examples/wip/tilesprite fixed to cam.js b/examples/wip/tilesprite fixed to cam.js index a99d6426..f69b43d9 100644 --- a/examples/wip/tilesprite fixed to cam.js +++ b/examples/wip/tilesprite fixed to cam.js @@ -21,6 +21,7 @@ function create() { sprite = game.add.tileSprite(100, 100, 200, 200, 'starfield'); sprite.autoScroll(0, 100); sprite.fixedToCamera = true; + console.log(sprite.parent); mushroom = game.add.sprite(400, 400, 'mushroom'); diff --git a/src/core/Group.js b/src/core/Group.js index c1183520..ef1d0a18 100644 --- a/src/core/Group.js +++ b/src/core/Group.js @@ -734,7 +734,9 @@ Phaser.Group.prototype.preUpdate = function () { return false; } - for (var i = this.children.length - 1; i >= 0; i--) + var i = this.children.length; + + while (i--) { this.children[i].preUpdate(); } @@ -750,7 +752,9 @@ Phaser.Group.prototype.preUpdate = function () { */ Phaser.Group.prototype.update = function () { - for (var i = this.children.length - 1; i >= 0; i--) + var i = this.children.length; + + while (i--) { this.children[i].update(); } @@ -771,7 +775,9 @@ Phaser.Group.prototype.postUpdate = function () { this.y = this.game.camera.view.y + this.cameraOffset.y; } - for (var i = this.children.length - 1; i >= 0; i--) + var i = this.children.length; + + while (i--) { this.children[i].postUpdate(); } diff --git a/src/core/Stage.js b/src/core/Stage.js index 5ee01cd3..7bdd84d3 100644 --- a/src/core/Stage.js +++ b/src/core/Stage.js @@ -49,6 +49,12 @@ Phaser.Stage = function (game, width, height) { */ this.checkOffsetInterval = 2500; + /** + * @property {boolean} exists - If exists is true the Stage and all children are updated, otherwise it is skipped. + * @default + */ + this.exists = true; + /** * @property {number} _nextOffsetCheck - The time to run the next offset check. * @private diff --git a/src/core/World.js b/src/core/World.js index 91e6b2d4..421e44f8 100644 --- a/src/core/World.js +++ b/src/core/World.js @@ -95,81 +95,6 @@ Phaser.World.prototype.setBounds = function (x, y, width, height) { } -/** -* This is called automatically after the plugins preUpdate and before the State.update. -* Most objects have preUpdate methods and it's where initial movement and positioning is done. -* -* @method Phaser.World#preUpdate -*/ -Phaser.World.prototype.preUpdate = function () { - - this.currentRenderOrderID = 0; - - var i = this.children.length; - - while (i--) - { - this.children[i].preUpdate(); - } - -} - -/** -* This is called automatically after the State.update, but before particles or plugins update. -* -* @method Phaser.World#update -*/ -Phaser.World.prototype.update = function () { - - var i = this.children.length; - - while (i--) - { - this.children[i].update(); - } - -} - -/** -* This is called automatically before the renderer runs and after the plugins have updated. -* In postUpdate this is where all the final physics calculatations and object positioning happens. -* The objects are processed in the order of the display list. -* The only exception to this is if the camera is following an object, in which case that is updated first. -* -* @method Phaser.World#postUpdate -*/ -Phaser.World.prototype.postUpdate = function () { - - if (this.game.world.camera.target) - { - this.game.world.camera.target.postUpdate(); - - this.game.world.camera.update(); - - var i = this.children.length; - - while (i--) - { - if (this.children[i] !== this.game.world.camera.target) - { - this.children[i].postUpdate(); - } - } - } - else - { - this.game.world.camera.update(); - - var i = this.children.length; - - while (i--) - { - this.children[i].postUpdate(); - } - } - -} - /** * Destroyer of worlds. * @method Phaser.World#destroy diff --git a/src/physics/Spring.js b/src/physics/Spring.js new file mode 100644 index 00000000..5d8d8b84 --- /dev/null +++ b/src/physics/Spring.js @@ -0,0 +1,66 @@ +/** +* @author Richard Davey +* @copyright 2014 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Creates a spring, connecting two bodies. +* +* @class Phaser.Physics.Spring +* @classdesc Physics Spring Constructor +* @constructor +* @param {Phaser.Game} game - A reference to the current game. +* @param {p2.Body} bodyA - First connected body. +* @param {p2.Body} bodyB - Second connected body. +* @param {number} [restLength=1] - Rest length of the spring. A number > 0. +* @param {number} [stiffness=100] - Stiffness of the spring. A number >= 0. +* @param {number} [damping=1] - Damping of the spring. A number >= 0. +* @param {Array} [worldA] - Where to hook the spring to body A, in world coordinates, i.e. [32, 32]. +* @param {Array} [worldB] - Where to hook the spring to body B, in world coordinates, i.e. [32, 32]. +* @param {Array} [localA] - Where to hook the spring to body A, in local body coordinates. +* @param {Array} [localB] - Where to hook the spring to body B, in local body coordinates. +*/ +Phaser.Physics.Spring = function (game, bodyA, bodyB, restLength, stiffness, damping, worldA, worldB, localA, localB) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + if (typeof restLength === 'undefined') { restLength = 1; } + if (typeof stiffness === 'undefined') { stiffness = 100; } + if (typeof damping === 'undefined') { damping = 1; } + + var options = { + restLength: restLength, + stiffness: stiffness, + damping: damping + }; + + if (typeof worldA !== 'undefined') + { + options.worldAnchorA = [ game.math.px2p(worldA[0]), game.math.px2p(worldA[1]) ]; + } + + if (typeof worldB !== 'undefined') + { + options.worldAnchorB = [ game.math.px2p(worldB[0]), game.math.px2p(worldB[1]) ]; + } + + if (typeof localA !== 'undefined') + { + options.localAnchorA = [ game.math.px2p(localA[0]), game.math.px2p(localA[1]) ]; + } + + if (typeof localB !== 'undefined') + { + options.localAnchorB = [ game.math.px2p(localB[0]), game.math.px2p(localB[1]) ]; + } + + p2.Spring.call(this, bodyA, bodyB, options); + +} + +Phaser.Physics.Spring.prototype = Object.create(p2.Spring.prototype); +Phaser.Physics.Spring.prototype.constructor = Phaser.Physics.Spring; diff --git a/src/physics/World.js b/src/physics/World.js index 56e3f170..86dada14 100644 --- a/src/physics/World.js +++ b/src/physics/World.js @@ -221,3 +221,14 @@ Phaser.Physics.World.prototype.update = function () { this.step(1 / 60); }; + +/** +* @method Phaser.Physics.World.prototype.destroy +*/ +Phaser.Physics.World.prototype.destroy = function () { + + this.clear(); + + this.game = null; + +}; diff --git a/src/physics/arcade/Body.js b/src/physics/arcade/Body.js deleted file mode 100644 index e3c782fd..00000000 --- a/src/physics/arcade/Body.js +++ /dev/null @@ -1,1585 +0,0 @@ -/** -* @author Richard Davey -* @copyright 2014 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ - -/** -* The Physics Body is linked to a single Sprite and defines properties that determine how the physics body is simulated. -* These properties affect how the body reacts to forces, what forces it generates on itself (to simulate friction), and how it reacts to collisions in the scene. In most cases, the properties are used to simulate physical effects. -* Each body also has its own property values that determine exactly how it reacts to forces and collisions in the scene. -* -* @class Phaser.Physics.Arcade.Body -* @classdesc Arcade Physics Body Constructor -* @constructor -* @param {Phaser.Sprite} sprite - The Sprite object this physics body belongs to. -*/ -Phaser.Physics.Arcade.Body = function (sprite) { - - /** - * @property {Phaser.Sprite} sprite - Reference to the parent Sprite. - */ - this.sprite = sprite; - - /** - * @property {Phaser.Game} game - Local reference to game. - */ - this.game = sprite.game; - - /** - * @property {Phaser.Point} offset - The offset of the Physics Body from the Sprite x/y position. - */ - this.offset = new Phaser.Point(); - - /** - * @property {number} preX - The previous x position of the physics body. - * @readonly - */ - this.preX = sprite.world.x; - - /** - * @property {number} preY - The previous y position of the physics body. - * @readonly - */ - this.preY = sprite.world.y; - - /** - * @property {number} preRotation - The previous rotation of the physics body. - * @readonly - */ - this.preRotation = sprite.angle; - - /** - * @property {Phaser.Point} velocity - The velocity of the Body. - */ - this.velocity = new Phaser.Point(); - - /** - * @property {Phaser.Point} acceleration - The acceleration in pixels per second sq. of the Body. - */ - this.acceleration = new Phaser.Point(); - - /** - * @property {number} speed - The speed in pixels per second sq. of the Body. - */ - this.speed = 0; - - /** - * @property {number} angle - The angle of the Body based on its velocity in radians. - */ - this.angle = 0; - - /** - * @property {number} deltaCap - The maximum a delta is allowed to reach before its capped. - * @default - */ - this.deltaCap = 10; - - /** - * @property {Phaser.Point} gravity - The gravity applied to the motion of the Body. This works in addition to any gravity set on the world. - */ - this.gravity = new Phaser.Point(); - - /** - * @property {Phaser.Point} bounce - The elasticitiy of the Body when colliding. This property determines how much energy a body maintains during a collision, i.e. its bounciness. - */ - this.bounce = new Phaser.Point(); - - /** - * @property {Phaser.Point} minVelocity - When a body rebounds off another body or a wall the minVelocity is checked. If the new velocity is lower than minVelocity the body is stopped. - * @default - */ - this.minVelocity = new Phaser.Point(); - - /** - * @property {Phaser.Point} maxVelocity - The maximum velocity that the Body can reach. - * @default - */ - this.maxVelocity = new Phaser.Point(1000, 1000); - - /** - * @property {number} angularVelocity - The angular velocity of the Body. - * @default - */ - this.angularVelocity = 0; - - /** - * @property {number} angularAcceleration - The angular acceleration of the Body. - * @default - */ - this.angularAcceleration = 0; - - /** - * @property {number} angularDrag - angularDrag is used to calculate friction on the body as it rotates. - * @default - */ - this.angularDrag = 0; - - /** - * @property {number} maxAngular - The maximum angular velocity that the Body can reach. - * @default - */ - this.maxAngular = 1000; - - /** - * @property {number} mass - The mass property determines how forces affect the body, as well as how much momentum the body has when it is involved in a collision. - * @default - */ - this.mass = 1; - - /** - * @property {number} linearDamping - linearDamping is used to calculate friction on the body as it moves through the world. For example, this might be used to simulate air or water friction. - * @default - */ - this.linearDamping = 0.0; - - /** - * Set the checkCollision properties to control which directions collision is processed for this Body. - * For example checkCollision.up = false means it won't collide when the collision happened while moving up. - * @property {object} checkCollision - An object containing allowed collision. - */ - this.checkCollision = { none: false, any: true, up: true, down: true, left: true, right: true }; - - /** - * This object is populated with boolean values when the Body collides with another. - * touching.up = true means the collision happened to the top of this Body for example. - * @property {object} touching - An object containing touching results. - */ - this.touching = { none: true, up: false, down: false, left: false, right: false }; - - /** - * This object is populated with boolean values when the Body collides with the World bounds or a Tile. - * For example if blocked.up is true then the Body cannot move up. - * @property {object} blocked - An object containing on which faces this Body is blocked from moving, if any. - */ - this.blocked = { x: 0, y: 0, up: false, down: false, left: false, right: false }; - - /** - * @property {number} facing - A const reference to the direction the Body is traveling or facing. - * @default - */ - this.facing = Phaser.NONE; - - /** - * @property {boolean} rebound - A Body set to rebound will exchange velocity with another Body during collision. Set to false to allow this body to be 'pushed' rather than exchange velocity. - * @default - */ - this.rebound = true; - - /** - * @property {boolean} immovable - An immovable Body will not receive any impacts or exchanges of velocity from other bodies. - * @default - */ - this.immovable = false; - - /** - * @property {boolean} moves - Set to true to allow the Physics system (such as velocity) to move this Body, or false to move it manually. - * @default - */ - this.moves = true; - - /** - * @property {number} rotation - The amount the parent Sprite is rotated. - * @default - */ - this.rotation = 0; - - /** - * @property {boolean} allowRotation - Allow angular rotation? This will cause the Sprite to be rotated via angularVelocity, etc. - * @default - */ - this.allowRotation = true; - - /** - * @property {boolean} allowGravity - Allow this Body to be influenced by the global Gravity value? Note: It will always be influenced by the local gravity if set. - * @default - */ - this.allowGravity = true; - - /** - * @property {function} customSeparateCallback - If set this callback will be used for Body separation instead of the built-in one. Callback should return true if separated, otherwise false. - * @default - */ - this.customSeparateCallback = null; - - /** - * @property {object} customSeparateContext - The context in which the customSeparateCallback is called. - * @default - */ - this.customSeparateContext = null; - - /** - * @property {function} collideCallback - If set this callback will be fired whenever this Body is hit (on any face). It will send three parameters, the face it hit on, this Body and the Body that hit it. - * @default - */ - this.collideCallback = null; - - /** - * @property {object} collideCallbackContext - The context in which the collideCallback is called. - * @default - */ - this.collideCallbackContext = null; - - /** - * A Body can be set to collide against the World bounds automatically and rebound back into the World if this is set to true. Otherwise it will leave the World. - * @property {boolean} collideWorldBounds - Should the Body collide with the World bounds? - */ - this.collideWorldBounds = false; - - /** - * @property {Phaser.Physics.Arcade.RECT|Phaser.Physics.Arcade.CIRCLE} type - The type of SAT Shape. - */ - this.type = Phaser.Physics.Arcade.RECT; - - /** - * @property {SAT.Box|SAT.Circle|SAT.Polygon} shape - The SAT Collision shape. - */ - this.shape = null; - - /** - * @property {SAT.Polygon} polygon - The SAT Polygons, as derived from the Shape. - */ - this.polygon = null; - - /** - * @property {number} left - The left-most point of this Body. - * @readonly - */ - this.left = 0; - - /** - * @property {number} right - The right-most point of this Body. - * @readonly - */ - this.right = 0; - - /** - * @property {number} top - The top-most point of this Body. - * @readonly - */ - this.top = 0; - - /** - * @property {number} bottom - The bottom-most point of this Body. - * @readonly - */ - this.bottom = 0; - - /** - * @property {number} width - The current width of the Body, taking into account the point rotation. - * @readonly - */ - this.width = 0; - - /** - * @property {number} height - The current height of the Body, taking into account the point rotation. - * @readonly - */ - this.height = 0; - - /** - * @property {array} contacts - Used to store references to bodies this Body is in contact with. - * @protected - */ - this.contacts = []; - - /** - * @property {number} overlapX - Mostly used internally to store the overlap values from Tile seperation. - * @protected - */ - this.overlapX = 0; - - /** - * @property {number} overlapY - Mostly used internally to store the overlap values from Tile seperation. - * @protected - */ - this.overlapY = 0; - - /** - * @property {Phaser.Point} _temp - Internal cache var. - * @private - */ - this._temp = null; - - /** - * @property {number} _dx - Internal cache var. - * @private - */ - this._dx = 0; - - /** - * @property {number} _dy - Internal cache var. - * @private - */ - this._dy = 0; - - /** - * @property {number} _sx - Internal cache var. - * @private - */ - this._sx = sprite.scale.x; - - /** - * @property {number} _sy - Internal cache var. - * @private - */ - this._sy = sprite.scale.y; - - /** - * @property {array} _distances - Internal cache var. - * @private - */ - this._distances = [0, 0, 0, 0]; - - /** - * @property {number} _vx - Internal cache var. - * @private - */ - this._vx = 0; - - /** - * @property {number} _vy - Internal cache var. - * @private - */ - this._vy = 0; - - // Set-up the default shape - this.setRectangle(sprite.width, sprite.height, 0, 0); - - // Set-up contact events - this.sprite.events.onBeginContact = new Phaser.Signal(); - this.sprite.events.onEndContact = new Phaser.Signal(); - -}; - -Phaser.Physics.Arcade.Body.prototype = { - - /** - * Internal method that updates the Body scale in relation to the parent Sprite. - * - * @method Phaser.Physics.Arcade.Body#updateScale - * @protected - */ - updateScale: function () { - - if (this.polygon) - { - this.polygon.scale(this.sprite.scale.x / this._sx, this.sprite.scale.y / this._sy); - } - else - { - this.shape.r *= Math.max(this.sprite.scale.x, this.sprite.scale.y); - } - - this._sx = this.sprite.scale.x; - this._sy = this.sprite.scale.y; - - }, - - /** - * Internal method that updates the Body position in relation to the parent Sprite. - * - * @method Phaser.Physics.Arcade.Body#preUpdate - * @protected - */ - preUpdate: function () { - - this.x = (this.sprite.world.x - (this.sprite.anchor.x * this.sprite.width)) + this.offset.x; - this.y = (this.sprite.world.y - (this.sprite.anchor.y * this.sprite.height)) + this.offset.y; - - // This covers any motion that happens during this frame, not since the last frame - this.preX = this.x; - this.preY = this.y; - this.preRotation = this.sprite.angle; - - this.rotation = this.preRotation; - - if (this.sprite.scale.x !== this._sx || this.sprite.scale.y !== this._sy) - { - this.updateScale(); - } - - this.checkBlocked(); - - this.touching.none = true; - this.touching.up = false; - this.touching.down = false; - this.touching.left = false; - this.touching.right = false; - - if (this.moves) - { - if (this._vx !== this.velocity.x || this._vy !== this.velocity.y) - { - // No need to re-calc these if they haven't changed - this._vx = this.velocity.x; - this._vy = this.velocity.y; - this.speed = Math.sqrt(this.velocity.x * this.velocity.x + this.velocity.y * this.velocity.y); - this.angle = Math.atan2(this.velocity.y, this.velocity.x); - } - - if (this.game.physics.checkBounds(this)) - { - this.reboundCheck(true, true, true); - } - - this.applyDamping(); - - this.integrateVelocity(); - - this.updateBounds(); - - this.checkBlocked(); - } - else - { - this.updateBounds(); - } - - }, - - /** - * Internal method that checks and potentially resets the blocked status flags. - * - * @method Phaser.Physics.Arcade.Body#checkBlocked - * @protected - */ - checkBlocked: function () { - - if ((this.blocked.left || this.blocked.right) && (Math.floor(this.x) !== this.blocked.x || Math.floor(this.y) !== this.blocked.y)) - { - this.blocked.left = false; - this.blocked.right = false; - } - - if ((this.blocked.up || this.blocked.down) && (Math.floor(this.x) !== this.blocked.x || Math.floor(this.y) !== this.blocked.y)) - { - this.blocked.up = false; - this.blocked.down = false; - } - - }, - - /** - * Internal method that updates the left, right, top, bottom, width and height properties. - * - * @method Phaser.Physics.Arcade.Body#updateBounds - * @protected - */ - updateBounds: function () { - - if (this.type === Phaser.Physics.Arcade.CIRCLE) - { - this.left = this.shape.pos.x - this.shape.r; - this.right = this.shape.pos.x + this.shape.r; - this.top = this.shape.pos.y - this.shape.r; - this.bottom = this.shape.pos.y + this.shape.r; - } - else - { - this.left = Phaser.Math.minProperty('x', this.polygon.points) + this.polygon.pos.x; - this.right = Phaser.Math.maxProperty('x', this.polygon.points) + this.polygon.pos.x; - this.top = Phaser.Math.minProperty('y', this.polygon.points) + this.polygon.pos.y; - this.bottom = Phaser.Math.maxProperty('y', this.polygon.points) + this.polygon.pos.y; - } - - this.width = this.right - this.left; - this.height = this.bottom - this.top; - - }, - - /** - * Internal method that checks the acceleration and applies damping if not set. - * - * @method Phaser.Physics.Arcade.Body#applyDamping - * @protected - */ - applyDamping: function () { - - if (this.linearDamping > 0 && this.acceleration.isZero()) - { - if (this.speed > this.linearDamping) - { - this.speed -= this.linearDamping; - } - else - { - this.speed = 0; - } - - // Don't bother if speed 0 - if (this.speed > 0) - { - this.velocity.x = Math.cos(this.angle) * this.speed; - this.velocity.y = Math.sin(this.angle) * this.speed; - - this.speed = Math.sqrt(this.velocity.x * this.velocity.x + this.velocity.y * this.velocity.y); - this.angle = Math.atan2(this.velocity.y, this.velocity.x); - } - } - - }, - - /** - * Check if we're below minVelocity and gravity isn't trying to drag us in the opposite direction. - * - * @method Phaser.Physics.Arcade.Body#reboundCheck - * @protected - * @param {boolean} x - Check the X axis? - * @param {boolean} y - Check the Y axis? - * @param {boolean} rebound - If true it will reverse the velocity on the given axis - */ - reboundCheck: function (x, y, rebound) { - - if (x) - { - if (rebound && this.bounce.x !== 0 && (this.blocked.left || this.blocked.right || this.touching.left || this.touching.right)) - { - // Don't rebound if they've already rebounded in this frame - if (!(this._vx <= 0 && this.velocity.x > 0) && !(this._vx >= 0 && this.velocity.x < 0)) - { - this.velocity.x *= -this.bounce.x; - this.angle = Math.atan2(this.velocity.y, this.velocity.x); - } - } - - if (this.bounce.x === 0 || Math.abs(this.velocity.x) < this.minVelocity.x) - { - var gx = this.getUpwardForce(); - - if (((this.blocked.left || this.touching.left) && (gx < 0 || this.velocity.x < 0)) || ((this.blocked.right || this.touching.right) && (gx > 0 || this.velocity.x > 0))) - { - this.velocity.x = 0; - } - } - } - - if (y) - { - if (rebound && this.bounce.y !== 0 && (this.blocked.up || this.blocked.down || this.touching.up || this.touching.down)) - { - // Don't rebound if they've already rebounded in this frame - if (!(this._vy <= 0 && this.velocity.y > 0) && !(this._vy >= 0 && this.velocity.y < 0)) - { - this.velocity.y *= -this.bounce.y; - this.angle = Math.atan2(this.velocity.y, this.velocity.x); - } - } - - if (this.bounce.y === 0 || Math.abs(this.velocity.y) < this.minVelocity.y) - { - var gy = this.getDownwardForce(); - - if (((this.blocked.up || this.touching.up) && (gy < 0 || this.velocity.y < 0)) || ((this.blocked.down || this.touching.down) && (gy > 0 || this.velocity.y > 0))) - { - this.velocity.y = 0; - } - } - } - - }, - - /** - * Gets the total force being applied on the X axis, including gravity and velocity. - * - * @method Phaser.Physics.Arcade.Body#getUpwardForce - * @return {number} The total force being applied on the X axis. - */ - getUpwardForce: function () { - - if (this.allowGravity) - { - return this.gravity.x + this.game.physics.gravity.x + this.velocity.x; - } - else - { - return this.gravity.x + this.velocity.x; - } - - }, - - /** - * Gets the total force being applied on the X axis, including gravity and velocity. - * - * @method Phaser.Physics.Arcade.Body#getDownwardForce - * @return {number} The total force being applied on the Y axis. - */ - getDownwardForce: function () { - - if (this.allowGravity) - { - return this.gravity.y + this.game.physics.gravity.y + this.velocity.y; - } - else - { - return this.gravity.y + this.velocity.y; - } - - }, - - /** - * Subtracts the given Vector from this Body. - * - * @method Phaser.Physics.Arcade.Body#sub - * @protected - * @param {SAT.Vector} v - The vector to substract from this Body. - */ - sub: function (v) { - - this.x -= v.x; - this.y -= v.y; - - }, - - /** - * Adds the given Vector to this Body. - * - * @method Phaser.Physics.Arcade.Body#add - * @protected - * @param {SAT.Vector} v - The vector to add to this Body. - */ - add: function (v) { - - this.x += v.x; - this.y += v.y; - - }, - - /** - * Separation response handler. - * - * @method Phaser.Physics.Arcade.Body#give - * @protected - * @param {Phaser.Physics.Arcade.Body} body - The Body that collided. - * @param {SAT.Response} response - The SAT Response object containing the collision data. - */ - give: function (body, response) { - - this.add(response.overlapV); - - if (this.rebound) - { - this.processRebound(body); - this.reboundCheck(true, true, false); - body.reboundCheck(true, true, false); - } - - }, - - /** - * Separation response handler. - * - * @method Phaser.Physics.Arcade.Body#take - * @protected - * @param {Phaser.Physics.Arcade.Body} body - The Body that collided. - * @param {SAT.Response} response - The SAT Response object containing the collision data. - */ - take: function (body, response) { - - this.sub(response.overlapV); - - if (this.rebound) - { - this.processRebound(body); - this.reboundCheck(true, true, false); - body.reboundCheck(true, true, false); - } - - }, - - /** - * Split the collision response evenly between the two bodies. - * - * @method Phaser.Physics.Arcade.Body#split - * @protected - * @param {Phaser.Physics.Arcade.Body} body - The Body that collided. - * @param {SAT.Response} response - The SAT Response object containing the collision data. - */ - split: function (body, response) { - - response.overlapV.scale(0.5); - this.sub(response.overlapV); - body.add(response.overlapV); - - if (this.rebound) - { - this.exchange(body); - this.reboundCheck(true, true, false); - body.reboundCheck(true, true, false); - } - - }, - - /** - * Exchange velocity with the given Body. - * - * @method Phaser.Physics.Arcade.Body#exchange - * @protected - * @param {Phaser.Physics.Arcade.Body} body - The Body that collided. - */ - exchange: function (body) { - - if (this.mass === body.mass && this.speed > 0 && body.speed > 0) - { - // A direct velocity exchange (as they are both moving and have the same mass) - this._dx = body.velocity.x; - this._dy = body.velocity.y; - - body.velocity.x = this.velocity.x * body.bounce.x; - body.velocity.y = this.velocity.y * body.bounce.x; - - this.velocity.x = this._dx * this.bounce.x; - this.velocity.y = this._dy * this.bounce.y; - } - else - { - var nv1 = Math.sqrt((body.velocity.x * body.velocity.x * body.mass) / this.mass) * ((body.velocity.x > 0) ? 1 : -1); - var nv2 = Math.sqrt((this.velocity.x * this.velocity.x * this.mass) / body.mass) * ((this.velocity.x > 0) ? 1 : -1); - var average = (nv1 + nv2) * 0.5; - nv1 -= average; - nv2 -= average; - - this.velocity.x = nv1; - body.velocity.x = nv2; - - nv1 = Math.sqrt((body.velocity.y * body.velocity.y * body.mass) / this.mass) * ((body.velocity.y > 0) ? 1 : -1); - nv2 = Math.sqrt((this.velocity.y * this.velocity.y * this.mass) / body.mass) * ((this.velocity.y > 0) ? 1 : -1); - average = (nv1 + nv2) * 0.5; - nv1 -= average; - nv2 -= average; - - this.velocity.y = nv1; - body.velocity.y = nv2; - } - - // update speed / angle? - - }, - - /** - * Rebound the velocity of this Body. - * - * @method Phaser.Physics.Arcade.Body#processRebound - * @protected - * @param {Phaser.Physics.Arcade.Body} body - The Body that collided. - */ - processRebound: function (body) { - - // Don't rebound again if they've already rebounded in this frame - if (!(this._vx <= 0 && this.velocity.x > 0) && !(this._vx >= 0 && this.velocity.x < 0)) - { - this.velocity.x = body.velocity.x - this.velocity.x * this.bounce.x; - } - - if (!(this._vy <= 0 && this.velocity.y > 0) && !(this._vy >= 0 && this.velocity.y < 0)) - { - this.velocity.y = body.velocity.y - this.velocity.y * this.bounce.y; - } - - this.angle = Math.atan2(this.velocity.y, this.velocity.x); - - this.reboundCheck(true, true, false); - - }, - - /** - * Checks for an overlap between this Body and the given Body. - * - * @method Phaser.Physics.Arcade.Body#overlap - * @param {Phaser.Physics.Arcade.Body} body - The Body that is being checked against this Body. - * @param {SAT.Response} response - SAT Response handler. - * @return {boolean} True if the two bodies overlap, otherwise false. - */ - overlap: function (body, response) { - - var result = false; - - if ((this.type === Phaser.Physics.Arcade.RECT || this.type === Phaser.Physics.Arcade.POLYGON) && (body.type === Phaser.Physics.Arcade.RECT || body.type === Phaser.Physics.Arcade.POLYGON)) - { - result = SAT.testPolygonPolygon(this.polygon, body.polygon, response); - } - else if (this.type === Phaser.Physics.Arcade.CIRCLE && body.type === Phaser.Physics.Arcade.CIRCLE) - { - result = SAT.testCircleCircle(this.shape, body.shape, response); - } - else if ((this.type === Phaser.Physics.Arcade.RECT || this.type === Phaser.Physics.Arcade.POLYGON) && body.type === Phaser.Physics.Arcade.CIRCLE) - { - result = SAT.testPolygonCircle(this.polygon, body.shape, response); - } - else if (this.type === Phaser.Physics.Arcade.CIRCLE && (body.type === Phaser.Physics.Arcade.RECT || body.type === Phaser.Physics.Arcade.POLYGON)) - { - result = SAT.testCirclePolygon(this.shape, body.polygon, response); - } - - if (!result) - { - this.removeContact(body); - } - - return result; - - }, - - /** - * Checks if this Body is already in contact with the given Body. - * - * @method Phaser.Physics.Arcade.Body#inContact - * @param {Phaser.Physics.Arcade.Body} body - The Body to be checked. - * @return {boolean} True if the given Body is already in contact with this Body. - */ - inContact: function (body) { - - return (this.contacts.indexOf(body) != -1); - - }, - - /** - * Adds the given Body to the contact list of this Body. Also adds this Body to the contact list of the given Body. - * - * @method Phaser.Physics.Arcade.Body#addContact - * @param {Phaser.Physics.Arcade.Body} body - The Body to be added. - * @return {boolean} True if the given Body was added to this contact list, false if already on it. - */ - addContact: function (body) { - - if (this.inContact(body)) - { - return false; - } - - this.contacts.push(body); - - this.sprite.events.onBeginContact.dispatch(this.sprite, body.sprite, this, body); - - body.addContact(this); - - return true; - - }, - - /** - * Removes the given Body from the contact list of this Body. Also removes this Body from the contact list of the given Body. - * - * @method Phaser.Physics.Arcade.Body#removeContact - * @param {Phaser.Physics.Arcade.Body} body - The Body to be removed. - * @return {boolean} True if the given Body was removed from this contact list, false if wasn't on it. - */ - removeContact: function (body) { - - if (!this.inContact(body)) - { - return false; - } - - this.contacts.splice(this.contacts.indexOf(body), 1); - - this.sprite.events.onEndContact.dispatch(this.sprite, body.sprite, this, body); - - body.removeContact(this); - - return true; - - }, - - /** - * This separates this Body from the given Body unless a customSeparateCallback is set. - * It assumes they have already been overlap checked and the resulting overlap is stored in the SAT response. - * - * @method Phaser.Physics.Arcade.Body#separate - * @protected - * @param {Phaser.Physics.Arcade.Body} body - The Body to be separated from this one. - * @param {SAT.Response} response - SAT Response handler. - * @return {boolean} True if the bodies were separated, false if not (for example checkCollide allows them to pass through) - */ - separate: function (body, response) { - - if (this.inContact(body)) - { - // return false; - } - - this._distances[0] = body.right - this.x; // Distance of B to face on left side of A - this._distances[1] = this.right - body.x; // Distance of B to face on right side of A - this._distances[2] = body.bottom - this.y; // Distance of B to face on bottom side of A - this._distances[3] = this.bottom - body.y; // Distance of B to face on top side of A - - // If we've zero distance then check for side-slicing - if (response.overlapN.x && (this._distances[0] === 0 || this._distances[1] === 0)) - { - response.overlapN.x = false; - response.overlapN.y = true; - } - else if (response.overlapN.y && (this._distances[2] === 0 || this._distances[3] === 0)) - { - response.overlapN.x = true; - response.overlapN.y = false; - } - - if (this.customSeparateCallback) - { - return this.customSeparateCallback.call(this.customSeparateContext, this, response, this._distances); - } - - var hasSeparated = false; - - if (response.overlapN.x) - { - // Which is smaller? Left or Right? - if (this._distances[0] < this._distances[1]) - { - hasSeparated = this.hitLeft(body, response); - } - else if (this._distances[1] < this._distances[0]) - { - hasSeparated = this.hitRight(body, response); - } - } - else if (response.overlapN.y) - { - // Which is smaller? Top or Bottom? - if (this._distances[2] < this._distances[3]) - { - hasSeparated = this.hitTop(body, response); - } - else if (this._distances[3] < this._distances[2]) - { - hasSeparated = this.hitBottom(body, response); - } - } - - if (hasSeparated) - { - this.game.physics.checkBounds(this); - this.game.physics.checkBounds(body); - } - else - { - // They can only contact like this if at least one of their sides is open, otherwise it's a separation - if (!this.checkCollision.up || !this.checkCollision.down || !this.checkCollision.left || !this.checkCollision.right || !body.checkCollision.up || !body.checkCollision.down || !body.checkCollision.left || !body.checkCollision.right) - { - this.addContact(body); - } - } - - return hasSeparated; - - }, - - /** - * Process a collision with the left face of this Body. - * Collision and separation can be further checked by setting a collideCallback. - * This callback will be sent 4 parameters: The face of collision, this Body, the colliding Body and the SAT Response. - * If the callback returns true then separation, rebounds and the touching flags will all be set. - * If it returns false this will be skipped and must be handled manually. - * - * @method Phaser.Physics.Arcade.Body#hitLeft - * @protected - * @param {Phaser.Physics.Arcade.Body} body - The Body that collided. - * @param {SAT.Response} response - The SAT Response object containing the collision data. - */ - hitLeft: function (body, response) { - - if (!this.checkCollision.left || !body.checkCollision.right) - { - return false; - } - - if (this.collideCallback && !this.collideCallback.call(this.collideCallbackContext, Phaser.LEFT, this, body, response)) - { - return; - } - - if (!this.moves || this.immovable || this.blocked.right || this.touching.right) - { - body.give(this, response); - } - else - { - if (body.immovable || body.blocked.left || body.touching.left) - { - // We take the full separation - this.take(body, response); - } - else - { - // Share out the separation - this.split(body, response); - } - } - - this.touching.left = true; - body.touching.right = true; - - }, - - /** - * Process a collision with the right face of this Body. - * Collision and separation can be further checked by setting a collideCallback. - * This callback will be sent 4 parameters: The face of collision, this Body, the colliding Body and the SAT Response. - * If the callback returns true then separation, rebounds and the touching flags will all be set. - * If it returns false this will be skipped and must be handled manually. - * - * @method Phaser.Physics.Arcade.Body#hitRight - * @protected - * @param {Phaser.Physics.Arcade.Body} body - The Body that collided. - * @param {SAT.Response} response - The SAT Response object containing the collision data. - */ - hitRight: function (body, response) { - - if (!this.checkCollision.right || !body.checkCollision.left) - { - return false; - } - - if (this.collideCallback && !this.collideCallback.call(this.collideCallbackContext, Phaser.RIGHT, this, body)) - { - return; - } - - if (!this.moves || this.immovable || this.blocked.left || this.touching.left) - { - body.give(this, response); - } - else - { - if (body.immovable || body.blocked.right || body.touching.right) - { - // We take the full separation - this.take(body, response); - } - else - { - // Share out the separation - this.split(body, response); - } - } - - this.touching.right = true; - body.touching.left = true; - - }, - - /** - * Process a collision with the top face of this Body. - * Collision and separation can be further checked by setting a collideCallback. - * This callback will be sent 4 parameters: The face of collision, this Body, the colliding Body and the SAT Response. - * If the callback returns true then separation, rebounds and the touching flags will all be set. - * If it returns false this will be skipped and must be handled manually. - * - * @method Phaser.Physics.Arcade.Body#hitTop - * @protected - * @param {Phaser.Physics.Arcade.Body} body - The Body that collided. - * @param {SAT.Response} response - The SAT Response object containing the collision data. - */ - hitTop: function (body, response) { - - if (!this.checkCollision.up || !body.checkCollision.down) - { - return false; - } - - if (this.collideCallback && !this.collideCallback.call(this.collideCallbackContext, Phaser.UP, this, body)) - { - return false; - } - - if (!this.moves || this.immovable || this.blocked.down || this.touching.down) - { - body.give(this, response); - } - else - { - if (body.immovable || body.blocked.up || body.touching.up) - { - // We take the full separation - this.take(body, response); - } - else - { - // Share out the separation - this.split(body, response); - } - } - - this.touching.up = true; - body.touching.down = true; - - return true; - - }, - - /** - * Process a collision with the bottom face of this Body. - * Collision and separation can be further checked by setting a collideCallback. - * This callback will be sent 4 parameters: The face of collision, this Body, the colliding Body and the SAT Response. - * If the callback returns true then separation, rebounds and the touching flags will all be set. - * If it returns false this will be skipped and must be handled manually. - * - * @method Phaser.Physics.Arcade.Body#hitBottom - * @protected - * @param {Phaser.Physics.Arcade.Body} body - The Body that collided. - * @param {SAT.Response} response - The SAT Response object containing the collision data. - */ - hitBottom: function (body, response) { - - if (!this.checkCollision.down || !body.checkCollision.up) - { - return false; - } - - if (this.collideCallback && !this.collideCallback.call(this.collideCallbackContext, Phaser.DOWN, this, body)) - { - return false; - } - - if (!this.moves || this.immovable || this.blocked.up || this.touching.up) - { - body.give(this, response); - } - else - { - if (body.immovable || body.blocked.down || body.touching.down) - { - // We take the full separation - this.take(body, response); - } - else - { - // Share out the separation - this.split(body, response); - } - } - - this.touching.down = true; - body.touching.up = true; - - return true; - - }, - - /** - * Internal method. Integrates velocity, global gravity and the delta timer. - * - * @method Phaser.Physics.Arcade.Body#integrateVelocity - * @protected - */ - integrateVelocity: function () { - - this._temp = this.game.physics.updateMotion(this); - this._dx = this.game.time.physicsElapsed * (this.velocity.x + this._temp.x / 2); - this._dy = this.game.time.physicsElapsed * (this.velocity.y + this._temp.y / 2); - - // positive = RIGHT / DOWN - // negative = LEFT / UP - - if ((this._dx < 0 && !this.blocked.left && !this.touching.left) || (this._dx > 0 && !this.blocked.right && !this.touching.right)) - { - this.x += this._dx; - this.velocity.x += this._temp.x; - } - - if ((this._dy < 0 && !this.blocked.up && !this.touching.up) || (this._dy > 0 && !this.blocked.down && !this.touching.down)) - { - this.y += this._dy; - this.velocity.y += this._temp.y; - } - - if (this.velocity.x > this.maxVelocity.x) - { - this.velocity.x = this.maxVelocity.x; - } - else if (this.velocity.x < -this.maxVelocity.x) - { - this.velocity.x = -this.maxVelocity.x; - } - - if (this.velocity.y > this.maxVelocity.y) - { - this.velocity.y = this.maxVelocity.y; - } - else if (this.velocity.y < -this.maxVelocity.y) - { - this.velocity.y = -this.maxVelocity.y; - } - - }, - - /** - * Internal method. This is called directly before the sprites are sent to the renderer and after the update function has finished. - * - * @method Phaser.Physics.Arcade.Body#postUpdate - * @protected - */ - postUpdate: function () { - - if (this.moves) - { - this.game.physics.checkBounds(this); - - this.reboundCheck(true, true, true); - - this._dx = this.deltaX(); - this._dy = this.deltaY(); - - if (this._dx < 0) - { - this.facing = Phaser.LEFT; - } - else if (this._dx > 0) - { - this.facing = Phaser.RIGHT; - } - - if (this._dy < 0) - { - this.facing = Phaser.UP; - } - else if (this._dy > 0) - { - this.facing = Phaser.DOWN; - } - - if (this._dx !== 0 || this._dy !== 0) - { - this.sprite.x += this._dx; - this.sprite.y += this._dy; - } - - if (this.allowRotation && this.deltaZ() !== 0) - { - this.sprite.angle += this.deltaZ(); - } - - if (this.sprite.scale.x !== this._sx || this.sprite.scale.y !== this._sy) - { - this.updateScale(); - } - } - - }, - - /** - * Resets the Body motion values: velocity, acceleration, angularVelocity and angularAcceleration. - * Also resets the forces to defaults: gravity, bounce, minVelocity,maxVelocity, angularDrag, maxAngular, mass, friction and checkCollision if 'full' specified. - * - * @method Phaser.Physics.Arcade.Body#reset - * @param {boolean} [full=false] - A full reset clears down settings you may have set, such as gravity, bounce and drag. A non-full reset just clears motion values. - */ - reset: function (full) { - - if (typeof full === 'undefined') { full = false; } - - if (full) - { - this.gravity.setTo(0, 0); - this.bounce.setTo(0, 0); - this.minVelocity.setTo(5, 5); - this.maxVelocity.setTo(1000, 1000); - this.angularDrag = 0; - this.maxAngular = 1000; - this.mass = 1; - this.friction = 0.0; - this.checkCollision = { none: false, any: true, up: true, down: true, left: true, right: true }; - } - - this.velocity.setTo(0, 0); - this.acceleration.setTo(0, 0); - this.angularVelocity = 0; - this.angularAcceleration = 0; - this.blocked = { x: 0, y: 0, up: false, down: false, left: false, right: false }; - this.x = (this.sprite.world.x - (this.sprite.anchor.x * this.sprite.width)) + this.offset.x; - this.y = (this.sprite.world.y - (this.sprite.anchor.y * this.sprite.height)) + this.offset.y; - this.preX = this.x; - this.preY = this.y; - this.updateBounds(); - - this.contacts.length = 0; - - }, - - /** - * Destroys this Body and all references it holds to other objects. - * - * @method Phaser.Physics.Arcade.Body#destroy - */ - destroy: function () { - - this.sprite = null; - - this.collideCallback = null; - this.collideCallbackContext = null; - - this.customSeparateCallback = null; - this.customSeparateContext = null; - - this.contacts.length = 0; - - }, - - /** - * Sets this Body to use a circle of the given radius for all collision. - * The Circle will be centered on the center of the Sprite by default, but can be adjusted via the Body.offset property and the setCircle x/y parameters. - * - * @method Phaser.Physics.Arcade.Body#setCircle - * @param {number} radius - The radius of this circle (in pixels) - * @param {number} [offsetX=0] - The x amount the circle will be offset from the Sprites center. - * @param {number} [offsetY=0] - The y amount the circle will be offset from the Sprites center. - */ - setCircle: function (radius, offsetX, offsetY) { - - if (typeof offsetX === 'undefined') { offsetX = this.sprite._cache.halfWidth; } - if (typeof offsetY === 'undefined') { offsetY = this.sprite._cache.halfHeight; } - - this.type = Phaser.Physics.Arcade.CIRCLE; - this.shape = new SAT.Circle(new SAT.Vector(this.sprite.x, this.sprite.y), radius); - this.polygon = null; - - this.offset.setTo(offsetX, offsetY); - - }, - - /** - * Sets this Body to use a rectangle for all collision. - * If you don't specify any parameters it will be sized to match the parent Sprites current width and height (including scale factor) and centered on the sprite. - * - * @method Phaser.Physics.Arcade.Body#setRectangle - * @param {number} [width] - The width of the rectangle. If not specified it will default to the width of the parent Sprite. - * @param {number} [height] - The height of the rectangle. If not specified it will default to the height of the parent Sprite. - * @param {number} [translateX] - The x amount the rectangle will be translated from the Sprites center. - * @param {number} [translateY] - The y amount the rectangle will be translated from the Sprites center. - */ - setRectangle: function (width, height, translateX, translateY) { - - if (typeof width === 'undefined') { width = this.sprite.width; } - if (typeof height === 'undefined') { height = this.sprite.height; } - if (typeof translateX === 'undefined') { translateX = -this.sprite._cache.halfWidth; } - if (typeof translateY === 'undefined') { translateY = -this.sprite._cache.halfHeight; } - - this.type = Phaser.Physics.Arcade.RECT; - this.shape = new SAT.Box(new SAT.Vector(this.sprite.world.x, this.sprite.world.y), width, height); - this.polygon = this.shape.toPolygon(); - this.polygon.translate(translateX, translateY); - - this.offset.setTo(0, 0); - - }, - - /** - * Sets this Body to use a convex polygon for collision. - * The points are specified in a counter-clockwise direction and must create a convex polygon. - * Use Body.translate and/or Body.offset to re-position the polygon from the Sprite origin. - * - * @method Phaser.Physics.Arcade.Body#setPolygon - * @param {(SAT.Vector[]|number[]|...SAT.Vector|...number)} points - This can be an array of Vectors that form the polygon, - * a flat array of numbers that will be interpreted as [x,y, x,y, ...], or the arguments passed can be - * all the points of the polygon e.g. `setPolygon(new SAT.Vector(), new SAT.Vector(), ...)`, or the - * arguments passed can be flat x,y values e.g. `setPolygon(x,y, x,y, x,y, ...)` where `x` and `y` are Numbers. - */ - setPolygon: function (points) { - - this.type = Phaser.Physics.Arcade.POLYGON; - this.shape = null; - - if (!Array.isArray(points)) - { - points = Array.prototype.slice.call(arguments); - } - - if (typeof points[0] === 'number') - { - var p = []; - - for (var i = 0, len = points.length; i < len; i += 2) - { - p.push(new SAT.Vector(points[i], points[i + 1])); - } - - points = p; - } - - this.polygon = new SAT.Polygon(new SAT.Vector(this.sprite.center.x, this.sprite.center.y), points); - - this.offset.setTo(0, 0); - - }, - - /** - * Used for translating rectangle and polygon bodies from the Sprite parent. Doesn't apply to Circles. - * See also the Body.offset property. - * - * @method Phaser.Physics.Arcade.Body#translate - * @param {number} x - The x amount the polygon or rectangle will be translated by from the Sprite. - * @param {number} y - The y amount the polygon or rectangle will be translated by from the Sprite. - */ - translate: function (x, y) { - - if (this.polygon) - { - this.polygon.translate(x, y); - } - - }, - - /** - * Determines if this Body is 'on the floor', which means in contact with a Tile or World bounds, or other object that has set 'down' as blocked. - * - * @method Phaser.Physics.Arcade.Body#onFloor - * @return {boolean} True if this Body is 'on the floor', which means in contact with a Tile or World bounds, or object that has set 'down' as blocked. - */ - onFloor: function () { - return this.blocked.down; - }, - - /** - * Determins if this Body is 'on a wall', which means horizontally in contact with a Tile or World bounds, or other object but not the ground. - * - * @method Phaser.Physics.Arcade.Body#onWall - * @return {boolean} True if this Body is 'on a wall', which means horizontally in contact with a Tile or World bounds, or other object but not the ground. - */ - onWall: function () { - return (!this.blocked.down && (this.blocked.left || this.blocked.right)); - }, - - /** - * Returns the delta x value. The amount the Body has moved horizontally in the current step. - * This value is capped by Body.deltaCap. - * - * @method Phaser.Physics.Arcade.Body#deltaX - * @return {number} The delta value. Positive if the motion was to the right, negative if to the left. - */ - deltaX: function () { - - var d = this.x - this.preX; - - if (d < -this.deltaCap) - { - d = -this.deltaCap; - } - else if (d > this.deltaCap) - { - d = this.deltaCap; - } - - return d; - - }, - - /** - * Returns the delta y value. The amount the Body has moved vertically in the current step. - * This value is capped by Body.deltaCap. - * - * @method Phaser.Physics.Arcade.Body#deltaY - * @return {number} The delta value. Positive if the motion was downwards, negative if upwards. - */ - deltaY: function () { - - var d = this.y - this.preY; - - if (d < -this.deltaCap) - { - d = -this.deltaCap; - } - else if (d > this.deltaCap) - { - d = this.deltaCap; - } - - return d; - - }, - - /** - * Returns the delta z value. The amount the Body has rotated in the current step. - * This value is capped by Body.deltaCap. - * - * @method Phaser.Physics.Arcade.Body#deltaZ - * @return {number} The delta value. - */ - deltaZ: function () { - - var d = this.rotation - this.preRotation; - - if (d < -this.deltaCap) - { - d = -this.deltaCap; - } - else if (d > this.deltaCap) - { - d = this.deltaCap; - } - - return d; - - } - -}; - -Phaser.Physics.Arcade.Body.prototype.constructor = Phaser.Physics.Arcade.Body; - -/** -* @name Phaser.Physics.Arcade.Body#x -* @property {number} x - The x coordinate of this Body. -*/ -Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "x", { - - get: function () { - - if (this.type === Phaser.Physics.Arcade.CIRCLE) - { - return this.shape.pos.x; - } - else - { - return this.polygon.pos.x; - } - - }, - - set: function (value) { - - if (this.type === Phaser.Physics.Arcade.CIRCLE) - { - this.shape.pos.x = value; - } - else - { - this.polygon.pos.x = value; - } - - } - -}); - -/** -* @name Phaser.Physics.Arcade.Body#y -* @property {number} y - The y coordinate of this Body. -*/ -Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "y", { - - get: function () { - - if (this.type === Phaser.Physics.Arcade.CIRCLE) - { - return this.shape.pos.y; - } - else - { - return this.polygon.pos.y; - } - - }, - - set: function (value) { - - if (this.type === Phaser.Physics.Arcade.CIRCLE) - { - this.shape.pos.y = value; - } - else - { - this.polygon.pos.y = value; - } - - } - -}); diff --git a/src/physics/arcade/SAT.js b/src/physics/arcade/SAT.js deleted file mode 100644 index 63570ece..00000000 --- a/src/physics/arcade/SAT.js +++ /dev/null @@ -1,862 +0,0 @@ -// Version 0.2 - Copyright 2013 - Jim Riecken -// -// Released under the MIT License - https://github.com/jriecken/sat-js -// -// A simple library for determining intersections of circles and -// polygons using the Separating Axis Theorem. -/** @preserve SAT.js - Version 0.2 - Copyright 2013 - Jim Riecken - released under the MIT License. https://github.com/jriecken/sat-js */ - -/*global define: false, module: false*/ -/*jshint shadow:true, sub:true, forin:true, noarg:true, noempty:true, - eqeqeq:true, bitwise:true, strict:true, undef:true, - curly:true, browser:true */ - -// Create a UMD wrapper for SAT. Works in: -// -// - Plain browser via global SAT variable -// - AMD loader (like require.js) -// - Node.js -// -// The quoted properties all over the place are used so that the Closure Compiler -// does not mangle the exposed API in advanced mode. -/** - * @param {*} root - The global scope - * @param {Function} factory - Factory that creates SAT module - */ -(function (root, factory) { - "use strict"; - if (typeof define === 'function' && define['amd']) { - define(factory); - } else if (typeof exports === 'object') { - module['exports'] = factory(); - } else { - root['SAT'] = factory(); - } -}(this, function () { - "use strict"; - - var SAT = {}; - - // - // ## Vector - // - // Represents a vector in two dimensions with `x` and `y` properties. - - - // Create a new Vector, optionally passing in the `x` and `y` coordinates. If - // a coordinate is not specified, it will be set to `0` - /** - * @param {?number=} x The x position. - * @param {?number=} y The y position. - * @constructor - */ - function Vector(x, y) { - this['x'] = x || 0; - this['y'] = y || 0; - } - SAT['Vector'] = Vector; - // Alias `Vector` as `V` - SAT['V'] = Vector; - - - // Copy the values of another Vector into this one. - /** - * @param {Vector} other The other Vector. - * @return {Vector} This for chaining. - */ - Vector.prototype['copy'] = Vector.prototype.copy = function(other) { - this['x'] = other['x']; - this['y'] = other['y']; - return this; - }; - - // Change this vector to be perpendicular to what it was before. (Effectively - // roatates it 90 degrees in a clockwise direction) - /** - * @return {Vector} This for chaining. - */ - Vector.prototype['perp'] = Vector.prototype.perp = function() { - var x = this['x']; - this['x'] = this['y']; - this['y'] = -x; - return this; - }; - - // Rotate this vector (counter-clockwise) by the specified angle (in radians). - /** - * @param {number} angle The angle to rotate (in radians) - * @return {Vector} This for chaining. - */ - Vector.prototype['rotate'] = Vector.prototype.rotate = function (angle) { - var x = this['x']; - var y = this['y']; - this['x'] = x * Math.cos(angle) - y * Math.sin(angle); - this['y'] = x * Math.sin(angle) + y * Math.cos(angle); - return this; - }; - - // Rotate this vector (counter-clockwise) by the specified angle (in radians) which has already been calculated into sin and cos. - /** - * @param {number} sin - The Math.sin(angle) - * @param {number} cos - The Math.cos(angle) - * @return {Vector} This for chaining. - */ - Vector.prototype['rotatePrecalc'] = Vector.prototype.rotatePrecalc = function (sin, cos) { - var x = this['x']; - var y = this['y']; - this['x'] = x * cos - y * sin; - this['y'] = x * sin + y * cos; - return this; - }; - - // Reverse this vector. - /** - * @return {Vector} This for chaining. - */ - Vector.prototype['reverse'] = Vector.prototype.reverse = function() { - this['x'] = -this['x']; - this['y'] = -this['y']; - return this; - }; - - - // Normalize this vector. (make it have length of `1`) - /** - * @return {Vector} This for chaining. - */ - Vector.prototype['normalize'] = Vector.prototype.normalize = function() { - var d = this.len(); - if(d > 0) { - this['x'] = this['x'] / d; - this['y'] = this['y'] / d; - } - return this; - }; - - // Add another vector to this one. - /** - * @param {Vector} other The other Vector. - * @return {Vector} This for chaining. - */ - Vector.prototype['add'] = Vector.prototype.add = function(other) { - this['x'] += other['x']; - this['y'] += other['y']; - return this; - }; - - // Subtract another vector from this one. - /** - * @param {Vector} other The other Vector. - * @return {Vector} This for chaiing. - */ - Vector.prototype['sub'] = Vector.prototype.sub = function(other) { - this['x'] -= other['x']; - this['y'] -= other['y']; - return this; - }; - - // Scale this vector. An independant scaling factor can be provided - // for each axis, or a single scaling factor that will scale both `x` and `y`. - /** - * @param {number} x The scaling factor in the x direction. - * @param {?number=} y The scaling factor in the y direction. If this - * is not specified, the x scaling factor will be used. - * @return {Vector} This for chaining. - */ - Vector.prototype['scale'] = Vector.prototype.scale = function(x,y) { - this['x'] *= x; - this['y'] *= y || x; - return this; - }; - - // Project this vector on to another vector. - /** - * @param {Vector} other The vector to project onto. - * @return {Vector} This for chaining. - */ - Vector.prototype['project'] = Vector.prototype.project = function(other) { - var amt = this.dot(other) / other.len2(); - this['x'] = amt * other['x']; - this['y'] = amt * other['y']; - return this; - }; - - // Project this vector onto a vector of unit length. This is slightly more efficient - // than `project` when dealing with unit vectors. - /** - * @param {Vector} other The unit vector to project onto. - * @return {Vector} This for chaining. - */ - Vector.prototype['projectN'] = Vector.prototype.projectN = function(other) { - var amt = this.dot(other); - this['x'] = amt * other['x']; - this['y'] = amt * other['y']; - return this; - }; - - // Reflect this vector on an arbitrary axis. - /** - * @param {Vector} axis The vector representing the axis. - * @return {Vector} This for chaining. - */ - Vector.prototype['reflect'] = Vector.prototype.reflect = function(axis) { - var x = this['x']; - var y = this['y']; - this.project(axis).scale(2); - this['x'] -= x; - this['y'] -= y; - return this; - }; - - // Reflect this vector on an arbitrary axis (represented by a unit vector). This is - // slightly more efficient than `reflect` when dealing with an axis that is a unit vector. - /** - * @param {Vector} axis The unit vector representing the axis. - * @return {Vector} This for chaining. - */ - Vector.prototype['reflectN'] = Vector.prototype.reflectN = function(axis) { - var x = this['x']; - var y = this['y']; - this.projectN(axis).scale(2); - this['x'] -= x; - this['y'] -= y; - return this; - }; - - // Get the dot product of this vector and another. - /** - * @param {Vector} other The vector to dot this one against. - * @return {number} The dot product. - */ - Vector.prototype['dot'] = Vector.prototype.dot = function(other) { - return this['x'] * other['x'] + this['y'] * other['y']; - }; - - // Get the squared length of this vector. - /** - * @return {number} The length^2 of this vector. - */ - Vector.prototype['len2'] = Vector.prototype.len2 = function() { - return this.dot(this); - }; - - // Get the length of this vector. - /** - * @return {number} The length of this vector. - */ - Vector.prototype['len'] = Vector.prototype.len = function() { - return Math.sqrt(this.len2()); - }; - - // ## Circle - // - // Represents a circle with a position and a radius. - - // Create a new circle, optionally passing in a position and/or radius. If no position - // is given, the circle will be at `(0,0)`. If no radius is provided, the circle will - // have a radius of `0`. - /** - * @param {Vector=} pos A vector representing the position of the center of the circle - * @param {?number=} r The radius of the circle - * @constructor - */ - function Circle(pos, r) { - this['pos'] = pos || new Vector(); - this['r'] = r || 0; - } - SAT['Circle'] = Circle; - - // ## Polygon - // - // Represents a *convex* polygon with any number of points (specified in counter-clockwise order) - // - // The edges/normals of the polygon will be calculated on creation and stored in the - // `edges` and `normals` properties. If you change the polygon's points, you will need - // to call `recalc` to recalculate the edges/normals. - - // Create a new polygon, passing in a position vector, and an array of points (represented - // by vectors relative to the position vector). If no position is passed in, the position - // of the polygon will be `(0,0)`. - /** - * @param {Vector=} pos A vector representing the origin of the polygon. (all other - * points are relative to this one) - * @param {Array.=} points An array of vectors representing the points in the polygon, - * in counter-clockwise order. - * @constructor - */ - function Polygon(pos, points) { - this['pos'] = pos || new Vector(); - this['points'] = points || []; - this.recalc(); - } - SAT['Polygon'] = Polygon; - - // Recalculates the edges and normals of the polygon. This **must** be called - // if the `points` array is modified at all and the edges or normals are to be - // accessed. - /** - * @return {Polygon} This for chaining. - */ - Polygon.prototype['recalc'] = Polygon.prototype.recalc = function() { - // The edges here are the direction of the `n`th edge of the polygon, relative to - // the `n`th point. If you want to draw a given edge from the edge value, you must - // first translate to the position of the starting point. - this['edges'] = []; - // The normals here are the direction of the normal for the `n`th edge of the polygon, relative - // to the position of the `n`th point. If you want to draw an edge normal, you must first - // translate to the position of the starting point. - this['normals'] = []; - var points = this['points']; - var len = points.length; - for (var i = 0; i < len; i++) { - var p1 = points[i]; - var p2 = i < len - 1 ? points[i + 1] : points[0]; - var e = new Vector().copy(p2).sub(p1); - var n = new Vector().copy(e).perp().normalize(); - this['edges'].push(e); - this['normals'].push(n); - } - return this; - }; - - // Rotates this polygon counter-clockwise around the origin of *its local coordinate system* (i.e. `pos`). - // - // Note: You do **not** need to call `recalc` after rotation. - /** - * @param {number} angle The angle to rotate (in radians) - * @return {Polygon} This for chaining. - */ - Polygon.prototype['rotate'] = Polygon.prototype.rotate = function(angle) { - var i; - var points = this['points']; - var edges = this['edges']; - var normals = this['normals']; - var len = points.length; - - // Calc it just the once, rather than 4 times per array element - var cos = Math.cos(angle); - var sin = Math.sin(angle); - - for (i = 0; i < len; i++) { - points[i].rotatePrecalc(sin, cos); - edges[i].rotatePrecalc(sin, cos); - normals[i].rotatePrecalc(sin, cos); - } - return this; - }; - - // Rotates this polygon counter-clockwise around the origin of *its local coordinate system* (i.e. `pos`). - // - // Note: You do **not** need to call `recalc` after rotation. - /** - * @param {number} angle The angle to rotate (in radians) - * @return {Polygon} This for chaining. - */ - Polygon.prototype['scale'] = Polygon.prototype.scale = function(x, y) { - var i; - var points = this['points']; - var edges = this['edges']; - var normals = this['normals']; - var len = points.length; - for (i = 0; i < len; i++) { - points[i].scale(x,y); - edges[i].scale(x,y); - normals[i].scale(x,y); - } - return this; - }; - - // Translates the points of this polygon by a specified amount relative to the origin of *its own coordinate - // system* (i.e. `pos`). - // - // This is most useful to change the "center point" of a polygon. - // - // Note: You do **not** need to call `recalc` after translation. - /** - * @param {number} x The horizontal amount to translate. - * @param {number} y The vertical amount to translate. - * @return {Polygon} This for chaining. - */ - Polygon.prototype['translate'] = Polygon.prototype.translate = function (x, y) { - var i; - var points = this['points']; - var len = points.length; - for (i = 0; i < len; i++) { - points[i].x += x; - points[i].y += y; - } - return this; - }; - - // ## Box - // - // Represents an axis-aligned box, with a width and height. - - - // Create a new box, with the specified position, width, and height. If no position - // is given, the position will be `(0,0)`. If no width or height are given, they will - // be set to `0`. - /** - * @param {Vector=} pos A vector representing the top-left of the box. - * @param {?number=} w The width of the box. - * @param {?number=} h The height of the box. - * @constructor - */ - function Box(pos, w, h) { - this['pos'] = pos || new Vector(); - this['w'] = w || 0; - this['h'] = h || 0; - } - SAT['Box'] = Box; - - // Returns a polygon whose edges are the same as this box. - /** - * @return {Polygon} A new Polygon that represents this box. - */ - Box.prototype['toPolygon'] = Box.prototype.toPolygon = function() { - var pos = this['pos']; - var w = this['w']; - var h = this['h']; - return new Polygon(new Vector(pos['x'], pos['y']), [ - new Vector(), new Vector(w, 0), - new Vector(w,h), new Vector(0,h) - ]); - }; - - // ## Response - // - // An object representing the result of an intersection. Contains: - // - The two objects participating in the intersection - // - The vector representing the minimum change necessary to extract the first object - // from the second one (as well as a unit vector in that direction and the magnitude - // of the overlap) - // - Whether the first object is entirely inside the second, and vice versa. - /** - * @constructor - */ - function Response() { - this['a'] = null; - this['b'] = null; - this['overlapN'] = new Vector(); - this['overlapV'] = new Vector(); - this.clear(); - } - SAT['Response'] = Response; - - // Set some values of the response back to their defaults. Call this between tests if - // you are going to reuse a single Response object for multiple intersection tests (recommented - // as it will avoid allcating extra memory) - /** - * @return {Response} This for chaining - */ - Response.prototype['clear'] = Response.prototype.clear = function() { - this['aInB'] = true; - this['bInA'] = true; - this['overlap'] = Number.MAX_VALUE; - return this; - }; - - // ## Object Pools - - // A pool of `Vector` objects that are used in calculations to avoid - // allocating memory. - /** - * @type {Array.} - */ - var T_VECTORS = []; - for (var i = 0; i < 10; i++) { T_VECTORS.push(new Vector()); } - - // A pool of arrays of numbers used in calculations to avoid allocating - // memory. - /** - * @type {Array.>} - */ - var T_ARRAYS = []; - for (var i = 0; i < 5; i++) { T_ARRAYS.push([]); } - - // ## Helper Functions - - // Flattens the specified array of points onto a unit vector axis, - // resulting in a one dimensional range of the minimum and - // maximum value on that axis. - /** - * @param {Array.} points The points to flatten. - * @param {Vector} normal The unit vector axis to flatten on. - * @param {Array.} result An array. After calling this function, - * result[0] will be the minimum value, - * result[1] will be the maximum value. - */ - function flattenPointsOn(points, normal, result) { - var min = Number.MAX_VALUE; - var max = -Number.MAX_VALUE; - var len = points.length; - for (var i = 0; i < len; i++ ) { - // The magnitude of the projection of the point onto the normal - var dot = points[i].dot(normal); - if (dot < min) { min = dot; } - if (dot > max) { max = dot; } - } - result[0] = min; result[1] = max; - } - - // Check whether two convex polygons are separated by the specified - // axis (must be a unit vector). - /** - * @param {Vector} aPos The position of the first polygon. - * @param {Vector} bPos The position of the second polygon. - * @param {Array.} aPoints The points in the first polygon. - * @param {Array.} bPoints The points in the second polygon. - * @param {Vector} axis The axis (unit sized) to test against. The points of both polygons - * will be projected onto this axis. - * @param {Response=} response A Response object (optional) which will be populated - * if the axis is not a separating axis. - * @return {boolean} true if it is a separating axis, false otherwise. If false, - * and a response is passed in, information about how much overlap and - * the direction of the overlap will be populated. - */ - function isSeparatingAxis(aPos, bPos, aPoints, bPoints, axis, response) { - var rangeA = T_ARRAYS.pop(); - var rangeB = T_ARRAYS.pop(); - // The magnitude of the offset between the two polygons - var offsetV = T_VECTORS.pop().copy(bPos).sub(aPos); - var projectedOffset = offsetV.dot(axis); - // Project the polygons onto the axis. - flattenPointsOn(aPoints, axis, rangeA); - flattenPointsOn(bPoints, axis, rangeB); - // Move B's range to its position relative to A. - rangeB[0] += projectedOffset; - rangeB[1] += projectedOffset; - // Check if there is a gap. If there is, this is a separating axis and we can stop - if (rangeA[0] > rangeB[1] || rangeB[0] > rangeA[1]) { - T_VECTORS.push(offsetV); - T_ARRAYS.push(rangeA); - T_ARRAYS.push(rangeB); - return true; - } - // This is not a separating axis. If we're calculating a response, calculate the overlap. - if (response) { - var overlap = 0; - // A starts further left than B - if (rangeA[0] < rangeB[0]) { - response['aInB'] = false; - // A ends before B does. We have to pull A out of B - if (rangeA[1] < rangeB[1]) { - overlap = rangeA[1] - rangeB[0]; - response['bInA'] = false; - // B is fully inside A. Pick the shortest way out. - } else { - var option1 = rangeA[1] - rangeB[0]; - var option2 = rangeB[1] - rangeA[0]; - overlap = option1 < option2 ? option1 : -option2; - } - // B starts further left than A - } else { - response['bInA'] = false; - // B ends before A ends. We have to push A out of B - if (rangeA[1] > rangeB[1]) { - overlap = rangeA[0] - rangeB[1]; - response['aInB'] = false; - // A is fully inside B. Pick the shortest way out. - } else { - var option1 = rangeA[1] - rangeB[0]; - var option2 = rangeB[1] - rangeA[0]; - overlap = option1 < option2 ? option1 : -option2; - } - } - // If this is the smallest amount of overlap we've seen so far, set it as the minimum overlap. - var absOverlap = Math.abs(overlap); - if (absOverlap < response['overlap']) { - response['overlap'] = absOverlap; - response['overlapN'].copy(axis); - if (overlap < 0) { - response['overlapN'].reverse(); - } - } - } - T_VECTORS.push(offsetV); - T_ARRAYS.push(rangeA); - T_ARRAYS.push(rangeB); - return false; - } - - // Calculates which Vornoi region a point is on a line segment. - // It is assumed that both the line and the point are relative to `(0,0)` - // - // | (0) | - // (-1) [S]--------------[E] (1) - // | (0) | - /** - * @param {Vector} line The line segment. - * @param {Vector} point The point. - * @return {number} LEFT_VORNOI_REGION (-1) if it is the left region, - * MIDDLE_VORNOI_REGION (0) if it is the middle region, - * RIGHT_VORNOI_REGION (1) if it is the right region. - */ - function vornoiRegion(line, point) { - var len2 = line.len2(); - var dp = point.dot(line); - // If the point is beyond the start of the line, it is in the - // left vornoi region. - if (dp < 0) { return LEFT_VORNOI_REGION; } - // If the point is beyond the end of the line, it is in the - // right vornoi region. - else if (dp > len2) { return RIGHT_VORNOI_REGION; } - // Otherwise, it's in the middle one. - else { return MIDDLE_VORNOI_REGION; } - } - // Constants for Vornoi regions - /** - * @const - */ - var LEFT_VORNOI_REGION = -1; - /** - * @const - */ - var MIDDLE_VORNOI_REGION = 0; - /** - * @const - */ - var RIGHT_VORNOI_REGION = 1; - - // ## Collision Tests - - // Check if two circles collide. - /** - * @param {Circle} a The first circle. - * @param {Circle} b The second circle. - * @param {Response=} response Response object (optional) that will be populated if - * the circles intersect. - * @return {boolean} true if the circles intersect, false if they don't. - */ - function testCircleCircle(a, b, response) { - // Check if the distance between the centers of the two - // circles is greater than their combined radius. - var differenceV = T_VECTORS.pop().copy(b['pos']).sub(a['pos']); - var totalRadius = a['r'] + b['r']; - var totalRadiusSq = totalRadius * totalRadius; - var distanceSq = differenceV.len2(); - // If the distance is bigger than the combined radius, they don't intersect. - if (distanceSq > totalRadiusSq) { - T_VECTORS.push(differenceV); - return false; - } - // They intersect. If we're calculating a response, calculate the overlap. - if (response) { - var dist = Math.sqrt(distanceSq); - response['a'] = a; - response['b'] = b; - response['overlap'] = totalRadius - dist; - response['overlapN'].copy(differenceV.normalize()); - response['overlapV'].copy(differenceV).scale(response['overlap']); - response['aInB']= a['r'] <= b['r'] && dist <= b['r'] - a['r']; - response['bInA'] = b['r'] <= a['r'] && dist <= a['r'] - b['r']; - } - T_VECTORS.push(differenceV); - return true; - } - SAT['testCircleCircle'] = testCircleCircle; - - // Check if a polygon and a circle collide. - /** - * @param {Polygon} polygon The polygon. - * @param {Circle} circle The circle. - * @param {Response=} response Response object (optional) that will be populated if - * they interset. - * @return {boolean} true if they intersect, false if they don't. - */ - function testPolygonCircle(polygon, circle, response) { - // Get the position of the circle relative to the polygon. - var circlePos = T_VECTORS.pop().copy(circle['pos']).sub(polygon['pos']); - var radius = circle['r']; - var radius2 = radius * radius; - var points = polygon['points']; - var len = points.length; - var edge = T_VECTORS.pop(); - var point = T_VECTORS.pop(); - - // For each edge in the polygon: - for (var i = 0; i < len; i++) { - var next = i === len - 1 ? 0 : i + 1; - var prev = i === 0 ? len - 1 : i - 1; - var overlap = 0; - var overlapN = null; - - // Get the edge. - edge.copy(polygon['edges'][i]); - // Calculate the center of the circle relative to the starting point of the edge. - point.copy(circlePos).sub(points[i]); - - // If the distance between the center of the circle and the point - // is bigger than the radius, the polygon is definitely not fully in - // the circle. - if (response && point.len2() > radius2) { - response['aInB'] = false; - } - - // Calculate which Vornoi region the center of the circle is in. - var region = vornoiRegion(edge, point); - // If it's the left region: - if (region === LEFT_VORNOI_REGION) { - // We need to make sure we're in the RIGHT_VORNOI_REGION of the previous edge. - edge.copy(polygon['edges'][prev]); - // Calculate the center of the circle relative the starting point of the previous edge - var point2 = T_VECTORS.pop().copy(circlePos).sub(points[prev]); - region = vornoiRegion(edge, point2); - if (region === RIGHT_VORNOI_REGION) { - // It's in the region we want. Check if the circle intersects the point. - var dist = point.len(); - if (dist > radius) { - // No intersection - T_VECTORS.push(circlePos); - T_VECTORS.push(edge); - T_VECTORS.push(point); - T_VECTORS.push(point2); - return false; - } else if (response) { - // It intersects, calculate the overlap. - response['bInA'] = false; - overlapN = point.normalize(); - overlap = radius - dist; - } - } - T_VECTORS.push(point2); - // If it's the right region: - } else if (region === RIGHT_VORNOI_REGION) { - // We need to make sure we're in the left region on the next edge - edge.copy(polygon['edges'][next]); - // Calculate the center of the circle relative to the starting point of the next edge. - point.copy(circlePos).sub(points[next]); - region = vornoiRegion(edge, point); - if (region === LEFT_VORNOI_REGION) { - // It's in the region we want. Check if the circle intersects the point. - var dist = point.len(); - if (dist > radius) { - // No intersection - T_VECTORS.push(circlePos); - T_VECTORS.push(edge); - T_VECTORS.push(point); - return false; - } else if (response) { - // It intersects, calculate the overlap. - response['bInA'] = false; - overlapN = point.normalize(); - overlap = radius - dist; - } - } - // Otherwise, it's the middle region: - } else { - // Need to check if the circle is intersecting the edge, - // Change the edge into its "edge normal". - var normal = edge.perp().normalize(); - // Find the perpendicular distance between the center of the - // circle and the edge. - var dist = point.dot(normal); - var distAbs = Math.abs(dist); - // If the circle is on the outside of the edge, there is no intersection. - if (dist > 0 && distAbs > radius) { - // No intersection - T_VECTORS.push(circlePos); - T_VECTORS.push(normal); - T_VECTORS.push(point); - return false; - } else if (response) { - // It intersects, calculate the overlap. - overlapN = normal; - overlap = radius - dist; - // If the center of the circle is on the outside of the edge, or part of the - // circle is on the outside, the circle is not fully inside the polygon. - if (dist >= 0 || overlap < 2 * radius) { - response['bInA'] = false; - } - } - } - - // If this is the smallest overlap we've seen, keep it. - // (overlapN may be null if the circle was in the wrong Vornoi region). - if (overlapN && response && Math.abs(overlap) < Math.abs(response['overlap'])) { - response['overlap'] = overlap; - response['overlapN'].copy(overlapN); - } - } - - // Calculate the final overlap vector - based on the smallest overlap. - if (response) { - response['a'] = polygon; - response['b'] = circle; - response['overlapV'].copy(response['overlapN']).scale(response['overlap']); - } - T_VECTORS.push(circlePos); - T_VECTORS.push(edge); - T_VECTORS.push(point); - return true; - } - SAT['testPolygonCircle'] = testPolygonCircle; - - // Check if a circle and a polygon collide. - // - // **NOTE:** This is slightly less efficient than polygonCircle as it just - // runs polygonCircle and reverses everything at the end. - /** - * @param {Circle} circle The circle. - * @param {Polygon} polygon The polygon. - * @param {Response=} response Response object (optional) that will be populated if - * they interset. - * @return {boolean} true if they intersect, false if they don't. - */ - function testCirclePolygon(circle, polygon, response) { - // Test the polygon against the circle. - var result = testPolygonCircle(polygon, circle, response); - if (result && response) { - // Swap A and B in the response. - var a = response['a']; - var aInB = response['aInB']; - response['overlapN'].reverse(); - response['overlapV'].reverse(); - response['a'] = response['b']; - response['b'] = a; - response['aInB'] = response['bInA']; - response['bInA'] = aInB; - } - return result; - } - SAT['testCirclePolygon'] = testCirclePolygon; - - // Checks whether polygons collide. - /** - * @param {Polygon} a The first polygon. - * @param {Polygon} b The second polygon. - * @param {Response=} response Response object (optional) that will be populated if - * they interset. - * @return {boolean} true if they intersect, false if they don't. - */ - function testPolygonPolygon(a, b, response) { - var aPoints = a['points']; - var aLen = aPoints.length; - var bPoints = b['points']; - var bLen = bPoints.length; - // If any of the edge normals of A is a separating axis, no intersection. - for (var i = 0; i < aLen; i++) { - if (isSeparatingAxis(a['pos'], b['pos'], aPoints, bPoints, a['normals'][i], response)) { - return false; - } - } - // If any of the edge normals of B is a separating axis, no intersection. - for (var i = 0;i < bLen; i++) { - if (isSeparatingAxis(a['pos'], b['pos'], aPoints, bPoints, b['normals'][i], response)) { - return false; - } - } - // Since none of the edge normals of A or B are a separating axis, there is an intersection - // and we've already calculated the smallest overlap (in isSeparatingAxis). Calculate the - // final overlap vector. - if (response) { - response['a'] = a; - response['b'] = b; - response['overlapV'].copy(response['overlapN']).scale(response['overlap']); - } - return true; - } - SAT['testPolygonPolygon'] = testPolygonPolygon; - - return SAT; -})); \ No newline at end of file