Physics

Unity Logo

Are we recording?

Meow Cam

Review

What are properties?

  • A convenient way of providing encapsulation for your fields

Review

What is a delegate?

  • A reference type variable that can hold a reference to one or more methods

Review

What is a coroutine?

  • Special methods that can be executed over several frames by the engine

Collision vs Physics

  • Collision is whether two objects intersect
  • Physics for our purposes is collision + applied force

Meshes

They are the objects that we will be applying physics on. You can think of them as sets of triangles (or vertices, edges and faces). In unity we use meshes with the Mesh Filter and Mesh Renderer component.

Suzanne

Quick blender demo

Bounding Volumes

Simple shapes that completely contain an object. Used for optimizing collision detection. The most popular bounding volumes are bounding boxes, spheres and capsules.

Boxed Suzanne
Suzanne in a sphere

Axis Aligned Bounding Box
(AABB)

Suzanne Hierarchy
						
bool Intersect(Bounds a, Bounds b) {
	return (a.min.x <= b.max.x && a.max.x >= b.min.x)
	    && (a.min.y <= b.max.y && a.max.y >= b.min.y)
	    && (a.min.z <= b.max.z && a.max.z >= b.min.z);
}
						
					

Bounding Spheres

Suzanne Hierarchy
						
bool Intersect(Vector3 aCenter, float aRadius, 
               Vector3 bCenter, float bRadius) {
  float distance = Mathf.Sqrt(
	  (aCenter.x - bCenter.x) * (aCenter.x - bCenter.x) +
	  (aCenter.y - bCenter.y) * (aCenter.y - bCenter.y) +
	  (aCenter.z - bCenter.z) * (aCenter.z - bCenter.z));
  return distance < (aRadius + bRadius);
}
						
					

Bounding Volume Hierarchies

A tree structure of bounding volumes. Can make the time complexity of the collision detection algorithm logarithmic in the number of objects.

Suzanne Hierarchy

Colliders 3D

  • Unity's implementation of 3D bounding volumes
  • Invisible in Game View
  • GameObjects can have multiple colliders (compound colliders)
  • Examples:
    • Box Collider
    • Sphere Collider
    • Capsule Collider

Colliders 2D

  • Unity's implementation of 2D bounding volumes
  • Are incompatible with 3D colliders
  • Work in a separate 2D Physics Engine
  • Examples:
    • Box Collider 2D
    • Circle Collider 2D
    • Capsule Collider 2D
    • Polygon Collider 2D

Mesh Colliders

If even compound colliders don't offer enough precission then we can use Mesh Colliders to match the shape of the GameObject’s mesh exactly.

Suzanne Mesh Collider

Important!

Mesh Colliders don't collide with other Mesh Colliders. For that to happen we need to make them into convex hulls.

Click Convex Hull

Triggers

By default colliders work for physics. To make them work just for collision we have to make them triggers. In scripts we work with triggers differently.

Click Is Trigger( ͡° ͜ʖ ͡°)╭∩╮

FixedUpdate

  • The framerate independent version of Update
  • Called 50 times a second
  • Use Time.fixedDeltaTime instead of Time.deltaTime
  • Used for physics calculations

RigidBody(3D)

  • Unity's implementation for 3D physics
  • Applies physical forces on a GameObject based on its colliders
  • Allows modification of gravity
  • Has properties like Mass and Drag

RigidBody in action

Falling block

RigidBody Code

						
RigidBody body = GetComponent<RigidBody>();
// All forces are applied for the period of fixedDeltaTime

// Apply Force
body.AddForce(Vector3 force, ForceMode mode = ForceMode.Force);

// Apply Torque
body.AddTorque(Vector3 torque, ForceMode mode = ForceMode.Force);

// Move the RigidBody towards a position
body.MovePosition(Vector3 position);
						
					

RigidBody2D

  • Unity's implementation for 2D physics
  • Provides the same functionality in 2D that the Rigidbody component provides in 3D
  • Is incompatible with the regular Rigidbody
  • Works in a separate 2D Physics Engine

Static Colliders

When a GameObject has a collider but doesn't have a RigidBody

  • Used for motionless objects
  • Don't change their transform because that could cause errors in the physics engine!
  • Example usage:
    • Ground Terrain
    • Buildings
    • Walls

Physics Materials

  • Can give additional properties to colliders like friction and bounciness

Kinematic Rigidbody Collider

Controls whether physics affects the rigidbody

  • Example usage:
    • Sliding Doors
    • Traps
Click Is Kinematic(╯°□°)╯︵ ┻━┻

Physics Loop - Collisions

						
// XXX can be:
//   Enter - Called the first frame when this collider 
//           touches another collider
//   Stay  - Called once per frame for every collider 
//           that is touching this collider
//   Exit  - Called when this collider stops touching 
//           other colliders
// For 2D collisions:
//   OnCollisionXXX2D(Collision2D collisionInfo) {...} 
void OnCollisionXXX(Collision collisionInfo) {
	if (collisionInfo.gameObject.CompareTag("Enemy")) {
		Destroy(collisionInfo.gameObject);
	}
}
						
					

Physics Loop - Triggers

						
	// XXX is the same as for collisions:
	//   Enter
	//   Stay
	//   Exit
	// ----------------------------------
	// For 2D triggers:
	//   OnTriggerXXX2D(Collider2D collision) {...} 
	private void OnTriggerXXX(Collider other) {
		if (other.CompareTag("MyTag")) {
			Destroy(other.gameObject);
		}
	}
						
					

Physics Layers

  • Every GameObject belongs to a Physics Layer
  • We can define our own custom physics layers
  • Can be used in Raycast LayerMasks
  • We can customize which layer can collide with which other layer:
    Edit/Project Settings/Physics/Layer Collision Matrix
Layer Collision Matrix

Raycasting 3D

Cast a ray from some point in some direction and return information on what was hit

						
void Foo() {
	int mask = LayerMask.GetMask("MyCustomLayer", "Other");
	float rayLength = 200;
	Vector3 origin = ...;
	Vector3 direction = ...;
	if (Physics.Raycast(origin, 
	                    direction,
	                    out RaycastHit hit, 
	                    rayLength, 
	                    mask, 
	                    QueryTriggerInteraction.Collide)) {
		//...
	}
}
						
					

Raycasting 2D

						
void Foo() {
	int mask = LayerMask.GetMask("MyCustomLayer", "Other");
	float rayLength = 200;
	Vector3 origin = ...;
	Vector3 direction = ...;
	RaycastHit2D hitInfo = Physics2D.Raycast(origin, 
	                                         direction, 
	                                         rayLength, 
	                                         mask);
	if (hitInfo.collider != null) {
		//...
	}
}
						
					

Debugging Raycasts

						
// Draw a line from start to start + dir in world coordinates
Debug.DrawRay(Vector3 start, Vector3 dir);

// Draw a line between specified start and end points
Debug.DrawLine(Vector3 start, Vector3 end);
						
					

Shape Casting 3D

  • Cast the shape along a ray with:
    • Physics.[Box|Sphere|Capsule]Cast
  • Check all colliders touching or inside a shape with:
    • Physics.Overlap[Box|Sphere|Capsule]

Shape Casting vs Overlap

Overlap vs Shapecast

Shape Casting 2D

  • The 2D equivalent of shape casting:
    • Physics.Overlap[Box|Circle|Capsule]
    • Physics.[Box|Circle|Capsule]Cast

RaycastAll

  • All physics XXXCast methods have an XXXCastAll variant
  • A regular cast detects a collision with only the object hit
  • An all-cast detects all hit objects

Questions?

Question Cat