And yea, after three years of Unity development, I am back to revisit the most basic fundamentals.
Update Ongoing
This post will be updated.
Post Series
This posts belongs to the series: Down to Unity 2D Stacks. You can see all posts in this series here.
Expected Reader Experience: Medium
This post is good for readers having some basic knowledge on the topic: Unity 2D Physics. The ideal reader group include those who have a good practical command of Unity 2D yet want to check whether they have missed anything important or wonder about the underlying concept. However, since this post belongs to a series, you are expected to master the previous posts in the series.
Overview
- z-coordinate dose not makes any influence on 2D physics. All 2D physics happens at Z coordinate 0.
- Physics 2D and 3D components do not interact.
Physics 2D Project Settings
- Gravity: Default force field applied globally.
- This would take effect even if
Rigidbody.velocity
is set by code each physics frame!
- This would take effect even if
- Default Material: The physical material used by default if none assigned to Rigidbody 2D and Collider 2D.
Rigidbody 2D
- Three important roles of Rigidbody 2D
- Allows the GameObject to be affected by Unity Physics2D Engine. It overrides the
Transform
and updates it to a position/rotation defined by the Rigidbody 2D. - Define important physics data for the GameObject (e.g.
Mass
,Angular Drag
) - Keep track of runtime physics data (e.g.
Velocity
)
- Allows the GameObject to be affected by Unity Physics2D Engine. It overrides the
- Any Collider 2D component added to the same GameObject or child GameObject is implicitly âattachedâ to that Rigidbody 2D.
- Collider 2Ds attached to the same Rigidbody 2D wonât collide with each other. That means you can âcompoundâ Collider 2Ds.
Material
: specify a common Material for all Collider 2D attached to it. Collider 2D would prioritize its own Material, of course. If no Materials are specified anywhere, default Material in Physics 2D setting are used.- Think of
Mass
as the regular mass in the real physical sense.- The most important effect of mass is to determine two
Dynamic
GameObjects collide (Think about the momentum conservation formula). Use Auto Mass
will detect a mass from its Collider 2D.
- The most important effect of mass is to determine two
- Think of
Drag
as air resistance. Body Type
affects movement and collision.Dynamic
is âfull-fledgedâ use of rigidbody 2D, also most performance-expensive.Kinematic
allows a GameObjectâs velocity not to be influenced by forces, gravity and drags. It still will interact with otherDynamic
GameObject through collider2D.- This is usually for things like moving platform whose movement is controlled by scripts rather than physics engine using
Rigidbody2D.MovePosition
andMoveRotation
. - It behaves like an immovable objects as if it has infinite mass during collision. Mass-related properties are not available.
- It does not collide with
Static
orKinematic
GameObjects (but trigger would still fire), unless this is demanded inUse Full Kinematic Contacts
.
- This is usually for things like moving platform whose movement is controlled by scripts rather than physics engine using
Static
is for totally unmoved object, also least performance-expensive.- Simply not attaching any Rigidbody 2D component to a GameObject makes it static too. All its colliders by default would be attached to a single hidden
Static
Rigidbody 2D component. - Having a dedicated
Static
Rigidbody 2D has better performance whenBody Type
needs to be changed at runtime. - Rigidbody 2D is here solely for collision, not for movement. It is immovable as if it has infinite mass.
- Normally, it will not collide with
Kinetic
GameObjects; but if the Collider 2D is used as trigger it will fire.
- Simply not attaching any Rigidbody 2D component to a GameObject makes it static too. All its colliders by default would be attached to a single hidden
Interpolate
: When the GameObject moved by rigidbody appears jittering, checkingInterpolate
(smooth using last frame) orExtrapolate
(smooth using next frame) may smooth.Sleeping Mode
: There are three threshold values to be adjusted in Physics 2D settings to set a Rigidbody 2D below a certain velocity for a certain duration to sleep.- Avoid using
Never Sleep
if possible. - Relevant APIs:
Rigidbody2D.Sleep()
WakeUp()
IsSleeping()
- Avoid using
Collision Detection
: Best just keep asDiscrete
unless there are problems (e.g., fast-moving objects).Simulated
- Check and uncheck this property to stop and resume a Rigidbody 2D and its Collider 2Ds and Joint 2Ds from 2D physics engine.
- This is much less expensive than disabling individual Collider 2Ds and Joint 2Ds components.
Collider 2D
Collider General
- Hold SHIFT key to drag collider shape in the scene view.
- Hold CTRL key to click and delete points for edge and polygon colliders.
- Using a zig-zagged edge collider for a surface is better than compounding several box colliders.
- Minimum requirement for collisions to happen: two GameObjects both have Collider 2D and at least one of them have a
Dynamic
Rigidbody 2D. This is due to the collision rules specified above. - General rule of thumb for performance (best to worst): circle < capsule < box.
Tag and Layer, Collision Layer Matrix
- All gameobjects by default are in
Default
collision layer. Try to create layers for each type of gameobjects and never leave anything inDefault
. - A good practice is to uncheck everything except the
Default
row in Collision Matrix at the beginning of project. Remember, always cut off unused collision checks.
Circle Collider 2D
Box Collider 2D
Capsule Collider 2D
Edge Collider 2D
Polygon Collider 2D
Auto Tiling
: Check it to allow the collider shape to keep updated from Spriteâs dimensions. The Sprite RendererâsDraw Mode
need to be set toTiled
to make this work.
Composite Collider 2D
- Can only merge Box and Polygon Collider 2Ds.
Geometry Type
:Outlines
makes it effectively an Edge Collider 2D,Polygon
Polygon.Generation Type
:Synchronous
makes the composite always updated when its sub-colliders change. InManual
you need to recalculate it usingCompositeCollider2D.GenerateGeometry()
.Vertex Distance
: Minimum spacing allowed among vertices. Think of this as collision resolution.Edge Radius
: WhenGeometry Type
isOutlines
, setting this higher than 0 gives a larger collider with rounded convex corners.
Material 2D
- Physics Material should not be confused with Rendering Material.
Friction
: does not seem to have an upper limit or threshold value; but, the higher this value is the higher the friction would be. This is different from linear/angular drag in that it triggers only when GameObjects collide.Bounciness
: 0 is no bounce, 1 is perfect bounce. It is possible to set a value higher than 1.- Empirical values:
- Icy ground: (0, 0)
- Bouncy ball: (0.2, 0.8)
Joint 2D
Joint General
- 2D joints work with both 2D and 3D GameObjects.
- Constraint: All joints constrain GameObjects in some way (âlimitingâ it, âdrivingâ it). When GameObjects, subject to some external reason, temporarily breaks out from the constraint, joints would try fix this situation over time.
- Joint Break: When GameObject experience a force/torque that exceeds limit, joint breaks and the component deletes itself from its GameObject. Relevant options:
Break Force
,Break Torque
. Connected Rigidbody
: bind the current GameObject to another Rigidbody 2D. Leaving it blank to bind to the fixed space. If bound to a gameobject, you can checkEnable Collision
to allow these two to collide.Anchor
is the connection point at this gameobject,Connected Anchor
is the connection point at the attached gameobject/world. The coordinates are in local space if attached to an gameobject, and in world otherwise.
Hinge Joint 2D
Motor Speed
is the speed at which motor runs in normal situation; when the gameobject breaks away from the constraint, the joint attempts to bring it back but with a maximum corrective force specified byMaximum Motor Force
. The larger the force, the faster the correction.- You can achieve effects like scissors, auto-closing door, see-saw, and rotating platforms.
Distance Joint 2D
- It is not a âabsolutely hardâ joint, but it is pretty hard. It is still possible to break away from the set distance but the joint would bring back the gameobject as fast as possible.
Max Distance Only
lets theDistance
value to be just a max value, rather than both a max and min value. In this case, the min value is 0.- You can achieve effects like hanging ball, yo-yo.
Fixed Joint 2D
Friction Joint 2D
Relative Joint 2D
Slider Joint 2D
Spring Joint 2D
Target Joint 2D
Wheel Joint 2D
Effector 2D
Effector General
- Add force to gameobjects in a certain area.
Force Direction
,Force Magnitude
,Force Variation
:Force Direction
is clamped in 0 - 359.99. It uses degrees. Be careful to note whether this angle is in world or local space.Force Magnitude
can be both negative and positive. Usually positive is repulsion and negative is attraction.Force Variation
is not both ways! Hence, it can also be negative and positive. For example, if it is set to 4, then a noise of 0 to 4 can be added to the original force. If it is set to -4, then the noise range is -4 to 0.
Drag
,Angular Drag
: Applies another drag/angular drag on top of the original drag/angular drag specified in Rigidbody 2D.- A large
Drag
can drain the gameobjectâs movements in other directions and better forces the gameobject to move in the specified direction of Area Effector 2D. - A large
Drag
might also be used to smoothen out the movement in Point Effect 2D, preventing the gameobject from overshooting its target point and oscillating. - A large
Angular Drag
prevents the gameobject from rotating too fast (not visually pleasing) in the area.
- A large
Force Target
: SelectingCollider
might generate torque if the Collider 2D is not at CM (the object collider is in an irregular shape); selectingRigidbody
will always apply force to CM and always not generating torque.- When you have an irregularly shaped object you probably want it to rotate under external force field. Hence, select
Collider
.
- When you have an irregularly shaped object you probably want it to rotate under external force field. Hence, select
Area Effector 2D
- Works usually with Collider 2D set to trigger.
Use Global Angle
: If unchecked, the direction of the force is defined in local space. So, when the gameobject with effector rotates, the force direction rotates.
Point Effector 2D
Force Source
: UsingCollider
as the source allows you to adjust the offset of center of force of Point Effector 2D using offset of collider.Distance Scale
is used withInverse Linear
andInverse Squared
mode to control a coefficient of changing rate.
Buoyancy Effector 2D
Platform Effector 2D
Surface Effector 2D
Constant Force 2D
- A component used to apply a constant force/torque to the Rigidbody 2D attached to the same Gameobject.
Force
uses global coordinates (so it is indepedent of gameobjectâs current rotation),Relative Force
uses local coordinates.
Raycast 2D
- For Physics 2D Raycaster: a gameobject must have a Collider 2D and it must not be a trigger. There is no need for Rigidbody 2D to present. If the gameobject does have a Rigidbody 2D and it is set to not simulating or sleeping, however, raycasting would not find the object.
- Core APIs:
Physics2D.Raycast(Vector 2 origin, Vector 2 dir, float distance, int layerMask)
returns anRaycastHit2D
object. You can directly test this object like a boolean value to check whether anything is hit. There are two more arguments that are rarely used.- The
RaycastHit2D
objects have reference to the relevant gameobjectâscollider
,rigidbody
,transform
, and hit information likedistance
,point
. - There is also a
Physics2D.RaycastAll
that tries to return all object in ray range (instead of being blocked by the first gameobject hit).
- Make the length and layer masks as restricted as possible.
- Donât use use Raycasts inside a
FixedUpdate()
function, sometimes even inside anUpdate()
may be an overkill.
- Donât use use Raycasts inside a
- Relevant static methods:
BoxCast
,BoxCastAll
,CircleCast
âŠOverlapArea
,OverlapAreaAll
,OverlapBox
âŠ
Other Utility Method
- ClosestPoint
- Distance
- GetContacts
- GetIgnoreCollision, GetIgnoreLayerCollision, GetIgnoreCollisionMask
- IsTouching, IsTouchingLayers
- IgnoreCollision, IgnoreLayerCollision
Buy me a cup of coffee?
- Post link: https://reimirno.github.io/2021/11/23/Unity-2D-Collections/
- Copyright Notice: All articles in this blog are licensed under unless otherwise stated.
GitHub Discussions