using UnityEngine; using System.Collections; public enum ElevatorState{ Idle, Moving } public class ElevatorController : MonoBehaviour { public Trigger startTrigger; public ElevatorState state; public GameObject target; public float moveState; private float moveDirection = 1.0f; private Vector3 startupPosition; private Vector3 targetPosition; public float speed = 2.0f; public AudioSource startStopSource; public AudioSource moveSource; public AudioClip startSound; public AudioClip stopSound; public AudioClip moveSound; void Start () { startupPosition = transform.localPosition; targetPosition = startupPosition + transform.InverseTransformPoint(target.transform.position); targetPosition.z = startupPosition.z; if(startTrigger != null){ startTrigger.Trig += HandleTrig; } } void HandleTrig () { Debug.Log("Trig"); if(state == ElevatorState.Idle){ StartMovement(); } } void StartMovement(){ SetState(ElevatorState.Moving); } void SetState(ElevatorState s){ if(state == s){ return; } if(s == ElevatorState.Moving){ startStopSource.PlayOneShot(startSound); moveSource.clip = moveSound; moveSource.loop = true; moveSource.PlayDelayed(0.5f); }else{ moveSource.Stop(); startStopSource.PlayOneShot(stopSound); moveDirection = -moveDirection; } state = s; Debug.Log("Set state: " + state); } void FixedUpdate(){ } void Update () { if(state == ElevatorState.Moving){ Vector3 t = moveDirection > 0 ? targetPosition : startupPosition; Vector3 dir = t - transform.localPosition; float dist = dir.magnitude; if(dist <= 0.001f){ transform.localPosition = t; SetState(ElevatorState.Idle); }else{ float moveLen = speed * Time.deltaTime; if(moveLen > dist){ moveLen = dist; } transform.localPosition += dir.normalized * moveLen; } } } }