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>
<div id="rootDiv">
<canvas id="renderCanvas"></canvas>
<canvas id="canvas_2D"></canvas>
</div>
CSS
html, body, div, canvas {
width: 100%;
height: 100%;
padding: 0;
margin: 0;
overflow: hidden;
}
button {
height: 30px;
}
#canvas_2D {
position: absolute;
top: 30px;
pointer-events: none;
}
JavaScript
var cache = {};
document.getElementById("attachToModel").onclick = function() {
cache.position = customCamera.position.clone();
cache.rotation = customCamera.rotation.clone();
cache.scaling = customCamera.scaling.clone();
var pvm = customCamera.getPivotMatrix();
cache.pivotMatrix = pvm ? pvm.clone() : BABYLON.Matrix.Identity();
cache.parent = customCamera.parent;
var parentWorldMatrix = customCamera.parent ? customCamera.parent.getWorldMatrix() : BABYLON.Matrix.Identity();
var invModelWorldMatrix = model.getWorldMatrix().clone();
invModelWorldMatrix.invert();
var customCameraSpaceToModelSpace = parentWorldMatrix.multiply(invModelWorldMatrix);
var positionInModelSpace = BABYLON.Vector3.TransformCoordinates(customCamera.position, customCameraSpaceToModelSpace);
//var rotationInModelSpace = BABYLON.Vector3.TransformNormal(customCamera.rotation, customCameraSpaceToModelSpace);
var scalingInModelSpace = BABYLON.Vector3.TransformNormal(customCamera.scaling, customCameraSpaceToModelSpace);
var scalingM = BABYLON.Matrix.Scaling(scalingInModelSpace.x, scalingInModelSpace.y, scalingInModelSpace.z);
//var rotationM = BABYLON.Matrix.RotationYawPitchRoll(rotationInModelSpace.y, rotationInModelSpace.x, rotationInModelSpace.z);
var positionM = BABYLON.Matrix.Translation(positionInModelSpace.x, positionInModelSpace.y, positionInModelSpace.z);
var pivotMatrix = scalingM/*.multiply(rotationM)*/.multiply(positionM); // no rotation to look at the model
customCamera.setPivotMatrix(pivotMatrix);
customCamera.position = BABYLON.Vector3.Zero();
customCamera.rotation = BABYLON.Vector3.Zero();
customCamera.scaling = new BABYLON.Vector3(1, 1, 1);
customCamera.parent = model;
};
document.getElementById("rotate").onclick = function() {
customCamera.rotation.z += Math.PI / 8;
};
document.getElementById("reset").onclick = function() {
customCamera.position =...