0% found this document useful (0 votes)
10 views49 pages

Slides 18

Uploaded by

huangzhouexport
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views49 pages

Slides 18

Uploaded by

huangzhouexport
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

the

gamedesigninitiative
at cornell university

Lecture 18

box2d Physics
Physics in Games

— Moving objects about the screen


— Kinematics: Motion ignoring external forces
(Only consider position, velocity, acceleration)
— Dynamics: The effect of forces on the screen

— Collisions between objects


— Collision Detection: Did a collision occur?
— Collision Resolution: What do we do?

the
2 Physics Overview gamedesigninitiative
at cornell university
Physics in Games

— Moving objects about the screen


— Kinematics: Motion ignoring external forces
lass Bod
(Only considerCposition, y
velocity, acceleration)
— Dynamics: The effect of forces on the screen

— Collisions between objects


— Collision Detection: Did a collision occur?
C la s s Fixture
— Collision Resolution: What do we do?

the
3 Physics Overview gamedesigninitiative
at cornell university
Body in box2d
— Represents a single point
— Center of the object’s mass
— Object must move as unit
— Properties in class Body
— Position
— Linear Velocity
Body
— Angular Velocity
— Body Type
— There are 3 body types
— Static: Does not move
— Kinematic: Moves w/o force
— Dynamic: Obeys forces
the
4 Collisions gamedesigninitiative
at cornell university
Body in box2d
— Represents a single point
— Center of the object’s mass
Linear
— Object must move as unit
Velocity
— Properties in class Body Angular
Velocity
— Position
— Linear Velocity
— Angular Velocity
— Body Type Position
— There are 3 body types
— Static: Does not move
— Kinematic: Moves w/o force
— Dynamic: Obeys forces
the
5 Collisions gamedesigninitiative
at cornell university
Body in box2d
— Represents a single point — Kinematic is rarely useful
— Center of the object’s mass — Limited collision detection
— Object must move as unit — Only collides w/ dynamics
— Properties in class Body — Does not bounce or react
— Position
— Application: Bullets
— Linear Velocity
— Light, fast-moving objects
— Angular Velocity
— Body Type
— Should not bounce

— There are 3 body types


— Static: Does not move Looks like
— Kinematic: Moves w/o force last lecture
— Dynamic: Obeys forces
the
6 Collisions gamedesigninitiative
at cornell university
Forces vs. Impulses

Forces Impulses

— Instantaneous push — Push with duration


— To be applied over time — To be applied in one frame
— Gradually accelerates — Quickly accelerates
— Momentum if sustained — Immediate momentum

Impulse
Impulse = Force x Time

the
7 Collisions gamedesigninitiative
at cornell university
Forces vs. Impulses

Forces Impulses

— Instantaneous push — Push with duration


— To be applied over time — To be applied in one frame
— Gradually accelerates — Quickly accelerates
— Momentum if sustained — Immediate momentum

Impulse
Impulse = Force x 1 Sec

in Box2D
the
8 Collisions gamedesigninitiative
at cornell university
Force and Acceleration
— What do we need to compute motion?
— Dp = vDt = v0Dt + ½a(Dt)2 = v0Dt + ½(F/m)(Dt)2
— So depends on Force, current velocity and mass
— Where does that mass come from?
— Class Body has a getter, but no setter!
— It comes from the Fixture class
— Fixture gives volume to body
— Will revisit this later with collisions
the
9 Collisions gamedesigninitiative
at cornell university
Force and Acceleration
— What do we need to compute motion?
— Dp = vDt = v0Dt + ½a(Dt)2 = v0Dt + ½(F/m)(Dt)2
— So depends on Force, current velocity and mass
— Where does that mass come from?
— Class Body has a getter, but no setter!
— It comes from the Fixture class
— Fixture gives volume to body
— Will revisit this later with collisions
the
10 Collisions gamedesigninitiative
at cornell university
Four Ways to Move a Dynamic Body
— Forces
— applyForce (linear)
— applyTorque (angular) Force
Torque
— Impulses
— applyLinearImpulse
— applyAngularImpulse
— Velocity
— setLinearVelocity
— setAngularVelocity
— Translation
— setTransform

the
11 Collisions gamedesigninitiative
at cornell university
Four Ways to Move a Dynamic Body
— Forces — Great for joints, complex shapes
— applyForce (linear) — Laggy response to user input
— applyTorque (angular) — A bit hard to control
— Impulses — Great for joints, complex shapes
— applyLinearImpulse — Good response to user input
— applyAngularImpulse — Extremely hard to control
— Velocity — Bad for joints, complex shapes
— setLinearVelocity — Excellent response to user input
— setAngularVelocity — Very easy to control
— Translation — Completely ignores physics!
— setTransform — Very easy to control
the
12 Collisions gamedesigninitiative
at cornell university
Example: box2d Demo

