Tuesday, 4 March 2014

Flashlight Code

Below is the code for the flashlight, it does the following:


  • Upon spawn the player will not have a flashlight
  • When a flashlight is collected it will be off until it is turned on
  • if the player has a torch and it is on reduce the battery life
  • if the right bumper (xbox controller) is pressed the light will turn on if it not
  • likewise if the right bumper button is pressed when the flashlight is on, it will turn off
  • when the flashlight is collected the HUD for the battery life will be set to 100
  • if the battery life is less than or equal to 0 set it to zero and turn the flashlight off
  • if the battery life is 0 and the HUD shows that batteries are held reduce the battery count by one and add 100 to the battery life (for the flashlight)

using UnityEngine;
using System.Collections;

public class Flashlight : MonoBehaviour {

public static float BatteryLife = 100;

public Light Torch;
public float BatteryReductionSpeed = 3.0f;

void Awake()
{
Torch.enabled = false;
}

void Update()
{
if (Torch.enabled) 
{
BatteryLife = BatteryLife - (BatteryReductionSpeed * Time.deltaTime);

}

if (Input.GetButtonDown ("RightBumper") && HUD.HasFlashlight && !Torch.enabled) 
{
if (BatteryLife <= 0 && HUD.BatteryCount>0)
{
HUD.BatteryCount--;
BatteryLife = 100;
}
Torch.enabled = true;
else if (Input.GetButtonDown ("RightBumper") && HUD.HasFlashlight && Torch.enabled)
{
Torch.enabled = false;
}

if (BatteryLife <= 0) 
{
BatteryLife = 0;
Torch.enabled = false;
}
}
}

No comments:

Post a Comment