I am so grateful to have knowledgeable people like you in this community.
This works perfectly and I can confirm that it works.
Here is the code after the change.
const radius = terrainManager.radius;
const intersectPosition = intersects[0].point;
const cloneGeometry = ref.current.geometry.clone();
if (!cloneGeometry.attributes.color) {
const count = cloneGeometry.attributes.position.count;
const buffer = new BufferAttribute( new Float32Array( count * 3 ), 3 );
cloneGeometry.setAttribute("color", buffer);
}
const numVertices = cloneGeometry.attributes.color.array;
let colors = new Float32Array(numVertices);
const color = new Color(terrainManager.color);
const vertex = new Vector3();
const positionArray = Array.from(cloneGeometry.attributes.position.array);
for (let i = 0; i <= positionArray.length - 3; i += 3) {
vertex.set(positionArray[i], positionArray[i + 1], positionArray[i + 2]);
vertex.applyMatrix4(ref.current.matrixWorld); // Consider rotation
const distance = vertex.distanceTo(intersectPosition);
if (distance <= radius) {
colors.set(color.toArray(), i);
}
}
cloneGeometry.setAttribute("color", new BufferAttribute(colors, 3));
ref.current.geometry.copy(cloneGeometry);