Certainly! Below is a Unity C# script that simulates simple Minecraft-style clouds. The script generates cloud meshes using Perlin noise, moves them in a specified direction, and efficiently spawns/despawns them by regenerating the mesh only when necessary. All cloud cubes are merged into a single mesh to optimize rendering performance.
using UnityEngine;
using System.Collections.Generic;
[RequireComponent(typeof(MeshFilter), typeof(MeshRenderer))]
public class CloudGenerator : MonoBehaviour
{
// Cloud generation settings
public int width = 100; // Width of the cloud area
public int length = 100; // Length of the cloud area
public float cubeSize = 1f; // Size of each cloud cube
public float noiseScale = 10f; // Scale of the Perlin noise
public float threshold = 0.5f; // Noise threshold for cloud formation
// Cloud movement settings
public float speed = 1f; // Speed of cloud movement
public Vector3 direction = Vector3.right; // Direction of cloud movement
private MeshFilter meshFilter; // MeshFilter component
private Mesh mesh; // Combined cloud mesh
private Mesh cubeMesh; // Single cube mesh for reuse
private float noiseOffsetX = 0f; // Perlin noise offset in X
private float noiseOffsetY = 0f; // Perlin noise offset in Y
void Start()
{
// Initialize components
meshFilter = GetComponent<MeshFilter>();
mesh = new Mesh();
meshFilter.mesh = mesh;
// Create a reusable cube mesh
cubeMesh = CreateCubeMesh(cubeSize);
// Generate the initial cloud mesh
GenerateCloudMesh();
}
void Update()
{
MoveClouds();
}
// Generates the cloud mesh based on Perlin noise
void GenerateCloudMesh()
{
List<CombineInstance> combineList = new List<CombineInstance>();
// Loop through the grid and place cubes based on noise
for (int x = 0; x < width; x++)
{
for (int z = 0; z < length; z++)
{
float sampleX = (x + noiseOffsetX) / noiseScale;
float sampleZ = (z + noiseOffsetY) / noiseScale;
// Sample Perlin noise
float noiseValue = Mathf.PerlinNoise(sampleX, sampleZ);
if (noiseValue > threshold)
{
// Position for the cube
Vector3 position = new Vector3(x * cubeSize, 0, z * cubeSize);
// Combine cube mesh at the position
CombineInstance ci = new CombineInstance();
ci.mesh = cubeMesh;
ci.transform = Matrix4x4.Translate(position);
combineList.Add(ci);
}
}
}
// Combine all cube meshes into one mesh
mesh = new Mesh();
mesh.CombineMeshes(combineList.ToArray(), true, true);
meshFilter.mesh = mesh;
}
// Moves the cloud mesh in the specified direction
void MoveClouds()
{
// Move the entire cloud mesh
Vector3 delta = direction.normalized * speed * Time.deltaTime;
transform.position += delta;
// Update noise offsets for cloud regeneration
noiseOffsetX += delta.x / cubeSize;
noiseOffsetY += delta.z / cubeSize;
// Regenerate the cloud mesh when moved by at least one cube size
if (Mathf.Abs(noiseOffsetX) >= 1f || Mathf.Abs(noiseOffsetY) >= 1f)
{
// Wrap the noise offsets to prevent overflow
noiseOffsetX = Mathf.Repeat(noiseOffsetX, 1f);
noiseOffsetY = Mathf.Repeat(noiseOffsetY, 1f);
GenerateCloudMesh();
}
}
// Creates a cube mesh to represent a cloud block
Mesh CreateCubeMesh(float size)
{
Mesh mesh = new Mesh();
float s = size * 0.5f;
// Define the vertices of the cube
Vector3[] vertices = {
// Front face
new Vector3(-s, -s, s), new Vector3(s, -s, s), new Vector3(s, s, s), new Vector3(-s, s, s),
// Back face
new Vector3(-s, -s, -s), new Vector3(-s, s, -s), new Vector3(s, s, -s), new Vector3(s, -s, -s),
// Left face
new Vector3(-s, -s, -s), new Vector3(-s, -s, s), new Vector3(-s, s, s), new Vector3(-s, s, -s),
// Right face
new Vector3(s, -s, -s), new Vector3(s, s, -s), new Vector3(s, s, s), new Vector3(s, -s, s),
// Top face
new Vector3(-s, s, s), new Vector3(s, s, s), new Vector3(s, s, -s), new Vector3(-s, s, -s),
// Bottom face
new Vector3(-s, -s, s), new Vector3(-s, -s, -s), new Vector3(s, -s, -s), new Vector3(s, -s, s),
};
// Define the triangles of the cube
int[] triangles = {
// Front face
0, 2, 1, 0, 3, 2,
// Back face
4, 6, 5, 4, 7, 6,
// Left face
8, 10, 9, 8, 11, 10,
// Right face
12, 14, 13, 12, 15, 14,
// Top face
16, 18, 17, 16, 19, 18,
// Bottom face
20, 22, 21, 20, 23, 22,
};
// Assign vertices and triangles to the mesh
mesh.vertices = vertices;
mesh.triangles = triangles;
mesh.RecalculateNormals();
return mesh;
}
}
How to Use the Script:
-
Create a New GameObject:
- In your Unity scene, create an empty GameObject (e.g.,
Clouds).
-
Attach the Script:
- Attach the
CloudGenerator script to the GameObject.
-
Assign a Material:
- The script requires a
MeshRenderer component, which should be automatically added due to the [RequireComponent] attribute.
- Assign a material to the
MeshRenderer. A simple unlit white material works well to simulate clouds.
-
Configure the Parameters:
- Width and Length: Adjust to set the size of the cloud field.
- Cube Size: Set the size of each cloud block (Minecraft clouds are usually 4 units wide).
- Noise Scale: Controls the variations in the cloud formation. Lower values make larger clouds.
- Threshold: Determines how dense the clouds are. Lower values result in more clouds.
- Speed and Direction: Adjust to change how fast and in which direction the clouds move.
-
Run the Scene:
- Press Play to see the clouds generated and moving across the scene.
Optimization Notes:
- Mesh Combining: By combining all cloud cubes into a single mesh, we reduce draw calls and improve rendering performance.
- Mesh Regeneration: The mesh is only regenerated when the clouds have moved a significant distance (at least one cube size), reducing unnecessary computations.
- Perlin Noise Offsets: By updating noise offsets based on movement, we create a seamless transition of cloud formations without sudden changes.
- Reusable Cube Mesh: The cube mesh is created once and reused for all cloud blocks, saving memory and processing time.
Visual Tweaks:
- Flat Clouds: To make the clouds flatter like in Minecraft, you can adjust the
cubeSize in the Y-axis when creating the cube mesh. For example, use a smaller value for the Y dimension.
- Cloud Height: If you want the clouds to be at a certain height above the ground, adjust the Y position in the
position vector when placing cubes.
- Materials and Textures: Apply cloud textures or adjust material settings to enhance the visual appearance of the clouds.
Final Thoughts:
This script provides a simple and efficient way to simulate Minecraft-style clouds in Unity. By utilizing Perlin noise and mesh combining, it ensures that the clouds are both visually appealing and performance-friendly.