Physics with Cannon.js

Description

Animation can also be achieved using a Physics library. I will use Cannon.js. Cannon.js is a rigid body simulation library. It can be used to make objects move and interact in a realistic way and provide collision detection possibilities.

Basic Concepts

• Shape : A geometrical shape, such as a sphere, cube or plane, used for the the physics calculations.
• Rigid Body : A rigid body has a shape and a number of other properties used in the calculations such as mass and inertia.
• Constraint : A 3D body has 6 degrees of freedom, 3 for position and three to describe the rotation vector. A constraint is a limit on one of the degrees of freedom.
• Contact constraint : A type of constraint to simulate friction and restitution. These are like the faces of an object where the constraint is applied.
• World : A collection of bodies and constraints that interact together.
• Solver : The algorithm that is passed over the bodies and constraints to calculate there physical properties and adjust them accordingly.

Collision Detection

Collision detection algorithms determine what pairs of objects may be colliding. Collision detection is a computationally expensive process, so various methods can be used to simplify the collision detection.

• Narrowphase : Outright body vs body collision detection. This is the most computationally expensive.
• Broadphase : Is a compromise on Narrowphase where various techniques can be used to improve collision detection performance.

Cannonjs provides several options for broadphase detection.

Phase Description
NaiveBroadphase Default. The NaiveBroadphase looks at all possible pairs without restriction, therefore it has complexity N^2. It is similar to the Narrowphase technique, except it decides first whether objects are close enough before checking if there bodies touch. NaiveBroadphase is the default and is suitable for the most common use cases, but becomes less performant if there are many objects in the physics world.
SAPBroadphase The Sweep and Prune algorithm sorts bodies along an axis and then moves down that list finding pairs by looking at body size and position of the next bodies. For best performance, choose an axis that the bodies are spread out more on. Set to 0 for X axis, and 1 for Y axis. Default axisIndex is 0 (X axis).
GridBroadphase Axis aligned uniform grid broadphase. Divides space into a grid of cells. Bodies are placed into the cells they overlap and bodies in the same cell are paired. GridBroadphase needs to know the size of the space ahead of time. Set number of cells when you create the object. Default number of cells is X = 10, Y = 10, Z = 10.

Iterations

The Solver algorithms decide what force to add to bodies in contact. The solver is iterative, which means that it solves the equations incrementally on each animation pass. It will get closer to the solution for each iteration during the loop. A number too low for the solver iterations will result in increasingly inaccurate contact forces, which can appear as jittering or vibrations on the object, and a higher number will increase precision and stability, but also compromise performance.

The default solver iterations is 10.

 `1` ```world.solver.iterations = 10; ```

Supported Cannon.js Shape Collisions

. Box Sphere Cylinder Plane Convex Trimesh
Box
Sphere
Cylinder
Plane
Convex
Trimesh

Setup

Install cannonjs

 `1` ```npm install cannon ```

Start Scripts

