43
Unity Lecture Unity Build-in Physics Engine

Unity Lecture Unity Build-in Physics Engine. Unity contains powerful 3D physics engine NVIDIA PhysX Physics. Create immersive and visceral scenes with

Embed Size (px)

Citation preview

Page 1: Unity Lecture Unity Build-in Physics Engine. Unity contains powerful 3D physics engine NVIDIA PhysX Physics. Create immersive and visceral scenes with

Unity Lecture

Unity Build-in Physics Engine

Page 2: Unity Lecture Unity Build-in Physics Engine. Unity contains powerful 3D physics engine NVIDIA PhysX Physics. Create immersive and visceral scenes with

• Unity contains powerful 3D physics engine NVIDIA PhysX Physics. Create immersive and visceral scenes with clothes and hair that blow in the wind; tires that screech and burn; walls that crumble; glass that shatters, and weapons that inflict major damage!

• Unity’s easy-to-use integrated 2D physics system

• Perhaps one of the most surprising things about games is the ways in which we will accept different physical systems.

• Interestingly I had to think carefully about how I phrased this because many of these systems are actually very different.

Page 3: Unity Lecture Unity Build-in Physics Engine. Unity contains powerful 3D physics engine NVIDIA PhysX Physics. Create immersive and visceral scenes with

• These systems often do not differ greatly from our experiences in the world – they are often a reconfiguration or adaptation of the physical ‘laws’ we are subject to….

Page 4: Unity Lecture Unity Build-in Physics Engine. Unity contains powerful 3D physics engine NVIDIA PhysX Physics. Create immersive and visceral scenes with
Page 5: Unity Lecture Unity Build-in Physics Engine. Unity contains powerful 3D physics engine NVIDIA PhysX Physics. Create immersive and visceral scenes with
Page 6: Unity Lecture Unity Build-in Physics Engine. Unity contains powerful 3D physics engine NVIDIA PhysX Physics. Create immersive and visceral scenes with

• In essence this is what we encounter in most games – whether it be the ability to leap to far greater heights…

Page 7: Unity Lecture Unity Build-in Physics Engine. Unity contains powerful 3D physics engine NVIDIA PhysX Physics. Create immersive and visceral scenes with
Page 8: Unity Lecture Unity Build-in Physics Engine. Unity contains powerful 3D physics engine NVIDIA PhysX Physics. Create immersive and visceral scenes with

• However perhaps this is something that we are used to thinking about because gravity can have a variety of effects dependant on context…

• Game packages such as UnrealEd makes use of an Acceleration module rather than specifically referring to the notion of Gravity...

• …which undoubtedly was used on a title such as Prey.

Page 9: Unity Lecture Unity Build-in Physics Engine. Unity contains powerful 3D physics engine NVIDIA PhysX Physics. Create immersive and visceral scenes with

• Although there is gravity in Unity this can be applied in a number of ways…• You can access the Physics Manager by selecting Edit->Project Settings-

>Physics from the menu bar

Page 10: Unity Lecture Unity Build-in Physics Engine. Unity contains powerful 3D physics engine NVIDIA PhysX Physics. Create immersive and visceral scenes with

2. ‘Gravity’ and some simple warnings…

Page 11: Unity Lecture Unity Build-in Physics Engine. Unity contains powerful 3D physics engine NVIDIA PhysX Physics. Create immersive and visceral scenes with

• A Rigidbody is the main component that enables physical behaviour for an object. With a Rigidbody attached, the object will immediately respond to gravity. If one or more Collider components are also added then the object will be moved by incoming collisions.

• Since a Rigidbody component takes over the movement of the object it is attached to, you shouldn’t 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.

• 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.

• Sleeping mode optimisation means that no processor time will be spent updating the rigidbody until the next time it is “awoken”.

Rigid body

Page 12: Unity Lecture Unity Build-in Physics Engine. Unity contains powerful 3D physics engine NVIDIA PhysX Physics. Create immersive and visceral scenes with
Page 13: Unity Lecture Unity Build-in Physics Engine. Unity contains powerful 3D physics engine NVIDIA PhysX Physics. Create immersive and visceral scenes with

• Collider components define the shape of an object for the purposes of physical collisions. A collider, which is invisible, need not be the exact same shape as the object’s mesh and in fact, a rough approximation is often more efficient and indistinguishable in gameplay.

• The simplest (and least processor-intensive) colliders and the so-called primitive collider types. In 3D, these are the Box Collider, Sphere Collider and Capsule Collider.

