Here is the script starting from a Rotate method section:
public class ShadowSpawner : MonoBehaviour {
public void Rotate() {
// Rotate shadow figure towards target direction
shadowInstance.transform.rotation = Quaternion.Slerp(
shadowInstance.transform.rotation,
Quaternion.LookRotation(targetDir),
Time.deltaTime * 5f);
}
void Update() {
if(Time.time > nextSpawnTime) {
float spawnY = player.position.y;
float spawnX = Random.Range(-10f, 10f);
float spawnZ = Random.Range(10f, 20f);
GameObject shadowInstance;
if(objectPool.TryGetObject(out shadowInstance)) {
shadowInstance.SetActive(true);
}
else {
shadowInstance = Instantiate(shadowFigurePrefab);
}
shadowInstance.transform.position = new Vector3(spawnX, spawnY, spawnZ);
Vector3 targetDir = (player.position - shadowInstance.transform.position).normalized;
StartCoroutine(FadeRoutine(shadowInstance));
nextSpawnTime = Time.time + Random.Range(5f, 10f);
}
}
IEnumerator FadeRoutine(GameObject shadow) {
while(shadow.GetComponent<SkinnedMeshRenderer>().material.color.a > 0) {
Rotate();
shadow.GetComponent<SkinnedMeshRenderer>().material.color -= Time.deltaTime * Color.white;
yield return null;
}
shadow.SetActive(false);
}
}
This starts by defining a Rotate method to smoothly rotate the shadow figure prefab towards the target direction of the player. The Update and FadeRoutine methods are then filled in around that to spawn, position, fade and deactivate the shadow prefab over time.