./src/server/server.ts

 ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33``` ```import express from "express" import path from "path" import http from "http" const port: number = 3000 class App { private server: http.Server private port: number constructor(port: number) { this.port = port const app = express() app.use(express.static(path.join(__dirname, '../client'))) app.use('/build/three.module.js', express.static(path.join(__dirname, '../../node_modules/three/build/three.module.js'))) app.use('/jsm/controls/OrbitControls', express.static(path.join(__dirname, '../../node_modules/three/examples/jsm/controls/OrbitControls.js'))) app.use('/jsm/libs/stats.module', express.static(path.join(__dirname, '../../node_modules/three/examples/jsm/libs/stats.module.js'))) app.use('/jsm/libs/dat.gui.module', express.static(path.join(__dirname, '../../node_modules/three/examples/jsm/libs/dat.gui.module.js'))) app.use('/cannon/cannon.min', express.static(path.join(__dirname, '../../node_modules/cannon/build/cannon.min.js'))) this.server = new http.Server(app); } public Start() { this.server.listen(this.port, () => { console.log( `Server listening on port \${this.port}.` ) }) } } new App(port). Start() ```

./src/client/client.ts

 ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193``` ```import * as THREE from '/build/three.module.js' import { OrbitControls } from '/jsm/controls/OrbitControls' import Stats from '/jsm/libs/stats.module' import { GUI } from '/jsm/libs/dat.gui.module' //import '/cannon/cannon.min' const scene: THREE.Scene = new THREE.Scene() const axesHelper = new THREE.AxesHelper(5) scene.add(axesHelper) var light1 = new THREE.SpotLight(); light1.position.set(2.5, 5, 5) light1.angle = Math.PI / 4 light1.penumbra = 0.5 light1.castShadow = true; light1.shadow.mapSize.width = 1024; light1.shadow.mapSize.height = 1024; light1.shadow.camera.near = 0.5; light1.shadow.camera.far = 20 scene.add(light1); var light2 = new THREE.SpotLight(); light2.position.set(-2.5, 5, 5) light2.angle = Math.PI / 4 light2.penumbra = 0.5 light2.castShadow = true; light2.shadow.mapSize.width = 1024; light2.shadow.mapSize.height = 1024; light2.shadow.camera.near = 0.5; light2.shadow.camera.far = 20 scene.add(light2); const camera: THREE.PerspectiveCamera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000) const renderer: THREE.WebGLRenderer = new THREE.WebGLRenderer() renderer.setSize(window.innerWidth, window.innerHeight) renderer.shadowMap.enabled = true renderer.shadowMap.type = THREE.PCFSoftShadowMap document.body.appendChild(renderer.domElement) const controls = new OrbitControls(camera, renderer.domElement) controls.screenSpacePanning = true // const world = new CANNON.World() // world.gravity.set(0, -9.82, 0) // //world.broadphase = new CANNON.NaiveBroadphase() // // //world.solver.iterations = 10 // //world.allowSleep = true const normalMaterial: THREE.MeshNormalMaterial = new THREE.MeshNormalMaterial() const phongMaterial: THREE.MeshPhongMaterial = new THREE.MeshPhongMaterial() const cubeGeometry: THREE.BoxGeometry = new THREE.BoxGeometry(1, 1, 1) const cubeMesh: THREE.Mesh = new THREE.Mesh(cubeGeometry, normalMaterial) cubeMesh.position.x = -3 cubeMesh.position.y = 3 cubeMesh.castShadow = true scene.add(cubeMesh) // const cubeShape = new CANNON.Box(new CANNON.Vec3(.5, .5, .5)) // const cubeBody = new CANNON.Body({ mass: 1 }); // cubeBody.addShape(cubeShape) // cubeBody.position.x = cubeMesh.position.x // cubeBody.position.y = cubeMesh.position.y // cubeBody.position.z = cubeMesh.position.z // world.addBody(cubeBody) const sphereGeometry: THREE.SphereGeometry = new THREE.SphereGeometry() const sphereMesh: THREE.Mesh = new THREE.Mesh(sphereGeometry, normalMaterial) sphereMesh.position.x = -1 sphereMesh.position.y = 3 sphereMesh.castShadow = true scene.add(sphereMesh) // const sphereShape = new CANNON.Sphere(1) // const sphereBody = new CANNON.Body({ mass: 1 }); // sphereBody.addShape(sphereShape) // sphereBody.position.x = sphereMesh.position.x // sphereBody.position.y = sphereMesh.position.y // sphereBody.position.z = sphereMesh.position.z // world.addBody(sphereBody) const icosahedronGeometry: THREE.IcosahedronGeometry = new THREE.IcosahedronGeometry(1, 0) const icosahedronMesh: THREE.Mesh = new THREE.Mesh(icosahedronGeometry, normalMaterial) icosahedronMesh.position.x = 1 icosahedronMesh.position.y = 3 icosahedronMesh.castShadow = true scene.add(icosahedronMesh) // const icosahedronPoints = (icosahedronMesh.geometry).vertices.map(function (v) { // return new CANNON.Vec3(v.x, v.y, v.z) // }) // const icosahedronFaces = (icosahedronMesh.geometry).faces.map(function (f) { // return [f.a, f.b, f.c] // }) // const icosahedronShape = new CANNON.ConvexPolyhedron(icosahedronPoints, icosahedronFaces) // const icosahedronBody = new CANNON.Body({ mass: 1 }); // icosahedronBody.addShape(icosahedronShape) // icosahedronBody.position.x = icosahedronMesh.position.x // icosahedronBody.position.y = icosahedronMesh.position.y // icosahedronBody.position.z = icosahedronMesh.position.z // world.addBody(icosahedronBody) const torusKnotGeometry: THREE.TorusKnotGeometry = new THREE.TorusKnotGeometry() const torusKnotMesh: THREE.Mesh = new THREE.Mesh(torusKnotGeometry, normalMaterial) torusKnotMesh.position.x = 4 torusKnotMesh.position.y = 3 torusKnotMesh.castShadow = true scene.add(torusKnotMesh) // const torusKnotPoints = (torusKnotMesh.geometry).vertices.map(function (v) { // return new CANNON.Vec3(v.x, v.y, v.z) // }) // const torusKnotFaces = (torusKnotMesh.geometry).faces.map(function (f) { // return [f.a, f.b, f.c] // }) // const torusKnotShape = new CANNON.ConvexPolyhedron(torusKnotPoints, torusKnotFaces) // const torusKnotShape = CreateTrimesh(torusKnotMesh.geometry) // const torusKnotBody = new CANNON.Body({ mass: 1 }); // torusKnotBody.addShape(torusKnotShape) // torusKnotBody.position.x = torusKnotMesh.position.x // torusKnotBody.position.y = torusKnotMesh.position.y // torusKnotBody.position.z = torusKnotMesh.position.z // world.addBody(torusKnotBody) // function CreateTrimesh(geometry){ // if (!geometry.attributes) { // geometry = new THREE.BufferGeometry().fromGeometry(geometry); // } // const vertices = geometry.attributes.position.array // const indices = Object.keys(vertices).map(Number); // return new CANNON.Trimesh(vertices, indices); // } const planeGeometry: THREE.PlaneGeometry = new THREE.PlaneGeometry(25, 25) const planeMesh: THREE.Mesh = new THREE.Mesh(planeGeometry, phongMaterial) planeMesh.rotateX(-Math.PI / 2) planeMesh.receiveShadow = true; scene.add(planeMesh) // const planeShape = new CANNON.Plane() // const planeBody = new CANNON.Body({ mass: 0 }) // planeBody.addShape(planeShape) // planeBody.quaternion.setFromAxisAngle(new CANNON.Vec3(1, 0, 0), -Math.PI / 2) // world.addBody(planeBody) camera.position.y = 4 camera.position.z = 4 controls.target.y = 2 window.addEventListener('resize', onWindowResize, false) function onWindowResize() { camera.aspect = window.innerWidth / window.innerHeight camera.updateProjectionMatrix() renderer.setSize(window.innerWidth, window.innerHeight) render() } const stats = Stats() document.body.appendChild(stats.dom) const gui = new GUI() // const physicsFolder = gui.addFolder("Physics") // physicsFolder.add(world.gravity, "x", -10.0, 10.0, 0.1) // physicsFolder.add(world.gravity, "y", -10.0, 10.0, 0.1) // physicsFolder.add(world.gravity, "z", -10.0, 10.0, 0.1) // physicsFolder.open() const clock: THREE.Clock = new THREE.Clock() var animate = function () { requestAnimationFrame(animate) controls.update() // let delta = clock.getDelta() // if (delta > .1) delta = .1 // world.step(delta) // Copy coordinates from Cannon.js to Three.js // cubeMesh.position.set(cubeBody.position.x, cubeBody.position.y, cubeBody.position.z); // cubeMesh.quaternion.set(cubeBody.quaternion.x, cubeBody.quaternion.y, cubeBody.quaternion.z, cubeBody.quaternion.w); // sphereMesh.position.set(sphereBody.position.x, sphereBody.position.y, sphereBody.position.z); // sphereMesh.quaternion.set(sphereBody.quaternion.x, sphereBody.quaternion.y, sphereBody.quaternion.z, sphereBody.quaternion.w); // icosahedronMesh.position.set(icosahedronBody.position.x, icosahedronBody.position.y, icosahedronBody.position.z); // icosahedronMesh.quaternion.set(icosahedronBody.quaternion.x, icosahedronBody.quaternion.y, icosahedronBody.quaternion.z, icosahedronBody.quaternion.w); // torusKnotMesh.position.set(torusKnotBody.position.x, torusKnotBody.position.y, torusKnotBody.position.z); // torusKnotMesh.quaternion.set(torusKnotBody.quaternion.x, torusKnotBody.quaternion.y, torusKnotBody.quaternion.z, torusKnotBody.quaternion.w); render() stats.update() }; function render() { renderer.render(scene, camera) } animate(); ```

