Documentation

Unity Engine


User Manual

Script Reference

Unity Engine


PhysicsBody

A body is contained within a world and has 3 degrees-of-freedom, two for position and one for rotation. A body can have forces, torques and impulses applied to it. A body has three distinct types: Static: This type of body does not move under simulation and behaves as if it has infinite mass, essentially an immovable object. Static bodies never interact with other Static or Kinematic bodies. Dynamic: This type of body is fully simulated and moves according to forces and torques applied to its linear/angular velocities. It can interact with all other body types. It always has finite, non-zero mass. Kinematic: This type of body moves under simulation and moves according to its linear/angular velocities and never uses forces or torques. It only interacts with Dynamic body types. It behaves as if it has infinite mass. A body is automatically destroyed when the world it is in is destroyed. A body cannot exist outside a world.
Read time 18 minutesLast updated 10 days ago

Definition

public readonly struct PhysicsBody : IEquatable<PhysicsBody>

Remarks

Create a body with PhysicsWorld.CreateBody, then attach a shape with PhysicsBody.CreateShape. After you create a shape from a geometry object, the shape doesn't change if you later change the geometry object. Unity draws shapes as a debug visualization in the Scene view and Game view, with a line indicating the shape's rotation direction.
Additional Resources: PhysicsShape, PhysicsWorld

Examples

// Create a body, then attach a circle shape to it.using UnityEngine;using Unity.U2D.Physics;public class CreateWorldAndObjects : MonoBehaviour{ // Declare definitions that contain default properties for the body and shape. public PhysicsBodyDefinition bodyDefinition = PhysicsBodyDefinition.defaultDefinition; public PhysicsShapeDefinition shapeDefinition = PhysicsShapeDefinition.defaultDefinition; void Start() { // Get the default world. PhysicsWorld world = PhysicsWorld.defaultWorld; // Create the physics body with the body definition. PhysicsBody myObject = world.CreateBody(bodyDefinition); // Create the circle geometry. CircleGeometry circleGeometry = new CircleGeometry { radius = 1.5f }; // Create the shape with both the geometry and the shape definition. myObject.CreateShape(circleGeometry, shapeDefinition); }}

Constructors

Constructor

Description

PhysicsBody(Unity.U2D.Physics.PhysicsHandle)Create a body from a physics handle.

Properties

Property

Description

