using UnityEngine;
/// <summary>
/// 在模型上绘画
/// </summary>
public class DrawOnModel:BaseMonoBehaviour{
[Tooltip("颜色")]
public Color color=Color.cyan;
[Tooltip("笔刷大小")]
public float brushSize=10f;
private Camera m_mainCamera;
private Texture2D m_texture2D;
protected override void Awake(){
base.Awake();
m_mainCamera=Camera.main;
//创建一个副本,避免修改原纹理
Renderer renderer=GetComponent<Renderer>();
Texture2D mainTexture=(Texture2D)renderer.material.mainTexture;
Texture2D tempTexture2D=new Texture2D(mainTexture.width,mainTexture.height);
tempTexture2D.SetPixels(mainTexture.GetPixels());
tempTexture2D.Apply();
renderer.material.mainTexture=tempTexture2D;
m_texture2D=tempTexture2D;
}
protected override void Update2(){
base.Update2();
if(Input.GetMouseButton(0)){
RaycastHit[] raycastHits=new RaycastHit[1];
Physics.RaycastNonAlloc(m_mainCamera.ScreenPointToRay(Input.mousePosition),raycastHits);
var hit=raycastHits[0];
if(hit.collider!=null&&hit.collider.gameObject==gameObject){
DrawCircleDot(hit.textureCoord,m_texture2D,color,brushSize);
//DrawRectDot(hit.textureCoord,m_texture2D,color,brushSize);
}
}
}
/// <summary>
/// 画矩形点
/// </summary>
/// <param name="point">坐标</param>
/// <param name="texture">贴图</param>
/// <param name="color">颜色</param>
/// <param name="width">宽度</param>
private void DrawRectDot(Vector2 point,Texture2D texture,Color color,float width){
point.x*=texture.width;
point.y*=texture.height;
point.x-=width*0.5f;
point.y-=width*0.5f;
int x=Mathf.FloorToInt(point.x);
int y=Mathf.FloorToInt(point.y);
for (int i=0;i<width;i++){
for (int j=0;j<width;j++){
texture.SetPixel(x+i,y+j,color);
}
}
texture.Apply();
}
/// <summary>
/// 画圆形点
/// </summary>
/// <param name="point">坐标</param>
/// <param name="texture">贴图</param>
/// <param name="color">颜色</param>
/// <param name="diameter">直径</param>
private void 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);
for (int i=0;i<diameter;i++){
for (int j=0;j<diameter;j++){
float dx=i-radius;
float dy=j-radius;
float distance=Mathf.Sqrt(dx*dx+dy*dy);
if(distance<=radius){
texture.SetPixel(x+i,y+j,color);
}
}
}
texture.Apply();
}
}
原文地址:https://www.cnblogs.com/kingBook/p/12283840.html
时间: 2024-10-14 06:55:34