• Any number of these can be added to a single object to create compound colliders. With careful positioning and sizing, compound colliders can often approximate the shape of an object quite well while keeping a low processor overhead.

• There are some cases, however, where even compound colliders are not accurate enough. In 3D, you can use Mesh Colliders to match the shape of the object’s mesh exactly.

Colliders

Page 14: Unity Lecture Unity Build-in Physics Engine. Unity contains powerful 3D physics engine NVIDIA PhysX Physics. Create immersive and visceral scenes with

Collision Detection• Detect when an world object or element has made

contact with another world object or element– Collision with world boundaries e.g. terrain– Player collides with world object– Player acquires a resource

• Collisions must be accurately detected

• Collision events must be handled by system logic

• World state changed to reflect changes made by collisions – update values, acquire energy, add time bonus, communicate with other objects via scripts etc.

Page 15: Unity Lecture Unity Build-in Physics Engine. Unity contains powerful 3D physics engine NVIDIA PhysX Physics. Create immersive and visceral scenes with

2D Collisions

Page 16: Unity Lecture Unity Build-in Physics Engine. Unity contains powerful 3D physics engine NVIDIA PhysX Physics. Create immersive and visceral scenes with

2D Bounding Boxes

Page 17: Unity Lecture Unity Build-in Physics Engine. Unity contains powerful 3D physics engine NVIDIA PhysX Physics. Create immersive and visceral scenes with

False Collisions

Sprite boundaries overlap but sprites not colliding

Page 18: Unity Lecture Unity Build-in Physics Engine. Unity contains powerful 3D physics engine NVIDIA PhysX Physics. Create immersive and visceral scenes with

• Some 3D scenarios may use bounding spheres

• A bounding sphere is a hypothetical sphere that completely encompasses an object.

• For finer-grain collision detection several spheres could be used on a single object

• Each would need to be coded to see if a collision had occurred

• Most 3D APIs provide some functional collision detection.

Collision Detection for 3D

Page 19: Unity Lecture Unity Build-in Physics Engine. Unity contains powerful 3D physics engine NVIDIA PhysX Physics. Create immersive and visceral scenes with

• When choosing colliders there is a need to take account of the accuracy of collision detection required versus the computational impact of the chosen collider.

• A box collider would use much less computation than a mesh collider.

• Unity also provides a capsule collider, which is the default collider for a First Person Controller.

Physics ‘Colliders’ in Unity 3D

Page 20: Unity Lecture Unity Build-in Physics Engine. Unity contains powerful 3D physics engine NVIDIA PhysX Physics. Create immersive and visceral scenes with

Example Colliders: BoxExample Colliders: Box

Cube Box Collider

Page 21: Unity Lecture Unity Build-in Physics Engine. Unity contains powerful 3D physics engine NVIDIA PhysX Physics. Create immersive and visceral scenes with

Example Colliders: BoxExample Colliders: Sphere

Cube Sphere Collider

Page 22: Unity Lecture Unity Build-in Physics Engine. Unity contains powerful 3D physics engine NVIDIA PhysX Physics. Create immersive and visceral scenes with

Example Colliders: BoxExample Colliders: Capsule

Cube Capsule Collider

Page 23: Unity Lecture Unity Build-in Physics Engine. Unity contains powerful 3D physics engine NVIDIA PhysX Physics. Create immersive and visceral scenes with

Example Colliders: BoxExample Colliders: Mesh

Cube Mesh Collider

Page 24: Unity Lecture Unity Build-in Physics Engine. Unity contains powerful 3D physics engine NVIDIA PhysX Physics. Create immersive and visceral scenes with

Example Colliders: BoxExample Colliders: False Collisions

Cube Collider on Sphere

False Collision

Page 25: Unity Lecture Unity Build-in Physics Engine. Unity contains powerful 3D physics engine NVIDIA PhysX Physics. Create immersive and visceral scenes with

Example Colliders: BoxUsing Colliders as ‘Colliders’

• The default setting for any collider attached to an object is to restrict the object being passed through be other world objects. The collision event must be handled by a script attached to one or both of the objects involved in the collision

Page 26: Unity Lecture Unity Build-in Physics Engine. Unity contains powerful 3D physics engine NVIDIA PhysX Physics. Create immersive and visceral scenes with

Example Colliders: BoxHandling Events Initiated by Collisions

This function is attached to the First Person Controller (Capsule Collider)

