Game Development Reference
In-Depth Information
Listing 6-6. Detecting Enemy Hits
062 //Calculate hit
063
064
//Get ray from screen center target
065 Ray R = Camera.main.ScreenPointToRay(new Vector3(Screen.width/2,
Screen.height/2,0));
066
067 //Test for ray collision
068 RaycastHit hit;
069
070 if(Physics.Raycast(R.origin, R.direction, out hit, Range))
071 {
072 //Target hit - check if target is enemy
073
if(hit.collider.gameObject.CompareTag("enemy"))
074 {
075 //Play collection sound, if audio source is available
076 if(SFX){SFX.PlayOneShot(WeaponAudio, 1.0f);}
077
078
//Send damage message (deal damage to enemy)
079 hit.collider.gameObject.SendMessage("Damage",Damage,
SendMessageOptions.DontRequireReceiver);
080 }
081 }
082
Collision detection and damage dealing begins by constructing a
ray
. A ray is a mathematical
structure representing an imaginary straight line, projected from the screen into the scene space
ahead. In our case, the ray will act as an imaginary beam cast outward from the tip of our weapon
(assumed to be screen-center). Line 65 uses the Unity camera function
ScreenPointToRay
to
construct a ray that begins from the screen center and is projected forward, away from the camera
and inward into the scene.
Note
More information on
ScreenPointToRay
can be found in the online Unity documentation at
After a ray has been constructed and cast into the scene, the
Physics.Raycast
function is used
to access the
first
collidable GameObject intersecting the ray. This object is the nearest collidable
object
to us
.
Note
More information on
Physics.Raycast
can be found in the online Unity documentation at