ProjectSquareBall/Assets/Scripts/Mover.cs
2024-10-13 16:13:44 +05:30

441 lines
14 KiB
C#

using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using TMPro;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.Rendering.Universal;
using UnityEngine.SceneManagement;
using UnityEngine.U2D;
using UnityEngine.UI;
public class Mover : MonoBehaviour
{
[Header("Prep Mode stuff")]
public GameObject prepModePanel;
public TMP_Text txtProgress;
public Button btnBackToPrep;
public Button btnSave;
public Button btnRun;
[Header("End of prep mode stuff")]
public Vector3 movingSpeed;
public float loudBoost = 1f;
public float momentumBoost = 1f;
public float loudnessThreshold = 0.08f;
public float yieldTime = 0.2f;
float LastTime;
public LineRenderer botLineRenderer, topLineRenderer;
public DrawShape botDrawer;
public DrawShape topDrawer;
public GameObject txtDebug;
public bool isDebug = false;
public Light2D glowLight;
public Transform scalingObject;
public float scalingEffect = 0.1f;
public float scalingResetLerp = 0.05f;
Vector3 defaultSize;
public float glowReductionSpeed = 2f;
public float fovZoomingSpeed = 0.5f;
[SerializeField]
public List<RecorderStep> currentSteps = new List<RecorderStep>();
[SerializeField]
List<RecorderStep> recordedSteps = new List<RecorderStep>();
public string currentStepsJson = "";
public string recordedStepsJson;
public bool playReplay = false;
float defFOV;
List<float> recordedTimes = null;
List<float> pastTimes = null;
float startedTime =0;
private void Awake()
{
startedTime = Time.time;
defaultSize = scalingObject.localScale;
defFOV = Camera.main.orthographicSize;
if (!playReplay) { themeMan.Randomize(); }
if(PrepConnector.saveLoadData != null){
recordedTimes = PrepConnector.saveLoadData.hits;
}
playReplay = PlayerPrefs.HasKey("prep_data");
if(playReplay){
recordedStepsJson = PlayerPrefs.GetString("prep_data");
}
Screen.orientation = ScreenOrientation.Portrait;
}
public List<float> allHits = new List<float>();
private void Start()
{
// Application.targetFrameRate = 164;
if(recordedStepsJson.Length > 1 && playReplay)
{
recordedSteps = JsonConvert.DeserializeObject<List<RecorderStep>>(recordedStepsJson);
GenerateRecordedPlatform();
}else{
//Show prep mode
prepModePanel.SetActive(true);
btnBackToPrep.onClick.AddListener(()=>{ SceneManager.LoadScene("prep"); });
btnRun.onClick.AddListener(OnRun);
btnSave.onClick.AddListener(OnSaveBtn);
}
}
void OnRun(){
PlayerPrefs.SetString("prep_data", currentStepsJson);
PlayerPrefs.Save();
SceneManager.LoadScene("Runner");
}
void OnSaveBtn(){
}
int totalHits = 0;
public void SetHits(List<float> hits){
allHits.AddRange(hits);
float lastTime = hits[hits.Count-1];
for(int i=1; i < 3; i++){
foreach(float hit in hits){
allHits.Add(hit + lastTime*i);
}
}
totalHits = hits.Count * 3;
}
Vector3 LastPos;
float movingSpeedMultiplier = 1;
public bool manualFlip = true;
public bool manualFlipX = false;
void Update()
{
if (glowLight.intensity > 0)
{
glowLight.intensity=(glowLight.intensity- (Time.deltaTime * glowReductionSpeed));
}
trailParticle.emissionRate = 300 * (glowLight.intensity);
if (playReplay) { Camera.main.orthographicSize -= Time.deltaTime * fovZoomingSpeed; }
if (!manualFlip) { return; }
if(Input.GetKeyDown(KeyCode.LeftArrow))
{
manualFlipX = false;
movingSpeed.x = -Mathf.Abs(movingSpeed.x);
}else if (Input.GetKeyDown(KeyCode.RightArrow))
{
manualFlipX = false;
movingSpeed.x = Mathf.Abs(movingSpeed.x);
}else if (Input.GetKeyDown(KeyCode.UpArrow))
{
manualFlipX = true;
movingSpeed.y = Mathf.Abs(movingSpeed.y);
}else if (Input.GetKeyDown(KeyCode.DownArrow))
{
manualFlipX = true;
movingSpeed.y = -Mathf.Abs(movingSpeed.y);
}
cube.rotation = Quaternion.Lerp(cube.rotation, targetRotation, cubeRotateSpeed * Time.deltaTime);
}
void FixedUpdate()
{
time=Time.time - startedTime;
movingSpeedMultiplier = Mathf.Lerp(movingSpeedMultiplier, 1, Time.deltaTime * 2);
float boostedX = movingSpeed.x * Mathf.Clamp((movingSpeedMultiplier * 1),0,1.25f);
float boostedY = movingSpeed.y * (movingSpeedMultiplier * 1f);
//transform.Translate(new Vector3(boostedX, boostedY)*Time.deltaTime);
transform.Translate(movingSpeed * Time.deltaTime * movingSpeedMultiplier);
if(recordedStepsJson.Length > 1 && playReplay)
{
PostWork();
}
else
{
PreWork();
}
}
void GenerateRecordedPlatform()
{
List<Vector3> botPoints = GetBottomPoints();
botLineRenderer.positionCount = botPoints.Count;
botLineRenderer.SetPositions(botPoints.ToArray());
List<Vector3> topPoints = GetTopPoints();
topLineRenderer.positionCount = topPoints.Count;
topLineRenderer.SetPositions(topPoints.ToArray());
botDrawer.Draw(botPoints, new Vector3(0, 30));
topDrawer.Draw(topPoints, new Vector3(0,-30));
}
void FixSpriteShape(SpriteShapeController ssc)
{
if (ssc.spriteShape != null && ssc.spriteShape.fillTexture != null)
{
// Bake the mesh after setting up the spline
ssc.BakeMesh();
}
else
{
Debug.LogError("SpriteShape or fillTexture is missing.");
}
ssc.BakeMesh();
ssc.GetComponent<SpriteShapeRenderer>().enabled = true;
}
List<Vector3> bottomPoints = new List<Vector3>();
List<Vector3> topPoints = new List<Vector3>();
public List<Vector3> GetBottomPoints()
{
List<Vector3> botPoints = new List<Vector3>();
for (int i = 0; i < recordedSteps.Count; i++)
{
Vector3 point = recordedSteps[i].point;
if (i % 2 == 0)
{
if (i > 2)
{
Vector3 prevPoint = recordedSteps[i-2].point;
float xMid = prevPoint.x + ((point.x - prevPoint.x) / (2f *xFactorBot));
xMid = recordedSteps[i - 1].point.x;
float yMid = prevPoint.y + ((point.y - prevPoint.y) / 2f);
Vector3 newP1 = new Vector3(xMid, prevPoint.y);
Vector3 newP2 = new Vector3(xMid, point.y);
botPoints.Add(newP1);
botPoints.Add(newP2);
}
botPoints.Add(point);
}
}
return botPoints;
}
public List<Vector3> GetTopPoints()
{
List<Vector3> botPoints = new List<Vector3>();
for (int i = 0; i < recordedSteps.Count; i++)
{
Vector3 point = recordedSteps[i].point;
if (i % 2 != 0)
{
if (i > 2)
{
Vector3 prevPoint = recordedSteps[i - 2].point;
float xMid = prevPoint.x + ((point.x - prevPoint.x) / (2f * xFactorTop));
float yMid = prevPoint.y + ((point.y - prevPoint.y) / 2f);
xMid = recordedSteps[i - 1].point.x; ;
Vector3 newP1 = new Vector3(xMid, prevPoint.y);
Vector3 newP2 = new Vector3(xMid, point.y);
botPoints.Add(newP1);
botPoints.Add(newP2);
}
botPoints.Add(point);
}
}
return botPoints;
}
void AddPointToShape(SpriteShapeController shapeController, Vector3 point)
{
Spline spline = shapeController.spline;
spline.InsertPointAt(spline.GetPointCount(), point);
spline.SetTangentMode(spline.GetPointCount() - 1, ShapeTangentMode.Continuous);
}
public float xFactorBot,xFactorTop = 1f;
private void OnDrawGizmos()
{
if (playReplay && !Application.isPlaying)
{
recordedSteps = JsonConvert.DeserializeObject<List<RecorderStep>>(recordedStepsJson);
List<Vector3> botPoints = GetBottomPoints();
Gizmos.color = Color.yellow;
//Bottom lines
for(int i=1; i < botPoints.Count; i++)
{
Gizmos.DrawLine(botPoints[i - 1], botPoints[i]);
}
List<Vector3> topPoints = GetTopPoints();
//top lines
for (int i = 1; i < topPoints.Count; i++)
{
Gizmos.DrawLine(topPoints[i - 1], topPoints[i]);
}
Gizmos.color = Color.red;
//moving path
for(int i =1; i < recordedSteps.Count; i++)
{
Gizmos.DrawLine(recordedSteps[i-1].point, recordedSteps[i].point);
}
}
}
float tensionBuildup = 0f;
float endTimer = 0;
public float time=0;
void PreWork()
{
bool notTooShort = (time - LastTime) > yieldTime;
bool newPrepLogic = allHits[0] <time;
if(newPrepLogic){
allHits.RemoveAt(0);
}
txtProgress.text = $"{allHits.Count} left of {totalHits}. One cycle : {(totalHits/3f).ToString("n0")}";
// bool newDynamicLogic = recordedTimes == null ? oldLoudLogic : prepLogic ;
tensionBuildup += Time.deltaTime;
if (newPrepLogic || Input.GetKeyDown(KeyCode.Space))
{
Debug.Log(LastTime - time);
//Instantiate(prefab, transform.position, Quaternion.identity);
int random = Random.Range(0, 3);
bool flippedX = LastPos.x - transform.position.x > LastPos.y - transform.position.y;
if (manualFlip) { flippedX = manualFlipX; }
if (flippedX)
{
movingSpeed.x = -movingSpeed.x;
}
else
{
movingSpeed.y = -movingSpeed.y;
}
movingSpeedMultiplier += (loudBoost) / loudnessThreshold;
movingSpeedMultiplier += tensionBuildup * momentumBoost;
LastTime = time;
currentSteps.Add(new RecorderStep(LastTime, movingSpeed, movingSpeedMultiplier, transform.position));
currentStepsJson = JsonConvert.SerializeObject(currentSteps);
LastPos = transform.position;
tensionBuildup = 0;
}
}
int index = 0;
void PostWork()
{
scalingObject.localScale = Vector3.Lerp(scalingObject.localScale, defaultSize, scalingResetLerp);
if(recordedSteps.Count <= 0) { return; }
tensionBuildup += Time.deltaTime;
if (time >= recordedSteps[0].time)
{
//Time to act
movingSpeed = recordedSteps[0].movingSpeed;
movingSpeedMultiplier = recordedSteps[0].movingSpeedMultiplier;
musicSourceToSync.time = (float)recordedSteps[0].time % (musicSourceToSync.clip.length);
if(!musicSourceToSync.isPlaying){
musicSourceToSync.Play();
}
recordedSteps.RemoveAt(0);
HitFX();
tensionBuildup = 0;
index++;
if (isDebug) { Instantiate(txtDebug, transform.position, Quaternion.identity).GetComponent<TextMeshPro>().text = index.ToString(); }
}
}
public GameObject particleFxPrefab;
public AudioSource musicSourceToSync;
public float fovChangeOnHit = 0.1f;
public ParticleSystem trailParticle;
public GameObject shockwavePrefab;
public ThemeManager themeMan;
public Transform cube;
public float cubeRotateSpeed = 15f;
Quaternion targetRotation = Quaternion.identity;
void HitFX()
{
StartCoroutine(CoroutineScaleupGlow());
Vector3 movingSpeedY = movingSpeed;
movingSpeedY.x = 0;
Vector3 hitpoint = transform.position - (movingSpeedY / 5f);
Instantiate(particleFxPrefab, hitpoint, Quaternion.LookRotation(-movingSpeedY)).GetComponent<ParticleSystem>().startColor =themeMan.mainColor;
Camera.main.orthographicSize = Mathf.Clamp(Camera.main.orthographicSize + (fovZoomingSpeed), 0,defFOV);
shockwavePrefab.GetComponent<ShockwaveShaderHelper>().Reset();
Instantiate(glowLight,hitpoint, Quaternion.identity).AddComponent<DyingLight>();
themeMan.Randomize(movingSpeedMultiplier /3f);
targetRotation *= Quaternion.Euler(0, 0, -90);
scalingObject.localScale -= (Vector3.one * scalingEffect);
// themeMan.SetColor(new Color(Random.Range(0f,1f), Random.Range(0f,1f),Random.Range(0f,1f)));
/*themeMan.r = Random.Range(0f, 1f);
themeMan.g = Random.Range(0f, 1f);
themeMan.b = Random.Range(0f, 1f);
themeMan.Refresh();*/
// Instantiate(shockwavePrefab, shockwavePrefab.transform.parent).GetComponent<ShockwaveShaderHelper>().started = true;
}
IEnumerator CoroutineScaleupGlow()
{
glowLight.intensity += 0.4f;
while(glowLight.intensity < 0.65f)
{
glowLight.intensity = (glowLight.intensity + (Time.deltaTime * glowReductionSpeed * 8));
yield return null;
}
}
}
[System.Serializable]
public class RecorderStep
{
public double time;
public Vector3 movingSpeed;
public float movingSpeedMultiplier;
public Vector3 point;
public RecorderStep(double t, Vector3 s, float m, Vector3 p)
{
time = t; movingSpeed = s; movingSpeedMultiplier = m; point = p;
}
}