Unity Shader学习(五)鼠标移动方块

根据上一节的内容,创建了一个方块
现在我们来移动该方块
原理其实也很简单,只需要将方块的中心点位置等于鼠标位置即可
Shader代码如下:

Shader "Unlit/shader6"
{ 
    ///鼠标移动正方形
    Properties
    {
    _MouseCenter("MouseCenter",Vector)=(0,0,0,0)
    _RectColor("RectColor",Color)=(1,1,1,1)
    }
    SubShader
    {
        Tags { "RenderType"="Opaque" }
        LOD 100

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag


            #include "UnityCG.cginc"
        struct v2f{
            float4 vertex:SV_POSITION;
            float4 position:TEXCOORD1;
            float2 uv:TEXCOORD;
        };
        v2f vert(appdata_base v){
            v2f o;
            o.vertex=UnityObjectToClipPos(v.vertex);
            o.position=v.vertex;
            o.uv=v.texcoord;
            return o;
        }
        //中心点
        float4 _MouseCenter;
        //颜色
        fixed4 _RectColor;
        //绘制正方形
        float rect(float2 pt,float2 size,float2 center){
            float2 p=pt-center;
            float2 halfsize=size*0.5;
            float hotz=step(-halfsize.x,p.x)-step(halfsize.x,p.x);
            float vert=step(-halfsize.y,p.y)-step(halfsize.y,p.y);
            return hotz*vert;
        }

            fixed4 frag (v2f i) : SV_Target
            {
                float2 pos=i.uv;
                float2 size=0.2;
                float inRect=rect(pos,size,_MouseCenter);
                fixed3 col=fixed3(1,1,0)*inRect;
                return fixed4(col,1.0);
            }
            ENDCG
        }
    }
}

然后只需要控制_MouseCenter这个参数,通过unity脚本对_MouseCenter进行赋值

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

public class MouseSquare : MonoBehaviour
{
   public Material mat;
    Vector4 mouse;
    Camera cam;
    void Start()
    {
        MeshRenderer rend = GetComponent<MeshRenderer>();
        mat = rend.material;
        mouse = new Vector4();
        mouse.z = Screen.height;
        mouse.w = Screen.width;
        cam = Camera.main;
    }

    // Update is called once per frame
    void Update()
    {
        RaycastHit hit;
        Ray ray = cam.ScreenPointToRay(Input.mousePosition);
        if (Physics.Raycast(ray,out hit))
        {
       
            mouse.x = hit.textureCoord.x;
            mouse.y = hit.textureCoord.y;
           // Debug.Log(hit.textureCoord);
            Debug.DrawLine(cam.transform.position, hit.point, Color.red);
        }
        mat.SetVector("_MouseCenter", mouse);
    }
}

脚本拖在物体上即可
在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ToDoNothing

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值