Unity开发绘画板——01.前言

发布于:2024-10-12 ⋅ 阅读:(11) ⋅ 点赞:(0)

 在做这个之前其实是想研究一下在Unity中交互雪的实现,交互雪顾名思义就是可以进行交互的雪,玩家角色从雪上走过时雪被踩凹陷的效果;交互雪的一种实现方案就是将地面看做一个画板,将玩家角色的躯体看做笔刷,将角色经过的路径绘制为一张图片并作为地面雪的高度图传给shader去进行处理,在实现这个之前对如何实现轨迹的绘制比较感兴趣,故而想先以绘画板为切入点,研究研究。

不过既然研究了,就做一个尽量完整的方案,我想要实现的绘画板应包含如下基本功能:

  • 1.笔刷大小调节
  • 2.线条颜色调节
  • 3.可以自定义笔刷形状
  • 4.可自定义线条纹理
  • 5.绘制的图片可存储至本地
  • 6.带橡皮擦功能
  • 7.可一键清空画板
  • 8.带撤销和重做功能

说干就干,先介绍一下开发环境:

Unity2022.3.30f1 + Rider

用什么版本和IDE无所谓啦哈哈,就是玩!

需要具备一定的unity基础(有一些基本操作就不一一截图了),和shaderlab基础,不需要太深,感兴趣的话可以跟着我一起来做。

技术路线选择

其实要实现绘画的功能有很多种实现方式,例如,可以使用Texture2D.SetPixel, Texture2D.SetPixels,也可以使用Unity提供的图形接口Graphics.DrawTexture,从执行效率上来讲,Graphics.DrawTexture的效率更高一些,Texture2D的相关接口通过遍历像素来实现效率低一些,且不方便实现我们想要的可自定义线条纹理和笔刷形状的功能,因此本文采用Graphics.DrawTexture来实现

源代码:

/// <summary>
///   <para>Draw a texture in screen coordinates.</para>
/// </summary>
/// <param name="screenRect">Rectangle on the screen to use for the texture. In pixel coordinates with (0,0) in the upper-left corner.</param>
/// <param name="texture">Texture to draw.</param>
/// <param name="sourceRect">Region of the texture to use. In normalized coordinates with (0,0) in the bottom-left corner.</param>
/// <param name="leftBorder">Number of pixels from the left that are not affected by scale.</param>
/// <param name="rightBorder">Number of pixels from the right that are not affected by scale.</param>
/// <param name="topBorder">Number of pixels from the top that are not affected by scale.</param>
/// <param name="bottomBorder">Number of pixels from the bottom that are not affected by scale.</param>
/// <param name="color">Color that modulates the output. The neutral value is (0.5, 0.5, 0.5, 0.5). Set as vertex color for the shader.</param>
/// <param name="mat">Custom Material that can be used to draw the texture. If null is passed, a default material with the Internal-GUITexture.shader is used.</param>
/// <param name="pass">If -1 (default), draws all passes in the material. Otherwise, draws given pass only.</param>
[ExcludeFromDocs]
public static void DrawTexture(Rect screenRect, Texture texture, Material mat)
{
  Graphics.DrawTexture(screenRect, texture, mat, -1);
}
[ExcludeFromDocs]
public static void DrawTexture(Rect screenRect, Texture texture)
{
  Graphics.DrawTexture(screenRect, texture, (Material) null, -1);
}

在下面的文章中我们会详细介绍该接口的用法。