Alle Dateien
Welt244 Zeilen

VoxelWorld.cs

Das Herzstück: ein dreidimensionales Block-Array, Prozedural-Generierung mit Perlin-Noise, Bäume, ein Holzarten-Rundgang am Kartenrand und ein Voxel-Raycast, der beim Zielen den getroffenen Block und seine Fläche liefert.

Assets/Scripts/VoxelWorld.cs
using UnityEngine;

namespace Blockwerk
{
    /// <summary>Die Welt als reines Datenmodell: keine GameObjects, keine Meshes.</summary>
    public class VoxelWorld
    {
        public const int SizeX = 48;
        public const int SizeZ = 48;
        public const int Height = 40;
        public const int WaterLevel = 5;

        private readonly BlockType[,,] _blocks = new BlockType[SizeX, Height, SizeZ];
        // Ausrichtung je Zelle: Bei Treppen steht hier, wohin sie ansteigen.
        private readonly byte[,,] _facing = new byte[SizeX, Height, SizeZ];

        public int Seed { get; private set; }

        public VoxelWorld(int seed)
        {
            Seed = seed;
            Generate();
        }

        public static bool InBounds(int x, int y, int z)
        {
            return x >= 0 && x < SizeX && y >= 0 && y < Height && z >= 0 && z < SizeZ;
        }

        public BlockType Get(int x, int y, int z)
        {
            return InBounds(x, y, z) ? _blocks[x, y, z] : BlockType.Air;
        }

        /// <summary>Setzt einen Block. Die unterste Ebene (y = 0) bleibt unzerstörbar.</summary>
        public bool Set(int x, int y, int z, BlockType type)
        {
            return Set(x, y, z, type, 0);
        }

        /// <summary>Setzt einen Block samt Ausrichtung — Treppen merken sich, wohin sie ansteigen.</summary>
        public bool Set(int x, int y, int z, BlockType type, int facing)
        {
            if (!InBounds(x, y, z) || y == 0) return false;
            _blocks[x, y, z] = type;
            _facing[x, y, z] = (byte)(BlockInfo.IsStairs(type) ? facing & 3 : 0);
            return true;
        }

        /// <summary>Ausrichtung einer Treppe: 0 = Norden, 1 = Osten, 2 = Süden, 3 = Westen.</summary>
        public int Facing(int x, int y, int z)
        {
            return InBounds(x, y, z) ? _facing[x, y, z] : 0;
        }

        /* ---------------- Generierung ---------------- */

        private float Noise(float x, float z)
        {
            return Mathf.PerlinNoise(x + Seed * 0.731f, z + Seed * 0.417f);
        }

        private int HeightAt(int x, int z)
        {
            float wide = Noise(x * 0.07f + 120f, z * 0.07f + 120f);
            float detail = Noise(x * 0.19f, z * 0.19f);
            float hills = Noise(x * 0.035f + 40f, z * 0.035f + 40f);
            float raw = 2f + wide * 8f + detail * 2.2f + hills * hills * 6f;
            return Mathf.Clamp(Mathf.RoundToInt(raw), 1, Height - 10);
        }

        private void Generate()
        {
            for (int x = 0; x < SizeX; x++)
            {
                for (int z = 0; z < SizeZ; z++)
                {
                    int h = HeightAt(x, z);
                    bool beach = h <= WaterLevel;

                    for (int y = 0; y <= h; y++)
                    {
                        BlockType type = BlockType.Stone;
                        if (y == h) type = beach ? BlockType.Sand : BlockType.Grass;
                        else if (y > h - 3) type = beach ? BlockType.Sand : BlockType.Dirt;
                        _blocks[x, y, z] = type;
                    }

                    for (int y = h + 1; y <= WaterLevel; y++)
                        _blocks[x, y, z] = BlockType.Water;
                }
            }

            PlantWoodRow();
            PlantTrees();
        }

        /// <summary>Jede Holzart einmal am Kartenrand: Stamm mit einem Brettblock darüber.</summary>
        private void PlantWoodRow()
        {
            int z = SizeZ - 2;
            int last = Mathf.Max(1, BlockInfo.Logs.Length - 1);

            for (int i = 0; i < BlockInfo.Logs.Length; i++)
            {
                int x = 3 + Mathf.RoundToInt(i * (SizeX - 7f) / last);
                int y = SurfaceY(x, z);

                if (y + 1 >= Height) continue;

                _blocks[x, y, z] = BlockInfo.Logs[i];
                _blocks[x, y + 1, z] = BlockInfo.Planks[i];
            }
        }

