igp 04 game math and physics - cs. · pdf file... multiply method (many overloaded versions)...

11
Introduction to Game Programming Autumn 2014 04. On game math and physics Juha Vihavainen University of Helsinki Outline A non-mathematical introduction to concepts and terms Vectors and matrices multiplying by matrices for transformations On coordinate spaces, transformations, and math libraries Game physics fundamentals S.Madhav: Game Programming Algorithms and Techniques, 2014. Chapter 7. Physics J. Gregory: Game Engine Architecture, 2014. Chapter 12. Collision and Rigid Body Dynamics 28.11.2017 Juha Vihavainen / University of Helsinki 2

Upload: doanthu

Post on 12-Mar-2018

217 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: IGP 04 Game math and physics - cs.  · PDF file... multiply method (many overloaded versions) ... Kinetics: the effect of force on motion ... F= force m= mass a= acceleration

Introduction to Game ProgrammingAutumn 2014

04. On game math and physics

Juha Vihavainen

University of Helsinki

Outline

� A non-mathematical introduction to concepts and terms

� Vectors and matrices

� multiplying by matrices for transformations

� On coordinate spaces, transformations, and math libraries

� Game physics fundamentals

� S.Madhav: Game Programming Algorithms and

Techniques, 2014.

� Chapter 7. Physics

� J. Gregory: Game Engine Architecture, 2014.

� Chapter 12. Collision and Rigid Body Dynamics

28.11.2017 Juha Vihavainen / University of Helsinki 2

Page 2: IGP 04 Game math and physics - cs.  · PDF file... multiply method (many overloaded versions) ... Kinetics: the effect of force on motion ... F= force m= mass a= acceleration

Vector definition

� A vector represents a magnitude and direction in n-dimensional

space, with one real number per dimension

� for games, usually 2D or 3D vectors, though sometimes we

use 4D in 3D games (for technical reasons..)

� Can be expressed as

� Not (necessarily) any concept of position

� Where we draw a vector does not change its magnitude or

direction, so it doesn't change the vector

� Often helpful to draw with the tail starting

at the origin: < 0, 0 > → < x, y >

28.11.2017 3Juha Vihavainen / University of Helsinki

Unit vectors and normalization

� Unit vectors have a length of 1

� Drawn with a hat, like

� To convert a non-unit vector to a unit one, normalize the

vector, i.e., divide by the magnitude (length)

� Of course, normalizing loses the magnitude info

� if you care about magnitude, don't normalize

� if you only care about direction, do normalize

28.11.2017 4Juha Vihavainen / University of Helsinki

Page 3: IGP 04 Game math and physics - cs.  · PDF file... multiply method (many overloaded versions) ... Kinetics: the effect of force on motion ... F= force m= mass a= acceleration

Linear interpolation

Lerp from a to b with different f values

28.11.2017 5Juha Vihavainen / University of Helsinki

� Produces points between

a and b, when f in 0..1

� Extensively used in game

graphics, e.g.

� animation file defines

only major keyframes,

and we must interpolate

the between positions

for all output frames

Matrices

� A m x n matrix is a grid of real numbers with m rows and n

columns

� For games, 3x3 or 4x4 matrices are the most common

(sometimes even 4x3 but extended with zeros on demand)

28.11.2017 6Juha Vihavainen / University of Helsinki

3 x 3 matrix

Page 4: IGP 04 Game math and physics - cs.  · PDF file... multiply method (many overloaded versions) ... Kinetics: the effect of force on motion ... F= force m= mass a= acceleration

Matrix multiplication

� Matrices A and B can be multiplied only if the number of

columns in A are equal to the number of rows in B (gives the

same number of corresponding terms)

� Note: 4,4 x 4,4 = 4, 4 1,2 x 2,2 = 1,228.11.2017 7Juha Vihavainen / University of Helsinki

Left- vs. right-handed coordinate systems

� item

28.11.2017 Juha Vihavainen / University of Helsinki 8

DirectX OpenGL and XNA/MonoGame

Left-handed Right-handed

� Which coordinate system we choose is arbitrary, but must be

consistent (but still easy to convert between coord. systems)

Page 5: IGP 04 Game math and physics - cs.  · PDF file... multiply method (many overloaded versions) ... Kinetics: the effect of force on motion ... F= force m= mass a= acceleration

On matrix transforms

� A 4 x 4 matrix used by the game entity to place and rotate objects

� for technical reasons, need an extra 4th row used for translation

(move), and to generalize handling points / direction vectors

� "vectors are kind matrices containing one column or row"

� "row-vector matrices view vectors as a row from left to right"

