实现原理:将一张图片像素点融合到另一张图图片的指定位置上
1.首先需要两张图片:一张是墙的图片,一张是弹痕贴图
2.新建工程,把图片拖到工程里.设置参数:两张图片都要勾选上Read/WriteEnable属性,允许图片进行像素编辑;
3.新建墙的材质.赋到plane上
4.新建脚本Plane_Bullet,挂到plane上
定义必要的字段:
初始化参数
实现鼠标点击是出现弹痕
恢复弹痕的方法(这里3s后弹痕消失,使用的原理是将之前保存的图片信息中的像素点信息取出后再次进行替换。)
5.设置tag和参数
6.运行看效果
7.注意:
1、鼠标点击出现弹痕是通过摄像机发射一条射线,射线产生的碰撞信息hit.textureCoord是uv坐标,该坐标是一个0~1的范围的值;
2、这里3s后弹痕消失,使用的原理是将之前保存的图片信息中的像素点信息取出后再次进行替换。8.源码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Plane_Bullet : MonoBehaviour {
//墙和弹痕纹理图片
public Texture2D Bullet_Texture2D;
public Texture2D Plane_Texture2D;
//定义一个墙的纹理用于修改纹理像素点
private Texture2D Plane_Texture_Two;
//墙的高和宽
float plane_HT;
float plane_WT;
//弹痕的高宽
float bullet_HT;
float bullet_WT;
//射线反馈信息
RaycastHit hit;
//队列存储像素点信息
Queue<Vector2> Queue_v2;
//初始化参数
void Start () {
Queue_v2 = new Queue<Vector2> ();
//获取墙的纹理图片
Plane_Texture2D = GetComponent<MeshRenderer> ().material.mainTexture as Texture2D;
//获得一个墙的纹理
Plane_Texture_Two = Instantiate (Plane_Texture2D);
//将这个贴图复制回去作为修改的对象
GetComponent<MeshRenderer> ().material.mainTexture = Plane_Texture_Two;
//获得墙和弹痕的宽和高
plane_HT = Plane_Texture2D.height;
plane_WT = Plane_Texture2D.width;
bullet_HT = Bullet_Texture2D.height;
bullet_WT = Bullet_Texture2D.width;
}
//实现鼠标点击是出现弹痕
void Update () {
if (Input.GetMouseButtonDown(0)) {
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if (Physics.Raycast(ray,out hit)) {
//判断是否集中墙
if (hit.collider.tag =="Plane") {
//hit.textureCoord是uv坐标,该坐标是一个0~1的范围的值;
Vector2 v2 = hit.textureCoord;
Queue_v2.Enqueue (v2);
//遍历弹痕图片区域
for (int i = 0; i < bullet_WT; i++) {
for (int j = 0; j < bullet_HT; j++) {
//得到墙上对应弹痕应出现的每一个像素点
float W = v2.x * plane_WT - bullet_WT / 2 + i;
float H = v2.y * plane_HT - bullet_HT / 2 + j;
//获取墙上每一个应该出现弹痕像素点的颜色
Color Wall_Color = Plane_Texture_Two.GetPixel ((int)W, (int)H);
//获取弹痕贴图每一个像素点的颜色
Color bullet_Color = Bullet_Texture2D.GetPixel (i, j);
//融合像素点
Plane_Texture_Two.SetPixel ((int)W, (int)H, Wall_Color * bullet_Color);
}
}
//Apply
Plane_Texture_Two.Apply ();
//3s之后恢复
Invoke("Restore_Plane",3f);
}
}
}
}
//恢复弹痕的方法(这里3s后弹痕消失,使用的原理是将之前保存的图片信息中的像素点信息取出后再次进行替换。)
void Restore_Plane()
{
//获取队列中弹痕的中心点
Vector2 v2 = Queue_v2.Dequeue ();
for (int i = 0; i < bullet_WT; i++) {
for (int j = 0; j < bullet_HT; j++) {
float W = v2.x * plane_WT - bullet_WT / 2 + i;
float H = v2.y * plane_HT - bullet_HT / 2 + j;
//获取原始墙上像素点
Color plane_Color = Plane_Texture2D.GetPixel((int)W,(int)H);
Plane_Texture_Two.SetPixel((int)W,(int)H,plane_Color);
}
}
Plane_Texture_Two.Apply();
}
}