之前知道一个方法比较复杂就是取出贴图,类似于从上到下从左到右的去遍历一张图,去除像素点改变像素点。今天在选丞大佬那看到下面这个方法,觉得十分简单,原理应该是相同的吧。
官方文档:
https://docs.unity3d.com/ScriptReference/RaycastHit-textureCoord.html
附上中文版:
http://www.manew.com/youxizz/2393.html
新建一个脚本把上面链接中的代码复制进去,记得改下脚本名。将脚本挂在场景主相机上面:
在场景中随便搞个物体 组件如图:记得Mesh Collider 的Convex 不要勾选 PS:Unity省点的Convex解释:
(这个Convex 没太懂 知乎说也就是效率什么什么的。。https://www.zhihu.com/question/40575282)
接下来还要注意下这种贴图的设置 是否可写:
设置完了Apply.运行游戏就可以了:
只有草羊看看就画了一个草羊。关闭游戏后也可以看见贴图文件改变了:
以上。
没事还是应该多逛逛官方的文档的 有不少好东西。
也可以乱改改 试试有什么效果 - -
Color[] c = tex.GetPixels(0, 0, 5, 5); tex.SetPixels((int)pixelUV.x,(int)pixelUV.y,5,5,c);
源码上面链接就有了,由于不是特别多末尾在留一份吧,手懒直接粘:
// Write black pixels onto the GameObject that is located // by the script. The script is attached to the camera. // Determine where the collider hits and modify the texture at that point. // // Note that the MeshCollider on the GameObject must have Convex turned off. This allows // concave GameObjects to be included in collision in this example. // // Also to allow the texture to be updated by mouse button clicks it must have the Read/Write // Enabled option set to true in its Advanced import settings. using UnityEngine; using System.Collections; public class ExampleClass : MonoBehaviour { public Camera cam; void Start() { cam = GetComponent<Camera>(); } void Update() { if (!Input.GetMouseButton(0)) return; RaycastHit hit; if (!Physics.Raycast(cam.ScreenPointToRay(Input.mousePosition), out hit)) return; Renderer rend = hit.transform.GetComponent<Renderer>(); MeshCollider meshCollider = hit.collider as MeshCollider; if (rend == null || rend.sharedMaterial == null || rend.sharedMaterial.mainTexture == null || meshCollider == null) return; Texture2D tex = rend.material.mainTexture as Texture2D; Vector2 pixelUV = hit.textureCoord; pixelUV.x *= tex.width; pixelUV.y *= tex.height; tex.SetPixel((int)pixelUV.x, (int)pixelUV.y, Color.black); tex.Apply(); } }
时间: 2024-10-12 08:22:55