实现面料模拟一直是一个比较难的问题,因此今天说一下我的具体实现方案,和代码
先展示结果,这是没有加物理效果的衣服
这是加了物理效果的衣服
是不是效果很明显
首先,先说原理,通过修改每个顶点的位置来实现衣服的移动和变形,最简单的实现方式就是,设置一个重力,每秒向y轴的负方向移动固定或递增的距离,来实现基本的物理效果
其次,如何实现面料效果呢?需要让面料的各个点之间实现拉力的影响,相互约束,从而使得衣服的粒子不会到处乱跑
然后,就是衣服传到人模上面,具体的实现方案是:人模使用八叉树,判断衣服粒子能否进入到八叉树的各个正方体中,一旦进入,则开启该粒子的碰撞检测,threejs的八叉树有自己的射线功能,性能还是可以的
上代码吧
let neighbors;
import * as THREE from "three";function vecScale(a,anr, scale) {anr *= 3;a[anr++] *= scale;a[anr++] *= scale;a[anr] *= scale;
}function vecCopy(a,anr, b,bnr) {anr *= 3; bnr *= 3;a[anr++] = b[bnr++]; a[anr++] = b[bnr++]; a[anr] = b[bnr];
}// 向量相加
function vecAdd(a,anr, b,bnr, scale = 1.0) {anr *= 3; bnr *= 3;a[anr++] += b[bnr++] * scale; a[anr++] += b[bnr++] * scale; a[anr] += b[bnr] * scale;
}function vecSetDiff(dst,dnr, a,anr, b,bnr, scale = 1.0) {dnr *= 3; anr *= 3; bnr *= 3;dst[dnr++] = (a[anr++] - b[bnr++]) * scale;dst[dnr++] = (a[anr++] - b[bnr++]) * scale;dst[dnr] = (a[anr] - b[bnr]) * scale;
}function vecLengthSquared(a,anr) {anr *= 3;let a0 = a[anr], a1 = a[anr + 1], a2 = a[anr + 2];return a0 * a0 + a1 * a1 + a2 * a2;
}function vecDistSquared(a,anr, b,bnr) {anr *= 3; bnr *= 3;let a0 = a[anr] - b[bnr], a1 = a[anr + 1] - b[bnr + 1], a2 = a[anr + 2] - b[bnr + 2];return a0 * a0 + a1 * a1 + a2 * a2;
} function vecSetCross(a,anr, b,bnr, c,cnr) {anr *= 3; bnr *= 3; cnr *= 3;a[anr++] = b[bnr + 1] * c[cnr + 2] - b[bnr + 2] * c[cnr + 1];a[anr++] = b[bnr + 2] * c[cnr + 0] - b[bnr + 0] * c[cnr + 2];a[anr] = b[bnr + 0] * c[cnr + 1] - b[bnr + 1] * c[cnr + 0];
}function findTriNeighbors(triIds)
{// create common edges// 将点的关联放入到edges当中let edges = [];let numTris = triIds.length / 3;for (let i = 0; i < numTris; i++) {for (let j = 0; j < 3; j++) {let id0 = triIds[3 * i + j];let id1 = triIds[3 * i + (j + 1) % 3];edges.push({id0 : Math.min(id0, id1), id1 : Math.max(id0, id1), edgeNr : 3 * i + j});}}// sort so common edges are next to each othe