Physics
The top-level namespace. All of PhysicsJS is contained in
the Physics
namespace.
It may (and should) be invoked as a function to create a world instance. For all intensive purposes, Physics and Physics.world are the same thing.
See new Physics.world for config options and function signature.
Example:
Physics( cfg, function( world ) {
// use world
}); // -> world
source: src/intro.js : 37
Physics.transform
Vector Transformations class for rotating and translating vectors
source: src/math/transform.js : 8
new Physics.transform()
Transform Constructor / Factory
- new Physics.transform(vect, angle, origin)
- new Physics.transform(transform)
accepts
- transform
- (Physics.transform)
Transform to copy
source: src/math/transform.js : 19
this.clone()
Clone another transform. Or clone self into new transform.
accepts
- transform
- (Physics.transform)optional
Transform to copy
returns
- this
For chaining
- Physics.transform
New copy of
this
if none is specified as an argument
source: src/math/transform.js : 82
this.setRotation()
Set the rotation portion of the transform
accepts
returns
source: src/math/transform.js : 60
this.setTranslation()
Set the translation portion of the transform.
source: src/math/transform.js : 47
Physics.vector
The vector class and factory function.
Call Physics.vector
with the same arguments as
new Physics.vector to create an instance.
The vector methods mostly modify the vector instance. This makes computations faster because creating vectors is avoided.
Creating vectors is generally an expensive operation so try to avoid doing this in the simulation loop. Instead you can use Physics.scratchpad to get temporary vectors for use in performance critical code.
Note: The coordinate system is left-handed, meaning that the clockwise angular direction is positive. This has implications for the cross-product rule.
source: src/math/vector.js : 38
new Physics.vector()
Vector Constructor.
- new Physics.vector(x, y)
- new Physics.vector(vect)
accepts
- vect
- (Vectorish)
A vector-like object to clone
source: src/math/vector.js : 59
this._internal use only
Private storage array for data.
Do not access this directly. Private. Keep out.
source: src/math/vector.js : 80
this.add()
Add scalars Physics.vector to the coordinates.
returns
source: src/math/vector.js : 198
this.angle()
Compute the angle between this
and vector v
or this and x axis.
accepts
- v
- (Physics.vector)optional
The other vector
returns
- Number
The angle in radians between this vector and the x-axis OR
v
if specified
source: src/math/vector.js : 297
this.angle2()
Compute the angle created between three points; left -> this -> right.
accepts
- left
- (Physics.vector)
The position on the left
- right
- (Physics.vector)
The position on the right
returns
source: src/math/vector.js : 336
this.clamp()
Constrain vector components to minima and maxima.
returns
The vector analog of scalar clamping).
source: src/math/vector.js : 733
this.clone()
Create a clone of this vector, or clone another vector into this instance.
accepts
- v
- (Vectorish)optional
The vector-like object to clone
returns
- this
If
v
is specified as an argument- Physics.vector
A new vector instance that clones this vector, if no argument is specified
This is especially useful in vector algorithms that use temporary vectors (which most should). You can create temporary vectors and then do things like...
temp.clone( otherVector );
// compute things with temp...
// then save the result
result.clone( tmp );
source: src/math/vector.js : 632
this.cross()
Compute the (left-handed) cross product of this vector with v
.
accepts
- v
- (Physics.vector)
The other vector
returns
source: src/math/vector.js : 261
this.dist()
Compute the distance from this vector to another vector v
.
accepts
- v
- (Physics.vector)
The other vector
returns
source: src/math/vector.js : 394
this.distSq()
Compute the distance squared from this vector to another vector v
.
accepts
- v
- (Physics.vector)
The other vector
returns
source: src/math/vector.js : 409
this.dot()
Compute the dot product of this vector with v
.
accepts
- v
- (Physics.vector)
The other vector
returns
source: src/math/vector.js : 250
this.equals()
Determine if this vector equals another.
accepts
- v
- (Physics.vector)
The other vector
returns
source: src/math/vector.js : 758
this.get()deprecated0.6.0—1.0.0
Get the x or y component by index.
source: src/math/vector.js : 156
this.mult()
Multiply this by a scalar quantity.
Same as scaling the vector by an amount m
.
source: src/math/vector.js : 231
this.negate()
Flip this vector in the opposite direction.
returns
source: src/math/vector.js : 711
this.norm()
Compute the norm (length) of this vector.
returns
source: src/math/vector.js : 361
this.normSq()
Compute the norm (length) squared of this vector.
returns
source: src/math/vector.js : 377
this.normalize()
Normalise this vector, making it a unit vector.
returns
source: src/math/vector.js : 454
this.perp()
Change this vector into a vector that will be perpendicular.
In other words, rotate by (+-) 90 degrees.
source: src/math/vector.js : 426
this.proj()
Compute the scalar projection of this along v
.
accepts
- v
- (Physics.vector)
The other vector
returns
source: src/math/vector.js : 272
this.rotate()
Rotate this vector.
accepts
- t
- (Physics.transform)
The transformation to apply the rotational part of
returns
accepts
returns
An angle and rotation origin can be specified, or a transform can be specified and only the rotation portion of that transform will be applied
source: src/math/vector.js : 535
this.rotateInv()
Apply the inverse rotation of a transform.
accepts
- t
- (Physics.transform)
The transformation to apply the inverse rotational part of
returns
Only the inverse rotation portion of that transform will be applied.
source: src/math/vector.js : 577
this.set()
Sets the x and y components of this vector.
returns
source: src/math/vector.js : 141
this.sub()
Subtract scalars Physics.vector from the coordinates.
accepts
returns
source: src/math/vector.js : 214
this.swap()
Swap values with other vector.
accepts
- v
- (Physics.vector)
The other vector
returns
source: src/math/vector.js : 665
this.toString()
Get a formatted string of this vector's coordinates.
returns
source: src/math/vector.js : 746
this.transform()
Apply a Physics.transform to this vector.
accepts
- t
- (Physics.transform)
The transformation to apply
returns
source: src/math/vector.js : 480
this.transformInv()
Apply an inverse Physics.transform to this vector.
accepts
- t
- (Physics.transform)
The transformation to apply the inverse of
returns
source: src/math/vector.js : 504
this.translate()
Apply the translation of a transform.
accepts
- t
- (Physics.transform)
The transformation to apply the translational part of
returns
Only the translation portion of that transform will be applied.
source: src/math/vector.js : 594
this.translateInv()
Apply the inverse translation of a transform.
accepts
- t
- (Physics.transform)
The transformation to apply the inverse translational part of
returns
Only the inverse translation portion of that transform will be applied.
source: src/math/vector.js : 608
this.vadd()
Add a Physics.vector to this
.
accepts
- v
- (Physics.vector)
vector to add
returns
source: src/math/vector.js : 167
this.values()
Get the coordinate values as an object literal.
returns
source: src/math/vector.js : 682
this.vproj()
Compute the vector projection of this along v
and copy the result into this vector.
accepts
- v
- (Physics.vector)
The other vector
returns
source: src/math/vector.js : 284
this.vsub()
Subtract a Physics.vector from this
.
accepts
- v
- (Physics.vector)
vector to subtract
returns
source: src/math/vector.js : 182
this.x
Getter/setter property for the x coordinate.
source: src/math/vector.js : 103
this.y
Getter/setter property for the y coordinate.
source: src/math/vector.js : 118
this.zero()
Set the coordinates of this vector to zero.
returns
source: src/math/vector.js : 696
Physics.vector.axis
Read-only axis vectors for general reference.
- Physics.vector.axis = Array;
Example:
Physics.vector.axis[0]; // The x axis unit vector
Physics.vector.axis[1]; // The y axis unit vector
source: src/math/vector.js : 777
Physics.vector.zero
Read-only zero vector for reference
- Physics.vector.zero = zeroVector;
source: src/math/vector.js : 787
Physics.world
The world class and factory function.
Use Physics to create worlds.
source: src/core/world.js : 8
new Physics.world()alias of:Physics
World Constructor.
- new Physics.world(options, fn(world, Physics))
accepts
- options
- (Object)optional
configuration options (see description)
- fn(world, Physics)
- (Function|Array)optional
Callback function or array of callbacks called with this === world
Accepts:
accepts
- world
- (Physics.world)
The current world created
- Physics
- (Physics)
The Physics namespace
Use Physics to create worlds.
Configuration options and defaults:
{
// default timestep
timestep: 6,
// maximum number of iterations per step
maxIPF: 4,
// default integrator
integrator: 'verlet',
// is sleeping disabled?
sleepDisabled: false,
// speed at which bodies wake up
sleepSpeedLimit: 0.1,
// variance in position below which bodies fall asleep
sleepVarianceLimit: 2,
// time (ms) before sleepy bodies fall asleep
sleepTimeLimit: 500
}
If called with an array of functions, and any functions return a promise-like object, each remaining callback will be called only when that promise is resolved.
Example:
// hypothetical resources need to be loaded...
Physics( cfg, [
function( world ){
var dfd = $.Deferred()
,images = []
,toLoad = myImages.length
,callback = function(){
toLoad--;
// wait for all images to be loaded
if ( toLoad <= 0 ){
dfd.resolve();
}
}
;
// load images
$.each(myImages, function( src ){
var img = new Image();
img.onload = callback;
img.src = src;
});
return dfd.promise();
},
function( world ){
// won't be executed until images are loaded
// initialize world... etc...
}
]);
source: src/core/world.js : 124
this.add()
Multipurpose add method. Add one or many bodies, behaviors, integrators, renderers...
accepts
returns
source: src/core/world.js : 204
this.addBehavior()
Add a behavior to the world
source: src/core/world.js : 467
this.addBody()
Add a body to the world
source: src/core/world.js : 535
this.destroy()
Destroy the world. (Bwahahahahaha!)
source: src/core/world.js : 803
this.find()
Find all matching bodies based on query rules.
accepts
- rules
- (Object)
Query rules
returns
accepts
returns
source: src/core/world.js : 624
this.findOne()
Find first matching body based on query rules.
accepts
- rules
- (Object)
Query rules.
accepts
source: src/core/world.js : 606
this.getBehaviors()
Get copied list of behaviors in the world
returns
source: src/core/world.js : 492
this.getBodies()
Get copied list of bodies in the world
returns
source: src/core/world.js : 560
this.has()
Determine if a thing has been added to world.
accepts
- thing
- (Object)
The thing to test
returns
- Boolean
true
if thing is in the world,false
otherwise.
source: src/core/world.js : 305
this.init()internal use only
Initialization
source: src/core/world.js : 144
this.integrator()
Get or Set the integrator
accepts
- integrator
- (Integrator)optional
The integrator to set on the world
returns
- Integrator
The currently set integrator if
integrator
not specified- this
for chaining if
integrator
specified
source: src/core/world.js : 351
this.isPaused()
Determine if world is paused.
returns
source: src/core/world.js : 792
this.iterate()internal use only
Do a single iteration.
accepts
- dt
- (Number)
The timestep
source: src/core/world.js : 639
this.options()
Set config options. Also access options by .options.<option>
.
source: src/core/world.js : 196
this.pause()
Pause the world (step calls do nothing).
returns
source: src/core/world.js : 767
this.remove()
Multipurpose remove method. Remove one or many bodies, behaviors, integrators, renderers...
accepts
returns
source: src/core/world.js : 252
this.removeBehavior()
Remove a behavior from the world
source: src/core/world.js : 504
this.removeBody()
Remove a body from the world
source: src/core/world.js : 572
this.render()
Render current world state using the renderer
returns
source: src/core/world.js : 747
this.renderer()
Get or Set the renderer
accepts
- renderer
- (Renderer)optional
The renderer to set on the world
source: src/core/world.js : 391
this.step()
Step the world up to specified time or do one step if no time is specified.
source: src/core/world.js : 650
this.timestep()
Get or Set the timestep
accepts
- dt
- (Number)optional
The time step for the world
source: src/core/world.js : 431
this.unpause()
Unpause the world (step calls continue as usual).
returns
source: src/core/world.js : 779
this.wakeUpAll()
Wake up all bodies in world.
returns
source: src/core/world.js : 451
this.warp()
Speed up or slow down the iteration by this factor.
accepts
- warp
- (Number)optional
The time warp factor
Example:
// slow motion... 10x slower
world.warp( 0.01 );
source: src/core/world.js : 732
Physics.aabb()
Create an Axis Aligned Bounding Box.
accepts
returns
returns
accepts
returns
Signature:
{
x: Number, // the x coord of the center point
y: Number, // the y coord of the center point
hw: Number, // the half-width
hh: Number, // the half-height
}
source: src/math/aabb.js : 30
Physics.aabb.clone()
Clone an aabb.
source: src/math/aabb.js : 93
Physics.aabb.contains()
Check if a point is inside an aabb.
returns
- Boolean
true
ifpt
is insideaabb
,false
otherwise
source: src/math/aabb.js : 78
Physics.aabb.overlap()
Check if two AABBs overlap.
returns
- Boolean
true
if they overlap,false
otherwise
source: src/math/aabb.js : 136
Physics.aabb.union()
Get the union of two aabbs.
accepts
returns
- Object
The union of two aabbs. If modify is
true
, then the first aabb will be modified and returned.
source: src/math/aabb.js : 110
Physics.behavior()
Factory function for creating Behaviors.
accepts
returns
Visit the PhysicsJS wiki on Behaviors for usage documentation.
source: src/core/behavior.js : 24
Behavior
The base class for behaviors created by Physics.behavior factory function.
source: src/core/behavior.js : 31
AttractorBehaviorextends:Behavior
Physics.behavior('attractor')
.
Attractor behavior attracts bodies to a specific point.
Additional options include:
- pos: The position of the attraction point
- strength: How strong the attraction is (default:
1
) - order: The power of the inverse distance (default:
2
because that is newtonian gravity... inverse square) - max: The maximum distance in which to apply the attraction (default: Infinity)
- min: The minimum distance above which to apply the attraction (default: very small non-zero)
source: src/behaviors/attractor.js : 15
this.position()
Get or set the position of the attractor.
accepts
- pos
- (Vectorish)optional
The position to set
source: src/behaviors/attractor.js : 56
BodyCollisionDetectionBehaviorextends:Behavior
Physics.behavior('body-collision-detection')
.
Detect collisions of bodies.
Publishes collision events to the world as a group of detected collisions per iteration.
The event data will have a .collisions
property that is an array of collisions of the form:
{
bodyA: // the first body
bodyB: // the second body
norm: // the normal vector (Vectorish)
mtv: // the minimum transit vector. (the direction and length needed to extract bodyB from bodyA)
pos: // the collision point relative to bodyA
overlap: // the amount bodyA overlaps bodyB
}
Additional options include:
- check: channel to listen to for collision candidates (default:
collisions:candidates
). set totrue
to force check every pair of bodies in the world - channel: channel to publish events to (default:
collisions:detected
)
source: src/behaviors/body-collision-detection.js : 27
this.check()internal use only
Event callback to check pairs of objects that have been flagged by broad phase for possible collisions.
accepts
- data
- (Object)
The event data
this.checkAll()internal use only
Event callback to check all pairs of objects in the list for collisions
accepts
- data
- (Object)
The event data
BodyImpulseResponseBehaviorextends:Behavior
Physics.behavior('body-impulse-response')
.
Responds to collisions by applying impulses.
Additional options include:
- check: channel to listen to for collisions (default:
collisions:detected
). - mtvThreshold: apply partial extraction of bodies if the minimum transit vector is less than this value ( default:
1
) this will depend on your simulation characteristic length scale - bodyExtractDropoff: every body overlap correction (underneith mtvThreshold) will only extract by this fraction (0..1). Helps with stablizing contacts. (default:
0.5
) - forceWakeupAboveOverlapThreshold: force bodies to wake up if the overlap is above mtvThreshold ( default:
true
)
source: src/behaviors/body-impulse-response.js : 15
this.collideBodes()internal use only
Collide two bodies by modifying their positions and velocities to conserve momentum
accepts
- bodyA
- (Object)
First Body
- bodyB
- (Object)
Second body
- normal
- (Vector)
Normal vector of the collision surface
- point
- (Vector)
Contact point of the collision
- mtrans
- (Vector)
Minimum transit vector that is the smallest displacement to separate the bodies
- contact
- (Boolean)
Are the bodies in resting contact relative to each other
this.respond()internal use only
Event callback to respond to collision data.
accepts
- data
- (Object)
event data
ConstantAccelerationBehaviorextends:Behavior
Physics.behavior('constant-acceleration')
.
Constant acceleration behavior.
Basically the "gravity" behavior. Used to give "earth-like gravity" to the world.
Additional options include:
- acc: The acceleration vector (Vectorish). (default:
{ x: 0, y: 0.0004 }
)
source: src/behaviors/constant-acceleration.js : 13
this.setAcceleration()
Set the acceleration of the behavior.
EdgeCollisionDetectionBehaviorextends:Behavior
Physics.behavior('edge-collision-detection')
.
Used to detect collisions with the boundaries of an AABB.
Additional options include:
- aabb: The Physics.aabb bounds to use as the constraining boundary
- restitution: The restitution of the boundary walls (default:
0.99
) - cof: The coefficient of friction of the boundary walls (default:
1
) - channel: The channel to publish collisions to. (default: 'collisions:detected')
source: src/behaviors/edge-collision-detection.js : 14
this.checkAll()internal use only
Event callback to check all bodies for collisions with the edge
accepts
- data
- (Object)
Event data
this.setAABB()
Set the boundaries of the edge.
accepts
- aabb
- (Physics.aabb)
The aabb to use as the boundary
returns
InteractiveBehaviorextends:Behavior
Physics.behavior('interactive')
.
User interaction helper.
Used to get mouse/touch events and add grab interactions.
Additional options include:
- el: The element of the renderer. What you input as the
el
for the renderer. - moveThrottle: The min time between move events (default:
10
). - minVel: The minimum velocity clamp Vectorish (default: { x: -5, y: -5 }) to restrict velocity a user can give to a body
- maxVel: The maximum velocity clamp Vectorish (default: { x: 5, y: 5 }) to restrict velocity a user can give to a body
The behavior also triggers the following events on the world:
// a body has been grabbed
world.on('interact:grab', function( data ){
data.x; // the x coord
data.y; // the y coord
data.body; // the body that was grabbed
});
// no body was grabbed, but the renderer area was clicked, or touched
world.on('interact:poke', function( data ){
data.x; // the x coord
data.y; // the y coord
});
// when a mouse or pointer moves
world.on('interact:move', function( data ){
data.x; // the x coord
data.y; // the y coord
data.body; // the grabbed body that was moved (if applicable)
});
// when the viewport is released (mouseup, touchend)
world.on('interact:release', function( data ){
data.x; // the x coord
data.y; // the y coord
data.body; // the body that was grabbed (if applicable)
});
The behavior also sets body.isGrabbed = true for any grabbed bodies while they are grabbed.
NewtonianBehaviorextends:Behavior
Physics.behavior('newtonian')
.
Newtonian attraction between bodies (inverse square law).
Additional options include:
- strength: The strength of the interaction between bodies. (default:
1
) - max: The maximum distance between bodies at which to apply the behavior. (default:
false
... infinite) - min: The minimum distance between bodies at which to apply the behavior. (default:
false
... autocalculate)
source: src/behaviors/newtonian.js : 13
SweepPruneBehaviorextends:Behavior
Physics.behavior('sweep-prune')
.
Sweep and Prune implementation for broad phase collision detection.
This massively improves the speed of collision detection. It's set up to always be used with BodyCollisionDetection, and BodyImpulseResponse.
Additional options include:
- channel: The channel to publish collision candidates to. (default:
collisions:candidates
)
source: src/behaviors/sweep-prune.js : 13
this.broadPhase()internal use only
Execute the broad phase and get candidate collisions
returns
this.checkOverlaps()internal use only
Check each axis for overlaps of bodies AABBs
returns
this.clear()
Refresh tracking data
this.getPair()internal use only
Get a pair object for the tracker objects
returns
- Object
Pair object or null if not found
this.sortIntervalLists()internal use only
Simple insertion sort for each axis
this.sweep()internal use only
Event callback to sweep and publish event if any candidate collisions are found
accepts
- data
- (Object)
Event data
this.trackBody()internal use only
Event callback to add body to list of those tracked by sweep and prune
accepts
- data
- (Object)
Event data
this.untrackBody()internal use only
Event callback to remove body from list of those tracked
accepts
- data
- (Object)
Event data
this.updateIntervals()internal use only
Update position intervals on each axis
VerletConstraintsBehaviorextends:Behavior
Physics.behavior('verlet-constraints')
.
Verlet constraints manager.
Handles distance constraints, and angle constraints
Additional options include:
- iterations: The number of iterations to take to relax the constraints. (default:
2
)
source: src/behaviors/verlet-constraints.js : 13
this.angleConstraint()
Constrain three bodies to a target relative angle
accepts
returns
- Object
The constraint data object
Returns constraint data that can be used to remove the constraint later.
.bodyA
,.bodyB
, and.bodyC
are references to the bodies.type
is the type of constraint.id
is the string ID of the constraint.stiffness
is the stiffness.targetAngle
is the target angle
this.distanceConstraint()
Constrain two bodies to a target relative distance.
accepts
returns
- Object
The constraint data object
Returns constraint data that can be used to remove the constraint later.
.bodyA
and.bodyB
are references to the bodies.type
is the type of constraint.id
is the string ID of the constraint.stiffness
is the stiffness.targetLength
is the target length
this.drop()
Remove all constraints
returns
this.getConstraints()
Get all constraints.
returns
this.remove()
Remove a constraint
this.resolve()internal use only
Resolve all constraints.
this.resolveAngleConstraints()internal use only
Resolve angle constraints.
accepts
- coef
- (Number)
Coefficient for this resolution phase
this.resolveDistanceConstraints()internal use only
Resolve distance constraints.
accepts
- coef
- (Number)
Coefficient for this resolution phase
this.shuffleConstraints()internal use only
Mix up the constraints.
this.applyTo()
Apply the behavior to a group of bodies.
accepts
- arr
- (Array)
Array of bodies to apply this behavior to. Specify
true
for all objects in world.
returns
source: src/core/behavior.js : 66
this.behave()
Default method run on every world integration.
accepts
- data
- (Object)
The pubsub
integrate:positions
event data
You must extend this when creating a behavior, unless you extend the Behavior#connect and Behavior#disconnect methods.
source: src/core/behavior.js : 151
this.connect()
Connect to a world.
accepts
- world
- (Physics.world)
The world to connect to
Extend this when creating behaviors if you need to specify pubsub management. Automatically called when added to world by the Behavior#setWorld method.
source: src/core/behavior.js : 119
this.disconnect()
Disconnect from a world.
accepts
- world
- (Physics.world)
The world to disconnect from
Extend this when creating behaviors if you need to specify pubsub management. Automatically called when added to world by the Behavior#setWorld method.
source: src/core/behavior.js : 135
this.getTargets()
Get the array of bodies (by reference!) this behavior is applied to.
returns
source: src/core/behavior.js : 82
this.init()internal use only
Initialization. Internal use.
accepts
- options
- (Object)
The configuration options passed by the factory
source: src/core/behavior.js : 38
this.options()
Set options on this instance.
Access options directly from the options object.
Example:
this.options.someOption;
source: src/core/behavior.js : 56
this.setWorld()
Set which world to apply to.
Usually this is called internally. Shouldn't be a need to call this yourself usually.
source: src/core/behavior.js : 95
Physics.body()
Factory function for creating Bodies.
accepts
- name
- (String)
The name of the body to create
- options
- (Object)optional
The configuration for that body ( depends on body ).
Available options and defaults:
{ // is the body hidden (not to be rendered)? hidden: false, // is the body `dynamic`, `kinematic` or `static`? // http://www.box2d.org/manual.html#_Toc258082973 treatment: 'dynamic', // body mass mass: 1.0, // body restitution. How "bouncy" is it? restitution: 1.0, // what is its coefficient of friction with another surface with COF = 1? cof: 0.8, // what is the view object (mixed) that should be used when rendering? view: null, // the vector offsetting the geometry from its center of mass offset: Physics.vector(0,0) }
returns
Visit the PhysicsJS wiki on Bodies for usage documentation.
source: src/core/body.js : 91
Body
The base class for bodies created by Physics.body factory function.
source: src/core/body.js : 98
CircleBodyextends:Body
Physics.body('circle')
The circle body has a circular shape.
Additional options include:
- radius: the radius
Example:
var round = Physics.body('circle', {
x: 30,
y: 20,
radius: 5
});
source: src/bodies/circle.js : 24
CompoundBodyextends:Body
Physics.body('compound')
Not a body in itself. It's a container to group other bodies. The position of the body is the center of mass. It must have at least one child before being added to the world.
Additional config options:
- children: Array of Body objects.
Example:
var thing = Physics.body('compound', {
// place the center of mass at (300, 200)
x: 300,
y: 200,
// the center of mass is automatically calculated and used to position the shape
children: [
body1,
body2,
// ...
]
});
source: src/bodies/compound.js : 32
this.addChild()
Add a body as a child.
source: src/bodies/compound.js : 68
this.addChildren()
Add an array of children to the compound.
source: src/bodies/compound.js : 80
this.clear()
Remove all children.
returns
source: src/bodies/compound.js : 142
this.refreshGeometry()
If the children's positions change, refreshGeometry()
should be called to fix the shape.
returns
source: src/bodies/compound.js : 159
ConvexPolygonBodyextends:Body
Physics.body('convex-polygon')
Body for convex polygons. The position of the body is the centroid of the polygon.
Additional config options:
- vertices: Array of Vectorish objects representing the polygon vertices in clockwise (or counterclockwise) order.
Example:
var pentagon = Physics.body('convex-polygon', {
// place the centroid of the polygon at (300, 200)
x: 300,
y: 200,
// the centroid is automatically calculated and used to position the shape
vertices: [
{ x: 0, y: -30 },
{ x: -29, y: -9 },
{ x: -18, y: 24 },
{ x: 18, y: 24 },
{ x: 29, y: -9 }
]
});
PointBodyalias of:Bodyextends:Body
Physics.body('point')
The point body represents a point.
source: src/bodies/point.js : 8
RectangleBodyextends:Body
Physics.body('rectangle')
Body for rectangles. The position of the body is the centroid of the rectangle.
Additional config options:
- width: The width
- height: The height
Example:
var rect = Physics.body('rectangle', {
// place the centroid of the rectangle at (300, 200)
x: 300,
y: 200,
width: 30,
height: 40
});
source: src/bodies/rectangle.js : 28
this.aabb()
Get the Axis aligned bounding box for the body in its current position and rotation
returns
source: src/core/body.js : 483
this.accelerate()
Accelerate the body by adding supplied vector to its current acceleration
accepts
- acc
- (Physics.vector)
The acceleration vector
returns
source: src/core/body.js : 420
this.applyForce()
Apply a force at center of mass, or at point p
relative to the center of mass
accepts
returns
source: src/core/body.js : 436
this.cof
The coefficient of friction of the body.
- this.cof = 0.8;
It's how much "slide" it has during collisions.
A cof
of 0
will really slidy.
A cof
of 1
has no slide.
This is a very simplistic implementation at the moment. What would be better is to have both static and kinetic friction. But that's not done yet.
source: src/core/body.js : 251
this.geometry
The geometry for this body.
By default it is a point
geometry which gets overridden.
source: src/core/body.js : 204
this.getGlobalOffset()
Get the body offset vector (from the center of mass) for the body's shape in global coordinates.
accepts
- out
- (Physics.vector)optional
A vector to use to put the result into. One is created if
out
isn't specified.
returns
- Physics.vector
The offset in global coordinates
source: src/core/body.js : 470
Determines whether the body should be hidden by the renderer.
- this.hidden = false;
source: src/core/body.js : 270
this.init()internal use only
Initialization. Internal use.
accepts
- options
- (Object)
The configuration options passed by the factory
source: src/core/body.js : 105
this.mass
The mass.
- this.mass = 1;
source: src/core/body.js : 211
this.offset
The vector offsetting the body's shape from its center of mass.
source: src/core/body.js : 217
this.options()
Set options on this instance.
Access options directly from the options object.
Example:
this.options.someOption;
source: src/core/body.js : 126
this.recalc()
Recalculate properties.
returns
Intended to be overridden by subclasses. Call when body physical properties are changed.
source: src/core/body.js : 528
this.restitution
The restitution.
- this.restitution = 1;
This is the "bounciness" of the body.
It's a number between 0
and 1
.
A restitution of 1 is the bounciest.
A restitution of 0 is not bouncy.
When colliding the restitutions of bodies are multiplied together to get the restitution between two bodies.
source: src/core/body.js : 235
this.setWorld()
Set which world to apply to.
Usually this is called internally. Shouldn't be a need to call this yourself usually.
source: src/core/body.js : 399
this.sleep()
Get and/or set whether the body is asleep.
If called with a time (in ms), the time will be added to the idle time and sleep conditions will be checked.
source: src/core/body.js : 304
this.sleepCheck()
Check if the body should be sleeping.
accepts
- dt
- (Number)optional
Time to advance the idle time
Call with no arguments if some event could possibly wake up the body. This will force the body to recheck.
source: src/core/body.js : 336
this.state
The physical state container.
this.state.pos
(Physics.vector) The position vector.this.state.vel
(Physics.vector) The velocity vector.this.state.acc
(Physics.vector) The acceleration vector.this.state.angular.pos
(Number) The angular position (in radians, positive is clockwise starting along the x axis)this.state.angular.vel
(Number) The angular velocitythis.state.angular.acc
(Number) The angular acceleration
Properties from the previous timestep are stored in:
this.state.old; // .pos, .vel, ...
source: src/core/body.js : 150
this.styles
The styles the renderer should use for creating the view.
The styles depend on the renderer. See Renderer#createView for style options.
source: src/core/body.js : 293
this.toBodyCoords()
Transform a vector into coordinates relative to this body.
accepts
- v
- (Physics.vector)
The vector to transform
returns
- Physics.vector
The transformed vector
source: src/core/body.js : 506
this.toWorldCoords()
Transform a vector from body coordinates into world coordinates.
accepts
- v
- (Physics.vector)
The vector to transform
returns
- Physics.vector
The transformed vector
source: src/core/body.js : 517
this.treatment
How the body is treated by the simulation.
- this.treatment = String;
The body can be dynamic
, kinematic
or static
as
described by the analogous box2d docs.
- dynamic bodies are treated "normally". They are integrated, and collide, and all that.
- kinematic bodies are bodies that move at a specified velocity. Other bodies collide with them, but they don't bounce off of other bodies.
- static bodies just stand still. They are like obstacles.
source: src/core/body.js : 264
this.uid
The unique id for the body
- this.uid = Number;
source: src/core/body.js : 195
this.view
Storage for use by the renderer.
- this.view = it_depends;
The type of renderer will put different things in the view property. Basically, this is how the body "looks". It could be a HTMLElement, or an Image, etc...
If your body changes appearance (shape), you should modify this somehow
otherwise the renderer will keep using this same view. If you're letting
the renderer create the view for you, just set this to undefined
if the
body gets modified in shape during the simulation.
source: src/core/body.js : 285
Body.getCOM()
Get center of mass position from list of bodies.
accepts
- bodies
- (Array)
The list of bodies
- com
- (Physics.vector)optional
The vector to put result into. A new vector will be created if not provided.
returns
- Physics.vector
The center of mass position
source: src/core/body.js : 542
Physics.geometry()
Factory function for creating Geometries.
accepts
returns
Visit the PhysicsJS wiki on Geometries for usage documentation.
source: src/core/geometry.js : 12
Geometry
The base class for geometries created by Physics.geometry factory function.
source: src/core/geometry.js : 19
CircleGeometryextends:Geometry
Physics.geometry('circle')
The circle geometry has a circular shape.
Additional options include:
- radius: the radius
Example:
var round = Physics.body('circle', {
x: 30,
y: 20,
radius: 5
});
source: src/geometries/circle.js : 21
CompoundGeometryextends:Geometry
Physics.geometry('compound')
Geometry for compound shapes.
Example:
var thing = Physics.geometry('compound');
thing.addChild( child, pos, rotation );
source: src/geometries/compound.js : 15
this.addChild()
Add a child at relative position.
accepts
- geometry
- (Geometry)
The child to add.
- pos
- (Physics.vector)
The position to add the child at.
returns
source: src/geometries/compound.js : 45
this.clear()
Remove all children.
returns
source: src/geometries/compound.js : 62
ConvexPolygonGeometryextends:Geometry
Physics.geometry('convex-polygon')
Geometry for convex polygons.
Additional config options:
- vertices: Array of Vectorish objects representing the polygon vertices in clockwise (or counterclockwise) order.
Example:
var pentagon = Physics.geometry('convex-polygon', {
// the centroid is automatically calculated and used to position the shape
vertices: [
{ x: 0, y: -30 },
{ x: -29, y: -9 },
{ x: -18, y: 24 },
{ x: 18, y: 24 },
{ x: 29, y: -9 }
]
});
source: src/geometries/convex-polygon.js : 27
this.setVertices()
Set the vertices of this polygon.
accepts
returns
PointGeometryalias of:Geometryextends:Geometry
Physics.geometry('point')
The point geometry represents a point.
source: src/geometries/point.js : 8
RectangleGeometryextends:Geometry
Physics.geometry('rectangle')
Geometry for rectangles.
Additional config options:
- width: The width
- height: The height
Example:
var rectGeo = Physics.geometry('rectangle', {
width: 30,
height: 40
});
source: src/geometries/rectangle.js : 22
this.height
The height
- this.height = Number;
source: src/geometries/rectangle.js : 51
this.width
The width
- this.width = Number;
source: src/geometries/rectangle.js : 45
this.aabb()
Get axis-aligned bounding box for this object (rotated by angle if specified).
source: src/core/geometry.js : 57
this.getFarthestCorePoint()
Get farthest point on the core shape of this geometry
along the direction vector dir
returns local coordinates. Replaces result if provided.
accepts
- dir
- (Physics.vector)
Direction to look
- result
- (Physics.vector)optional
A vector to write result to. Speeds up calculations.
returns
- Physics.vector
The farthest hull point in local coordinates
This does almost the same thing as Geometry#getFarthestHullPoint but shrinks the shape by subtracting "margin" from it. Return the position of the point on the "core" shape.
source: src/core/geometry.js : 104
this.getFarthestHullPoint()
Get farthest point on the hull of this geometry
along the direction vector dir
returns local coordinates. Replaces result if provided.
accepts
- dir
- (Physics.vector)
Direction to look
- result
- (Physics.vector)optional
A vector to write result to. Speeds up calculations.
returns
- Physics.vector
The farthest hull point in local coordinates
Assume all coordinates are relative to the geometry centroid (IE: in the body frame).
This should take a direction vector then it should calculate the location (in that frame of reference) of the point on the perimeter (hull) if you traveled in a straight line from the centroid in the provided direction. The result should be returned/set just like it is in the other geometries.
source: src/core/geometry.js : 82
this.init()internal use only
Initialization. Internal use.
accepts
- options
- (Object)
The configuration options passed by the factory
source: src/core/geometry.js : 26
this.options()
Set options on this instance.
Access options directly from the options object.
Example:
this.options.someOption;
source: src/core/geometry.js : 44
Physics.geometry.getPolygonArea()
Get the signed area of the polygon.
returns
- Number
The area (positive for clockwise ordering)
Physics.geometry.getPolygonCentroid()
Get the coordinates of the centroid.
returns
- Physics.vector
The centroid
Physics.geometry.getPolygonMOI()
Gets the moment of inertia of a convex polygon
returns
- Number
The polygon's moment of inertia
See List of moments of inertia for more information.
Note: we make the following assumpations:
- mass is unitary (== 1)
- axis of rotation is the origin
Physics.geometry.isPointInPolygon()
Check if point is inside polygon hull.
returns
- Boolean
true
if pointpt
is inside the polygon
Physics.geometry.isPolygonConvex()
Determine if polygon hull is convex
returns
- Boolean
true
if the polygon is convex.false
otherwise.
Physics.geometry.nearestPointOnLine()
Get the closest point on a discrete line to specified point.
accepts
returns
- Vector
The closest point
Physics.gjk()
Implementation agnostic GJK function.
accepts
- support(axis)
- (Function)
The support function. Must return an object containing
the witness points (
.a
,.b
) and the support point (.pt
).Recommended to use simple objects.
Eg:
return { a: { x: 1, y:2 }, b: { x: 3, y: 4 }, pt: { x: 2, y: 2 } };
Accepts:
accepts
- axis
- seed
- (Physics.vector)optional
The starting direction for the simplex (defaults to x-axis)
- checkOverlapOnly
- (Boolean)optional
only check whether there is an overlap, don't calculate the depth
- debugFn
- (Function)optional
For debugging. Called at every iteration with the current simplex.
returns
Gilbert–Johnson–Keerthi object collison algorithm For general information about GJK see:
The algorithm information returned:
{
overlap: Boolean,
simplex: [] // array containing simplex points as simple x/y objects
}
source: src/math/gjk.js : 134
Physics.integrator()
Factory function for creating Integrators.
accepts
returns
Visit the PhysicsJS wiki on Integrators for usage documentation.
source: src/core/integrator.js : 31
Integrator
The base class for integrators created by Physics.integrator factory function.
source: src/core/integrator.js : 38
ImprovedEulerextends:Integrator
Physics.integrator('improved-euler')
.
The improved euler integrator.
VelocityVerletextends:Integrator
Physics.integrator('velocity-verlet')
.
The velocity-verlet integrator.
Verletextends:Integrator
Physics.integrator('verlet')
.
The verlet integrator.
source: src/integrators/verlet.js : 26
this.connect()
Connect to a world.
accepts
- world
- (Physics.world)
The world to connect to
Extend this when creating integrators if you need to specify pubsub management. Automatically called when added to world by the Integrator#setWorld method.
source: src/core/integrator.js : 134
this.disconnect()
Disconnect from a world.
accepts
- world
- (Physics.world)
The world to disconnect from
Extend this when creating integrators if you need to specify pubsub management. Automatically called when added to world by the Integrator#setWorld method.
source: src/core/integrator.js : 145
this.init()internal use only
Initialization. Internal use.
accepts
- options
- (Object)
The configuration options passed by the factory
source: src/core/integrator.js : 45
this.integrate()
Integrate bodies by timestep.
returns
Will emit integrate:velocities
and integrate:positions
events on the world.
this.integratePositions()
Just integrate the positions.
Called after Integrator#integrateVelocities.
Should be overridden when creating integrators.
source: src/core/integrator.js : 172
this.integrateVelocities()
Just integrate the velocities.
Should be overridden when creating integrators.
source: src/core/integrator.js : 156
this.options()
Set options on this instance.
Access options directly from the options object.
Example:
this.options.someOption;
source: src/core/integrator.js : 63
this.setWorld()
Set which world to apply to.
Usually this is called internally. Shouldn't be a need to call this yourself usually.
source: src/core/integrator.js : 75
Physics.noConflict()
Restore the original reference to the global window.Physics variable.
returns
Does nothing if PhysicsJS doesn't have a reference in global scope
source: src/util/noconflict.js : 12
Physics.query()
Creates a function that can be used to perform tests on objects.
accepts
- rules
- (Object)
The mongodb-like search rules. (See description).
returns
- Function
The test function
The test function will return a Boolean; true
if the object matches the tests.
Query rules are mongodb-like. You can specify a hash of values to match like this:
{
foo: 'bar',
baz: 2,
some: {
nested: 'value'
}
}
And they will all need to match (it's an AND rule).
You can also use operators for more versatility. The operators you can use include:
- $eq: Test if some property is equal to a value (this is done by default, and is thus redundant)
- $ne: Test if some property is NOT equal to a value
- $in: Test if some value (or array of values) is one of the specified array of values
- $nin: Test if some value (or array of values) is NOT one of the specified array of values
- $at: Test if a body's Physics.aabb includes specified point. It's a primative hit-test.
Example:
var wheelsArray = [];
var queryFn = Physics.query({
name: 'circle', // only circles
$nin: wheelsArray, // not in the wheelsArray
labels: { $in: [ 'player', 'monster' ] } // that have player OR monster labels
});
var obj = {
name: 'circle',
labels: [ 'round' ]
};
queryFn( obj ); // -> false
// give it a player tag
obj.labels.push('player');
queryFn( obj ); // -> true
// put it inside the wheelsArray
wheelsArray.push( obj );
queryFn( obj ); // -> false
source: src/core/query.js : 262
Physics.renderer()
Factory function for creating Renderers.
accepts
- name
- (String)
The name of the renderer to create
- options
- (Object)optional
The configuration for that renderer ( depends on renderer ).
Available options and defaults:
{ // draw meta data (fps, steps, etc) meta: false, // refresh rate of meta info metaRefresh: 200, // width of viewport width: 600, // height of viewport height: 600 // automatically resize the renderer autoResize: true }
returns
Visit the PhysicsJS wiki on Renderers for usage documentation.
source: src/core/renderer.js : 44
Renderer
The base class for renderers created by Physics.renderer factory function.
source: src/core/renderer.js : 51
CanvasRendererextends:Renderer
Physics.renderer('canvas')
Renderer that uses HTMLCanvas to render the world bodies.
Additional config options:
- metaEl: HTMLElement to write meta information like FPS and IPF into. (default: autogenerated)
- offset: Offset the shapes by this amount. (default:
{ x: 0, y: 0 }
) - styles: Styles to use to draw the shapes. (see below)
The styles property should contain default styles for each shape you want to draw.
Example:
styles: {
'circle' : {
strokeStyle: '#542437',
lineWidth: 1,
fillStyle: '#542437',
angleIndicator: 'white'
},
'convex-polygon' : {
strokeStyle: '#542437',
lineWidth: 1,
fillStyle: '#542437',
angleIndicator: 'white'
}
}
source: src/renderers/canvas.js : 37
Layer
A rendering layer for the canvas renderer.
Create by calling CanvasRenderer#addLayer.
source: src/renderers/canvas.js : 204
this.addToStack()
Add body (bodies) to the rendering stack for this layer.
Bodies must be added to the stack in order to be rendered by this layer UNLESS it is the "main" layer.
source: src/renderers/canvas.js : 293
this.bodies
The Bodies this layer is rendering.
- this.bodies = Array;
The "main" layer will render all world bodies if it's empty.
source: src/renderers/canvas.js : 269
this.el
The layer's Canvas
- this.el = HTMLElement;
source: src/renderers/canvas.js : 220
this.id
The layer's ID
- this.id = String;
source: src/renderers/canvas.js : 214
this.options()
Set options on this layer.
Access options directly from the options object.
Example:
this.options.someOption;
source: src/renderers/canvas.js : 236
this.removeFromStack()
Remove body (bodies) from the rendering stack for this layer.
source: src/renderers/canvas.js : 311
this.render()
Render the bodies in this layer's stack.
If you want you can replace this function with your own to do custom rendering.
Example:
layer.render = myCustomRenderFn;
source: src/renderers/canvas.js : 342
this.reset()
Reset the stack.
source: src/renderers/canvas.js : 277
this.addLayer()
Create a new layer.
accepts
- id
- (String)
The id for the layer
- el
- (HTMLElement)optional
The canvas element to use for this layer
- opts
- (Object)optional
The options for this layer (see below)
returns
Layers can have the following options:
- width: The width
- height: The height
- manual: Draw manually (default:
false
) - autoResize: Automatically resize the layer when the renderer's CanvasRenderer#resize method is called. (default:
true
) - follow: A Body. Offset this layer's rendering to follow a body's position. (default:
null
) - offset: The offset Vectorish for this layer. (default:
null
) - scale: Scale the layer by this amount. (default:
1
) - zIndex: The zIndex for the layer's HTMLElement. (default:
1
)
source: src/renderers/canvas.js : 195
this.draw()
Draw a geometry to a context.
accepts
- geometry
- (Geometry)
The shape to draw
- styles
- (Object)optional
The styles configuration
- ctx
- (Canvas2DContext)optional
The canvas context
- offset
- (Vectorish)optional
The offset from center
returns
source: src/renderers/canvas.js : 599
this.drawCircle()
Draw a circle to specified canvas context.
accepts
- x
- (Number)
The x coord
- y
- (Number)
The y coord
- r
- (Number)
The circle radius
- styles
- (Object)
The styles configuration
- ctx
- (Canvas2DContext)optional
The canvas context
source: src/renderers/canvas.js : 483
this.drawLine()
Draw a line onto specified canvas context.
accepts
- from
- (Vectorish)
The starting pt
- to
- (Vectorish)
The ending pt
- styles
- (Object)
The styles configuration
- ctx
- (Canvas2DContext)optional
The canvas context
source: src/renderers/canvas.js : 568
this.drawPolygon()
Draw a polygon to specified canvas context.
accepts
- verts
- (Array)
Array of Vectorish vertices
- styles
- (Object)
The styles configuration
- ctx
- (Canvas2DContext)optional
The canvas context
source: src/renderers/canvas.js : 503
this.drawRect()
Draw a rectangle to specified canvas context.
source: src/renderers/canvas.js : 544
this.layer()
Get the layer by id.
source: src/renderers/canvas.js : 167
this.removeLayer()
Remove a layer.
source: src/renderers/canvas.js : 413
this.resize()
Resize all layer canvases that have the autoResize
option set to true
.
returns
source: src/renderers/canvas.js : 433
this.setStyle()
Set styles on the specified canvas context (or main context).
accepts
- styles
- (Object|String)
Styles to set on the canvas context
- ctx
- (Canvas2DContext)optional
The canvas context
source: src/renderers/canvas.js : 457
DebugRendererextends:Renderer
Physics.renderer('debug')
Extends canvas renderer with special debugging functionality.
Additional config options:
- metaEl: HTMLElement to write meta information like FPS and IPF into. (default: autogenerated)
- offset: Offset the shapes by this amount. (default:
{ x: 0, y: 0 }
) - styles: Styles to use to draw the shapes. (see below)
- drawAABB: whether or not to draw bounding boxes. (default:
true
) - drawRealPosition: whether or not to draw the non-interpolated position of bodies. (default:
false
) - drawIntervals: whether or not to draw the broadphase (sweep-prune) intervals. (default:
false
) - drawContacts: whether or not to draw contact points. (default:
false
) - drawSleepState: whether or not to highlight sleeping bodies. (default:
false
) - drawBodyState: whether or not to show body position and velocity. (default:
false
) - aabbColor: the color of AABBs
- realBodyStyle: styles used to draw the image of the body at its true non-interpolated position
- intervalMinColor: color of interval minima
- intervalMaxColor: color of interval maxima
- mtvColor: color of minimum transit vector for contacts (overlaps)
- contactColor: color of contact points
The styles property should contain default styles for each shape you want to draw.
Example:
styles: {
'circle' : {
strokeStyle: '#542437',
lineWidth: 1,
fillStyle: '#542437',
angleIndicator: 'white'
},
'convex-polygon' : {
strokeStyle: '#542437',
lineWidth: 1,
fillStyle: '#542437',
angleIndicator: 'white'
}
}
source: src/renderers/debug.js : 52
DomRendererextends:Renderer
Physics.renderer('dom')
Renderer that manipulates DOM elements according to the physics simulation. Very primative...
source: src/renderers/dom.js : 8
this.attach()
Event callback to attach a node to the viewport
accepts
- data
- (HTMLElement|Object)
DOM node or event data (
data.body
)
returns
source: src/renderers/dom.js : 242
this.circleProperties()internal use only
Set dom element style properties for a circle.
accepts
- el
- (HTMLElement)
The element
- geometry
- (Geometry)
The body's geometry
source: src/renderers/dom.js : 136
this.detach()
Event callback to detach a node from the DOM
accepts
- data
- (HTMLElement|Object)
DOM node or event data (
data.body
)
returns
source: src/renderers/dom.js : 221
this.pointProperties()internal use only
Set dom element style properties for a point.
accepts
- el
- (HTMLElement)
The element
- geometry
- (Geometry)
The body's geometry
source: src/renderers/dom.js : 120
this.rectangleProperties()internal use only
Set dom element style properties for a rectangle.
accepts
- el
- (HTMLElement)
The element
- geometry
- (Geometry)
The body's geometry
source: src/renderers/dom.js : 154
PixiRendererextends:Renderer
Physics.renderer('pixi')
Renderer that uses the PIXI.js library. Documentation can be found here.
Additional config options:
- metaEl: HTMLElement to write meta information like FPS and IPF into. (default: autogenerated)
- offset: Offset the shapes by this amount. (default:
{ x: 0, y: 0 }
) - styles: Styles to use to draw the shapes. (see below)
The styles property should contain default styles for each shape you want to draw.
Example:
styles: {
// Defines the default canvas colour
'color': '0x66FF99',
'circle' : {
strokeStyle: '0xE8900C',
lineWidth: 3,
fillStyle: '0xD5DE4C',
angleIndicator: '0xE8900C'
},
'convex-polygon' : {
strokeStyle: '0xE8900C',
lineWidth: 3,
fillStyle: '0xD5DE4C',
angleIndicator: '0xE8900C'
}
}
source: src/renderers/pixi-renderer.js : 42
this.attach()
Event callback to attach a child to the stage
accepts
- data
- (PIXI.Graphics|Object)
Graphics object or event data (
data.body
)
returns
this.centerAnchor()
Centers the anchor to {x: 0.5, y: 0.5} of a view
accepts
- view
- (PIXI.DisplayObject)
The view to center
this.createCircle()
Create a circle for use in PIXI stage
accepts
returns
- PIXI.Graphics
A graphic object representing a circle.
this.createDisplay()
Create a PIXI sprite or movie clip.
accepts
returns
- PIXI.DisplayObject
An object that is renderable.
this.createLine()
Create a line for use in PIXI stage
accepts
returns
- PIXI.Graphics
A graphic object representing a polygon.
this.createPolygon()
Create a polygon for use in PIXI stage
returns
- PIXI.Graphics
A graphic object representing a polygon.
this.createRect()
Create a rectangle for use in PIXI stage
accepts
returns
- PIXI.Graphics
A graphic object representing a circle.
this.detach()
Event callback to detach a child from the stage
accepts
- data
- (PIXI.Graphics|Object)
Graphics object or event data (
data.body
)
returns
this.drawBody()
Draw a PIXI.DisplayObject to the stage.
accepts
- body
- (Body)
The body to draw
- view
- (DisplayObject)
The pixi display object
this.loadSpriteSheets()
Loads textures defined in a spritesheet
accepts
returns
this.setStyles()
Set styles on pixi graphics object
accepts
- graphics
- (PIXI.Graphics)
The graphics object to set styles on
- styles
- (Object)
The styles configuration
returns
- PIXI.Graphics
A graphic object
this.createView()
Create a view for the specified geometry.
returns
- Mixed
Whatever the renderer needs to render the body.
The view is used to render the body. It is a cached version of the body that gets moved and rotated according to the simulation.
The styles are used to modify the appearance of the view. They depend on the renderer.
Override this when creating renderers.
source: src/core/renderer.js : 182
this.drawBody()
Draw specified body using specified view.
Override this when creating renderers.
source: src/core/renderer.js : 226
this.drawMeta()
Draw the meta data.
accepts
- meta
- (Object)
The meta data
The meta data will look like this:
meta = {
fps: 60, // the frames per second
ipf: 4 // the number of iterations per frame
};
Override this when creating renderers.
source: src/core/renderer.js : 209
this.init()internal use only
Initialization. Internal use.
accepts
- options
- (Object)
The configuration options passed by the factory
source: src/core/renderer.js : 58
this.render()
Render the world bodies and meta. Called by world.render()
returns
source: src/core/renderer.js : 129
this.resize()
Set the dimensions of the renderer.
returns
If no dimensions are specified it will auto resize.
source: src/core/renderer.js : 87
this.setWorld()
Set which world to apply to.
Usually this is called internally. Shouldn't be a need to call this yourself usually.
source: src/core/renderer.js : 107
Physics.scratchpad()
Get a new scratch session to work from or wrap a function in a scratch session.
accepts
- fn
- (Function)optional
Some function you'd like to wrap in a scratch session. First argument is the scratch instance.
Call .done()
on it when finished.
Example:
// get a scratch session manually
var myAlg = function( scratch, arg1, arg2, ... ){
var scratch = Physics.scratchpad()
,vec = scratch.vector().set( 0, 0 ) // need to reinitialize... it's recycled!
;
// ...
return scratch.done( result );
};
// later...
while( awesome ){
myAlg( arg1, arg2, ... );
}
Example:
// wrap a function in a scratch session
var myAlg = Physics.scratchpad(function( scratch, arg1, arg2, ... ){
var vec = scratch.vector().set( 0, 0 ); // need to reinitialize... it's recycled!
//...
return result;
});
// later...
while( awesome ){
myAlg( arg1, arg2, ... );
}
source: src/util/scratchpad.js : 128
Scratch
A scratchpad session.
This class keeps track of temporary objects used
in this session and releases them when finished (call to .done()
).
Use this to retrieve temporary objects:
.vector()
: retrieve a temporary Physics.vector.transform()
: retrieve a temporary Physics.transform
See Physics.scratchpad for more info.
source: src/util/scratchpad.js : 37
this.done()
Declare that your work is finished.
accepts
- val
- (Mixed)optional
No effect on this method, just passed on to the return value so you can do things like:
return scratch.done( myReturnVal );
returns
- Mixed
Whatever you specified as
val
Release temp objects for use elsewhere. Must be called when immediate work is done.
You can wrap the return value in scratch.done() so that you don't forget to call it.
Example:
return scratch.done( myReturnValue );
source: src/util/scratchpad.js : 68
Physics.scratchpad.fn()
Wrap a function in a scratch session.
accepts
- fn
- (Function)
Some function you'd like to wrap in a scratch session. First argument is the scratch instance. See Physics.scratchpad.
returns
- Function
The wrapped function that can be reused like the original minus the first (scratch) parameter.
Same as calling Physics.scratchpad( fn )
with a function specified.
source: src/util/scratchpad.js : 152
Physics.scratchpad.register()
Register a new object to be included in scratchpads.
Example:
// register a hypothetical vector class...
Physics.scratchpad.register('vector', Vector);
source: src/util/scratchpad.js : 186
Physics.util
Namespace for utility functions.
source: src/intro.js : 47
Physics.util.pubsub
Fast pubsub implementation.
Can be mixed into other classes easily.
source: src/util/pubsub.js : 19
this.emit()
Publish data to a topic.
returns
source: src/util/pubsub.js : 160
this.off()
Unsubscribe callback(s) from topic(s).
accepts
- topic
- (String)
topic The topic name. Specify
true
to remove all listeners for all topics - fn
- (Function)
The original callback function. Specify
true
to remove all listeners for specified topic - scope
- (Object)optional
The scope the callback was bound to. This is important if you are binding methods that come from object prototypes.
returns
accepts
- topicCfg
- (Object)
A config with key/value pairs of
{ topic: callbackFn, ... }
returns
source: src/util/pubsub.js : 96
this.on()
Subscribe callback(s) to a topic(s).
accepts
returns
accepts
returns
source: src/util/pubsub.js : 41
this.one()
Subscribe callback(s) to a topic(s), but only ONCE.
accepts
returns
accepts
returns
source: src/util/pubsub.js : 211
Physics.util.ticker
The Ticker singleton for easily binding callbacks to animation loops (requestAnimationFrame).
Requires window.requestAnimationFrame... so polyfill it if you need to.
source: src/util/ticker.js : 8
Physics.util.ticker.isActive()
Determine if ticker is currently running.
returns
source: src/util/ticker.js : 107
Physics.util.ticker.off()
Unsubscribe a callback from the ticker.
source: src/util/ticker.js : 95
Physics.util.ticker.on()
Subscribe a callback to the ticker.
accepts
returns
source: src/util/ticker.js : 83
Physics.util.ticker.start()
Start the ticker
returns
source: src/util/ticker.js : 59
Physics.util.ticker.stop()
Stop the ticker
returns
source: src/util/ticker.js : 70
Physics.util.bind()
Bind a scope to a function.
accepts
returns
Basically the same functionality as Function.prototype.bind.
source: src/util/helpers.js : 183
Physics.util.clearArray()
Quickly clear an array.
source: src/util/helpers.js : 33
Physics.util.decorator()
Facilitates creation of decorator factory functions.
accepts
returns
- Function
The factory function
See the factory definition for the factory signatures. For full documentation and examples, please visit the wiki.
Example:
var factory = Physics.util.decorator('factory', {
// prototype methods...
method: function( args ){
}
});
// define
factory( 'name', 'parent-name', function( parent ){
// extend further...
return {
// overrides
init: function( cfg ){
parent.init.call(this, cfg);
}
};
});
// instantiate
var options = { key: 'val' };
var instance = factory( 'name', options );
source: src/util/decorator.js : 38
factory
Factory function for definition and instantiation of subclasses.
returns
Use the first signature (once) to define it first. If defining without the "cfg" parameter, void will be returned. Otherwise the class instance will be returned.
See Physics.util.decorator for more information.
source: src/util/decorator.js : 129
Physics.util.defaults()
Implementation of lodash.defaults.
accepts
returns
source: src/util/helpers.js : 650
Physics.util.extend()
Implementation of lodash.extend
accepts
returns
source: src/util/helpers.js : 640
Physics.util.filter()
Test an array of values against a test function and return another array of values for which the test function returns true.
accepts
returns
source: src/util/helpers.js : 235
Physics.util.find()
Test an array of values against a test function and return the first value for which the function returns true.
accepts
returns
source: src/util/helpers.js : 209
Physics.util.indexOf()
Fast indexOf implementation.
returns
- Number
The index of
value
in the array OR-1
if not found
source: src/util/helpers.js : 9
Physics.util.isArray()
Test if a value is an array.
source: src/util/helpers.js : 502
Physics.util.isFunction()
Test if a value is a function.
source: src/util/helpers.js : 494
Physics.util.isObject()
Test if a value is an object.
source: src/util/helpers.js : 476
Physics.util.isPlainObject()
Test if a value is a plain javascript object.
source: src/util/helpers.js : 540
Physics.util.options()
Options helper to keep track of options. Call it with a config object. Access options directly on the function.
accepts
returns
- Function
The options function
Example:
this.options = Physics.util.options({ foo: 'bar', opt: 'def' });
this.options({ opt: 'myVal' });
this.options.foo; // === 'bar'
this.options.def; // === 'myVal'
// can also change defaults later
this.options.defaults({ foo: 'baz' });
// can add a change callback
this.options.onChange(function( opts ){
// some option changed
// opts is the target
});
source: src/util/helpers.js : 102
Physics.util.pairHash()
Generate a unique numeric hash from two input IDs.
returns
- Number
A unique numeric hash (valid for values < 2^16)
Useful for speedy indexing of pairs.
source: src/util/helpers.js : 157
Physics.util.sortedIndex()
Implementation of lodash.sortedIndex.
accepts
returns
source: src/util/helpers.js : 682
Physics.util.throttle()
Ensure a function is only called once every specified time span.
returns
source: src/util/helpers.js : 48
Physics.util.uniq()
Create an array without duplicates.
accepts
returns
source: src/util/helpers.js : 597
Physics.util.uniqueId()
Generate a unique id, optionally prefixed.
source: src/util/helpers.js : 419