UnityGameProjectsCode / InTheDarkGame / Level / Lights / MovingSpotWallLight.cs
MovingSpotWallLight.cs
Raw
using UnityEngine;

public class MovingSpotWallLight : SpottingWallLight
{
    public float startingZ, endingZ, movementSpeed;
    private float baseStartZ, baseEndZ;
    private float startTime, journeyLength;
    public AudioSource turnAudio;
    public AudioSource alarmAudio;

    private void Start()
    {
        SpottingLightStart();

        startTime = Time.time;
        journeyLength = Mathf.Abs(startingZ + endingZ);
        baseStartZ = startingZ;
        baseEndZ = endingZ;
    }

    private void FixedUpdate()
    {
        SpottingLightUpdate();

        if (!GetPlayerSpotted())
        {
            if (alarmAudio.isPlaying && GetPlayerTraceState() == false)
                alarmAudio.Stop();

            if (startingZ != baseStartZ || startingZ != baseEndZ)
                if (endingZ == baseStartZ)
                    startingZ = baseEndZ;
                else
                    startingZ = baseStartZ;

            float distCovered = (Time.time - startTime) * movementSpeed;
            float fracJourney = distCovered / journeyLength;

            //using a given start and end float, get the current position of the rotation
            float zRot = Mathf.Lerp(startingZ, endingZ, fracJourney);

            //set the float from the lerp to the z rotation of the object
            transform.rotation = Quaternion.Euler(0, 0, zRot);

            //if the journey is complete, reverse the movement and start again
            if (fracJourney >= 1)
            {
                float tempStart = startingZ;
                startingZ = endingZ;
                endingZ = tempStart;
                startTime = Time.time;
            }


            if (turnAudio.isPlaying && fracJourney < 0.1f && fracJourney > 0.9f)
            {
                turnAudio.Stop();
            }

            if ((fracJourney > 0.1f && fracJourney < 0.9f) && !turnAudio.isPlaying)
            {
                turnAudio.Play();
            }
        }
        else
        {
            turnAudio.Stop();

            if (!alarmAudio.isPlaying)
                alarmAudio.Play();

            startTime += Time.fixedDeltaTime;
            startingZ = transform.rotation.z;
            journeyLength = Mathf.Abs(startingZ + endingZ);
        }
    }
}