一般来说他们做涂涂乐都用到shader,可惜渣渣的我不会shader,就算用了shader,我看不懂里面的原理,会让我很烦,所以就另寻他法
无意中看到unity的商店里有一个涂涂乐的免费教程
最终的实现效果:
里面就是不用shader来实现,核心原理大概是使用Render Texture,获取点击模型Uv的位置,然后在Render Texture前创建gameobject色块,到达一定数量,则截图保存给当前材质球,然后删除原来的色块
步骤:
1.创建一个Quad和名字为_canvasCamera相机
2.相机ClearFlags设置为Depth Only,Projection设置为Orthorgraphic,size大概0.5就差不多,自己调整
3.创建一个色块GameObject,加上spriteRenderer
4.再根据最后的图自己设置下
代码写的有点乱,但是菜鸟看菜鸟的代码或许看的比较明白吧
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class TestTurx : MonoBehaviour {
public RenderTexture _RenderTexture; //创建的_RenderTexture;
public Material _QuadMaterial; //涂涂乐物体上的材质球
public GameObject _fater; //放置显示板中央位置或者所示下面_canvasCamera的子类 vector3(0,0,3)的位置(在Qued前面,不要被Qued遮挡)
public Camera _canvasCamera; //观看显示板的相机
public GameObject instObject; //色块
// Use this for initialization
void Start () {
print(_canvasCamera.orthographicSize);
}
// Update is called once per frame
void Update () {
if (Input.GetMouseButton(0))
{
GetTextureMap();
}
SavePicture();
}
void SavePicture()
{
if (_fater.transform.childCount >200) //如果子物体数量大于200个
{
RenderTexture.active = _RenderTexture; //圣典说是激活当前渲染图贴,还没消化完
Texture2D tex = new Texture2D(_RenderTexture.width, _RenderTexture.height, TextureFormat.RGB24, false);
tex.ReadPixels(new Rect(0, 0, _RenderTexture.width, _RenderTexture.height), 0, 0); //读取屏幕像素,并保存
tex.Apply();
RenderTexture.active = null;
_QuadMaterial.mainTexture = tex; //保存的图片赋值给物体的材质球
foreach (Transform child in _fater.transform) //清除子类
{
Destroy(child.gameObject);
}
}
}
void GetTextureMap()
{
RaycastHit hit; //射线这部分不多说了
Ray r = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(r, out hit, 500))
{
Debug.DrawLine(transform.position, hit.point, Color.red);
MeshCollider mesh = hit.collider as MeshCollider;
if (mesh == null || mesh.sharedMesh == null) //判断物体上是否有meshCollider,同时mesh里要有对应的纹理
return;
Vector2 uv = new Vector2(hit.textureCoord.x, hit.textureCoord.y);//Unity官方API解释:射线射入现场。这textureCoord是射线撞击碰撞机的位置
print(uv.x + " " + uv.y);
GameObject obj = GameObject.Instantiate(instObject);
obj.transform.SetParent(_fater.transform);
obj.transform.localPosition = new Vector3(uv.x - _canvasCamera.orthographicSize, uv.y - _canvasCamera.orthographicSize, 0); //没搞懂减是怎么原理,待消化
}
}
}
脚本随意挂任意地方