� Provide redefined matrix operations

� +, -, *, /, ==, multiply method (many overloaded versions)

� Also, can provide convenience matrices (as static objects)

� identity matrix

� up, down, left, right member properties (of type vector3)

� Often, convenient factory methods to create needed transforms

� camera views into 3D world, rotations, determinants, invert...

928.11.2017 Juha Vihavainen / University of Helsinki

vector3 type (in game engines/libraries)

� The same value can represent (be interpreted) either as x, y, z location

coordinates (a point), or as direction (a vector)

� distances along x, y, z coordinates

� often as a unit vector: length is 1 and

x, y, z values between 0.0 and 1.0

� Provide x, y, z as accessible properties

� Overload arithmetic operators

� +, -, *, /, ==, !=

� Helper methods include: interpolations (lerp), rotations, distance, dot

product, cross product, vector normalization..

� Provide convenience vectors (short-hand notations)

� unit x (right,-left), unit y (up,-down), unit z (backward)..

x

y

z

(x,y,z) vector

1028.11.2017 Juha Vihavainen / University of Helsinki

Page 6: IGP 04 Game math and physics - cs.  · PDF file... multiply method (many overloaded versions) ... Kinetics: the effect of force on motion ... F= force m= mass a= acceleration

About vector and matrix data types

� A transform is a 4 x 4 matrix of floating-point values, used to

perform (affine) transformations for graphics

� scaling, rotation, translation (and sometimes shearing) of vectors

� A position (point) is first extended to a 4-vector by tacking on a "1"

� this allows translation (moving) to work with matrix

multiplications

� A direction vector (often normalized) is extended to a 4-vector by

tacking on a "0" as the fourth element

� means that only the "non-translation" part of a matrix will apply

� There are alternative ways to represent (store) matrices..

1128.11.2017 Juha Vihavainen / University of Helsinki

Example of matrix calculations

� Consider the following vector transformation (in pseudocode)

vector := new vector3 (0, 1, 0); // point on the Y axis

transformMx := create_from_translation (0, -2, 0);

// shift down Y axis by two units

//

//

//

//

//

vector := transform (vector, transformMx); // multiplication

assert (vector == new vector3 (0, -1, 0));

� The same transformation on a direction vector does nothing

12

1 0 0 0

0 1 0 0

0 0 1 0 = ( 0 -1 0 1)

0 -2 0 1

( 0 1 0 1) x

this is a point, too

28.11.2017 Juha Vihavainen / University of Helsinki

this is a point (= location)

Page 7: IGP 04 Game math and physics - cs.  · PDF file... multiply method (many overloaded versions) ... Kinetics: the effect of force on motion ... F= force m= mass a= acceleration

Why and how game physics?

� Games based on the real world should look realistic, meaning

realistic action and reaction

� More complex games need more physics

� sliding through a turn in a racecar, sports games, flight

simulation, etc.

� running and jumping off the edge of a cliff (or whatever)

� Two types of physics

� elastic, i.e., solid bodies with no deformation, rigid-body

physics, no loss of kinetic energy, F = ma, e.g., Pong

� inelastic: "soft objects" don't bounce and have deformations:

clothes, pony tails, a whip, chain, hair, volcanoes, liquid

� e.g., inelastic: crumples a car bumper using up kinetic

energy; elastic physics is easier to get right

28.11.2017 13