angularDampingThe angular damping of the body. This will reduce the angular velocity over time. See _angularVelocity.
angularVelocityThe angular velocity of the body, in degrees per second.
awakeThe awake state of the body.
callbackTargetGet/Set the Object that event callbacks for this body will be sent to. Care should be taken with any Object assigned as a callback target that isn't a Object as this assignment will not in itself keep the object alive and can be garbage collected. To avoid this, you should have at least a single reference to the object in your code. To remove the object assigned here, set the callback target to NULL.
collisionThresholdA threshold used to control when continuous collision detection is used when a body moves. The value is used to compare the body linear velocity movement against the extents of all the shapes added to the body scaled by this threshold. If the movement exceeds the extents scaled by the threshold then continuous collision detection is used to stop tunneling. Lower values reduce the distance the body must move before continuous collision detection is used and can have a considerable impact on performance! Higher values increase the distance the body must move before continuous collision detection is used. Too low a threshold will result in continuous collision detection being used more often therefore affecting performance so this should be limited to specific bodies only. The default threshold is 0.5 which equates to half the total shape extents. The threshold is clamped to a range of 0.0 to 1.0 with 0.0 meaning continuous collision detection will always be used.
constraintsGet/Set the degrees of freedom constraints (locks) for the body of Linear X, Linear Y and Rotation Z.
contactRecyclingAllowedControls contact recycling for this body. Enabled by default. Contact recycling reuses contact manifolds when bodies move only slightly, improving performance. Disabling it can avoid ghost collisions, at the cost of higher simulation time. Both bodies in a contact must have recycling enabled for that contact to be recycled. Existing contacts retain their prior setting; only contacts created after a change will be recycled. See _contactRecyclingAllowed.
definitionGet/Set a body definition by accessing all of its current properties. This is provided as convenience only and should not be used when performance is important as all the properties defined in the definition are accessed sequentially. You should try to only use the specific properties you need rather than using this feature.
drawTargetControls which Unity editor views this body is drawn into.
enabledThe enabled state of the body. If false, the body and anything attached to it will not participate in the simulation.
fastCollisionsAllowedTreat this body as high speed object that performs continuous collision detection against dynamic and kinematic bodies, but not other high speed bodies. Fast collision bodies should be used sparingly, not because they are slow but because everything using fast collisions does not work well. They are not a solution for general dynamic-versus-dynamic continuous collision. They also may interfere with joint constraints.
fastRotationAllowedThis allows this body to bypass rotational speed limits. This should only be used for circular objects, such as wheels, balls etc.
gravityScaleScales the world gravity that is applied to this body. Setting the gravity scale to zero stops any gravity being applied. Likewise, a negative value inverts gravity. See _gravity.
isOwnedGet if the body is owned. See PhysicsBody.SetOwner.
isValidChecks if a body is valid.
jointCountGet the number of joints attached to this body. Use PhysicsBody.GetJoints to retrieve the joints.
linearDampingThe linear damping of the body. This will reduce the linear velocity over time. See _linearVelocity.
linearVelocityThe linear velocity of the body.
localCenterOfMassThe center of mass position of the body in local space. This can be accessed as a union of _mass, _rotationalInertia and _localCenterOfMass using _massConfiguration. When this value is overridden with _massOverride, setting it authors the override value, which persists across mass recalculations.
massThe calculated mass of the body, usually in kilograms. This can be accessed as a union of _mass, _rotationalInertia and _localCenterOfMass using _massConfiguration. When this value is overridden with _massOverride, setting it authors the override value, which persists across mass recalculations.
massConfigurationThe body mass configuration comprised of the _mass, _rotationalInertia and _localCenterOfMass. Normally this is computed automatically as each PhysicsShape is added, removed or changed on a body. This will automatically change if the body type changes, for instance, a Static or Kinematic body always have zero mass and rotational inertia. The individual properties of the _massConfiguration and be accessed using _mass, _rotationalInertia and _localCenterOfMass. The PhysicsBody.MassConfiguration will be overwritten when setting this property or if PhysicsBody.ApplyMassFromShapes is called or when adding, removing or changing PhysicsShape with _startMassUpdate enabled. To make a value persist across those recalculations, override it with _massOverride; with anything overridden, setting this property authors the override values instead of writing the body directly, so overridden values persist and the rest are rederived from the attached shapes.
massOverrideSelects which of the mass, rotational inertia and center of mass are overridden with authored values instead of being computed from the attached shapes.
ownerThe owner object associated with this body, or NULL if no owner has been specified. This is a convenience property that returns the same value as PhysicsBody.GetOwner.
ownerUserDataGet PhysicsUserData that can be used for any purpose, typically by the owner only.
physicsHandleGet the physics handle.
positionThe position of the body in the world.
rotationThe rotation of the body.
rotationalInertiaThe rotational inertia of the body, usually in kg*m^2. This can be accessed as a union of _mass, _rotationalInertia and _localCenterOfMass using _massConfiguration. When this value is overridden with _massOverride, setting it authors the override value, which persists across mass recalculations.
selectedDrawingControls whether this body is drawn individually when the world is drawn.
shapeCountGet the number of shapes attached to this body. Use PhysicsBody.GetShapes to retrieve the shapes.
sleepingAllowedThe sleeping ability of the body. If false, the body will never sleep and will be woken up. See _awake.
sleepThresholdThe threshold below which the body will sleep, in meters/sec.
totalForceThe total user force that has been applied to this body since the last simulation step. Setting this value overrides any force that was previously requested.
totalTorqueThe total users torque that has been applied to this body since the last simulation step. Setting this value overrides any torque that was previously requested.
transformThe full transform of the body composed of position and rotation.
transformObjectGet/Set the transform object associated with the body. This can be used as a write transform and/or as a depth-hint for PhysicsWorld drawing. See _transformWriteMode.
transformWriteModeGet/Set how the _transformObject should be written to after the simulation has completed. Transform write will only occur if it is enabled on the world using _transformWriteMode.
typeA body is one of these three body types, Dynamic, Kinematic or Static, each of which determines how the body behaves in the simulation.
userDataGet/Set PhysicsUserData that can be used for any purpose. The physics system doesn't use this data, it is entirely for custom use.
worldGet the world the body is attached to.
worldCenterOfMassGet the center of mass position of the body in world space. This changes as the body moves i.e. as the _transform is changed.
worldDrawingControls whether this body is automatically drawn when the world is drawn.