the
13 Collisions gamedesigninitiative
at cornell university
Example: box2d Demo

Controls:
— WASD for linear force
— Left-right arrows to rotate
— 9 or 0 to change controls

the
14 Collisions gamedesigninitiative
at cornell university
Four Ways to Move a Dynamic Body
— Forces
— applyForce (linear)
— applyTorque (angular)
— Impulses Must Cap Velocity
— applyLinearImpulse
— applyAngularImpulse
— Velocity
— setLinearVelocity
— setAngularVelocity
— Translation
— setTransform

the
15 Collisions gamedesigninitiative
at cornell university
Basic Structure of a Update Loop

public void update(float dt) {


// Apply movement to relevant bodies
if (body above or equal to max velocity) {
body.setLinearVelocity(maximum velocity);
} else {
body.applyForce(force)
body.applyTorque(torque)
}
// Use physics engine to update positions
world.step(dt,vel_iterations,pos_iterations);
}
the
16 Collisions gamedesigninitiative
at cornell university
Basic Structure of a Update Loop

public void update(float dt) {


// Apply movement to relevant bodies
if (body above or equal to max velocity) {
body.setLinearVelocity(maximum velocity);
} else {
body.applyForce(force)
body.applyTorque(torque)
}
// Use physics engine to update positions
world.step(dt,vel_iterations,pos_iterations);
} Multiple times to
improve accuracy the
17 Collisions gamedesigninitiative
at cornell university
Basic Structure of a Update Loop

public void update(float dt) {


// Apply movement to relevant bodies
if (body above or equal to max velocity) {
body.setLinearVelocity(maximum velocity);
} else { Only before
body.applyForce(force) first iteration!
body.applyTorque(torque)
}
// Use physics engine to update positions
world.step(dt,vel_iterations,pos_iterations);
} Multiple times to
improve accuracy the
18 Collisions gamedesigninitiative
at cornell university
Collision Objects in box2d

Shape Fixture

— Stores the object geometry — Attaches a shape to a body


— Boxes, circles or polygons — Fixture has only one body
— Must be convex! — Bodies have many fixtures
— Has own coordinate space — Cannot change the shape
— Associated body is origin — Must destroy old fixture
— Unaffected if body moved — Must make a new fixture
— Cannot be resized later — Has other properties
— Also stores object density — Friction: stickiness
— Mass is area x density — Restitution: bounciness
the
19 Collisions gamedesigninitiative
at cornell university
Making a box2d Physics Object
// Create a body definition
// (this can be reused)
bodydef = new BodyDef();
bodydef.type = type;
bodydef.position.set(position);
bodydef.angle = angle;

// Allocate the body


body1 = world.createBody(bodydef);

// Another?
bodydef.position.set(position2);
body2 = world.createBody(bodydef);

the
20 Collisions gamedesigninitiative
at cornell university
Making a box2d Physics Object
// Create a body definition
// (this can be reused)
bodydef = new BodyDef();
bodydef.type = type;
bodydef.position.set(position);
Normal Allocation
bodydef.angle = angle;

// Allocate the body


body1 = world.createBody(bodydef);

// Another? Optimized Allocation


bodydef.position.set(position2);
body2 = world.createBody(bodydef);

the
21 Collisions gamedesigninitiative
at cornell university
Making a box2d Physics Object
// Create two triangles as shapes
shape1 = new PolygonShape().;
shape2 = new PolygonShape();
shape1.set(verts1); shape2.set(verts2);

// Create a fixture definition


fixdef = new FixtureDef();
fixdef.density = density;

// Attach the two shapes to body


fixdef.shape = shape1;
fixture1 = body1.createFixture(fixdef);
fixdef.shape = shape2;
fixture2 = body1.createFixture(fixdef);

the
22 Collisions gamedesigninitiative
at cornell university
Making a box2d Physics Object
// Create two triangles as shapes
shape1 = new PolygonShape().;
Other shapes possible shape2 = new PolygonShape();
shape1.set(verts1); shape2.set(verts2);

// Create a fixture definition


Also set friction and fixdef = new FixtureDef();
restitution parameters fixdef.density = density;

// Attach the two shapes to body


fixdef.shape = shape1;
Reason for separating fixture1 = body1.createFixture(fixdef);
Fixture & Body classes fixdef.shape = shape2;
fixture2 = body1.createFixture(fixdef);

