Graphics Reference
In-Depth Information
In an attempt to prevent projectiles from colliding either with the parent object or
with other projectiles spawned closely together, Physics.IgnoreLayerCollision() is used.
Physics.IgnoreLayerCollision() takes two layer numbers (both integers) referring to
which layers should ignore colliding with each other. The layer numbers come from the
Tags and Layers manager accessible via the menu Edit → Project Settings → Tags and Layers
or the Unity editor Inspector window by clicking on the layer dropdown and clicking on
the Add layer button. This is applied globally, which means that once two layers are on
Unity's ignore list, everything placed on those two layers will no longer register collisions.
In this case, the first layer is the weapon's layer from myTransform.gameObject.layer
and the second taken from the variable myLayer, which was set in the Init() function of
this script:
Physics.IgnoreLayerCollision( myTransform.gameObject.layer, myLayer );
A better solution to avoiding collisions between the projectile and any parent collider
is to set the parentCollider reference in the Unity editor Inspector window. This part of the
code checks that parentCollider is not null; then as long as it contains something, Physics.
When a collider is accessible to this script via parentCollider (as set in the Unity editor
Inspector window), IgnoreCollision is used to tell the engine to ignore collisions between
the two specific colliders.
Whereas Physics.IgnoreLayerCollision() worked to disable all collisions between
objects on two layers, the Physics.IgnoreCollision() function stops collision events on
specified colliders:
if( parentCollider!=null )
{
// disable collision between 'us' and our projectile
// so as not to hit ourselves with it!
Physics.IgnoreCollision( theProjectile.collider,
parentCollider );
}
The newly created projectile needs to be returned to the function calling (especially
when this is called from the Fire() function shown earlier in this section), and the last bit
of code from this script does just that:
// return this projectile in case we want to do something
// else to it
return theProjectile;
}
}
Further on in this topic, when the example games are examined, these base scripts
will come up again and we will see how they can be applied to real game situations. In
Chapter 9, we look at adding artificial intelligence (AI) to the game and how the weapon
controller can easily be tied into it and controlled by an AI player in a game.
Search WWH ::




Custom Search