using System; using System.Collections; using System.IO; using UnityEngine; public class CamRotationScenario : MonoBehaviour { [Header("Parameters")] [SerializeField] bool runOnAwake = false; [SerializeField] float rDeviationThr = 7f; [SerializeField] float rFollowDeviationThr = 3f; [Header("References")] [SerializeField] CameraEyeRotator cameraEyes = null; [SerializeField] EyeSimulator eyeSim = null; public bool IsRunning { get; private set; } = false; bool rDeviationRot = false; bool isReturningR = false; float firstTravelTime = 3f; float returnTime = 60f; Vector2 rDeviation = Vector2.zero; Vector2 rDevCurStart = Vector2.zero; float returningTime = 0f; private const string FILE_PATH = "/Results/Rotation.csv"; private StreamWriter file; private void Awake() { file = new StreamWriter(Application.dataPath + FILE_PATH, false); file.WriteLine("time;eyeX;eyeY;camX;camY"); if (runOnAwake) StartScenario(); } void Update() { if (IsRunning) { if (!rDeviationRot && (Mathf.Pow(eyeSim.RightEyeRotation.x, 2) + Mathf.Pow(eyeSim.RightEyeRotation.y, 2) > Mathf.Pow(rDeviationThr, 2))) { rDeviationRot = true; StartCoroutine(RotateCameraToDeviation()); } else if (isReturningR) { if (Mathf.Pow(eyeSim.RightEyeRotation.y - rDeviation.x, 2) + Mathf.Pow(eyeSim.RightEyeRotation.x + rDeviation.y, 2) > Mathf.Pow(rFollowDeviationThr, 2)) { isReturningR = false; StartCoroutine(RotateCameraToDeviation()); } else { rDeviation = Vector2.Lerp(rDevCurStart, Vector2.zero, returningTime / returnTime); cameraEyes.SetCameraEyesRotation(Vector2.zero, rDeviation); returningTime += Time.deltaTime; } } } } private void FixedUpdate() { try { Vector2 eyeR = eyeSim.RightEyeRotation; Vector4 camData = cameraEyes.CamData; file.WriteLine( $"{Time.time};{eyeR.x};{eyeR.y};{camData.w};{camData.z}"); } catch (Exception e) { Debug.LogError(e); throw; } } IEnumerator RotateCameraToDeviation() { float t = 0; Vector2 startR = rDeviation; while (t <= firstTravelTime) { t += Time.deltaTime; rDeviation.x = Mathf.SmoothStep(startR.x, eyeSim.RightEyeRotation.y, t / firstTravelTime); rDeviation.y = Mathf.SmoothStep(startR.y, -eyeSim.RightEyeRotation.x, t / firstTravelTime); cameraEyes.SetCameraEyesRotation(Vector2.zero, rDeviation); yield return null; } rDeviation.x = eyeSim.RightEyeRotation.y; rDeviation.y = -eyeSim.RightEyeRotation.x; cameraEyes.SetCameraEyesRotation(Vector2.zero, rDeviation); rDevCurStart = rDeviation; isReturningR = true; returnTime = rDeviation.magnitude; returningTime = 0; } public void StartScenario() { IsRunning = true; Debug.Log("Camera Rotation scenario active."); } public void CancelScenario() { IsRunning = false; StopAllCoroutines(); cameraEyes.SetCameraEyesRotation(Vector2.zero, Vector2.zero); Debug.Log("Finishing scenario."); } private void OnDestroy() { if (IsRunning) CancelScenario(); file.Close(); } }