Lecture 12
Lecture 12
Game Programming
Aims of the lecture
Vectors 2D
2D Physics
◦ Rigidbodies2D
◦ Colliders
◦ Joints
◦ Effectors
◦ Physics Materials
◦ Adding Force and Torque
◦ Gravity
◦ Raycasting
https://docs.unity3d.com/Manual/Physics2DReference.html
2D Physics
Unity has a separate physics engine for handling 2D physics so as
to make use of optimizations only available with 2D. The
fundamentals in both physics systems (2D and 3D) are equivalent.
Most 2D physics components are simply flattened versions of the
3D equivalents, but there are a few exceptions. These
components are:
◦ Rigidbodies2D.
◦ 2D Colliders:
Circle Collider 2D, Box Collider 2D, Polygon Collider 2D, Edge Collider 2D,
Capsule Collider 2D, Composite Collider 2D
◦ Joints:
Distance Joint 2D, Fixed Joint 2D, Friction Joint 2D, Hinge Joint 2D, Relative Joint
2D, Slider Joint 2D, Spring Joint 2D, Target Joint 2D, Wheel Joint 2D
◦ Forces and Torque in 2D.
◦ Effectors 2D
We'll also look at Physic Materials 2D and Raycasting in this
lecture.
2D Physics
2D versus 3D physics:
◦ 2D and 3D physics can be used together (they can be present in the
same scene) but they won't interact with each other.
◦ There is no concept of depth in 2D: All 2D physics occur in the XY plane,
with Z = 0. All physics interactions takes places at Z axis position 0.
◦ Game objects in 2D can only move along the XY axis and rotate around
the Z axis.
Rigidbody 2D
Attaching a rigidbody 2D component to a game object places the object
under the control of the physics 2D engine: it will respond to forces applied
through the scripting API.
Since a Rigidbody2D component takes over the movement of the object it
is attached to, you should not try to move it from a script by changing the
Transform properties such as position and rotation. Instead, you should
apply forces to push the object and let the physics engine calculate the
results.
Rigidbody 2D
Parameters (in 2D):
Body Type: Set the RigidBody 2D’s component settings, so
that you can manipulate movement (position and rotation)
behavior and Collider 2D interaction.
◦ Dynamic: The rigidbody 2D is designed to move under
simulation. It collides with every other body type, and is the
most interactive of body types.
◦ Kinematic: The rigidbody does not react to gravity or collisions.
It is designed to move under simulation, but only under very
explicit user control.
◦ Static: The rigidbody does not move under simulation at all; if
anything collides with it, a Static Rigidbody 2D behaves like an
immovable object (as though it has infinite mass).
Rigidbody 2D
Material: Used to specify a common material for all Collider 2Ds attached
to a specific parent Rigidbody 2D.
Simulated: Property to stop (unchecked) and start (checked) a Rigidbody
2D and any attached Collider 2Ds and Joint 2Ds from interacting with the
2D physics simulation.
Use Auto Mass: Rigidbody 2D automatically detect the GameObject’s
mass from its Collider 2D.
Mass: The mass of the object (arbitrary units).
Linear Drag: How much air resistance a affects the object when moving
from forces. 0 means no air resistance, and in Unity makes the object stop
moving immediately.
Angular Drag: How much air resistance a affects the object when rotating
from torque. 0 means no air resistance.
Gravity scale: Degree to which the object is affected by gravity.
Rigidbody 2D
Collision Detection:
◦ Discrete: Normal collision detection.
◦ Continuous: prevents fast-moving colliders from passing each other. This
may happen when using normal (Discrete) collision detection, when an
object is one side of a collider in one frame, and already passed the
collider in the next frame.
Sleeping Mode: Define how the GameObject “sleeps” to save
processor time when it is at rest. Once a rigidbody is moving at less than a
certain minimum linear or rotational speed, the physics engine will assume
it has come to a halt. When this happens, the object will not move again
until it receives a collision or force and so it will be set to sleeping mode.
This optimisation means that no processor time will be spent updating the
rigidbody until the next time it is set in motion again.
◦ Never Sleep: Sleeping is disabled (this should be avoided where possible, as it can
impact system resources).
◦ Start Awake: GameObject is initially awake.
◦ Start Asleep: GameObject is initially asleep but can be woken by collisions.
Rigidbody 2D
Interpolate: (The process of calculating values in-between two
defined values. (between physics time-steps)
◦ None: no interpolation (default).
◦ Interpolate: Transform smoothed based on the position of the previous
frames.
◦ Extrapolate: Transform smoothed based on the current velocity.
Constraints: Define any restrictions on the Rigidbody 2D’s
motion.
Freeze Position: Stops the Rigidbody 2D moving in the world X & Y
axes selectively.
Freeze Rotation: Stops the Rigidbody 2D rotating around the Z axes
selectively.
Kinematic game objects
If a game object is kinematic, the rigidbody does not react
to gravity or collisions. A kinematic body is meant to be
moved only by changing its transform.
Kinematic Rigidbody 2D is designed to be repositioned
explicitly via Rigidbody2D.MovePosition or
Rigidbody2D.MoveRotation. Use physics queries to detect
collisions, and scripts to decide where and how the
Rigidbody 2D should move.
Collider 2D (1/3)
Collider 2D
Collider 2D
Capsule Collider 2D: The Capsule Collider 2D component is a 2D physics
primitive that you can elongate in either a vertical or horizontal direction.
The capsule shape has no vertex corners; it has a continuous
circumference, which doesn’t get easily caught on other collider corners.
The capsule shape is solid, so any other Collider 2Ds that are fully inside
the capsule are considered to be in contact with the capsule and are forced
out of it over time.
Capsule configuration examples
Collider 2D
Composite Collider 2D: The Composite Collider 2D component
is a Collider for use with 2D physics. Unlike most colliders, it does
not define an inherent shape. Instead, it merges the shapes of
any Box Collider 2D or Polygon Collider 2D that you set it up to
use. The Composite Collider 2D uses the vertices (geometry) from
any of these Colliders, and merges them together into new
geometry controlled by the Composite Collider 2D itself.
Collider 2D
Physics Material 2D
Joints
Joints attach GameObjects together. It allows dynamic
connection between rigidbodies, usually allowing some
degree of movement.
Joints are used to restrict one object's movement so it
depends on another object. This dependence is implemented
by physics, instead of parenting in an object hierarchy.
◦ Distance Joint 2D
◦ Fixed Joint 2D
◦ Friction Joint 2D
◦ Hinge Joint 2D
◦ Relative Joint 2D
◦ Slider Joint 2D
◦ Spring Joint 2D
◦ Target Joint 2D
◦ Wheel Joint 2D
Hinge Joint 2D
Spring Joint 2D
Distance Joint 2D
Joints
Fixed Joint 2D: Apply this component to two GameObjects controlled by
Rigidbody2D physics to keep them in a position relative to each other, so
the GameObjects are always offset at a given position and angle.
Relative Joint 2D: This joint component allows two game objects
controlled by rigidbody physics to maintain in a position based on each
other’s location. Use this joint to keep two objects offset from each other,
at a position and angle you decide.
Joints
Slider Joint 2D: This joint allows a game object controlled by rigidbody
physics to slide along a line in space, like sliding doors, for example. The
object can freely move anywhere along the line in response to collisions or
forces or, alternatively, it can be moved along by a motor force, with limits
applied to keep its position within a certain section of the line.
Target Joint 2D: This joint connects to a specified target, rather than
another rigid body object, as other joints do. It is a spring type joint, which
you could use for picking up and moving an object acting under gravity, for
example.
◦ Force: The linear force applied to the Rigidbody 2D at each physics update.
◦ Relative Force: The linear force, relative to the Rigidbody 2D coordinate system,
applied each physics update.
◦ Torque: The torque applied to the Rigidbody 2D at each physics update.
Effector 2D
Effector 2D components is used with Collider 2D
components to direct the forces of physics when
GameObject colliders come into contact with each other.
◦ SurfaceEffector2D - Create conveyor belts
◦ AreaEffector2D - Randomly vary force and angle magnitude
◦ PlatformEffector2D - Create ‘platform’ behaviour such as one-way
collisions
◦ PointEffector2D - Attract or repulse against a given source point
◦ BuoyancyEffector2D - Make GameObjects float
PlatformEffector2D
The Platform Effector 2D applies various “platform”
behaviour such as one-way collisions, removal of side-
friction/bounce etc.
Point Effector 2D
It is an effector that gives "pulling" or "repelling" power
from the center to the objects in the range .
Area Effector 2D
Give force to the object in the range from the specified direction.
Surface Effector 2D
The Surface Effector 2D applies tangent forces along the surfaces
of colliders used by the effector in an attempt to match a specified
speed along the surface.
Buoyancy Effector 2D
The Buoyancy Effector 2D defines simple fluid behaviour
such as floating and the drag and flow of fluid.
Constant Force
Utility for adding constant forces to a Rigidbody 2D. This works well for
one-shot objects like rockets, if you want them to accelerate over time
rather than starting with a large velocity.
Constant Force 2D applies both linear and torque (angular) forces
continuously to the Rigidbody 2D, each time the physics engine
updates at runtime.
RayCasting
A ray is an infinite line starting at origin and going in some
direction.
A raycast is used to detect objects that lie along the path of
a ray and is conceptually like a laser beam that is fired from a
point in space along a particular direction. Any object making
contact with the beam can be detected and reported.
Game developers use raycasting all the time for things like
aiming, determining line of sight, gauging distance, and more
Basic Raycast Syntax
if (Physics.Raycast(origin, direction, out RaycastHit hitInfo,
maxDistance, layerMask))
{
// Do something with hitInfo, which contains information
about the hit object
}
void Update()
{
if (Input.GetMouseButtonDown(0)) // Left-click
{
Ray ray =
Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out RaycastHit hitInfo))
{
Debug.Log("Hit: " + hitInfo.collider.name); // Print the
name of the object hit
// Additional logic can go here, such as selecting the object
}
}
}
Example Ray casting- Shooting
Mechanics
When a player fires a weapon, a raycast can detect whether the shot
hits an enemy or obstacle.
void Shoot()
{
RaycastHit hit;
if (Physics.Raycast(transform.position, transform.forward, out hit,
shootingRange))
{
if (hit.collider.CompareTag("Enemy"))
{
Debug.Log("Enemy hit!");
// Apply damage to enemy
}
}
}
Example Ray casting- Player Interaction
(Selecting Objects)
Raycasts from the camera or player’s position allow selecting items
in the world.
void SelectObject()
{
if (Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out RaycastHit hit))
{
Debug.Log("Selected object: " + hit.collider.name);
}
}
}
Physics 2D Settings - The
physics 2D Manager
Task 03
During this task you will practice the concepts given in the
class.
Create a 2D scene and implement 2D physics concepts;
experiment with the different colliders, joints, effectors..
Bouncing & Sliding in 2D
https://unity3d.com/learn/tutorials/topics/2d-game-creation/bouncing-slidin
g-2d