Game Development Reference
In-Depth Information
Figure 6-3. Capsule Collider component in the Inspector
Stop to playtest after each of the following instructions. First, add a primitive game object cube,
name it Target, and change its Transform position to (1.4, 1, 7) and scale to (2, 2, 0.2). At least one of
the game objects involved in a collision must have a rigidbody component. In the Inspector, select
Add Component ➤ Physics ➤ Rigidbody. Play, and Target falls according to gravity.
In the Rigidbody component, uncheck Use Gravity. Play, and the projectile impacts the cube, then
falls under the force of gravity while the cube flies away, the rate of change of its position and
rotation governed by the physics engine. Here you see that though you disabled the target cube's
response to the force of gravity, with a Box Collider component it still responds to collision forces.
Change the target rigidbody constraints so it will rotate in place when hit. In the Inspector, find the
Rigidbody component and expand the Constraints property. Check X, Y, and Z for Freeze Position,
which will hold the target in place when struck. Play and the target still responds to being struck by
the projectile, but stays in position relative to world space.
Still in the Inspector, check Y and Z for Freeze Rotation. Play, and now the target stays in position
and rotates about the x axis. Save the scene and save the project.
The primitive objects provided by Unity come with colliders that match the size and shape of the
game object's rendered appearance, but you aren't limited to this. You can offset the collider from
the game object, change the size of the collider relative to the game object, or even use a collider
with a different shape than the game object for an even wider variety of behaviors. Continue to
experiment as you go!
OnCollision
While this is a nice little demo for what the physics engine can do with your game objects, let's get
back to scripting and take a look at what is going on behind the scenes. In the frame where the
projectile first impacts the target, the physics engine calls the function OnCollisionEnter() . In the
subsequent frames where the two objects remain in contact it calls OnCollisionStay() . Finally, when
the objects are no longer in contact with each other, OnCollisionExit() is called.
Create a new scene and add a directional light. Create a cube and assign a Transform position of
(0, 0.5, 0) and rotation of (0, 0, 10). Create a Sphere with a Transform position of (0, 3, 0) and add a
Rigidbody component by selecting Add Component ➤ Physics ➤ Rigidbody. Save the scene and
name it.
 
Search WWH ::




Custom Search