using UnityEngine; using System.Collections; using System;//for Math class public class MovingWall : MonoBehaviour { public float fSpeed = 100.0f; public Vector3 v3fFinalPos; private Vector3 v3fInitialPos; private bool bMovingToFinal = true; //Cache these values since they never change and are expensive to re-calculate each frame. private Vector3 v3fDirectionToFinalUnit; private Vector3 v3fDirectionToInitialUnit; private bool bInRecursiveCall = false; private GUIController m_pGUIController; // Use this for initialization void Start () { v3fInitialPos = transform.position; bMovingToFinal = true; bInRecursiveCall = false; //Calculate these values once instead of each frame. (Magnitude contains an implicit square root, which is computationally expensive!) Vector3 v3fTotalDisplacement = v3fFinalPos - v3fInitialPos; v3fDirectionToFinalUnit = v3fTotalDisplacement / v3fTotalDisplacement.magnitude; v3fDirectionToInitialUnit = -v3fDirectionToFinalUnit; //Get the GUIController so we know whether or not to update. m_pGUIController = GameObject.FindGameObjectWithTag("GUIController").GetComponent("GUIController") as GUIController; } //Called once per physics update void FixedUpdate() { //Just return if game is inactive if (!m_pGUIController.IsGameActive()) return; _UpdateMovement(Time.fixedDeltaTime); } //Actually updates the movement private void _UpdateMovement(float fDeltaT) { //Do nothing on 0 update and prevent divide-by-0 later. ///if (fDeltaT == 0.0) //We cannot directly compare if (Math.Abs(fDeltaT) < 0.0001f) return; float fMovement = fDeltaT * fSpeed; //Find distance to destination float fDistanceToDestination = 0.0f; if (bMovingToFinal) fDistanceToDestination = (v3fFinalPos - transform.position).magnitude; else fDistanceToDestination = (v3fInitialPos - transform.position).magnitude; //If we can make it to the destination this frame, do so and re-call update with remaining time if (fMovement >= fDistanceToDestination) { //Move to end point float fPartialMovement; if (bMovingToFinal) { fPartialMovement = (v3fFinalPos - transform.position).magnitude; transform.position = v3fFinalPos; } else { fPartialMovement = (v3fInitialPos - transform.position).magnitude; transform.position = v3fInitialPos; } //Toggle direction bMovingToFinal = !bMovingToFinal; //Guard against recursing more than once. if (bInRecursiveCall) { bInRecursiveCall = false; return; } //Recall Update with remaining time else { bInRecursiveCall = true; _UpdateMovement(fDeltaT * (1.0f - (fPartialMovement / fMovement))); } } //Else move as far as we can else { if (bMovingToFinal) ///transform.position += ((v3fFinalPos - v3fInitialPos) / (v3fFinalPos - v3fInitialPos).magnitude) * fMovement; transform.position += v3fDirectionToFinalUnit * fMovement; else ///transform.position += ((v3fInitialPos - v3fFinalPos) / (v3fInitialPos - v3fFinalPos).magnitude) * fMovement; transform.position += v3fDirectionToInitialUnit * fMovement; bInRecursiveCall = false; } } }