Why and how game physics? (cont'd)

� Computing motion of objects in virtual scene

� including player avatars, NPC’s, inanimate objects

� computing mechanical interactions of game objects

� A game physics simulation makes many small simple predictions

based on the laws of physics

� “given that the object is here, and is traveling this fast, in a short

amount of time from now should be over there”

� so-called integrator executes these calculations

� Improves immersion, and can support new gameplay elements

� Becoming increasingly expected part of high-end games

� Like AI and graphics, advanced by hardware developments (multi-

core, GPU), and maturation of engine market

28.11.2017 Juha Vihavainen / University of Helsinki 14

Page 8: IGP 04 Game math and physics - cs.  · PDF file... multiply method (many overloaded versions) ... Kinetics: the effect of force on motion ... F= force m= mass a= acceleration

What games can do with a physics system

� Detect collisions between dynamic objects and static world geometry

� Simulate free rigid bodies under the influence of gravity and other forces

� Trigger volumes (determine when objects enter, leave, or are inside

predefined regions in the game world) Define spring-mass systems

� Allow characters to pick up rigid objects

� Complex machines (moving platform puzzle, crane, industrial lift)

� Destructible buildings and structures

� Ray and shape casts (to determine line of sight, bullet impact points, etc.)

� Traps (such as an avalanche of boulders)

� Drivable vehicles with suspensions (stiff springs & shock absorbers )

� Rag doll (often for character deaths)

� Powered rag doll: a realistic blend between traditional animation and rag

doll physics . . .

28.11.2017 Juha Vihavainen / University of Helsinki 15

Game physics: concepts & terminology

� Kinematics: the study of motion (ignoring forces)

� how does acceleration affect velocity?

� how does velocity affect position?

� Particle: a point-mass; body rotation is ignored

� Rigid body: rotation of the body needs to be considered

� Force: objects change motion only when forces are applied

� Contact vs. field forces: hitting a baseball vs. gravity or magnetism

� Torque: force that induces rotation

� Environmental: friction, buoyancy (upthrust in fluid), air drag/lift

� Kinetics: the effect of force on motion

� Non-rigid objects

� joints and constraints: rag-doll physics, mass-spring systems

� flexible objects: soft bodies, meshes, cloth, hair

� Complex motion: fluid dynamics, smoke, particle systems

� Collisions: detection, response, and just prevention (e.g., for a camera)16

Kinetics has applications in

designing of automobiles

whereas kinematics finds

applications in movement of

celestial bodies.

Page 9: IGP 04 Game math and physics - cs.  · PDF file... multiply method (many overloaded versions) ... Kinetics: the effect of force on motion ... F= force m= mass a= acceleration

Game physics: concepts & .. (cont'd)

� Approximate real-world physics

� don’t want just the equations

� want efficient ways to compute physical values

� Some common assumptions or simplifications

(depending on the game)

� using 2D physics, only

� for need to generalize to 3D, add z dimension

� rigid bodies (no deformation)

� will just worry about center of mass

� don’t bother accuracy for all physical effects, e.g.,

� can use greater gravity for improving gameplay

28.11.2017 Juha Vihavainen / University of Helsinki 17

Linear mechanics

� Linear mechanics studies motion

� Linear means no rotational forces

� Position r is related to velocity v and

velocity v is related to acceleration a

� Newton's second law of motion says:

� where

� F = force

� m = mass

� a = acceleration

28.11.2017 18Juha Vihavainen / University of Helsinki

r = position

t = duration

Page 10: IGP 04 Game math and physics - cs.  · PDF file... multiply method (many overloaded versions) ... Kinetics: the effect of force on motion ... F= force m= mass a= acceleration

Linear mechanics for games

� We can apply forces to objects with a mass => get acceleration

� e.g., gravity and

� possibly impulses generated by the game to initiate movement

(say, jump signal)

� Given the position and velocity last frame, based on these new

forces, determine the position and velocity this frame

� To do this, we need to use numerical integration

� We must use fixed time steps (e.g., by using frame limiting or a

separate physics loop)

� otherwise, different time steps could cause things like different

misshaped jump arcs

28.11.2017 19Juha Vihavainen / University of Helsinki

Euler integration

� Simplest type of numeric integration, but least accurate

class PhysicsComponent

list forces; // list of all the force vectors active on this object

Vector3 acceleration, velocity, position;

float mass;

function Update (float deltaTime)

Vector3 sumOfForces := sum of all forces;

acceleration := sumOfForces / mass;

// Euler integration

position += velocity * deltaTime;

velocity += acceleration * deltaTime;

28.11.2017 20Juha Vihavainen / University of Helsinki

Uses old velocity

value

Page 11: IGP 04 Game math and physics - cs.  · PDF file... multiply method (many overloaded versions) ... Kinetics: the effect of force on motion ... F= force m= mass a= acceleration

Semi-implicit Euler integration

� Exactly like Euler integration, but the velocity is updated first,

before the position

// semi-implicit Euler integration

velocity += acceleration * deltaTime;

position += velocity * deltaTime;

� This ends up being a bit more accurate

� reasoning is omitted here

� used in physics systems such as Box2D

28.11.2017 21Juha Vihavainen / University of Helsinki

Velocity verlet integration

� Splits the time step into two

function Update (float deltaTime)

Vector3 avgVelocity := velocity + acceleration * deltaTime / 2.0f;

// position is integrated with the average velocity

position += avgVelocity * deltaTime;

// calculate new acceleration and velocity for the next round

Vector3 sumOfForces := sum of all forces;

acceleration := sumOfForces / mass;

velocity := avgVelocity + acceleration * deltaTime / 2.0f;

28.11.2017 22Juha Vihavainen / University of Helsinki

� Not too complicated but much more accurate

� Angular mechanics omitted here (similar but more complex)

Old acceleration