Unity一个弹痕的简单实现方法
Posted Mr.糖马儒
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Unity一个弹痕的简单实现方法相关的知识,希望对你有一定的参考价值。
之前知道一个方法比较复杂就是取出贴图,类似于从上到下从左到右的去遍历一张图,去除像素点改变像素点。今天在选丞大佬那看到下面这个方法,觉得十分简单,原理应该是相同的吧。
官方文档:
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.运行游戏就可以了:
只有草羊看看就画了一个草羊。关闭游戏后也可以看见贴图文件改变了: (后 经吃瓜群众反映,将这个贴图的读写关闭在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();
/*还可以 右键取消痕迹
else if (Input.GetMouseButton(1))
{
RaycastHit hit;
if (!Physics.Raycast(cam.ScreenPointToRay(Input.mousePosition), out hit))
return;
Texture2D tex = hit.transform.GetComponent<Renderer>().material.mainTexture as Texture2D;
print(tex.format);
TextureImporter ti = (TextureImporter)TextureImporter.GetAtPath(AssetDatabase.GetAssetPath(tex));
ti.isReadable = true; //图片Read/Write Enable的开关
AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(tex));
}
}
*/
}
}
以上是关于Unity一个弹痕的简单实现方法的主要内容,如果未能解决你的问题,请参考以下文章
Unity报错:Read only asset Packages/com.xxxxx.xxx.xxxx/Editor/VSCodeDiscovery.cs.IPGSD has no meta(代码片段
Unity报错:Read only asset Packages/com.xxxxx.xxx.xxxx/Editor/VSCodeDiscovery.cs.IPGSD has no meta(代码片段