Methods

Method

Description

ApplyAngularImpulseApply an angular impulse. This should be used for one-shot impulses. If you need a steady torque, use a torque instead, which will work better with the sub-stepping solver.
ApplyBuoyancyApply buoyancy, flow and damping forces to the body based on how its attached shapes are submerged in a fluid plane. Forces and torques are continuous (not impulses), so this is expected to be called every simulation step. The body must be PhysicsBody.BodyType.Dynamic; otherwise a warning is logged and the call is a no-op.
ApplyForceApply a force at a world point. If the force is not applied at the center of mass, it will generate a torque and affect the angular velocity.
ApplyForceToCenterApply a force to the center of mass.
ApplyLinearImpulseApply an impulse at a point. This immediately modifies the velocity and also modifies the angular velocity if the point of application is not at the center of mass. This should be used for one-shot impulses. If you need a steady force, use a force instead, which will work better with the sub-stepping solver.
ApplyLinearImpulseToCenterApply an impulse to the center of mass. This immediately modifies the velocity. This should be used for one-shot impulses. If you need a steady force, use a force instead, which will work better with the sub-stepping solver.
ApplyMassFromShapesTypically a body will automatically calculate the PhysicsBody.MassConfiguration using all the attached shapes. The PhysicsBody.MassConfiguration is automatically updated whenever a PhysicsShape is added, removed or modified. When adding many shapes to a body, you can choose to stop this automatic calculation, therefore improving performance, by disabling _startMassUpdate for each shape being added to the body. This call will result in the PhysicsBody.MassConfiguration being calculated using the currently added PhysicsShape so is typically called after many shapes are added if they have _startMassUpdate disabled. Alternately, if you wish to assign your own PhysicsBody.MassConfiguration then disabling the automatic calculation also makes sense. In either case, you must call this method or set _massConfiguration before any simulation step occurs otherwise the PhysicsBody will exhibit unstable collision behaviour. The PhysicsBody.MassConfiguration will be overwritten when calling PhysicsBody.ApplyMassFromShapes, if _massConfiguration is set or when adding, removing or changing PhysicsShape with _startMassUpdate enabled. Values overridden with _massOverride keep their authored values through this call; it refreshes the values that are computed from the attached shapes.
ApplyTorqueApply a torque. This affects the angular velocity without affecting the linear velocity.
ApplyWindApply wind forces to this body's attached shapes. Forces are continuous (not impulses) and are computed per shape by Box2D using the drag/lift coefficients in
input
; this method is expected to be called every simulation step while the body is exposed to the wind. The body must be PhysicsBody.BodyType.Dynamic; otherwise a warning is logged and the call is a no-op. Sleeping bodies are woken automatically by Box2D when the per-shape force is non-trivial.
ClearForcesClear any user forces that have been applied to this body. Forces on a body are automatically cleared when a simulation step completes, however under some circumstances it may be desirable to clear the forces explicitly.
CreateChainCreate a Chain of multiple shapes attached to this body.
CreateShapeCreate a Capsule shape, using its default definition, attached to this body.
CreateShapeBatchCreate a batch of Capsule shapes attached to this body.
DestroyDestroy a body, destroying all attached PhysicsShape and PhysicsJoint. If the object is owned with PhysicsBody.SetOwner then you must provide the owner key it returned. Failing to do so will return a warning and the body will not be destroyed.
DistanceGet the minimum distance between all the shapes attached to this body and the specified shape.
DrawDraw this body's current state once, as custom drawing.
GetAABBGet the world AABB that bounds all the shapes attached to this body. If there are no shapes attached to the body then the returned AABB is empty and centered on the body origin.
GetContactsGet all the touching contacts this body is currently participating in. Speculative collision is used so some contact points may be separated, a property available in the provided contact manifold.
GetJointsGet the joints attached to this body.
GetLocalPointGets a local point relative to the body given a world point.
GetLocalPointVelocityGet the linear velocity of a local point attached to a body. Usually in meters per second.
GetLocalVectorGets a local vector on a body given a world vector.
GetOwnerGet the owner object associated with this body as specified using PhysicsBody.SetOwner.
GetShapesGet the shapes attached to this body.
GetWorldPointGets a world point transformed from a local point relative to the body.
GetWorldPointVelocityGet the linear velocity of a world point attached to a body. Usually in meters per second.
GetWorldVectorGets a world vector transformed from a local vector relative to the body.
ReadPoseRead the full 3D position and rotation of the body given the specified Transform.
SetContactEventsEnable/disable contact events on all shapes attached to the body. See _contactEvents.
SetHitEventsEnable/disable hit events on all shapes attached to the body. See _hitEvents.
SetOwnerSet the owner object using the specified owner key. You can only set the owner once, multiple attempts will produce a warning. This call does not bind the lifetime of the specified owner object, it is simply a reference. It is also valid to not specify an owner object (NULL) to simply gain an owner key however it can be useful, if simply for debugging purposes and discovery, to know which object is the owner.
SetOwnerUserDataSet PhysicsUserData that can be used for any purpose, typically by the owner only.
SetTransformTargetSet the _linearVelocity and _angularVelocity to reach the specified transform in the specified time. The resultant transform will be closed by may not be exact. This is designed ideally for Kinematic bodies but will work with Dynamic bodies if nothing changes the assigned velocities. This will be ignored if the calculated _linearVelocity and _angularVelocity would be below the _sleepThreshold. This will automatically wake the body if it is asleep.
WakeTouchingWake any bodies that are touching this body via their shapes. This also works for Static bodies.
WritePoseWrite the full 3D position and rotation of the body to the currently set _transformObject. If no _transformObject is assigned, this method will do nothing and false will be returned.

