Game Development Reference
In-Depth Information
This breaks down as follows:
(1) var hit : RaycastHit;
Declares the RaycastHit type reference variable that will hold information about the collider that was
hit by the ray.
(2) if(Physics.Raycast(transform.position + Vector3(0, 0.5, 0),
transform.forward, hit))
The Raycast() function returns a boolean value of true when the ray intersects with a collider and
false when there is no intersection. If Raycast() returns true , then the block of code within the
conditional will be executed.
The ray itself is given an origin of the game object's transform.position , plus adding 0.5 to the
origin's y coordinate to bring it to about knee level of the character.
The ray direction corresponds to the game object's forward. Omitting the length of the ray means
it defaults to an infinitely long ray, so you will get hit information from any game object the player
character is facing.
(3) print ("Collided with game object " + hit.collider.gameObject.name);
Prints the name of any game object the ray detects.
Save the script. Save the scene and playtest. Notice that the ray detects everything with a collider,
including the ramp and other game objects populating the scene.
Let's say you want to destroy these evil spheres. Try adding a “Destroy” command to your Update()
function:
function Update () {
var hit : RaycastHit;
if(Physics.Raycast(transform.position+ Vector3(0, 0.5, 0),
transform.forward, hit)) {
print ("Collided with game object " +
hit.collider.gameObject.name);
Destroy(hit.collider.gameObject);
}
}
Save the script and playtest. Run your character around and destroy the evil spheres. But watch
out—you also destroyed the lower ramp and obstacle game objects that the ray collided with.
You have used gameObject.name in conditionals to test for a game object, but now you have five evil
spheres to contend with. You could destroy the spheres using this approach:
function Update () {
var hit : RaycastHit;
if(Physics.Raycast(transform.position+ Vector3(0, 0.5, 0), transform.forward, hit)) {
print ("Collided with game object " + hit.collider.gameObject.name);
 
Search WWH ::




Custom Search