./src/typings/cannon/index.d.ts

Create a new folder called ./src/typings/cannon/ and add the TypeScript definition file below for cannon.js and name it index.d.ts

 ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070``` ```// Type definitions for cannon 0.1 // Project: https://github.com/clark-stevenson/cannon.d.ts // Definitions by: Clark Stevenson // Grzegorz Rozdzialik // Sean Bradley // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare module CANNON { export interface IAABBOptions { upperBound?: Vec3; lowerBound?: Vec3; } export class AABB { lowerBound: Vec3; upperBound: Vec3; constructor(options?: IAABBOptions); clone(): AABB; copy(aabb: AABB): void; extend(aabb: AABB): void; getCorners(a: Vec3, b: Vec3, c: Vec3, d: Vec3, e: Vec3, f: Vec3, g: Vec3, h: Vec3): void; overlaps(aabb: AABB): boolean; setFromPoints(points: Vec3[], position?: Vec3, quaternion?: Quaternion, skinSize?: number): AABB; toLocalFrame(frame: Transform, target: AABB): AABB; toWorldFrame(frame: Transform, target: AABB): AABB; } export class ArrayCollisionMatrix { matrix: Mat3[]; get(i: number, j: number): number; set(i: number, j: number, value: number): void; reset(): void; setNumObjects(n: number): void; } export class BroadPhase { world: World; useBoundingBoxes: boolean; dirty: boolean; collisionPairs(world: World, p1: Body[], p2: Body[]): void; needBroadphaseCollision(bodyA: Body, bodyB: Body): boolean; intersectionTest(bodyA: Body, bodyB: Body, pairs1: Body[], pairs2: Body[]): void; doBoundingSphereBroadphase(bodyA: Body, bodyB: Body, pairs1: Body[], pairs2: Body[]): void; doBoundingBoxBroadphase(bodyA: Body, bodyB: Body, pairs1: Body[], pairs2: Body[]): void; makePairsUnique(pairs1: Body[], pairs2: Body[]): void; setWorld(world: World): void; boundingSphereCheck(bodyA: Body, bodyB: Body): boolean; aabbQuery(world: World, aabb: AABB, result: Body[]): Body[]; } export class GridBroadphase extends BroadPhase { nx: number; ny: number; nz: number; aabbMin: Vec3; aabbMax: Vec3; bins: any[]; constructor(aabbMin?: Vec3, aabbMax?: Vec3, nx?: number, ny?: number, nz?: number); } export class NaiveBroadphase extends BroadPhase { } export class ObjectCollisionMatrix { matrix: number[]; get(i: number, j: number): number; set(i: number, j: number, value: number): void; reset(): void; setNumObjects(n: number): void; } export class Ray { from: Vec3; to: Vec3; precision: number; checkCollisionResponse: boolean; constructor(from?: Vec3, to?: Vec3); getAABB(result: RaycastResult): void; } export class RaycastResult { rayFromWorld: Vec3; rayToWorld: Vec3; hitNormalWorld: Vec3; hitPointWorld: Vec3; hasHit: boolean; shape: Shape; body: Body; distance: number; reset(): void; set(rayFromWorld: Vec3, rayToWorld: Vec3, hitNormalWorld: Vec3, hitPointWorld: Vec3, shape: Shape, body: Body, distance: number): void; } export class SAPBroadphase extends BroadPhase { static insertionSortX(a: any[]): any[]; static insertionSortY(a: any[]): any[]; static insertionSortZ(a: any[]): any[]; static checkBounds(bi: Body, bj: Body, axisIndex?: number): boolean; axisList: any[]; world: World; axisIndex: number; constructor(world?: World); autoDetectAxis(): void; aabbQuery(world: World, aabb: AABB, result?: Body[]): Body[]; } export interface IConstraintOptions { collideConnected?: boolean; wakeUpBodies?: boolean; } export class Constraint { equations: any[]; bodyA: Body; bodyB: Body; id: number; collideConnected: boolean; constructor(bodyA: Body, bodyB: Body, options?: IConstraintOptions); update(): void; disable(): void; enable(): void; } export class DistanceConstraint extends Constraint { constructor(bodyA: Body, bodyB: Body, distance: number, maxForce?: number); } export interface IHingeConstraintOptions { pivotA?: Vec3; axisA?: Vec3; pivotB?: Vec3; axisB?: Vec3; maxForce?: number; } export class HingeConstraint extends Constraint { motorEnabled: boolean; motorTargetVelocity: number; motorMinForce: number; motorMaxForce: number; motorEquation: RotationalMotorEquation; axisA: Vec3; axisB: Vec3; constructor(bodyA: Body, bodyB: Body, options?: IHingeConstraintOptions); enableMotor(): void; disableMotor(): void; setMotorSpeed(speed: number): void; } export class PointToPointConstraint extends Constraint { constructor(bodyA: Body, pivotA: Vec3, bodyB: Body, pivotB: Vec3, maxForce?: number); } export interface ILockConstraintOptions { maxForce?: number; } export class LockConstraint extends Constraint { constructor(bodyA: Body, bodyB: Body, options?: ILockConstraintOptions); } export interface IConeTwistConstraintOptions { pivotA?: Vec3; pivotB?: Vec3; axisA?: Vec3; axisB?: Vec3; maxForce?: number; } export class ConeTwistConstraint extends Constraint { constructor(bodyA: Body, bodyB: Body, options?: IConeTwistConstraintOptions); } export class Equation { id: number; minForce: number; maxForce: number; bi: Body; bj: Body; a: number; b: number; eps: number; jacobianElementA: JacobianElement; jacobianElementB: JacobianElement; enabled: boolean; constructor(bi: Body, bj: Body, minForce?: number, maxForce?: number); setSpookParams(stiffness: number, relaxation: number, timeStep: number): void; computeB(a: number, b: number, h: number): number; computeGq(): number; computeGW(): number; computeGWlamda(): number; computeGiMf(): number; computeGiMGt(): number; addToWlamda(deltalambda: number): number; computeC(): number; } export class FrictionEquation extends Equation { constructor(bi: Body, bj: Body, slipForce: number); } export class RotationalEquation extends Equation { ni: Vec3; nj: Vec3; nixnj: Vec3; njxni: Vec3; invIi: Mat3; invIj: Mat3; relVel: Vec3; relForce: Vec3; constructor(bodyA: Body, bodyB: Body); } export class RotationalMotorEquation extends Equation { axisA: Vec3; axisB: Vec3; invLi: Mat3; invIj: Mat3; targetVelocity: number; constructor(bodyA: Body, bodyB: Body, maxForce?: number); } export class ContactEquation extends Equation { restitution: number; ri: Vec3; rj: Vec3; penetrationVec: Vec3; ni: Vec3; rixn: Vec3; rjxn: Vec3; invIi: Mat3; invIj: Mat3; biInvInertiaTimesRixn: Vec3; bjInvInertiaTimesRjxn: Vec3; constructor(bi: Body, bj: Body); } export interface IContactMaterialOptions { friction?: number; restitution?: number; contactEquationStiffness?: number; contactEquationRelaxation?: number; frictionEquationStiffness?: number; frictionEquationRelaxation?: number; } export class ContactMaterial { id: number; materials: Material[]; friction: number; restitution: number; contactEquationStiffness: number; contactEquationRelaxation: number; frictionEquationStiffness: number; frictionEquationRelaxation: number; constructor(m1: Material, m2: Material, options?: IContactMaterialOptions); } export class Material { name: string; id: number; friction: number; restitution: number; constructor(name: string); } export class JacobianElement { spatial: Vec3; rotational: Vec3; multiplyElement(element: JacobianElement): number; multiplyVectors(spacial: Vec3, rotational: Vec3): number; } export class Mat3 { constructor(elements?: number[]); identity(): void; setZero(): void; setTrace(vec3: Vec3): void; getTrace(target: Vec3): void; vmult(v: Vec3, target?: Vec3): Vec3; smult(s: number): void; mmult(m: Mat3): Mat3; scale(v: Vec3, target?: Mat3): Mat3; solve(b: Vec3, target?: Vec3): Vec3; e(row: number, column: number, value?: number): number; copy(source: Mat3): Mat3; toString(): string; reverse(target?: Mat3): Mat3; setRotationFromQuaternion(q: Quaternion): Mat3; transpose(target?: Mat3): Mat3; } export class Quaternion { x: number; y: number; z: number; w: number; constructor(x?: number, y?: number, z?: number, w?: number); set(x: number, y: number, z: number, w: number): void; toString(): string; toArray(): number[]; setFromAxisAngle(axis: Vec3, angle: number): void; toAxisAngle(targetAxis?: Vec3): any[]; setFromVectors(u: Vec3, v: Vec3): void; mult(q: Quaternion, target?: Quaternion): Quaternion; inverse(target?: Quaternion): Quaternion; conjugate(target?: Quaternion): Quaternion; normalize(): void; normalizeFast(): void; vmult(v: Vec3, target?: Vec3): Vec3; copy(source: Quaternion): Quaternion; toEuler(target: Vec3, order?: string): void; setFromEuler(x: number, y: number, z: number, order?: string): Quaternion; clone(): Quaternion; } export class Transform { static pointToLocalFrame(position: Vec3, quaternion: Quaternion, worldPoint: Vec3, result?: Vec3): Vec3; static pointToWorldFrame(position: Vec3, quaternion: Quaternion, localPoint: Vec3, result?: Vec3): Vec3; position: Vec3; quaternion: Quaternion; vectorToWorldFrame(localVector: Vec3, result?: Vec3): Vec3; vectorToLocalFrame(position: Vec3, quaternion: Quaternion, worldVector: Vec3, result?: Vec3): Vec3; } export class Vec3 { static ZERO: Vec3; x: number; y: number; z: number; constructor(x?: number, y?: number, z?: number); cross(v: Vec3, target?: Vec3): Vec3; set(x: number, y: number, z: number): Vec3; setZero(): void; vadd(v: Vec3, target?: Vec3): Vec3; vsub(v: Vec3, target?: Vec3): Vec3; crossmat(): Mat3; normalize(): number; unit(target?: Vec3): Vec3; norm(): number; norm2(): number; distanceTo(p: Vec3): number; mult(scalar: number, target?: Vec3): Vec3; scale(scalar: number, target?: Vec3): Vec3; dot(v: Vec3): number; isZero(): boolean; negate(target?: Vec3): Vec3; tangents(t1: Vec3, t2: Vec3): void; toString(): string; toArray(): number[]; copy(source: Vec3): Vec3; lerp(v: Vec3, t: number, target?: Vec3): void; almostEquals(v: Vec3, precision?: number): boolean; almostZero(precision?: number): boolean; isAntiparallelTo(v: Vec3, prescision?: number): boolean; clone(): Vec3; } export interface IBodyOptions { position?: Vec3; velocity?: Vec3; angularVelocity?: Vec3; quaternion?: Quaternion; mass?: number; material?: Material; type?: number; linearDamping?: number; angularDamping?: number; allowSleep?: boolean; sleepSpeedLimit?: number; sleepTimeLimit?: number; collisionFilterGroup?: number; collisionFilterMask?: number; fixedRotation?: boolean; shape?: Shape; } export class Body extends EventTarget { static DYNAMIC: number; static STATIC: number; static KINEMATIC: number; static AWAKE: number; static SLEEPY: number; static SLEEPING: number; static sleepyEvent: IEvent; static sleepEvent: IEvent; id: number; world: World; preStep: Function; postStep: Function; vlambda: Vec3; collisionFilterGroup: number; collisionFilterMask: number; collisionResponse: boolean; position: Vec3; previousPosition: Vec3; initPosition: Vec3; velocity: Vec3; initVelocity: Vec3; force: Vec3; mass: number; invMass: number; material: Material; linearDamping: number; type: number; allowSleep: boolean; sleepState: number; sleepSpeedLimit: number; sleepTimeLimit: number; timeLastSleepy: number; torque: Vec3; quaternion: Quaternion; initQuaternion: Quaternion; angularVelocity: Vec3; initAngularVelocity: Vec3; interpolatedPosition: Vec3; interpolatedQuaternion: Quaternion; shapes: Shape[]; shapeOffsets: any[]; shapeOrientations: any[]; inertia: Vec3; invInertia: Vec3; invInertiaWorld: Mat3; invMassSolve: number; invInertiaSolve: Vec3; invInteriaWorldSolve: Mat3; fixedRotation: boolean; angularDamping: number; aabb: AABB; aabbNeedsUpdate: boolean; wlambda: Vec3; constructor(options?: IBodyOptions); wakeUp(): void; sleep(): void; sleepTick(time: number): void; updateSolveMassProperties(): void; pointToLocalFrame(worldPoint: Vec3, result?: Vec3): Vec3; pointToWorldFrame(localPoint: Vec3, result?: Vec3): Vec3; vectorToWorldFrame(localVector: Vec3, result?: Vec3): Vec3; addShape(shape: Shape, offset?: Vec3, orientation?: Quaternion): void; updateBoundingRadius(): void; computeAABB(): void; updateInertiaWorld(force: Vec3): void; applyForce(force: Vec3, worldPoint: Vec3): void; applyImpulse(impulse: Vec3, worldPoint: Vec3): void; applyLocalForce(force: Vec3, localPoint: Vec3): void; applyLocalImpulse(impulse: Vec3, localPoint: Vec3): void; updateMassProperties(): void; getVelocityAtWorldPoint(worldPoint: Vec3, result: Vec3): Vec3; } export interface IRaycastVehicleOptions { chassisBody?: Body; indexRightAxis?: number; indexLeftAxis?: number; indexUpAxis?: number; } export interface IWheelInfoOptions { chassisConnectionPointLocal?: Vec3; chassisConnectionPointWorld?: Vec3; directionLocal?: Vec3; directionWorld?: Vec3; axleLocal?: Vec3; axleWorld?: Vec3; suspensionRestLength?: number; suspensionMaxLength?: number; radius?: number; suspensionStiffness?: number; dampingCompression?: number; dampingRelaxation?: number; frictionSlip?: number; steering?: number; rotation?: number; deltaRotation?: number; rollInfluence?: number; maxSuspensionForce?: number; isFronmtWheel?: boolean; clippedInvContactDotSuspension?: number; suspensionRelativeVelocity?: number; suspensionForce?: number; skidInfo?: number; suspensionLength?: number; maxSuspensionTravel?: number; useCustomSlidingRotationalSpeed?: boolean; customSlidingRotationalSpeed?: number; position?: Vec3; direction?: Vec3; axis?: Vec3; body?: Body; } export class WheelInfo { maxSuspensionTravbel: number; customSlidingRotationalSpeed: number; useCustomSlidingRotationalSpeed: boolean; sliding: boolean; chassisConnectionPointLocal: Vec3; chassisConnectionPointWorld: Vec3; directionLocal: Vec3; directionWorld: Vec3; axleLocal: Vec3; axleWorld: Vec3; suspensionRestLength: number; suspensionMaxLength: number; radius: number; suspensionStiffness: number; dampingCompression: number; dampingRelaxation: number; frictionSlip: number; steering: number; rotation: number; deltaRotation: number; rollInfluence: number; maxSuspensionForce: number; engineForce: number; brake: number; isFrontWheel: boolean; clippedInvContactDotSuspension: number; suspensionRelativeVelocity: number; suspensionForce: number; skidInfo: number; suspensionLength: number; sideImpulse: number; forwardImpulse: number; raycastResult: RaycastResult; worldTransform: Transform; isInContact: boolean; constructor(options?: IWheelInfoOptions); } export class RaycastVehicle { chassisBody: Body; wheelInfos: IWheelInfoOptions[]; sliding: boolean; world: World; iindexRightAxis: number; indexForwardAxis: number; indexUpAxis: number; constructor(options?: IRaycastVehicleOptions); addWheel(options?: IWheelInfoOptions): void; setSteeringValue(value: number, wheelIndex: number): void; applyEngineForce(value: number, wheelIndex: number): void; setBrake(brake: number, wheelIndex: number): void; addToWorld(world: World): void; getVehicleAxisWorld(axisIndex: number, result: Vec3): Vec3; updateVehicle(timeStep: number): void; updateSuspension(deltaTime: number): void; removeFromWorld(world: World): void; getWheelTransformWorld(wheelIndex: number): Transform; } export interface IRigidVehicleOptions { chassisBody: Body; } export class RigidVehicle { wheelBodies: Body[]; coordinateSystem: Vec3; chassisBody: Body; constraints: Constraint[]; wheelAxes: Vec3[]; wheelForces: Vec3[]; constructor(options?: IRigidVehicleOptions); addWheel(options?: IWheelInfoOptions): Body; setSteeringValue(value: number, wheelIndex: number): void; setMotorSpeed(value: number, wheelIndex: number): void; disableMotor(wheelIndex: number): void; setWheelForce(value: number, wheelIndex: number): void; applyWheelForce(value: number, wheelIndex: number): void; addToWorld(world: World): void; removeFromWorld(world: World): void; getWheelSpeed(wheelIndex: number): number; } export class SPHSystem { particles: Particle[]; density: number; smoothingRadius: number; speedOfSound: number; viscosity: number; eps: number; pressures: number[]; densities: number[]; neighbors: number[]; add(particle: Particle): void; remove(particle: Particle): void; getNeighbors(particle: Particle, neighbors: Particle[]): void; update(): void; w(r: number): number; gradw(rVec: Vec3, resultVec: Vec3): void; nablaw(r: number): number; } export interface ISpringOptions { restLength?: number; stiffness?: number; damping?: number; worldAnchorA?: Vec3; worldAnchorB?: Vec3; localAnchorA?: Vec3; localAnchorB?: Vec3; } export class Spring { restLength: number; stffness: number; damping: number; bodyA: Body; bodyB: Body; localAnchorA: Vec3; localAnchorB: Vec3; constructor(options?: ISpringOptions); setWorldAnchorA(worldAnchorA: Vec3): void; setWorldAnchorB(worldAnchorB: Vec3): void; getWorldAnchorA(result: Vec3): void; getWorldAnchorB(result: Vec3): void; applyForce(): void; } export class Box extends Shape { static calculateIntertia(halfExtents: Vec3, mass: number, target: Vec3): void; boundingSphereRadius: number; collisionResponse: boolean; halfExtents: Vec3; convexPolyhedronRepresentation: ConvexPolyhedron; constructor(halfExtents: Vec3); updateConvexPolyhedronRepresentation(): void; calculateLocalInertia(mass: number, target?: Vec3): Vec3; getSideNormals(sixTargetVectors: boolean, quat?: Quaternion): Vec3[]; updateBoundingSphereRadius(): number; volume(): number; forEachWorldCorner(pos: Vec3, quat: Quaternion, callback: Function): void; } export class ConvexPolyhedron extends Shape { static computeNormal(va: Vec3, vb: Vec3, vc: Vec3, target: Vec3): void; static project(hull: ConvexPolyhedron, axis: Vec3, pos: Vec3, quat: Quaternion, result: number[]): void; vertices: Vec3[]; worldVertices: Vec3[]; worldVerticesNeedsUpdate: boolean; faces: number[][]; faceNormals: Vec3[]; uniqueEdges: Vec3[]; constructor(points?: Vec3[], faces?: number[][]); computeEdges(): void; computeNormals(): void; getFaceNormal(i: number, target: Vec3): Vec3; clipAgainstHull(posA: Vec3, quatA: Quaternion, hullB: Vec3, quatB: Quaternion, separatingNormal: Vec3, minDist: number, maxDist: number, result: any[]): void; findSaparatingAxis(hullB: ConvexPolyhedron, posA: Vec3, quatA: Quaternion, posB: Vec3, quatB: Quaternion, target: Vec3, faceListA: any[], faceListB: any[]): boolean; testSepAxis(axis: Vec3, hullB: ConvexPolyhedron, posA: Vec3, quatA: Quaternion, posB: Vec3, quatB: Quaternion): number; getPlaneConstantOfFace(face_i: number): number; clipFaceAgainstHull(separatingNormal: Vec3, posA: Vec3, quatA: Quaternion, worldVertsB1: Vec3[], minDist: number, maxDist: number, result: any[]): void; clipFaceAgainstPlane(inVertices: Vec3[], outVertices: Vec3[], planeNormal: Vec3, planeConstant: number): Vec3; computeWorldVertices(position: Vec3, quat: Quaternion): void; computeLocalAABB(aabbmin: Vec3, aabbmax: Vec3): void; computeWorldFaceNormals(quat: Quaternion): void; calculateWorldAABB(pos: Vec3, quat: Quaternion, min: Vec3, max: Vec3): void; getAveragePointLocal(target: Vec3): Vec3; transformAllPoints(offset: Vec3, quat: Quaternion): void; pointIsInside(p: Vec3): boolean; } export class Cylinder extends Shape { constructor(radiusTop: number, radiusBottom: number, height: number, numSegments: number); } export interface IHightfield { minValue?: number; maxValue?: number; elementSize: number; } export class Heightfield extends Shape { data: number[][]; maxValue: number; minValue: number; elementSize: number; cacheEnabled: boolean; pillarConvex: ConvexPolyhedron; pillarOffset: Vec3; type: number; constructor(data: number[], options?: IHightfield); update(): void; updateMinValue(): void; updateMaxValue(): void; setHeightValueAtIndex(xi: number, yi: number, value: number): void; getRectMinMax(iMinX: number, iMinY: number, iMaxX: number, iMaxY: number, result: any[]): void; getIndexOfPosition(x: number, y: number, result: any[], clamp: boolean): boolean; getConvexTrianglePillar(xi: number, yi: number, getUpperTriangle: boolean): void; } export class Particle extends Shape { } export class Plane extends Shape { worldNormal: Vec3; worldNormalNeedsUpdate: boolean; boundingSphereRadius: number; computeWorldNormal(quat: Quaternion): void; calculateWorldAABB(pos: Vec3, quat: Quaternion, min: number, max: number): void; } export class Trimesh extends Shape { vertices: number[] indices: number[] scale: Vec3 constructor(vertices: number[], indices: number[]); updateTree(): void; getTrianglesInAABB(aabb: AABB, result: []): []; setScale(scale: Vec3): void updateNormals(): void; updateEdges(): void; getEdgeVertex(edgeIndex: number, firstOrSecond: number, vertexStore: Vec3): void; getEdgeVector(edgeIndex: number, vectorStore: Vec3): void; static computeNormal(va: Vec3, vb: Vec3, vc: Vec3, target: Vec3): void; getVertex(i: number, out: Vec3): Vec3; getWorldVertex(i: number, pos: Vec3, quat: Quaternion, out: Vec3): Vec3; getTriangleVertices(i: number, a: Vec3, b: Vec3, c: Vec3): void; getNormal(i: number, target: Vec3): Vec3; calculateLocalInertia(mass: number, target: Vec3): Vec3; computeLocalAABB(aabb: Vec3): void; updateAABB(): void; updateBoundingSphereRadius(): number; calculateWorldAABB(pos: Vec3, quat: Quaternion, min: number, max: number): void; volume(): number; createTorus(radius: number, tube: number, radialSegments: number, tubularSegments: number, arc: number): Trimesh; } export class Shape { static types: { SPHERE: number; PLANE: number; BOX: number; COMPOUND: number; CONVEXPOLYHEDRON: number; HEIGHTFIELD: number; PARTICLE: number; CYLINDER: number; TRIMESH: number; } type: number; boundingSphereRadius: number; collisionResponse: boolean; geometryId: number; updateBoundingSphereRadius(): number; volume(): number; calculateLocalInertia(mass: number, target: Vec3): Vec3; } export class Sphere extends Shape { radius: number; constructor(radius: number); } export class GSSolver extends Solver { iterations: number; tolerance: number; solve(dy: number, world: World): number; } export class Solver { iterations: number; equations: Equation[]; solve(dy: number, world: World): number; addEquation(eq: Equation): void; removeEquation(eq: Equation): void; removeAllEquations(): void; } export class SplitSolver extends Solver { subsolver: Solver; constructor(subsolver: Solver); solve(dy: number, world: World): number; } export class EventTarget { addEventListener(type: string, listener: Function): EventTarget; hasEventListener(type: string, listener: Function): boolean; removeEventListener(type: string, listener: Function): EventTarget; dispatchEvent(event: IEvent): IEvent; } export class Pool { objects: any[]; type: any[]; release(): any; get(): any; constructObject(): any; } export class TupleDictionary { data: { keys: any[]; }; get(i: number, j: number): number; set(i: number, j: number, value: number): void; reset(): void; } export class Utils { static defaults(options?: any, defaults?: any): any; } export class Vec3Pool extends Pool { type: any; constructObject(): Vec3; } export class NarrowPhase { contactPointPool: Pool[]; v3pool: Vec3Pool; } export class World extends EventTarget { iterations: number; dt: number; allowSleep: boolean; contacts: ContactEquation[]; frictionEquations: FrictionEquation[]; quatNormalizeSkip: number; quatNormalizeFast: boolean; time: number; stepnumber: number; default_dt: number; nextId: number; gravity: Vec3; broadphase: NaiveBroadphase; bodies: Body[]; solver: Solver; constraints: Constraint[]; narrowPhase: NarrowPhase; collisionMatrix: ArrayCollisionMatrix; collisionMatrixPrevious: ArrayCollisionMatrix; materials: Material[]; contactmaterials: ContactMaterial[]; contactMaterialTable: TupleDictionary; defaultMaterial: Material; defaultContactMaterial: ContactMaterial; doProfiling: boolean; profile: { solve: number; makeContactConstraints: number; broadphaser: number; integrate: number; narrowphase: number; }; subsystems: any[]; addBodyEvent: IBodyEvent; removeBodyEvent: IBodyEvent; getContactMaterial(m1: Material, m2: Material): ContactMaterial; numObjects(): number; collisionMatrixTick(): void; addBody(body: Body): void; addConstraint(c: Constraint): void; removeConstraint(c: Constraint): void; rayTest(from: Vec3, to: Vec3, result: RaycastResult): void; remove(body: Body): void; addMaterial(m: Material): void; addContactMaterial(cmat: ContactMaterial): void; step(dy: number, timeSinceLastCalled?: number, maxSubSteps?: number): void; } export interface IEvent { type: string; } export interface IBodyEvent extends IEvent { body: Body; } export interface ICollisionEvent extends IBodyEvent { contact: any; target: any; } } declare module "cannon" { export = CANNON; } ```