Static Methods

Method

Description

ApplyBuoyancyApply buoyancy, flow and damping forces to every body in
bodies
based on how their attached shapes are submerged in a fluid plane. The same PhysicsBody.BuoyancyInput is applied to all bodies. Each body must be PhysicsBody.BodyType.Dynamic; non-dynamic or invalid bodies log a warning and are skipped. Forces and torques are continuous (not impulses), so this is expected to be called every simulation step.
ApplyWindApply wind forces to every body in
bodies
by iterating each body's attached shapes. The same PhysicsBody.WindInput is applied to all bodies. Each body must be PhysicsBody.BodyType.Dynamic; non-dynamic or invalid bodies log a warning and are skipped. Forces are continuous (not impulses), so this is expected to be called every simulation step.
CreateCreate a body using _defaultDefinition in the specified world.
CreateBatchCreate a batch of bodies in the specified world.
DestroyBatchDestroy a batch of bodies, destroying all attached PhysicsShape and PhysicsJoint. Any invalid bodies will be ignored. Owned bodies will produce a warning and will not be destroyed (See PhysicsBody.SetOwner).
GetBatchTransformGet the transform for a batch of PhysicsBody.
GetBatchVelocityGet the velocity for a batch of PhysicsBody.
SetBatchForceApply a force for a batch of PhysicsBody using a span of PhysicsBody.BatchForce. If invalid values are passed to the batch, they will simply be ignored. For best performance, the bodies contained in the batch should all be part of the same PhysicsWorld. If the bodies in the batch are not contained in the same PhysicsWorld, the batch should be sorted by the PhysicsWorld the bodies are contained within.
SetBatchImpulseApply an impulse for a batch of PhysicsBody using a span of PhysicsBody.BatchImpulse. If invalid values are passed to the batch, they will simply be ignored. For best performance, the bodies contained in the batch should all be part of the same PhysicsWorld. If the bodies in the batch are not contained in the same PhysicsWorld, the batch should be sorted by the PhysicsWorld the bodies are contained within.
SetBatchTransformSet the transform for a batch of PhysicsBody using a span of PhysicsBody.BatchTransform. If invalid values are passed to the batch, they will simply be ignored. For best performance, the bodies contained in the batch should all be part of the same PhysicsWorld. If the bodies in the batch are not contained in the same PhysicsWorld, the batch should be sorted by the PhysicsWorld the bodies are contained within.
SetBatchVelocitySet the velocity for a batch of PhysicsBody using a span of PhysicsBody.BatchVelocity. If invalid values are passed to the batch, they will simply be ignored. For best performance, the bodies contained in the batch should all be part of the same PhysicsWorld. If the bodies in the batch are not contained in the same PhysicsWorld, the batch should be sorted by the PhysicsWorld the bodies are contained within.
SetOwnerSet the owner object using the specified owner key. You can only set the owner once, multiple attempts will produce a warning. This call does not bind the lifetime of the specified owner object, it is simply a reference. Whilst it is valid to not specify an owner object (NULL), it is recommended for debugging purposes.
SetOwnerUserDataSet PhysicsUserData on a batch of bodies that can be used for any purpose, typically by the owner only. The bodies and userDatas spans must be the same length; bodies[n] receives userDatas[n].
SetSelectedDrawingSet the selected drawing state on a batch of bodies.
SetUserDataSet PhysicsUserData on a batch of bodies that can be used for any purpose. The bodies and userDatas spans must be the same length; bodies[n] receives userDatas[n].

