Created
October 28, 2022 21:18
-
-
Save keidaroo/67602b17b6598371fc2240ca7cd50a4f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections; | |
using System.Collections.Generic; | |
using System.Numerics; | |
using UnityEngine; | |
using Vector3 = UnityEngine.Vector3; | |
public class PropsPositionCalculator2D : MonoBehaviour | |
{ | |
const int propsCount = 6; | |
private const float shadowPaperZ = -0.0075f; | |
public Transform lightPosition; | |
public GameObject[] props = new GameObject[propsCount]; | |
List<Vector3> calculatedPositions = new List<Vector3>(); | |
bool isMoving = false; | |
internal void CalculatePositions(Vector3[] targetPositions) | |
{ | |
if(isMoving) | |
{ | |
return; | |
} | |
isMoving = true; | |
calculatedPositions.Clear(); | |
for (int i = 0; i < propsCount; i++) | |
{ | |
float zPercent = (props[i].transform.position.z - shadowPaperZ) / (lightPosition.position.z - shadowPaperZ); | |
if (zPercent < 0 || zPercent > 1) | |
{ | |
Debug.LogError("zPercent is out of range"); | |
return; | |
} | |
Vector3 calculatedPosition = Vector3.Lerp(lightPosition.position, props[i].transform.position, zPercent); | |
calculatedPositions.Add(calculatedPosition); | |
} | |
StartCoroutine(MoveProps()); | |
} | |
IEnumerator MoveProps() | |
{ | |
const float duration = 10000f; | |
Vector3[] initialPos = new Vector3[propsCount]; | |
for (int i = 0; i < props.Length; i++) | |
{ | |
initialPos[i] = props[i].transform.position; | |
} | |
float elapsedTime = 0; | |
while (true) | |
{ | |
if (elapsedTime >= duration) | |
{ | |
break; | |
} | |
yield return new WaitForSeconds(0.01f); | |
elapsedTime += 10; | |
for (int i = 0; i < props.Length; i++) | |
{ | |
props[i].transform.position = Vector3.Lerp(initialPos[i], calculatedPositions[i], elapsedTime / duration); | |
} | |
} | |
isMoving = false; | |
yield return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment