本文將利用Texture2D的自身的方法在Unity中實現子彈痕跡的效果
一、首先在網上down兩張貼圖(然後將彈痕背景透明化):
1、牆
2、彈痕
二、將貼圖導入Unity並修改參數
1、保存可讀可寫
2、格式要對
三、在一個面片上掛載文章後面的腳本
1、如果不用for循環而用注掉的方法效果是這樣的
2、而我們需要的是這樣的
四、問題來了
實驗表明,如果彈孔重疊,效果不好,像這樣(暫時還沒有好辦法,歡迎指點!)
原碼如下:
using UnityEngine;
public class bulletHole : MonoBehaviour
{
private Renderer m_Renderer;
private RaycastHit hit;
public Texture2D bolt;
void Awake()
{
//獲取到渲染組件
m_Renderer = GetComponent<Renderer>();
}
void Update()
{
if (!Input.GetMouseButton(0)) return;
if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit))
{
Texture2D texture = (Texture2D)m_Renderer.material.mainTexture;
Vector2 point = hit.textureCoord;
point.x *= texture.width;
point.y *= texture.height;
//texture.SetPixels((int)point.x, (int)point.y, bolt.width, bolt.height, bolt.GetPixels());
for (int i = 0; i < bolt.width; i++)
{
for (int j = 0; j < bolt.height; j++)
{
Color c = bolt.GetPixel(i, j);
if (c.a >= 0.2f)
{
texture.SetPixel((int)point.x + i, (int)point.y + j, c);
}
}
}
texture.Apply();
}
}