unity 在模型上绘画
Posted kingbook
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了unity 在模型上绘画相关的知识,希望对你有一定的参考价值。
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();
}
}
以上是关于unity 在模型上绘画的主要内容,如果未能解决你的问题,请参考以下文章
Complete Paint丨一款Unity可实现《UI物体VR绘画》的插件