awacke1/HTML5-BabylonJS-Javascript-3DAnimation
4
1<!DOCTYPE html>2<html>3<head>4 <meta charset="utf-8" />5 <title>Babylon.js Game Example</title>6 <script src="https://cdn.babylonjs.com/babylon.js"></script>7 <script src="https://cdn.babylonjs.com/loaders/babylonjs.loaders.min.js"></script>8 <style>9 canvas {10 width: 100%;11 height: 100%;12 touch-action: none;13 }14 </style>15</head>16<body>17 <canvas id="renderCanvas"></canvas>18 <script>19 window.addEventListener('DOMContentLoaded', function () {20 var canvas = document.getElementById('renderCanvas');21 var engine = new BABYLON.Engine(canvas, true);22 23 var createScene = function () {24 var scene = new BABYLON.Scene(engine);25 26 // Create a camera27 var camera = new BABYLON.ArcRotateCamera("Camera", 0, 0, 10, BABYLON.Vector3.Zero(), scene);28 29 // Create a light30 var light = new BABYLON.HemisphericLight("light1", new BABYLON.Vector3(0, 1, 0), scene);31 32 // Create an array to hold the spheres33 var spheres = [];34 35 // Create a fountain of spheres that follow the mouse36 canvas.addEventListener('mousemove', function (event) {37 // Create a new sphere38 var sphere = BABYLON.MeshBuilder.CreateSphere("sphere", {diameter: Math.random() * 2 + 0.5}, scene);39 sphere.position = new BABYLON.Vector3(Math.random() * 4 - 2, Math.random() * 4 - 2, Math.random() * 4 - 2);40 spheres.push(sphere);41 42 // Follow the mouse with the spheres43 var ray = scene.createPickingRay(event.clientX, event.clientY, BABYLON.Matrix.Identity(), camera);44 var pickInfo = scene.pickWithRay(ray, function (mesh) { return mesh == sphere; });45 if (pickInfo.hit) {46 sphere.position.copyFrom(pickInfo.pickedPoint);47 }48 49 // Animate the spheres50 var animation = new BABYLON.Animation("myAnimation", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);51 var keys = [];52 keys.push({frame: 0, value: sphere.position.y});53 keys.push({frame: 50, value: sphere.position.y + 2});54 keys.push({frame: 100, value: sphere.position.y});55 animation.setKeys(keys);56 sphere.animations.push(animation);57 scene.beginAnimation(sphere, 0, 100, true);58 });59 60 return scene;61 }62 63 var scene = createScene();64 65 engine.runRenderLoop(function () {66 scene.render();67 });68 69 window.addEventListener('resize', function () {70 engine.resize();71 });72 });73 </script>74</body>75</html>76 