the
23 Collisions gamedesigninitiative
at cornell university
Making a box2d Physics Object
// Create a body definition // Create two triangles as shapes
// (this can be reused) shape1 = new PolygonShape().;
bodydef = new BodyDef(); shape2 = new PolygonShape();
bodydef.type = type; shape1.set(verts1); shape2.set(verts2);
bodydef.position.set(position); // Create a fixture definition
bodydef.angle = angle; fixdef = new FixtureDef();
fixdef.density = density;
// Allocate the body
body1 = world.createBody(bodydef); // Attach the two shapes to body
fixdef.shape = shape1;
// Another? fixture1 = body1.createFixture(fixdef);
bodydef.position.set(position2); fixdef.shape = shape2;
body2 = world.createBody(bodydef); fixture2 = body1.createFixture(fixdef);

the
24 Collisions gamedesigninitiative
at cornell university
Observations on Fixture Parameters
— Density can be anything non-zero
— The higher the density the higher the mass
— Heavier objects are harder to move
— Friction should be within 0 to 1
— Can be larger, but effects are unpredictable
— Affects everything, even manual velocity control
— Restitution should be within 0 to 1
— A value of 0 means no bounciness at all
— Unpredictable with manual velocity control
the
25 Collisions gamedesigninitiative
at cornell university
A Word on Units
— Size is not in pixels
— 1 box2d unit = 1 meter
1.5 60
— Also 1 density = 1 kg/m2
b2d units pixels
— Drawing scale in Lab 4
— This is rescalable
— Could say 1 unit = 10 m
— But must be consistent
60
— box2d likes units near 1 b2d units
— Best if objects same size
— Adjust scale so 1 default
the
26 Collisions gamedesigninitiative
at cornell university
Example: Box2D Demo

the
27 Collisions gamedesigninitiative
at cornell university
Example: Box2D Demo

Controls:
— 1 or 2 to change density
— 3 or 4 to change friction
— 5 or 6 to change restitution
— 7 or 8 to change shape

the
28 Collisions gamedesigninitiative
at cornell university
How Do We Find the Shape?
— Do not try to learn boundary
— Image recognition is hard
— Hull will have many sides

— Have artists draw the shape


— Cover shape with triangles
— But can ignore interiors
— Keep # sides small!

— Store shape in another file


— Do not ruin the art!
— Need coordinates as data

the
29 Collisions gamedesigninitiative
at cornell university
Data-Driven Design

character.jpg character.shape

120,2
130,4
125,50
150,65
160,100
150,110
125,80
140,200
130,200
120,110

the
30 Collisions gamedesigninitiative
at cornell university
Custom Collisions: ContactListeners
— Special listener attached to world object
— Reacts to any two fixtures that collide
— Allow you to override collision behavior
— Or you can augment collision behavior
— Two primary methods in interface
— beginContact: When objects first collide
— endContact: When objects no longer collide
— Example: Color changing in box2d demo
the
31 Collisions gamedesigninitiative
at cornell university
Collision is About Fixtures!

— Capsule obstacle is two circles and rectangle


— Allows smooth motion while walking
— Feet do not get hung up on surfaces
— But may register multiple collisions!
the
32 Collisions gamedesigninitiative
at cornell university
Collision Filtering
— FixtureDef has a Filter attribute
— categoryBits: Defines what can collide with it
— maskBits: Defines what it can collide with
— groupIndex: Collision group (overrides bits)
— Example:
— Fixture A category x001, Fixture B category x010
— Mask x101 or x001 only collides with A
— Mask x011 collides with both A and B
the
33 Collisions gamedesigninitiative
at cornell university
Collision Filtering
— FixtureDef has a Filter attribute
— categoryBits: Defines what can collide with it
— maskBits: Defines what it can collide with
— groupIndex: Collision group (overrides bits)
— Example:
— Fixture A category x001, Fixture B category x010
— Mask x101 or x001 only v e
collides
n e r d e
withte c
A te d !
g m e a n s is
Filterin
— Mask x011 collides with both A and B
the
34 Collisions gamedesigninitiative
at cornell university
How about Sort-of-Filtering?
— Want a non-sensor object where
— We always detect the collision
— But sometimes ignore the restitution
— Method beginContact has a Contact parameter
— Manages the physics while it resolves collision
— Can call the method contact.isEnabled(false)
— Turns off collision; endContact is never called
— See tutorials for “anatomy of a collision”
— https://www.iforce2d.net/b2dtut/collision-anatomy
the
35 Collisions gamedesigninitiative
at cornell university
Recall: Swept Shapes
— False positives happen if:
— Two objects are moving Blue
Red Frame
— Swept shapes intersect at
different intersection times

— What if only one moving?


