Attach camera

by gwenaelhagenmuller

HTML

<script src="https://rawgithub.com/BabylonJS/Babylon.js/v1.8.0/babylon.1.8.0.js"></script>
<button id="rotate">Rotate custom camera</button>
<button id="attachToModel">Attach custom camera to model</button>
<button id="reset">Reset</button>
<button id="toggle">Toggle active camera</button>
<canvas id="renderCanvas"></canvas>

CSS

html, body, div, canvas {
    width: 100%;
    height: 100%;
    padding: 0;
    margin: 0;
    overflow: hidden;
}

JavaScript

BABYLON.Camera.prototype.RotateAround = function(target) {
    
    if (!this.parent) // for now, I have to use a dumb parent to easily modify the transform of the camera
        return;
    
    if (!target && this.cache) {
        
        this.parent.position = this.cache.position;
        this.parent.rotation = this.cache.rotation;
        this.parent.scaling = this.cache.scaling;
        this.parent.setPivotMatrix(this.cache.pivotMatrix);
        this.parent.parent = this.cache.parent;
        
        delete this.cache;
        return;
        
    }
    
    if (this.cache) {
        this.RotateAround(null);
    }
    
    this.cache = {};
    
    this.cache.position = this.parent.position.clone();
    this.cache.rotation = this.parent.rotation.clone();
    this.cache.scaling = this.parent.scaling.clone();
    var pvm = this.parent.getPivotMatrix();
    this.cache.pivotMatrix = pvm ? pvm.clone() : BABYLON.Matrix.Identity();
    this.cache.parent = this.parent.parent;
    
    var parentWorldMatrix = this.parent.parent ? this.parent.parent.getWorldMatrix() : BABYLON.Matrix.Identity();
    var invModelWorldMatrix = target.getWorldMatrix().clone();
    invModelWorldMatrix.invert();
    var customCameraSpaceToModelSpace = parentWorldMatrix.multiply(invModelWorldMatrix);
    
    var positionInModelSpace = BABYLON.Vector3.TransformCoordinates(this.parent.position, customCameraSpaceToModelSpace);
    var scalingInModelSpace = BABYLON.Vector3.TransformNormal(this.parent.scaling, customCameraSpaceToModelSpace);
    
    var scalingM = BABYLON.Matrix.Scaling(scalingInModelSpace.x, scalingInModelSpace.y, scalingInModelSpace.z);
    var rotationM = BABYLON.Matrix.RotationYawPitchRoll(-Math.PI/2, 0, 0); // look at the model
    var positionM = BABYLON.Matrix.Translation(positionInModelSpace.x, positionInModelSpace.y, positionInModelSpace.z);
    
    var pivotMatrix = scalingM.multiply(rotationM).multiply(positionM); 
    
   ...