Game Development Reference
In-Depth Information
10. We have inished creaing our Door and Key . Next, we will go back to our code
and add some scriping to make our Door and Key work. Double-click our
CharacterController_2D.js , and add these parameters to it:
public var doorOpenTexture : Texture2D;
public var doorCloseTexture : Texture2D;
private var b_hasKey : boolean;
11. Then, we add these lines of code to the Start() funcion:
//Start with no Key
b_hasKey = false;
This will set the character to start without a key.
12. Next, we add the OnTriggerEnter() funcion to our code; this funcion will check
if our character hit Key or Door :
public function OnTriggerEnter (hit : Collider) : IEnumerator {
if (hit.collider.tag == "Key") {
if (!b_hasKey) {
//We hit our Key
b_hasKey = true;
Destroy (hit.gameObject);
}
}
if (hit.collider.tag == "Door") {
if (b_hasKey) {
//If we had Key and hit door the door will open
hit.gameObject.renderer.material.mainTexture =
doorOpenTexture;
//wait for 1 second and destroy our character
yieldWaitForSeconds(1);
Destroy (gameObject);
//We close the door
hit.gameObject.renderer.material.mainTexture =
doorCloseTexture;
}
}
}
In this funcion, we are checking if our character hit the key or door by checking
their tag. When the player hits the key , the key will destroy itself and we set our
character to have a key by seing b_hasKey = true . Also, when we hit the door ,
we are checking if our character has the key or not. If the character has the key, it
will change the door texture to doorOpen texture. Then, we wait for one second to
remove our character and we change the door texture back to doorClose texture
to close the door.
 
Search WWH ::




Custom Search