LoginSignup
1
5

More than 5 years have passed since last update.

Unity でShaderの勉強 その10 ShaderとScriptの連携

Posted at

良い記事を見つけたので試して見る
http://www.jonki.net/entry/20140215

コード

Shader
Shader "Custom/TestShader" {
    Properties {
        _HolePos("HolePos",vector) = (1,1,1,1)
        _HoleSize("HoleSize",Range(0,10)) = 1
        _BlurThick("BlurThick",Range(0,10)) = 1
        _MainColor("MainColor",Color) = (1,1,1,1)
    }

    SubShader {
        Tags {"Queue" = "Transparent" "RenderType" = "Transparent"}
        ZWrite On
        ZTest LEqual
        Blend SrcAlpha OneMinusSrcAlpha

        Pass {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            uniform float _HoleSize;
            uniform float4 _HolePos;
            uniform float _BlurThick;
            uniform float4 _MainColor;



            struct v2f {
                float4 wPos : SV_POSITION;
                float2 uv : TEXCOORD0;
            };

            v2f vert(float4 pos : POSITION ,float2 uv : TEXCOORD0) {
                v2f output;
                output.wPos = mul(UNITY_MATRIX_MVP,pos);
                output.uv = uv;
                return output;
            }

            float4 frag(v2f input) : SV_TARGET {
                half4 col = _MainColor;
                float2 pos = input.uv;

                float dist = distance(pos, float2(_HolePos.x, _HolePos.y));
                if(dist < _HoleSize) {
                    clip(-1.0);
                } else if(dist < _HoleSize + _BlurThick){
                    col.a = (dist - _HoleSize) * 10.0;
                    col.a = pow(col.a, 2.0);
                }

                return col;
            }

            ENDCG
        }
    }
}
Script
using UnityEngine;
using System.Collections;

public class ShaderScript : MonoBehaviour
{
    // Use this for initialization
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hitInfo;
        if (Physics.Raycast(ray, out hitInfo))
        {
            Renderer renderer = hitInfo.transform.GetComponent<Renderer>();
            if (renderer)
            {
                renderer.material.SetVector("_HolePos", hitInfo.textureCoord);    
            }

        }
    }
}

結果:
スクリーンショット 2017-02-23 20.22.27.png

変えたところ
Rayを投げて当たったところのTEXCOORDをHolePosに入れた。画面サイズに依存せず、見た目通りの位置に穴が開くようになった。

1
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
5