Skip to content

Instantly share code, notes, and snippets.

@keidaroo
Created October 28, 2022 21:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save keidaroo/67602b17b6598371fc2240ca7cd50a4f to your computer and use it in GitHub Desktop.
Save keidaroo/67602b17b6598371fc2240ca7cd50a4f to your computer and use it in GitHub Desktop.
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