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!
  • 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)
  • 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.
  • 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 other Dynamic GameObject through collider2D.
      • This is usually for things like moving platform whose movement is controlled by scripts rather than physics engine using Rigidbody2D.MovePosition and MoveRotation.
      • 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 or Kinematic GameObjects (but trigger would still fire), unless this is demanded in Use Full Kinematic Contacts.
    • 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 when Body 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.
  • Interpolate: When the GameObject moved by rigidbody appears jittering, checking Interpolate (smooth using last frame) or Extrapolate(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()
  • Collision Detection: Best just keep as Discrete 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 in Default.
  • 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’s Draw Mode need to be set to Tiled 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. In Manual you need to recalculate it using CompositeCollider2D.GenerateGeometry().
  • Vertex Distance: Minimum spacing allowed among vertices. Think of this as collision resolution.
  • Edge Radius: When Geometry Type is Outlines, 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 check Enable 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 by Maximum 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 the Distance 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.
  • Force Target: Selecting Collider might generate torque if the Collider 2D is not at CM (the object collider is in an irregular shape); selecting Rigidbody 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.

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: Using Collider 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 with Inverse Linear and Inverse 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 an RaycastHit2D 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’s collider, rigidbody, transform, and hit information like distance, 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 an Update() may be an overkill.
  • Relevant static methods:
    • BoxCast, BoxCastAll, CircleCast 

    • OverlapArea, OverlapAreaAll, OverlapBox 


Other Utility Method

  • ClosestPoint
  • Distance
  • GetContacts
  • GetIgnoreCollision, GetIgnoreLayerCollision, GetIgnoreCollisionMask
  • IsTouching, IsTouchingLayers
  • IgnoreCollision, IgnoreLayerCollision