        private void PlantTrees()
        {
            var random = new System.Random(Seed);

            for (int i = 0; i < 120; i++)
            {
                int x = random.Next(2, SizeX - 2);
                int z = random.Next(2, SizeZ - 2);
                int h = SurfaceY(x, z);

                if (h <= WaterLevel + 1) continue;
                if (_blocks[x, h - 1, z] != BlockType.Grass) continue;
                if (_blocks[x, h, z] != BlockType.Air) continue;

                BuildTree(x, h, z);
            }
        }

        private void BuildTree(int x, int y, int z)
        {
            int trunk = 4;
            for (int i = 0; i < trunk; i++) _blocks[x, y + i, z] = BlockType.OakLog;

            int top = y + trunk - 1;
            for (int dx = -2; dx <= 2; dx++)
            {
                for (int dz = -2; dz <= 2; dz++)
                {
                    for (int dy = 0; dy <= 2; dy++)
                    {
                        int ring = Mathf.Abs(dx) + Mathf.Abs(dz);
                        if (ring > 3) continue;
                        if (dy == 2 && ring > 1) continue;

                        int px = x + dx;
                        int py = top + dy;
                        int pz = z + dz;

                        if (!InBounds(px, py, pz)) continue;
                        if (_blocks[px, py, pz] != BlockType.Air) continue;
                        _blocks[px, py, pz] = BlockType.Leaf;
                    }
                }
            }
        }

        /// <summary>Erste freie Zelle über dem Boden an dieser Stelle.</summary>
        public int SurfaceY(int x, int z)
        {
            for (int y = Height - 1; y > 0; y--)
            {
                BlockType type = _blocks[x, y, z];
                if (type != BlockType.Air && type != BlockType.Water) return y + 1;
            }
            return 1;
        }

        /* ---------------- Voxel-Raycast ---------------- */

        /// <summary>
        /// Amanatides-Woo-Traversierung: läuft Zelle für Zelle durch das Gitter und
        /// liefert den ersten festen Block samt Eintrittsfläche (für das Setzen daneben).
        /// </summary>
        public bool Raycast(Ray ray, float maxDistance, out Vector3Int block, out Vector3Int normal)
        {
            Vector3 direction = ray.direction.normalized;
            Vector3 origin = ray.origin;

            int x = Mathf.FloorToInt(origin.x);
            int y = Mathf.FloorToInt(origin.y);
            int z = Mathf.FloorToInt(origin.z);

            int stepX = direction.x >= 0f ? 1 : -1;
            int stepY = direction.y >= 0f ? 1 : -1;
            int stepZ = direction.z >= 0f ? 1 : -1;

            float deltaX = direction.x == 0f ? float.PositiveInfinity : Mathf.Abs(1f / direction.x);
            float deltaY = direction.y == 0f ? float.PositiveInfinity : Mathf.Abs(1f / direction.y);
            float deltaZ = direction.z == 0f ? float.PositiveInfinity : Mathf.Abs(1f / direction.z);

            float maxX = FirstCrossing(origin.x, direction.x, x);
            float maxY = FirstCrossing(origin.y, direction.y, y);
            float maxZ = FirstCrossing(origin.z, direction.z, z);

            normal = Vector3Int.up;
            float distance = 0f;

            while (distance <= maxDistance)
            {
                if (InBounds(x, y, z) && IsSolid(Get(x, y, z)))
                {
                    block = new Vector3Int(x, y, z);
                    return true;
                }

                if (maxX < maxY && maxX < maxZ)
                {
                    x += stepX; distance = maxX; maxX += deltaX;
                    normal = new Vector3Int(-stepX, 0, 0);
                }
                else if (maxY < maxZ)
                {
                    y += stepY; distance = maxY; maxY += deltaY;
                    normal = new Vector3Int(0, -stepY, 0);
                }
                else
                {
                    z += stepZ; distance = maxZ; maxZ += deltaZ;
                    normal = new Vector3Int(0, 0, -stepZ);
                }
            }

            block = Vector3Int.zero;
            return false;
        }

        private static bool IsSolid(BlockType type)
        {
            return type != BlockType.Air && type != BlockType.Water;
        }

        private static float FirstCrossing(float origin, float direction, int cell)
        {
            if (Mathf.Approximately(direction, 0f)) return float.PositiveInfinity;
            float boundary = direction > 0f ? cell + 1 : cell;
            return Mathf.Abs((boundary - origin) / direction);
        }
    }
}