为什么我的程序生成的网格没有任何阴影?

问题描述 投票:0回答:1

我使用 C# 生成了一个网格,它有效,但没有阴影。我希望阴影能够像 Unity 中的内置地形一样工作,但事实并非如此。

我上面有一个指向网格的定向光源,并且网格渲染器设置为投射阴影和接收阴影 = ON。会不会和着色器有关?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[RequireComponent(typeof(MeshFilter))]
public class ChunkGeneration : MonoBehaviour
{
    Mesh mesh;

    Vector3[] vertices;
    int[] triangles;

    public int size = 100;
    // Start is called before the first frame update
    void Start()
    {
        //Create a new mesh 
        mesh = new Mesh();
        CreateShape();
        UpdateMesh();
        
        GetComponent<MeshFilter>().mesh = mesh;
        GetComponent<MeshCollider>().sharedMesh = mesh;
    }

    // Update is called once per frame
    void Update()
    {
    }

    void CreateShape() 
    {
        //Create vertices for mesh
        vertices = new Vector3[(size + 1 ) * (size + 1)];

        for (int i = 0, z = 0; z < size + 1; z++) {
            for (int x = 0; x < size + 1; x++) {

                float y = Mathf.PerlinNoise(x * .3f, z * .3f);
                vertices[i] = new Vector3(x, y, z); //WHY WHEN Z IN Y_VALUE IT WORK???
                i++;
            }
        }

        //Create triangles for mesh
        triangles = new int[size * size * 6];

        int vert = 0;
        int tris = 0;

        for (int z = 0; z < size; z++) 
        {
            for (int x = 0; x < size; x++) 
            {
                triangles[tris + 0] = vert + 0;
                triangles[tris + 1] = vert + size + 1;
                triangles[tris + 2] = vert + 1;
                triangles[tris + 3] = vert + 1;
                triangles[tris + 4] = vert + size + 1;
                triangles[tris + 5] = vert + size + 2;

                vert++;
                tris += 6;
            }
            vert++;
        }
    }

    void UpdateMesh() 
    {
        //Reset and update mesh
        mesh.Clear();
        mesh.vertices = vertices;
        mesh.triangles = triangles;
    }
}
c# unity-game-engine mesh shadow
1个回答
2
投票

这是因为你还没有计算Normal。因此,

MeshRenderer
仍然没有识别出哪一侧是Face的主方向以及如何计算光线。添加以下行,问题就解决了。

void UpdateMesh() {
    //Reset and update mesh
    mesh.Clear();

    mesh.vertices = vertices;
    mesh.triangles = triangles;
    
    mesh.RecalculateNormals(); // You need to calculate Normals..
}
© www.soinside.com 2019 - 2024. All rights reserved.