./src/client/tsconfig.json

Update the compiler options paths to point to the new cannon.js typescript definition file.

 ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21``` ```{ "compilerOptions": { "target": "ES6", "module": "ES6", "outDir": "../../dist/client", "baseUrl": ".", "paths": { "/build/three.module.js": ["../../node_modules/three/src/Three"], "/jsm/*": ["../../node_modules/three/examples/jsm/*"], "/jsm/libs/dat.gui.module": ["../typings/dat.gui"], "/jsm/libs/tween.module.min": ["../typings/tween.js"], "/cannon/cannon.min": ["../typings/cannon"] }, "moduleResolution": "node" }, "include": [ "**/*.ts" ] } ```

Final Scripts

./src/client/client.ts

 ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193``` ```import * as THREE from '/build/three.module.js' import { OrbitControls } from '/jsm/controls/OrbitControls' import Stats from '/jsm/libs/stats.module' import { GUI } from '/jsm/libs/dat.gui.module' import '/cannon/cannon.min' const scene: THREE.Scene = new THREE.Scene() const axesHelper = new THREE.AxesHelper(5) scene.add(axesHelper) var light1 = new THREE.SpotLight(); light1.position.set(2.5, 5, 5) light1.angle = Math.PI / 4 light1.penumbra = 0.5 light1.castShadow = true; light1.shadow.mapSize.width = 1024; light1.shadow.mapSize.height = 1024; light1.shadow.camera.near = 0.5; light1.shadow.camera.far = 20 scene.add(light1); var light2 = new THREE.SpotLight(); light2.position.set(-2.5, 5, 5) light2.angle = Math.PI / 4 light2.penumbra = 0.5 light2.castShadow = true; light2.shadow.mapSize.width = 1024; light2.shadow.mapSize.height = 1024; light2.shadow.camera.near = 0.5; light2.shadow.camera.far = 20 scene.add(light2); const camera: THREE.PerspectiveCamera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000) const renderer: THREE.WebGLRenderer = new THREE.WebGLRenderer() renderer.setSize(window.innerWidth, window.innerHeight) renderer.shadowMap.enabled = true renderer.shadowMap.type = THREE.PCFSoftShadowMap document.body.appendChild(renderer.domElement) const controls = new OrbitControls(camera, renderer.domElement) controls.screenSpacePanning = true const world = new CANNON.World() world.gravity.set(0, -9.82, 0) //world.broadphase = new CANNON.NaiveBroadphase() // //world.solver.iterations = 10 //world.allowSleep = true const normalMaterial: THREE.MeshNormalMaterial = new THREE.MeshNormalMaterial() const phongMaterial: THREE.MeshPhongMaterial = new THREE.MeshPhongMaterial() const cubeGeometry: THREE.BoxGeometry = new THREE.BoxGeometry(1, 1, 1) const cubeMesh: THREE.Mesh = new THREE.Mesh(cubeGeometry, normalMaterial) cubeMesh.position.x = -3 cubeMesh.position.y = 3 cubeMesh.castShadow = true scene.add(cubeMesh) const cubeShape = new CANNON.Box(new CANNON.Vec3(.5, .5, .5)) const cubeBody = new CANNON.Body({ mass: 1 }); cubeBody.addShape(cubeShape) cubeBody.position.x = cubeMesh.position.x cubeBody.position.y = cubeMesh.position.y cubeBody.position.z = cubeMesh.position.z world.addBody(cubeBody) const sphereGeometry: THREE.SphereGeometry = new THREE.SphereGeometry() const sphereMesh: THREE.Mesh = new THREE.Mesh(sphereGeometry, normalMaterial) sphereMesh.position.x = -1 sphereMesh.position.y = 3 sphereMesh.castShadow = true scene.add(sphereMesh) const sphereShape = new CANNON.Sphere(1) const sphereBody = new CANNON.Body({ mass: 1 }); sphereBody.addShape(sphereShape) sphereBody.position.x = sphereMesh.position.x sphereBody.position.y = sphereMesh.position.y sphereBody.position.z = sphereMesh.position.z world.addBody(sphereBody) const icosahedronGeometry: THREE.IcosahedronGeometry = new THREE.IcosahedronGeometry(1, 0) const icosahedronMesh: THREE.Mesh = new THREE.Mesh(icosahedronGeometry, normalMaterial) icosahedronMesh.position.x = 1 icosahedronMesh.position.y = 3 icosahedronMesh.castShadow = true scene.add(icosahedronMesh) const icosahedronPoints = (icosahedronMesh.geometry).vertices.map(function (v) { return new CANNON.Vec3(v.x, v.y, v.z) }) const icosahedronFaces = (icosahedronMesh.geometry).faces.map(function (f) { return [f.a, f.b, f.c] }) const icosahedronShape = new CANNON.ConvexPolyhedron(icosahedronPoints, icosahedronFaces) const icosahedronBody = new CANNON.Body({ mass: 1 }); icosahedronBody.addShape(icosahedronShape) icosahedronBody.position.x = icosahedronMesh.position.x icosahedronBody.position.y = icosahedronMesh.position.y icosahedronBody.position.z = icosahedronMesh.position.z world.addBody(icosahedronBody) const torusKnotGeometry: THREE.TorusKnotGeometry = new THREE.TorusKnotGeometry() const torusKnotMesh: THREE.Mesh = new THREE.Mesh(torusKnotGeometry, normalMaterial) torusKnotMesh.position.x = 4 torusKnotMesh.position.y = 3 torusKnotMesh.castShadow = true scene.add(torusKnotMesh) // const torusKnotPoints = (torusKnotMesh.geometry).vertices.map(function (v) { // return new CANNON.Vec3(v.x, v.y, v.z) // }) // const torusKnotFaces = (torusKnotMesh.geometry).faces.map(function (f) { // return [f.a, f.b, f.c] // }) // const torusKnotShape = new CANNON.ConvexPolyhedron(torusKnotPoints, torusKnotFaces) const torusKnotShape = CreateTrimesh(torusKnotMesh.geometry) const torusKnotBody = new CANNON.Body({ mass: 1 }); torusKnotBody.addShape(torusKnotShape) torusKnotBody.position.x = torusKnotMesh.position.x torusKnotBody.position.y = torusKnotMesh.position.y torusKnotBody.position.z = torusKnotMesh.position.z world.addBody(torusKnotBody) function CreateTrimesh(geometry: THREE.Geometry | THREE.BufferGeometry) { if (!(geometry as THREE.BufferGeometry).attributes) { geometry = new THREE.BufferGeometry().fromGeometry(geometry as THREE.Geometry); } const vertices = (geometry as THREE.BufferGeometry).attributes.position.array const indices = Object.keys(vertices).map(Number); return new CANNON.Trimesh(vertices as [], indices); } const planeGeometry: THREE.PlaneGeometry = new THREE.PlaneGeometry(25, 25) const planeMesh: THREE.Mesh = new THREE.Mesh(planeGeometry, phongMaterial) planeMesh.rotateX(-Math.PI / 2) planeMesh.receiveShadow = true; scene.add(planeMesh) const planeShape = new CANNON.Plane() const planeBody = new CANNON.Body({ mass: 0 }) planeBody.addShape(planeShape) planeBody.quaternion.setFromAxisAngle(new CANNON.Vec3(1, 0, 0), -Math.PI / 2) world.addBody(planeBody) camera.position.y = 4 camera.position.z = 4 controls.target.y = 2 window.addEventListener('resize', onWindowResize, false) function onWindowResize() { camera.aspect = window.innerWidth / window.innerHeight camera.updateProjectionMatrix() renderer.setSize(window.innerWidth, window.innerHeight) render() } const stats = Stats() document.body.appendChild(stats.dom) const gui = new GUI() const physicsFolder = gui.addFolder("Physics") physicsFolder.add(world.gravity, "x", -10.0, 10.0, 0.1) physicsFolder.add(world.gravity, "y", -10.0, 10.0, 0.1) physicsFolder.add(world.gravity, "z", -10.0, 10.0, 0.1) physicsFolder.open() const clock: THREE.Clock = new THREE.Clock() var animate = function () { requestAnimationFrame(animate) controls.update() let delta = clock.getDelta() if (delta > .1) delta = .1 world.step(delta) // Copy coordinates from Cannon.js to Three.js cubeMesh.position.set(cubeBody.position.x, cubeBody.position.y, cubeBody.position.z); cubeMesh.quaternion.set(cubeBody.quaternion.x, cubeBody.quaternion.y, cubeBody.quaternion.z, cubeBody.quaternion.w); sphereMesh.position.set(sphereBody.position.x, sphereBody.position.y, sphereBody.position.z); sphereMesh.quaternion.set(sphereBody.quaternion.x, sphereBody.quaternion.y, sphereBody.quaternion.z, sphereBody.quaternion.w); icosahedronMesh.position.set(icosahedronBody.position.x, icosahedronBody.position.y, icosahedronBody.position.z); icosahedronMesh.quaternion.set(icosahedronBody.quaternion.x, icosahedronBody.quaternion.y, icosahedronBody.quaternion.z, icosahedronBody.quaternion.w); torusKnotMesh.position.set(torusKnotBody.position.x, torusKnotBody.position.y, torusKnotBody.position.z); torusKnotMesh.quaternion.set(torusKnotBody.quaternion.x, torusKnotBody.quaternion.y, torusKnotBody.quaternion.z, torusKnotBody.quaternion.w); render() stats.update() }; function render() { renderer.render(scene, camera) } animate(); ```

Cannon.js GitHub

Cannon.js Parameter Tweaking

International System of Units