[UnityShader]shader书写技巧之制作新手指导

参考链接:http://www.unitymanual.com/thread-35475-1-1.html


由于原作者太厉害了,所以第一次看他的代码表示看不懂,但经过一番琢磨,终于想通了,所以想分享一下。根据原文章的指引,我们直接跳到最后一步——写一个高亮区域能跟随鼠标移动,且高亮区域可变的脚本。


重点:因为高亮区域要跟随鼠标移动,所以要更改offset的值;高亮区域可变,所以要更改tiling的值。


这是有透明区域的png图:

起始状态(tiling均为1,offset均为0;wrap mode为clamp):



将offset值与Input.mousePosition关联起来,在这里,我的Screen.width与Screen.height分别为600,320,因此Input.mousePosition的范围为(0,0)~(600,320),在不缩放高亮区域的情况下,offset的取值应该在0~1之间,因此有:

Vector3 pos = Input.mousePosition;
mainmat.mainTextureOffset = new Vector2(pos.x / Screen.width, pos.y / Screen.height);

把鼠标放在屏幕中间,得到的图像:



此时mainmat.mainTextureOffset为(0.5,0.5),但我们想让它取值为(0,0),因此有:

Vector3 pos = Input.mousePosition;
mainmat.mainTextureOffset = new Vector2(0.5f - pos.x / Screen.width, 0.5f - pos.y / Screen.height);


把鼠标放在屏幕中间,得到的图像:



此时高亮区域已经能跟随鼠标移动了,接下来处理区域可变。


先设置默认横向、竖向缩小10倍,因此有:

float sizeX = 10f;//默认高亮区域横向缩小十倍
float sizeY = 10f;//默认高亮区域竖向缩小十倍
mainmat.mainTextureScale = new Vector2(sizeX, sizeY);

把鼠标放在屏幕中间,得到的图像:


运行后发现高亮区域的位置又不对了,此时mainmat.mainTextureOffset为(0,0),但我们想让它取值为(-4.5,-4.5),于是就得到了最终的公式:

mainmat.mainTextureOffset = new Vector2(0.5f - pos.x / Screen.width * sizeX, 0.5f - pos.y / Screen.height * sizeY);

把鼠标放在屏幕中间,得到的图像:


所以这里给出最终的代码:

using UnityEngine;
using System.Collections;

public class moveuv : MonoBehaviour {

    Material mainmat;
    float sizeX = 10f;//默认高亮区域横向缩小十倍
    float sizeY = 10f;//默认高亮区域竖向缩小十倍

	// Use this for initialization
	void Start () 
    {
        mainmat = GetComponent<MeshRenderer>().material;
	}
	
	// Update is called once per frame
	void Update () 
    {
        Vector3 pos = Input.mousePosition;
        mainmat.mainTextureOffset = new Vector2(0.5f - pos.x / Screen.width * sizeX, 0.5f - pos.y / Screen.height * sizeY);

        if (Input.GetKey(KeyCode.W))
            sizeX -= 0.1f;//增大横向范围
        if (Input.GetKey(KeyCode.S))
            sizeX += 0.1f;//减少横向范围
        if (Input.GetKey(KeyCode.A))
            sizeY -= 0.1f;//增大竖向范围
        if (Input.GetKey(KeyCode.D))
            sizeY += 0.1f;//减少竖向范围

        mainmat.mainTextureScale = new Vector2(sizeX, sizeY);
	}
}

那么这个脚本有什么用呢?我们可以比较方便地通过储存tiling与offset的值来记录高亮区域的大小与位置。


这是unitypackage:

http://yun.baidu.com/share/link?shareid=4084063207&uk=1632474121&third=0&fid=338765527368857

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值