Unity 3D : Catmull-Rom 曲線調整小工具

版权声明:本文为博主 ( 黃彥霖 ) 原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_38884324/article/details/81330594

前言 :

本範例使用的 CatmullRom.cs 請參考這篇 ( 也建議先讀讀這篇原理,再來看這篇文章 ) :

https://blog.csdn.net/weixin_38884324/article/details/81328803

執行結果 :

这里写图片描述

C # :

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using MathTool.Curve;

public class Test6 : MonoBehaviour
{

    public RawImage imgCurve;
    public Slider s1, s2, s3, s4;
    public int width = 512, height = 512;
    public Color bgColor = new Color(1, 0, 0, 1);
    public Color lineColor = new Color(1, 1, 1, 1);

    Texture2D tCurveBG_Template = null;

    void Start()
    {
        tCurveBG_Template = new Texture2D(width, height);
        Color[] colors = new Color[width * height];
        for (int i = 0; i < colors.Length; i++)
        {
            colors[i] = bgColor;
        }
        tCurveBG_Template.SetPixels(colors);
        tCurveBG_Template.Apply();

        s1.value = 0;
        s2.value = 0.333f;
        s3.value = 0.666f;
        s4.value = 1;
    }

    Texture2D tCurve = null;

    public void SliderValueChange()
    {
        float y1 = s1.value * height;
        float y2 = s2.value * height;
        float y3 = s3.value * height;
        float y4 = s4.value * height - 1;

        Vector2[] pvs = {
            new Vector2(0,y1),
            new Vector2(0,y1),
            new Vector2(width/3f*1f,y2),
            new Vector2(width/3f*2f,y3),
            new Vector2(width,y4),
            new Vector2(width,y4)
        };

        for (int i = 0; i < width; i++)
        {
            Vector2 v = CatmullRom.Interp2D(pvs, i / (float)width);
            if (v.y < 0 || v.y >= width)
                return;
        }

        if (tCurve != null)
        {
            Destroy(tCurve);
        }

        tCurve = new Texture2D(width, height);

        tCurve.SetPixels(tCurveBG_Template.GetPixels());

        for (int i = 0; i < width; i++)
        {
            Vector2 v = CatmullRom.Interp2D(pvs, i / (float)width);
            tCurve.SetPixel(i, (int)v.y, lineColor);
            tCurve.SetPixel(i, (int)v.y + 1, lineColor);
            tCurve.SetPixel(i, (int)v.y - 1, lineColor);
        }

        tCurve.Apply();

        imgCurve.texture = tCurve;

    }
}

猜你喜欢

转载自blog.csdn.net/weixin_38884324/article/details/81330594
今日推荐