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

public class MovingWallLight : WallLight
{
    public float startingZ, endingZ, movementSpeed;
    public AudioSource turnAudio;
    private float startTime, journeyLength;

    private void Start()
    {
        LightStart();

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

    private void FixedUpdate()
    {
        LightUpdate();

        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();
        }
    }
}