How to use the MathUtils function from three

Find comprehensive JavaScript three.MathUtils code examples handpicked from public code repositorys.

three.MathUtils provides various math-related utility functions for use in Three.js.

4319
4320
4321
4322
4323
4324
4325
4326
4327

      if (this.scrollPositionY > this.scrollMaxOffsetY) {
        this.scrollPositionY = Three.MathUtils.lerp(this.scrollPositionY, this.scrollMaxOffsetY, this.scrollTween);
      }

      this.position[this.axisY] = Three.MathUtils.lerp(this.position[this.axisY], this.scrollPositionY, this.scrollTween);
    }
  });
}
fork icon8
star icon20
watch icon0

+ 97 other calls in file

436
437
438
439
440
441
442
443
444
445
446
Object3D.deepCopy = function (object3D) {
  const cloneJSON = object3D.toJSON(true);
  // Rename uuid
  Data.objectParse(cloneJSON, function (json, key) {
    const keyLowerCase = key.toLowerCase();
    if (keyLowerCase === 'uuid') json[key] = THREE.MathUtils.generateUUID();


    if (keyLowerCase === 'name') {
      json[key] = 'Clone of ' + json[key];
    }
fork icon15
star icon10
watch icon9

+ 21 other calls in file

How does three.MathUtils work?

three.MathUtils is a utility library that provides mathematical functions and constants commonly used in 3D graphics programming. It contains methods for common operations such as clamping values, converting between degrees and radians, and generating random numbers.

136
137
138
139
140
141
142
143
144
145
146
 * @memberof StringComposer
 * @param {string} largeString - a string with a size superior at {@link StringComposer.MAX_STRING_SIZE}
 * @returns {PartialString[]} - an array containing all the {@link PartialString}
 */
StringComposer.splitString = function (largeString) {
  const stringUUID = THREE.MathUtils.generateUUID();
  const result = [];


  // Cut in several partial message
  while (largeString.length > StringComposer.MAX_STRING_SIZE) {
fork icon15
star icon10
watch icon9

+ 10 other calls in file

26
27
28
29
30
31
32
33
34
const srcArray = attribute.isInterleavedBufferAttribute ? attribute.data.array : attribute.array;
const dstArray = new Float32Array( attribute.getCount() * attribute.itemSize );

for ( let i = 0, j = 0; i < attribute.getCount(); i ++ ) {

    dstArray[ j ++ ] = THREE.MathUtils.denormalize( attribute.getX( i ), srcArray );
    dstArray[ j ++ ] = THREE.MathUtils.denormalize( attribute.getY( i ), srcArray );

    if ( attribute.itemSize > 2 ) {
fork icon2
star icon10
watch icon0

+ 5 other calls in file

Ai Example

1
2
3
4
5
6
7
8
// Import MathUtils from three.js
import { MathUtils } from "three";

// Convert 45 degrees to radians
const degrees = 45;
const radians = MathUtils.degToRad(degrees);

console.log(radians); // Output: 0.7853981633974483

In the above example, we import the MathUtils object from three.js library and use its degToRad method to convert an angle in degrees to radians. The degToRad method accepts an angle in degrees and returns the equivalent angle in radians.

15
16
17
18
19
20
21
22
23
24
function getAttributeArray(attribute) {
    if (attribute.normalized || attribute.isInterleavedBufferAttribute) {
        const srcArray = attribute.isInterleavedBufferAttribute ? attribute.data.array : attribute.array;
        const dstArray = new Float32Array(attribute.getCount() * attribute.itemSize);
        for (let i = 0, j = 0; i < attribute.getCount(); i++) {
            dstArray[j++] = three_1.MathUtils.denormalize(attribute.getX(i), srcArray);
            dstArray[j++] = three_1.MathUtils.denormalize(attribute.getY(i), srcArray);
            if (attribute.itemSize > 2) {
                dstArray[j++] = three_1.MathUtils.denormalize(attribute.getZ(i), srcArray);
            }
fork icon1
star icon3
watch icon0

+ 5 other calls in file

402
403
404
405
406
407
408
409
410
411
for (let subrayIndex = 0; subrayIndex < this.numSubrays; subrayIndex++) {
    const subray = this.subrays[subrayIndex];
    this.currentSubray = subray;
    this.randomGenerator.setSeed(subray.seed);
    subray.endPropagationTime = three_1.MathUtils.lerp(subray.birthTime, subray.deathTime, subray.propagationTimeFactor);
    subray.beginVanishingTime = three_1.MathUtils.lerp(subray.deathTime, subray.birthTime, 1 - subray.vanishingTimeFactor);
    const random1 = this.randomGenerator.random;
    subray.linPos0.set(random1(), random1(), random1()).multiplyScalar(1000);
    subray.linPos1.set(random1(), random1(), random1()).multiplyScalar(1000);
    this.timeFraction = (time - subray.birthTime) / (subray.deathTime - subray.birthTime);
fork icon1
star icon3
watch icon0

+ 5 other calls in file

232
233
234
235
236
237
238
239
240
241
        sample.x = Math.random() * 2 - 1;
        sample.y = Math.random() * 2 - 1;
        sample.z = Math.random();
        sample.normalize();
        let scale = i / kernelSize;
        scale = three_1.MathUtils.lerp(0.1, 1, scale * scale);
        sample.multiplyScalar(scale);
        kernel.push(sample);
    }
}
fork icon1
star icon3
watch icon0

+ 5 other calls in file

349
350
351
352
353
354
355
356
357
358
}
this._v3_1.setFromMatrixPosition(this._cameraMatrixState);
const x = this._v3_1.distanceTo(this._gizmos.position);
let xNew = x / size; //distance between camera and gizmos if scale(size, scalepoint) would be performed
//check min and max distance
xNew = three_1.MathUtils.clamp(xNew, this.minDistance, this.maxDistance);
const y = x * Math.tan(three_1.MathUtils.DEG2RAD * this.camera.fov * 0.5);
//calculate new fov
let newFov = three_1.MathUtils.RAD2DEG * (Math.atan(y / xNew) * 2);
//check min and max fov
fork icon1
star icon3
watch icon0

+ 31 other calls in file

167
168
169
170
171
172
173
174
175
176
    water.rotation.x = -Math.PI / 2;
    this.water = water;
    this.scene.add(water);
};
OceanFactory.prototype.updateSun = function (elevation, azimuth) {
    var phi = THREE.MathUtils.degToRad(90 - elevation);
    var theta = THREE.MathUtils.degToRad(azimuth);
    var sun = new THREE.Vector3();
    sun.setFromSphericalCoords(1, phi, theta);
    this.sky.material.uniforms['sunPosition'].value.copy(sun);
fork icon0
star icon3
watch icon1

+ 27 other calls in file

184
185
186
187
188
189
190
191
192
193
    this.water = water;
    this.scene.add(water);
};
BasicOceanFactory.prototype.updateSun = function (elevation, azimuth) {
    var phi = THREE.MathUtils.degToRad(90 - elevation);
    var theta = THREE.MathUtils.degToRad(azimuth);
    var sun = new THREE.Vector3();
    sun.setFromSphericalCoords(1, phi, theta);
    this.sky.material.uniforms['sunPosition'].value.copy(sun);
    if (this.water) {
fork icon0
star icon3
watch icon1

+ 25 other calls in file

68
69
70
71
72
73
74
75
76
77
	}

	await loader.load(buffer, this.#parent, color);

	//Base rotation of 90deg because THREE.js handles xyz axes different to other programs
	var rad = THREE.MathUtils.degToRad(90);
	this.#parent.rotateX(rad);

	this.#positionCamera(padding);
}
fork icon0
star icon3
watch icon0

+ 5 other calls in file

244
245
246
247
248
249
250
251
252
  this.updateMatrixWorld(true);
  this.camera.position.copy(cameraPosition);
  this.target.worldToLocal(this.camera.position);
  var range = this.camera.position.length();
  this.target.rotation.x = Math.asin(this.camera.position.z / range);
  var cosPlanXY = THREE.MathUtils.clamp(this.camera.position.y / (Math.cos(this.target.rotation.x) * range), -1, 1);
  this.target.rotation.z = Math.sign(-this.camera.position.x || 1) * Math.acos(cosPlanXY);
  this.camera.position.set(0, range, 0);
} // set from target's coordinate, rotation and range between target and camera
fork icon0
star icon1
watch icon1

+ 43 other calls in file

45
46
47
48
49
50
51
52
53
54
}, {
  key: "geodeticSurfaceNormalCartographic",
  value: function geodeticSurfaceNormalCartographic(coordCarto) {
    var target = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : new THREE.Vector3();
    var longitude = THREE.MathUtils.degToRad(coordCarto.longitude);
    var latitude = THREE.MathUtils.degToRad(coordCarto.latitude);
    var cosLatitude = Math.cos(latitude);
    return target.set(cosLatitude * Math.cos(longitude), cosLatitude * Math.sin(longitude), Math.sin(latitude));
  }
}, {
fork icon0
star icon1
watch icon1

+ 13 other calls in file

1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
key: "getScaleFromDistance",
value: function getScaleFromDistance() {
  var pitch = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0.28;
  var distance = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
  pitch /= 1000;
  var fov = THREE.MathUtils.degToRad(this.camera.camera3D.fov);
  var unit = this.camera.height / (2 * distance * Math.tan(fov * 0.5));
  return pitch * unit;
}
/**
fork icon0
star icon1
watch icon0

615
616
617
618
619
620
621
622
623
dir.copy(pointUnderCursor).sub(this.camera.position);
dir.z = 0;
dir.normalize();
var distanceToPoint = this.camera.position.distanceTo(pointUnderCursor); // camera height (altitude above ground) at the end of the travel, 5000 is an empirical smoothing distance

var targetHeight = THREE.MathUtils.lerp(this.smartTravelHeightMin, this.smartTravelHeightMax, Math.min(distanceToPoint / 5000, 1)); // camera position at the end of the travel

var moveTarget = new THREE.Vector3();
moveTarget.copy(pointUnderCursor);
fork icon0
star icon1
watch icon0

532
533
534
535
536
537
538
539
540
    var contraryPhi = -Math.asin((contraryLimit - minDistanceZ) * 0.25 / spherical.radius); // clamp contraryPhi to make a less brutal exit

    contraryPhi = THREE.MathUtils.clamp(contraryPhi, minContraintPhi, 0); // the deeper the camera is in this zone, the bigger the factor is

    var contraryFactor = 1 - (contraryLimit - minDistanceZ) / (2 * contraryLimit);
    sphericalDelta.phi = THREE.MathUtils.lerp(sphericalDelta.phi, contraryPhi, contraryFactor);
    minDistanceZ -= Math.sin(sphericalDelta.phi) * spherical.radius;
  }
}
fork icon0
star icon1
watch icon0

+ 9 other calls in file

66
67
68
69
70
71
72
73
74
75
const controls = new OrbitControls_1.OrbitControls(camera, renderer.domElement);
function addStar() {
    const geometry = new THREE.SphereGeometry(0.25, 24, 24);
    const material = new THREE.MeshStandardMaterial({ color: 0xffffff });
    const star = new THREE.Mesh(geometry, material);
    const [x, y, z] = Array(3).fill(50).map(() => THREE.MathUtils.randFloatSpread(100));
    star.position.set(x, y, z);
    scene.add(star);
}
Array(200).fill(50).forEach(addStar);
fork icon0
star icon0
watch icon0

+ 4 other calls in file

236
237
238
239
240
241
242
243
244
245

console.log(currentVector.y);


// plane.rotation.set(currentVector.x,currentVector.y,currentVector.z);
// plane.rotation.x = THREE.MathUtils.radToDeg(-currentVector.x);
// plane.rotation.y = THREE.MathUtils.radToDeg(-currentVector.y);
// plane.rotation.z = THREE.MathUtils.radToDeg(-currentVector.z);

// plane.rotateX(currentVector.x);
fork icon0
star icon0
watch icon0

+ 5 other calls in file

Other functions in three

Sorted by popularity

function icon

three.Vector3 is the most popular function in three (22341 examples)