Unity一個彈痕的簡單實現方法
阿新 • • 發佈:2017-07-26
註意 allow 由於 div img determine 效率 pda 場景
之前知道一個方法比較復雜就是取出貼圖,類似於從上到下從左到右的去遍歷一張圖,去除像素點改變像素點。今天在選丞大佬那看到下面這個方法,覺得十分簡單,原理應該是相同的吧。
官方文檔:
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(); } }
Unity一個彈痕的簡單實現方法