Rotate and Scale About a Point
Rotating and Enlarging Relative to a Centre
The following two code snippets let you place a centre of rotation or enlargement, or pivot, at any time and have a mesh rotate or enlarge relative to that centre.
Rotate
import { Axis } from "@babylonjs/core/Maths/math.axis";import { Quaternion, Vector3 } from "@babylonjs/core/Maths/math.vector";import { Mesh } from "@babylonjs/core/Meshes/mesh";Mesh.prototype.rotateAroundPivot = function (pivotPoint, axis, angle) { if (!this._rotationQuaternion) { this._rq = Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z); } else this._rq = this.rotationQuaternion; var _p = new Quaternion(this.position.x - pivotPoint.x, this.position.y - pivotPoint.y, this.position.z - pivotPoint.z, 0); axis.normalize(); var _q = Quaternion.RotationAxis(axis, angle); //form quaternion rotation var _qinv = Quaternion.Inverse(_q); var _pdash = _q.multiply(_p).multiply(_qinv); this.position = new Vector3(pivotPoint.x + _pdash.x, pivotPoint.y + _pdash.y, pivotPoint.z + _pdash.z); this.rotationQuaternion = _q.multiply(this._rq);};mesh.rotateAroundPivot(new Vector3(1, 2, -1), new Axis.Y, Math.PI / 4);The parameters are the position of the pivot (centre of rotation) as a Vector3, the axis of rotation as a Vector3, and the angle of rotation as a number in radians.
Successive rotations are cumulative.
Enlargement
import { Vector3 } from "@babylonjs/core/Maths/math.vector";import { Mesh } from "@babylonjs/core/Meshes/mesh";Mesh.prototype.scaleFromPivot = function(pivotPoint, sx, sy, sz) { var _sx = sx / this.scaling.x; var _sy = sy / this.scaling.y; var _sz = sz / this.scaling.z; this.scaling = new Vector3(sx, sy, sz); this.position = new Vector3(pivotPoint.x + _sx * (this.position.x - pivotPoint.x), pivotPoint.y + _sy * (this.position.y - pivotPoint.y), pivotPoint.z + _sz * (this.position.z - pivotPoint.z));}
mesh.scaleFromPivotnew Vector3(1, 2, -1), 2, 6, 0.5);The parameters are the position of the pivot (centre of enlargement) as a Vector3, and the scaling in the x, y, and z directions as numbers.