Game Development Reference
In-Depth Information
•
Lines 062-072
: If a collision was detected, the UV coordinates of the hit
location should be retrieved through the
textureCoord
variable of the
RaycastHit
structure. More information on this variable can be found
online in the Unity documentation at
http://docs.unity3d.com/
ScriptReference/RaycastHit-textureCoord.html
.
This member, is
only valid if the intersected mesh has
MeshCollider
, as opposed to other
collider types, such as
BoxCollider
or
CapsuleCollider
. However, this
means that any object used as a texture-painting destination should feature
a
MeshCollider
component, since it contains UV data. Lines 63-72 then
convert the UV coordinates into absolute pixel positions, centering the brush
source texture at the position of the cursor. The result of this code is to clearly
identify a position on the source brush texture that should be the pivot or
origin point, and to establish a pixel
x
,
y
coordinate location at which the
source texture should be painted into the destination texture.
•
Line 075
: Finally, the
PaintSourceToDestTexture
function is called to
perform the paint operation itself.
•
Line 081
: The
PaintSourceToDestTexture
function accepts four arguments:
Source
,
Dest
,
Left
, and
Top
. On the basis of these, the
Source
texture is
painted onto the
Dest
at the positions
Left
and
Top
. This function is declared
as static, which means that no instance of this class needs to be declared.
•
Lines 084-087
: The first step in the texture-painting process is to retrieve
all pixels in both the
Source
and
Dest
textures. This is achieved using the
GetPixels
function. More information on
GetPixels
can be found online in
the Unity documentation at
http://docs.unity3d.com/ScriptReference/
Texture2D.GetPixels.html
.
Now, although each image is visually a two-
dimensional array of pixels, the returned array from
GetPixels
is in fact
linear (one-dimensional). This is the reason for both the
GetPixelFromArray
and
SetPixelFromArray
functions, which convert pixel
x
and
y
positions
into linear array indices.
•
Lines 89-101
: Here, each pixel is retrieved from the
Source
texture and
painted onto the destination. This checks to ensure that the brush texture is
painted with the destination bounds and allows clipping, if required. This
is necessary because a brush mark could, in principle, be made close to the
texture edge; in this case, only a part of the brush would actually be painted
onto the destination, as some pixels would be "cut off". Pixels are retrieved
from the
Source
texture with
GetPixelFromArray
, and destination pixels
are set with
SetPixelInArray
.