Unity教程之-制作闪亮的星星Star(二):创建Shader

继续上篇文章《Unity教程之-制作闪亮的星星Star(一):动态的创建Mesh》我们建立一个新的Shader将它命名为Star,然后写入以下代码。

什么是CGPROGRAM?

Basically, data flows from the Unity engine into the graphics card, where it’s processed per vertex. Then interpolated data flows from the vertices down to the individual pixels. In this case, we pass position and color data all the way down. The only additional thing we do is convert vertex positions from world space to screen space.
The statements above the CGPROGRAM switch off default lighting and depth buffer writing. Culling is switched off so we can see the triangles from both sides, not just the front. “Blend SrcAlpha OneMinusSrcAlpha” is default alpha blending, allowing for transparency.

为什么不使用fixed-function shader?

fixed-function shader已经属于过时的技术了。 CGPROGRAM 在将数据转化成屏幕像素方面拥有更强大的功能。

Shader "Star"{
    SubShader{
        Tags{ "Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent"}
        Blend SrcAlpha OneMinusSrcAlpha
        Cull Off
        Lighting Off
        ZWrite Off
        Pass{
            CGPROGRAM
                #pragma vertex vert
                #pragma fragment frag

                struct data {
                    float4 vertex : POSITION;
                    fixed4 color: COLOR;
                };

                data vert (data v) {
                    v.vertex = mul(UNITY_MATRIX_MVP, v.vertex);
                    return v;
                }

                fixed4 frag(data f) : COLOR {
                    return f.color;
                }
            ENDCG
        }
    }
}

现在我们建立一个新的材质球,命名为Star,将Shader设置为我们刚刚编写的Star,并且将这个材质球赋予My First Star。

game viewinspector

添加材质球之后

顶点着色默认是白色,所以我们的多边形现在变成了白色。我们想要一个更漂亮的星星。所以我们来为每个点定义一种颜色。

我们再添加一个frequency属性,这样我们就能让程序自动重复点的序列,而不用我们逐个定义全部的点。这个选项取代了numberOfPoints。

我们在最后需要确认frequency属性是否正确,并且星星至少拥有一个点。如果没有,我们的代码就可能出错。

Why check both for null and the length?

When freshly created, our star component won’t have an array yet. It’s also technically possible for scripts to explicitly set our array to null later on. We need to watch out for that, to prevent errors. Only if the array does exists do we go ahead and check its length as well.

using UnityEngine;

[RequireComponent(typeof(MeshFilter), typeof(MeshRenderer))]
public class Star : MonoBehaviour {

    public Vector3[] points;
    public int frequency = 1;

    private Mesh mesh;
    private Vector3[] vertices;
    private int[] triangles;

    void Start () {
        GetComponent<MeshFilter>().mesh = mesh = new Mesh();
        mesh.name = "Star Mesh";

        if(frequency < 1){
            frequency = 1;
        }
        if(points == null || points.Length == 0){
            points = new Vector3[]{ Vector3.up};
        }

        int numberOfPoints = frequency * points.Length;
        vertices = new Vector3[numberOfPoints + 1];
        triangles = new int[numberOfPoints * 3];
        float angle = -360f / numberOfPoints;
        for(int iF = 0, v = 1, t = 1; iF < frequency; iF++){
            for(int iP = 0; iP < points.Length; iP += 1, v += 1, t += 3){
                vertices[v] = Quaternion.Euler(0f, 0f, angle * (v - 1)) * points[iP];
                triangles[t] = v;
                triangles[t + 1] = v + 1;
            }
        }
        triangles[triangles.Length - 1] = 1;

        mesh.vertices = vertices;
        mesh.triangles = triangles;
    }
}

scene viewinspector

配置好的点

我们需要些颜色!如果把全部的顶点都指定相同的颜色就很简单,但这样太无聊了。我们来试试给每个顶点分配一个颜色。我们需要一个数组来保存这些颜色数据,而且必须保持颜色和顶点的数量一致。这有点小麻烦,我们干脆换成另外一种方式,在Star类中建立一个新的类,这个类可以保存一个顶点的颜色和位置。然后我们可以用这个类的数组来代替vector数组。

这类叫Point,如果在Star类之外使用,就是Star.Point。在Star里面Point就可以了。为了让Unity能够将Point序列化,我们为Point添加System.Serializable特性。

为什么不用结构体?

