preface

Recently saw a decal effect, feel good, so I want to personally achieve a.

The effect

Train of thought

There are many ways to implement decals, and I have used the most common and most adaptable one here. Based on the click position, cut the cube, and then project the cut mesh into the plane, and finally get the UV value in the two-dimensional plane. Finally, a new Meshrenderer is generated using the cropped mesh, and the resulting UV value is added to attach the decal to the corresponding model.

Key implementation steps

Find the location of the touch on the model

Find the upper touch point of the model, the following two steps are the most important, find the ray emitted from the screen, take the intersection of the ray and the model.

this.mainCamera? .screenPointToRay(point.x, point.y,this._ray);
const intersectCount = geometry.intersect.rayModel(this._ray, mo, this.modOpt);
Copy the code

Clipping the mesh around the touch point

Crop the current mesh with the touch point as the center of the six faces of the cube

// One of the faces
this.decalVertexes = this.clipGeometrylByPlane(this.decalVertexes, new Vec3( 1.0.0 ), this.scale.x/2);
Copy the code

Project the mesh onto the plane to get uv

And then we take the cropped mesh, we project it onto the surface, and then we normalize it, and then we can use the projected value as UV

decalVertex.uv = new Vec2(
        0.5 + ( decalVertex.viewPos.x / this.scale.x ),
        0.5 + ( decalVertex.viewPos.y / this.scale.y )
    );
Copy the code

Use the cropped mesh and UV to generate a new mesh

Finally, we use the new mesh, and we have the corresponding UV, and then we add the texture we want to decal, and there we are.

warehouse

Github.com/hugohuang11…