— Swept intersects stationary
— So no false positives
— Change reference frames
— Keep one shape still
— Move other in new coords
the
36 Collisions gamedesigninitiative
at cornell university
Recall: Swept Shapes
— False positives happen if:
— Two objects are moving Blue
Red Frame
— Swept shapes intersect at
different intersection times

— What if only one moving?


e ts ” a re h a n d le d
How “Bull
— Swept intersects stationary
— So no false positives
— Change reference frames
— Keep one shape still
Expensive!
— Move other in new coords
the
37 Collisions gamedesigninitiative
at cornell university
More Collisions: RayCasting
— Method rayCast in world
— Give it start, end of ray
— Also a RayCastCallback
— Executed when call step
— Invoked on all collisions
— Not just the first on
— Does not return in order!
— This is for optimization
— Sight-cones = many rays

the
38 Collisions gamedesigninitiative
at cornell university
The RayCastCallback Interface
float reportRayFixture(Fixture fixture, // Fixture found
Vector2 point, // Collision point
Vector2 nom, // Collision normal
float fraction // Fraction of ray
)

— Fraction is how far along ray (0 = start, 1 = end)


— First collision is one with lowest fraction
— But be prepared for larger fractions first
— Return value is optimization to limit search
— Ignores collisions with fraction later than return
the
39 Collisions gamedesigninitiative
at cornell university
The RayCastCallback Interface
float reportRayFixture(Fixture fixture, // Fixture found
Vector2 point, // Collision point
Allowed fraction Vector2 nom, // Collision normal
for future matches
float fraction // Fraction of ray
)

— Fraction is how far along ray (0 = start, 1 = end)


— First collision is one with lowest fraction
— But be prepared for larger fractions first
— Return value is optimization to limit search
— Ignores collisions with fraction later than return
the
40 Collisions gamedesigninitiative
at cornell university
AABB Queries
— Bounding Box queries
— Find all fixtures in box
— Must be axis aligned
— Rotation not allowed
— Similar to raycasting
— Provide callback listener
— Call step method in world
— Prepare for many matches
— Application: selection
— See Ragdoll Demo
the
41 Collisions gamedesigninitiative
at cornell university
Some Words on Joints
— Joints connect bodies
— Anchors can be offset body Rigid Body
— Coordinates relative to body Anchor

— Are affected by fixtures


— Fixtures prevent collisions Joint
(flexible)
— Limit relative movement
— Must control with forces Body
Anchor
— Manual velocity might
violate constraints Rigid
— Use force or impulse
the
42 Collisions gamedesigninitiative
at cornell university
The Distance Joint
— Extremely common joint Hard Distance
— Separates by a fixed amount
— Good for ropes/grappling
— Can be hard or soft
— Hard: Strong but very brittle
— Soft: Stretchy but very weak
Soft Distance
— Softness set in the joint def
— Damping, frequency values
— Turns the joint into a spring
— Damping: Use <1 to soften
— Frequency: Spring oscillation
the
43 Collisions gamedesigninitiative
at cornell university
The Distance Joint
— Extremely common joint Hard Distance
— Separates by a fixed amount
— Good for ropes/grappling
— Can be hard or soft
— Hard: Strong but very brittle
Older
— Soft: versions
Stretchy ofweak
but very box2d have aSoft
ropeDistance
joint.
This set
— Softness is deprecated
in the joint defin favor of soft distances.
— Damping, frequency values
— Turns the joint into a spring
— Damping: Use <1 to soften
— Frequency: Spring oscillation
the
44 Collisions gamedesigninitiative
at cornell university
Other Joint Types

Revolute Weld

— Joint binds at one point — Joint binds at one point


— Both translate together — Both translate together
— But rotate independently — Both rotate together
the
45 Collisions gamedesigninitiative
at cornell university
Other Joint Types

Prismatic Pulley

— Joint binds with a “track” — Joint binds through portals


— Both rotate together — Pulling one raises the other
— But translate along track — Distance w/ “teleportation”
the
46 Collisions gamedesigninitiative
at cornell university
Making a Rope: The Simple Way

Rectangular planks connected


by revolute joints at each step

Bridge in Lab 4
the
47 Collisions gamedesigninitiative
at cornell university
Making a Rope: The Better Way

Web of springy distance joints


with revolute joints at the end

Keeps rope strong but flexible!


the
48 Collisions gamedesigninitiative
at cornell university
Summary
— box2d support motion and collisions
— Body class provides the motion
— Fixture, Shape classes are for collisions

— Multiple ways to control a physics object


— Can apply forces or manually control velocity
— Joint constraints work best with forces

— Collisions are managed by callback functions


— Invoked once you call the world step method
— Collisions are processed per fixture, not per body
the
49 Collisions gamedesigninitiative
at cornell university

You might also like