Because Star.Point is so lightweight and its data is always needed all at once, it would make sense to use a struct type and avoid the overhead that objects add. However, Unity does not support serialization of custom struct types. So you’re stuck using classes to bundle data you want to store.
If you’re really concerned about the object overhead and possible null errors, you can always store the offset and color data in two separate arrays. However, then you would need to make sure that these arrays always stay synchronized. While that is definitely doable, the class approach is simpler. That’s why I use it in this tutorial.

using System;
using UnityEngine;

[RequireComponent(typeof(MeshFilter), typeof(MeshRenderer))]
public class Star : MonoBehaviour {

    [Serializable]
    public class Point {
        public Color color;
        public Vector3 offset;
    }

    public Point[] points;
    public int frequency = 1;

    private Mesh mesh;
    private Vector3[] vertices;
    private Color[] colors;
    private int[] triangles;

    void Start () {
        GetComponent<MeshFilter>().mesh = mesh = new Mesh();
        mesh.name = "Star Mesh";

        if(frequency < 1){
            frequency = 1;
        }
        if(points == null || points.Length == 0){
            points = new Point[]{ new Point()};
        }

        int numberOfPoints = frequency * points.Length;
        vertices = new Vector3[numberOfPoints + 1];
        colors = new Color[numberOfPoints + 1];
        triangles = new int[numberOfPoints * 3];
        float angle = -360f / numberOfPoints;
        for(int iF = 0, v = 1, t = 1; iF < frequency; iF++){
            for(int iP = 0; iP < points.Length; iP += 1, v += 1, t += 3){
                vertices[v] = Quaternion.Euler(0f, 0f, angle * (v - 1)) * points[iP].offset;
                colors[v] = points[iP].color;
                triangles[t] = v;
                triangles[t + 1] = v + 1;
            }
        }
        triangles[triangles.Length - 1] = 1;

        mesh.vertices = vertices;
        mesh.colors = colors;
        mesh.triangles = triangles;
    }
}


game viewinspector

有了颜色之后

最后是关于中心点的。现在,我们还没有给它设置颜色,所以它一直保持着透明。让我们来为它添加一个颜色属性,最终,这个星星看上去变漂亮了。

using System;
using UnityEngine;

[RequireComponent(typeof(MeshFilter), typeof(MeshRenderer))]
public class Star : MonoBehaviour {

    [Serializable]
    public class Point {
        public Color color;
        public Vector3 offset;
    }

    public Point[] points;
    public int frequency = 1;
    public Color centerColor;

    private Mesh mesh;
    private Vector3[] vertices;
    private Color[] colors;
    private int[] triangles;

    void Start () {
        GetComponent<MeshFilter>().mesh = mesh = new Mesh();
        mesh.name = "Star Mesh";

        if(frequency < 1){
            frequency = 1;
        }
        if(points == null || points.Length == 0){
            points = new Point[]{ new Point()};
        }

        int numberOfPoints = frequency * points.Length;
        vertices = new Vector3[numberOfPoints + 1];
        colors = new Color[numberOfPoints + 1];
        triangles = new int[numberOfPoints * 3];
        float angle = -360f / numberOfPoints;
        //colors[0] = centerColor;(原文直接赋值,无法绘制)
        colors[0] = new Color(centerColor.r, centerColor.g, centerColor.b, centerColor.a); ;
        for(int iF = 0, v = 1, t = 1; iF < frequency; iF++){
            for(int iP = 0; iP < points.Length; iP += 1, v += 1, t += 3){
                vertices[v] = Quaternion.Euler(0f, 0f, angle * (v - 1)) * points[iP].offset;
                //colors[v] = points[iP].color;(原文直接赋值,无法绘制)
                colors[v] = new Color(points[iP].color.r, points[iP].color.g, points[iP].color.b, points[iP].color.a);
                triangles[t] = v;
                triangles[t + 1] = v + 1;
            }
        }
        triangles[triangles.Length - 1] = 1;

        mesh.vertices = vertices;
        mesh.colors = colors;
        mesh.triangles = triangles;
    }
}


game viewscene viewinspector

漂亮的星星,麻烦的编辑器,下篇文章我们来学习下unity editor编辑器的创建,好了,本篇unity3d教程到此结束!
注意:若出现 使用colors[0] = centerColor;colors[v] = points[iP].color;无效的情况,请使用new Color()的方法构造。 转自:http://www.unity.5helpyou.com/3123.html


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值