function OnControllerColliderHit(hit:ControllerColliderHit){

if (hit.collider == GameObject.Find("RedSphere").collider){

Debug.Log("I've hit the Red Sphere");

};

if (hit.collider == GameObject.Find("BlueSphere").collider){

Debug.Log("I've hit the Blue Sphere");

};

};

• Unity has a built in function for detecting collisions:

Page 27: Unity Lecture Unity Build-in Physics Engine. Unity contains powerful 3D physics engine NVIDIA PhysX Physics. Create immersive and visceral scenes with

Saved SceneWheel Collider

Page 28: Unity Lecture Unity Build-in Physics Engine. Unity contains powerful 3D physics engine NVIDIA PhysX Physics. Create immersive and visceral scenes with

Saved SceneWheel Collider

• The Wheel Collider is a special collider for grounded vehicles. It has built-in collision detection, wheel physics, and a slip-based tire friction model. It can be used for objects other than wheels, but it is specifically designed for vehicles with wheels.

Page 29: Unity Lecture Unity Build-in Physics Engine. Unity contains powerful 3D physics engine NVIDIA PhysX Physics. Create immersive and visceral scenes with

Saved SceneDriving scripts (1)

Viewport

void FixedUpdate () {WheelRR.motorTorque = maxTorque *

Input.GetAxis("Vertical");WheelRL.motorTorque = maxTorque *

Input.GetAxis("Vertical");WheelFL.steerAngle = 10 * Input.GetAxis("Horizontal");WheelFR.steerAngle = 10 * Input.GetAxis("Horizontal");

}

Page 30: Unity Lecture Unity Build-in Physics Engine. Unity contains powerful 3D physics engine NVIDIA PhysX Physics. Create immersive and visceral scenes with

Saved SceneDriving scripts (2)

Viewport

void FixedUpdate () {currentSpeed = (2*3.1415926f *WheelRL.radius*WheelRL.rpm*60/1000); currentSpeed = Mathf.Round(currentSpeed);if(currentSpeed < topSpeed){

WheelRR.motorTorque = maxTorque * Input.GetAxis("Vertical"); WheelRL.motorTorque = maxTorque * Input.GetAxis("Vertical");

}else{

WheelRR.motorTorque = 0;WheelRL.motorTorque = 0;

}

if(Input.GetButton("Vertical")==false) //if no gas, slow down the car{

WheelRR.brakeTorque = decelerationSpeed;WheelRL.brakeTorque = decelerationSpeed;

}else{

WheelRR.brakeTorque = 0;WheelRL.brakeTorque = 0;

}

}

Page 31: Unity Lecture Unity Build-in Physics Engine. Unity contains powerful 3D physics engine NVIDIA PhysX Physics. Create immersive and visceral scenes with

Saved SceneMake handbrake using WheelFrictionCurve

Page 32: Unity Lecture Unity Build-in Physics Engine. Unity contains powerful 3D physics engine NVIDIA PhysX Physics. Create immersive and visceral scenes with

Saved ScenePhysics behind WheelFrictionCurve

• Wheel collider computes friction separately from the rest of physics engine

• It separates the overall friction force into a "forwards" component (in the direction of rolling, and responsible for acceleration and braking) and "sideways" component (orthogonal to rolling, responsible for keeping the car oriented).

• In both directions it is first determined how much the tire is slipping (what is the speed difference between the rubber and the road).

• Then this slip value is used to find out tire force exerted on the contact.

• The property of real tires is that for low slip they can exert high forces as the rubber compensates for the slip by stretching.

• Later when the slip gets really high, the forces are reduced as the tire starts to slide or spin.

Page 33: Unity Lecture Unity Build-in Physics Engine. Unity contains powerful 3D physics engine NVIDIA PhysX Physics. Create immersive and visceral scenes with

Saved SceneImplementation

Viewport

void SetSlip(float currentForwardFriction, float currentSidewayFriction){

WheelFrictionCurve rr = WheelRR.forwardFriction;WheelFrictionCurve rl = WheelRL.forwardFriction;rr.stiffness = currentForwardFriction;rl.stiffness = currentForwardFriction;WheelRR.forwardFriction = rr;WheelRL.forwardFriction = rl;

rr = WheelRR.sidewaysFriction;rl = WheelRL.sidewaysFriction;rr.stiffness = currentSidewayFriction;rl.stiffness = currentSidewayFriction;WheelRR.sidewaysFriction = rr;WheelRL.sidewaysFriction = rl;

}

