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>
<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
/////////// ideas for what dad72 wants to do
var cache = {};
document.getElementById("attachToModel").onclick = function() {
cache.position = customCameraParent.position.clone();
cache.rotation = customCameraParent.rotation.clone();
cache.scaling = customCameraParent.scaling.clone();
var pvm = customCameraParent.getPivotMatrix();
cache.pivotMatrix = pvm ? pvm.clone() : BABYLON.Matrix.Identity();
cache.parent = customCameraParent.parent;
var parentWorldMatrix = customCameraParent.parent ? customCameraParent.parent.getWorldMatrix() : BABYLON.Matrix.Identity();
var invModelWorldMatrix = model.getWorldMatrix().clone();
invModelWorldMatrix.invert();
var customCameraSpaceToModelSpace = parentWorldMatrix.multiply(invModelWorldMatrix);
var positionInModelSpace = BABYLON.Vector3.TransformCoordinates(customCameraParent.position, customCameraSpaceToModelSpace);
var scalingInModelSpace = BABYLON.Vector3.TransformNormal(customCameraParent.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);
customCameraParent.setPivotMatrix(pivotMatrix);
customCameraParent.position = BABYLON.Vector3.Zero();
customCameraParent.rotation = BABYLON.Vector3.Zero();
customCameraParent.scaling = new BABYLON.Vector3(1, 1, 1);
customCameraParent.parent = model;
};
document.getElementById("rotate").onclick = function() {
customCameraParent.rotation.z += Math.PI / 8;
};
document.getElementById("reset").onclick = function() {
customCameraParent.position = cache.position;
customCameraParent.rotation =...