Structs

Struct

Description

PhysicsBody.BatchForceA batch item used to apply a force to a PhysicsBody.
PhysicsBody.BatchImpulseA batch item used to apply an impulse to a PhysicsBody.
PhysicsBody.BatchTransformA batch item used to get/set the pose of a PhysicsBody.
PhysicsBody.BatchVelocityA batch item used to set the velocity of a PhysicsBody.
PhysicsBody.BuoyancyInputInput to PhysicsBody.ApplyBuoyancy describing the fluid surface, density, flow and damping used to compute buoyancy, flow and damping forces for the body.
PhysicsBody.MassConfigurationThis holds the mass configuration computed for a PhysicsBody.
PhysicsBody.TransformWriteTweenUsed to define a Transform write "tween" for a body.
PhysicsBody.WindInputInput to PhysicsBody.ApplyWind describing the wind velocity, drag and lift coefficients and the shape filter used to compute aerodynamic forces per attached shape.

Enums

Enum

Description

PhysicsBody.BodyConstraintsBody constrains constrain the degrees of freedom a body when solving the simulation.
PhysicsBody.BodyTypeA body is one of these three body types, Dynamic, Kinematic or Static, each of which determines how the body behaves in the simulation.
PhysicsBody.MassOverrideSelects which of the mass, rotational inertia and center of mass are overridden with authored values instead of being computed from the attached shapes.
PhysicsBody.TransformWriteModeThe method used to Write the body pose to the Transform. See _transformWriteMode.