2. 胶囊几何Capsule.js
# 胶囊几何Capsule.js
上节课给大家介绍了八叉树扩展库Octree.js
。
const worldOctree = new Octree();
const gltf = await loader.loadAsync("../地形.glb");
worldOctree.fromGraphNode(gltf.scene);
下面给大家介绍胶囊扩展库Capsule.js
,Capsule
表示胶囊形状的几何体,具体说就是上面一个半球、中间一个圆柱、下面一个半球拼接构成的胶囊形状几何体。
# 项目引入胶囊碰撞体Capsule.js
Three.js在目录/examples/jsm/math/
下提供了一个胶囊形状的几何体Capsule.js
。
npm安装threejs情况下,Capsule.js扩展库引入路径。
// 引入/examples/jsm/math/目录下胶囊扩展库Capsule.js
import { Capsule } from 'three/examples/jsm/math/Capsule.js';
本课程案例源码.html
里面自定义了新的路径。
import { Capsule } from 'three/addons/math/Capsule.js';
# 创建胶囊几何体
创建胶囊几何体:让胶囊底部半球与y=0的平面刚好相切即可。
const R = 0.4;//胶囊半径
const H = 1.7;//胶囊总高度
const start = new THREE.Vector3(0, R, 0);//底部半球球心坐标
const end = new THREE.Vector3(0, H - R, 0);//顶部半球球心坐标
const capsule = new Capsule(start, end, R);
log打印capsule
,你可以看到胶囊的两个属性.start
和.end
。
console.log('capsule', capsule);
# 练习:Mesh可视化上面胶囊几何体
const geometry = new THREE.CapsuleGeometry(R, H - 2 * R, 16, 16);
const material = new THREE.MeshLambertMaterial({
color: 0x00ffff
});
const capsuleMesh = new THREE.Mesh(geometry, material);
CapsuleGeometry
默认胶囊中心位于坐标原点,与上面Capsule位置有偏差,需要平移。
geometry.translate(0,H/2,0);
# 平移胶囊几何体
平移胶囊碰撞体,使底部半球球心.start
与坐标原点重合。
capsule.translate(new THREE.Vector3(0, -R, 0));
capsule.translate()
本质上改变就是自身的.start
和.end
属性
// 查看平移后的胶囊,`.start`和`.end`属性
console.log('capsule', capsule);
可视化胶囊的模型对象同步平移
capsuleMesh.position.y -= R;
换一种平移方式,同步capsuleMesh
与capsule
的位置。
因为capsule
没有.position
属性,所以可以复制.start
或.end
属性,然后capsuleMesh
的y方向偏移即可。
capsuleMesh.position.copy(capsule.start);
capsuleMesh.position.y -= R;
capsuleMesh.position.copy(capsule.end)
capsuleMesh.position.y -= (H-R);