using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
///
/// 在模型上绘画
///
public class DrawOnModel:BaseMonoBehaviour{
public GameObject target;
[Tooltip("颜色")]
public Color color=Color.cyan;
[Tooltip("笔刷大小")]
public float brushSize=10f;
public Texture2D texture2D { get; private set; }
private Camera m_mainCamera;
private struct PointColor{
public PointColor(int x,int y,Color cor){
point=new Vector2Int(x,y);
color=cor;
}
public Vector2Int point;
public Color color;
}
private List m_undoList=new List();
private List m_tempUndoList;
private RaycastHit[] m_raycastHits=new RaycastHit[1];
protected override void Awake(){
base.Awake();
m_mainCamera=Camera.main;
Renderer renderer=target.GetComponent();
Texture2D mainTexture=(Texture2D)renderer.material.mainTexture;
//创建一个副本,避免修改原纹理
texture2D=new Texture2D(mainTexture.width,mainTexture.height);
texture2D.SetPixels(mainTexture.GetPixels());
texture2D.Apply();
renderer.material.mainTexture=texture2D;
}
protected override void Update2(){
base.Update2();
if(Input.touchSupported){
if(Input.touchCount>0){
Touch touch=Input.GetTouch(0);
if(touch.phase==TouchPhase.Began){
DrawBegin(touch.position);
}else if(touch.phase==TouchPhase.Moved){
if(!EventSystem.current.IsPointerOverGameObject(touch.fingerId)){
DrawScreenPoint(touch.position);
}
}else if(touch.phase==TouchPhase.Ended||touch.phase==TouchPhase.Canceled){
DrawEnd();
}
}
}else{
Vector2 mousePos=Input.mousePosition;
if(Input.GetMouseButtonDown(0)){
DrawBegin(mousePos);
}
if(Input.GetMouseButton(0)&&!EventSystem.current.IsPointerOverGameObject()){
DrawScreenPoint(mousePos);
}
if(Input.GetMouseButtonUp(0)){
DrawEnd();
}
}
}
private void DrawBegin(Vector2 screenPos){
m_tempUndoList=new List();
}
private void DrawScreenPoint(Vector2 screenPos){
Physics.RaycastNonAlloc(m_mainCamera.ScreenPointToRay(screenPos),m_raycastHits);
var hit=m_raycastHits[0];
if(hit.collider!=null&&hit.collider.gameObject==target){
PointColor[] undoList=DrawCircleDot(hit.textureCoord,texture2D,color,brushSize);
if(undoList!=null&&undoList.Length>0){
m_tempUndoList.AddRange(undoList);
}
}
}
private void DrawEnd(){
if(m_tempUndoList!=null&&m_tempUndoList.Count>0){
m_undoList.Add(m_tempUndoList.ToArray());
m_tempUndoList=null;
}
}
///
/// 画圆形点
///
/// 坐标
/// 贴图
/// 颜色
/// 直径
/// 返回改变的像素的旧颜色列表
private PointColor[] DrawCircleDot(Vector2 point,Texture2D texture,Color color,float diameter){
float radius=diameter*0.5f;
point.x*=texture.width;
point.y*=texture.height;
point.x-=radius;
point.y-=radius;
int x=Mathf.FloorToInt(point.x);
int y=Mathf.FloorToInt(point.y);
List tempList=new List();
for (int i=0;i |