# three.js cannon.js物理引擎之ConvexPolyhedron多边形

## 1. cannon.js物理引擎多边形ConvexPolyhedron的构造函数

ConvexPolyhedron ( points  faces )

var points = [
new CANNON.Vec3(0,0,0),
new CANNON.Vec3(2,0,0),
new CANNON.Vec3(0,2,0),
new CANNON.Vec3(0,0,2)
];
var faces = [
[0,3,2],
[0,1,3],
[0,2,1],
[1,2,3],
]
var convex = new CANNON.ConvexPolyhedron( points faces );

## 2. 实现一个使用ConvexPolyhedron（多边形）的场景

### 1. 制作three几何体

parametricGeom = new THREE.ParametricGeometry(
(u, v, target) => {
let x = Math.sin(Math.PI * 2 * u) * 10 * Math.abs(Math.sin(Math.PI * v));
let y = v * 20 - 10;
let z = Math.cos(Math.PI * 2 * u) * 10 * Math.abs(Math.cos(Math.PI * v));
target.set(x, y, z);
},
30,
12
);
torusGeom = new THREE.TorusGeometry(5, 2, 16, 8);
torusKnotGeom = new THREE.TorusKnotGeometry(5, 1.5, 80, 8, 2, 3);
for(let i=0; i<parametricGeom.faces.length; i++) {
color.setHSL(Math.random(), 0.5, 0.5);
parametricGeom.faces[i].color.copy(color);
}
for(let i=0; i<torusGeom.faces.length; i++) {
color.setHSL(Math.random(), 0.5, 0.5);
torusGeom.faces[i].color.copy(color);
}
for(let i=0; i<torusKnotGeom.faces.length; i++) {
color.setHSL(Math.random(), 0.5, 0.5);
torusKnotGeom.faces[i].color.copy(color);
}

### 2. 用既有的three几何体制作cannon多边形

let parametricShape = this.createConvex(parametricGeom);
let torusShape = this.createConvex(torusGeom);
let torusKnotShape = this.createConvex(torusKnotGeom);

parametricBody = new CANNON.Body({
mass: 0,
position: new CANNON.Vec3(-20, 6, 0),
material: new CANNON.Material({friction: 0, restitution: 1}),
shape: parametricShape
})
torusBody = new CANNON.Body({
mass: 0,
position: new CANNON.Vec3(0, 6, 0),
material: new CANNON.Material({friction: 0, restitution: 1}),
shape: torusShape
})
torusKnotBody = new CANNON.Body({
mass: 0,
position: new CANNON.Vec3(20, 6, 0),
material: new CANNON.Material({friction: 0, restitution: 1}),
shape: torusKnotShape
})

createConvex(geometry) {
let vertices = [];
let faces = [];
for(let i=0; i<geometry.vertices.length; i++) {
vertices.push(new CANNON.Vec3(geometry.vertices[i].x, geometry.vertices[i].y, geometry.vertices[i].z));
}
for(let i=0; i<geometry.faces.length; i++) {
faces.push([geometry.faces[i].a, geometry.faces[i].b, geometry.faces[i].c]);
}
return new CANNON.ConvexPolyhedron(vertices, faces);
}

three的点和faces面存在geometry.vertices中和geometry.faces中，我们需要取出来并整理成我们想要的形式。然后下一步就是创建three.js网格，我们就不赘述了。

posted @ 2021-02-24 12:15  郭先生的博客  阅读(246)  评论(0编辑  收藏