Game Development Reference
In-Depth Information
function OnCollisionEnter(other : Collision) {
var checkColor : Color = other.gameObject.renderer.material.color;
if (checkColor == greenColor) {
other.gameObject.renderer.material.color = redColor;
} else {
other.gameObject.renderer.material.color = greenColor;
}
}
Save the script and attach it to the Rocket prefab by opening the Assets ➤ Prefabs folder in the
Project panel and selecting the Projectile prefab. In the Inspector, select Add Component ➤ Scripts,
then find the Projectile script in the drop-down menu and select it. The Projectile script should
appear in the Inspector as a new component for the Rocket prefab.
This code breaks this down as follows:
(1) public var aForce : float = 500;
private var redColor : Color = Color (1, 0, 0);
private var greenColor : Color = Color (0, 1, 0);
The aForce variable used to determine the launch force on the Projectile game object is declared as
public to allow for adjustment through the Inspector, and assigned an initial value. The redColor and
greenColor variables of type Color are assigned the corresponding RGB values for red and green.
(2) rigidbody.AddForce (Vector3.forward * aForce);
In the FixedUpdate() function, a forward-directed force is applied to the projectile.
(3) var checkColor : Color = other.gameObject.renderer.material.color;
if (checkColor == greenColor) {
other.gameObject.renderer.material.color = redColor;
} else {
other.gameObject.renderer.material.color = greenColor;
}
When the Rocket prefab projectile collides with a target, the onCollisionEnter() function is called
and the target will change color. The Color type reference variable checkColor is declared and
assigned the value of the target game object. The target object color is then tested arbitrarily to see
if it is green; if true it is changed to red. If false , meaning the target object is not green, then it is
changed to red.
In the editor, save the scene, save the project, then enter Play mode to test it out (Figure 6-7 ). There
you have it—your first game prototype!
 
Search WWH ::




Custom Search