stiffnessMultiplier for the extremumValue and asymptoteValue values (default 1).

Page 34: Unity Lecture Unity Build-in Physics Engine. Unity contains powerful 3D physics engine NVIDIA PhysX Physics. Create immersive and visceral scenes with

Saved SceneImplementation (2)

Viewport

if(Input.GetButton("Jump")) //space key for hand brake{

WheelFR.brakeTorque = maxBrakeTorque;WheelFL.brakeTorque = maxBrakeTorque;WheelRR.motorTorque = 0;WheelRL.motorTorque = 0;if(rigidbody.velocity.magnitude>1)

SetSlip(slipForwardFriction, slipSidewayFriction);else

SetSlip (1, 1);}else{

SetSlip(myForwardFriction,mySidewayFriction);WheelFR.brakeTorque = 0;WheelFL.brakeTorque = 0;

}

Page 35: Unity Lecture Unity Build-in Physics Engine. Unity contains powerful 3D physics engine NVIDIA PhysX Physics. Create immersive and visceral scenes with

Saved SceneImplementation (3)

Viewport

void Start () {

myForwardFriction = WheelRR.forwardFriction.stiffness;mySidewayFriction = WheelRR.sidewaysFriction.stiffness;slipForwardFriction = 0.01f;slipSidewayFriction = 0.005f;

}

Page 36: Unity Lecture Unity Build-in Physics Engine. Unity contains powerful 3D physics engine NVIDIA PhysX Physics. Create immersive and visceral scenes with

Saved SceneDemo

Page 37: Unity Lecture Unity Build-in Physics Engine. Unity contains powerful 3D physics engine NVIDIA PhysX Physics. Create immersive and visceral scenes with

Saved Scene

Add sound to Unity applications

Page 38: Unity Lecture Unity Build-in Physics Engine. Unity contains powerful 3D physics engine NVIDIA PhysX Physics. Create immersive and visceral scenes with

• Unity can import .aif, .wav, .mp3 and .ogg files. For .aif and .wav files, Unity lets you choose between using the native format or compressing into an appropriate format for the build target.

• However, Unity automatically re-encodes .mp3 and .ogg files if necessary to better suit the destination. For example, .ogg files are re-encoded as .mp3 files for iOS.

• There is a slight loss of sound quality if Unity needs to convert from one compressed format to another.

• For that reason, Unity’s documentation recommends that you import audio files in lossless formats like .aif and .wav and let Unity encode them to .mp3 or .ogg as needed.

Import Audio Files

Page 39: Unity Lecture Unity Build-in Physics Engine. Unity contains powerful 3D physics engine NVIDIA PhysX Physics. Create immersive and visceral scenes with

• For audio files you imported, you’ll leave most settings with their default values. However, you won’t be placing your sounds in 3D space, so uncheck 3D Sound, as shown below, and then click Apply:

Page 40: Unity Lecture Unity Build-in Physics Engine. Unity contains powerful 3D physics engine NVIDIA PhysX Physics. Create immersive and visceral scenes with

• To play a sound in Unity, you need to add an Audio Source component to a GameObject.

• Note that Play On Awake is already checked in the Audio Source component. This instructs Unity to begin playing this audio clip immediately when the scene loads.

Page 41: Unity Lecture Unity Build-in Physics Engine. Unity contains powerful 3D physics engine NVIDIA PhysX Physics. Create immersive and visceral scenes with

Add Codes for playing once

public AudioClip enemyContactSound;public AudioClip catContactSound;

// during specific collisionsaudio.PlayOneShot(catContactSound);audio.PlayOneShot(enemyContactSound);

Page 42: Unity Lecture Unity Build-in Physics Engine. Unity contains powerful 3D physics engine NVIDIA PhysX Physics. Create immersive and visceral scenes with

Add Codes for looping sound

audio.pitch = enginePitch;

Page 43: Unity Lecture Unity Build-in Physics Engine. Unity contains powerful 3D physics engine NVIDIA PhysX Physics. Create immersive and visceral scenes with

Example Colliders: BoxSummary

• Unity has a built-in Physics Engine that provides ‘motion-under-gravity’ properties and behaviors for objects with attached physics components

• Basic collision detection is also provided by several default colliders such as Box and Capsule for objects created in Unity. Models with more complex mesh topology must have colliders selected to suit their purpose while considering the computational impact on system performance.

• Unity provides basic functions to detect and handle collision events for both collision reactions and triggers events.