I have some clouds that I want to move across the sky. I’m wondering how to write a code that will move them from their starting position and then once they hit the end (essentially because there’s only a certain amount of cloud prefabs I have in the scene) will loop continuously and smoothly. Can anyone help?
You spawn the cloud prefab above the map, have a starting point marked, have the cloulds move at a specific rate across the sky. Once They reach beyond a certain point, you set their position to the starting point.
Here is something I wrote a while back that will spawn randomly sized clouds with random speed.
Will need a prefab of the cloud and they will spawn around the CloudMaker
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CloudMaker : MonoBehaviour
{
public Cloud cloudTemplate;
public Vector2 spawnHeight = new Vector2(3, 4);
public float SpawnFrequency = 2;
public float SpawnWidth = 200;
private float lastSpawn = 0;
// Update is called once per frame
void FixedUpdate ()
{
if (lastSpawn >= SpawnFrequency)
{
var cloud = Instantiate(cloudTemplate, transform, false);
cloud.Initialize();
var y = Random.Range(spawnHeight.x, spawnHeight.y);
var x = SpawnWidth / 2 * cloud.MoveDirection.x;
var z = SpawnWidth / 2 * cloud.MoveDirection.z;
cloud.transform.position = new Vector3(x, y, cloud.transform.position.z);
lastSpawn = 0;
}
else
{
lastSpawn += Time.fixedDeltaTime;
}
}
}
Attach this to the Cloud Prefab
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Cloud : MonoBehaviour
{
public Vector3 MoveDirection { get { return m_moveDirection; } }
public Vector2 ScaleRange = new Vector2(0.25f, 1);
public Vector2 SpeedRange = new Vector2(0.025f, 0.05f);
public float MaxLife = 3;
private Vector3 m_moveDirection = Vector2.zero;
private float life;
private float moveSpeed;
public void Initialize()
{
// Randomzie speed and scale
m_moveDirection = new Vector3(Random.Range(-1.0f, 1.0f), 0, Random.Range(-1.0f, 1.0f));
moveSpeed = Random.Range(SpeedRange.x, SpeedRange.y);
float scale = Random.Range(ScaleRange.x, ScaleRange.y);
transform.localScale = new Vector2(scale, scale);
}
IEnumerator Start()
{
yield return new WaitForSeconds(MaxLife);
Destroy(gameObject);
}
void FixedUpdate ()
{
Vector3 move = m_moveDirection * moveSpeed;
transform.position += move;
}
}