Skip to content

Instantly share code, notes, and snippets.

@tkojitu
Last active August 29, 2015 13:56
Show Gist options
  • Save tkojitu/8949675 to your computer and use it in GitHub Desktop.
Save tkojitu/8949675 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="../libs/three.js"></script>
<script src="bouncing-ball-3d.js"></script>
<style>
body{
margin: 0;
overflow: hidden;
}
</style>
</head>
<body onload="onLoad()">
<div id="canvas3d"></div>
</body>
</html>
function onLoad() {
var scene;
var renderer;
var camera;
var ball;
var dx = 0.2;
var dz = 0.2;
function setupScene() {
scene = newScene();
renderer = newRenderer();
camera = newCamera(scene.position);
var canvas = document.getElementById("canvas3d");
canvas.appendChild(renderer.domElement);
}
function newScene() {
var scene = new THREE.Scene();
var plane = newPlane();
scene.add(plane);
ball = newBall();
scene.add(ball);
var spotLight = newLight();
scene.add(spotLight);
return scene;
}
function newRenderer() {
var renderer = new THREE.WebGLRenderer();
renderer.setClearColorHex(0xEEEEEE, 1.0);
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMapEnabled = true;
return renderer;
}
function newPlane() {
var size = getPlaneSize();
var planeGeometry = new THREE.PlaneGeometry(size.width, size.height, 1, 1);
var planeMaterial = new THREE.MeshLambertMaterial({color: 0xffffff});
var plane = new THREE.Mesh(planeGeometry, planeMaterial);
plane.receiveShadow = true;
plane.rotation.x = -0.5 * Math.PI;
plane.position.x = 0;
plane.position.y = 0;
plane.position.z = 0;
return plane;
}
function getPlaneSize() {
return {
width: 60
,height: 20
};
}
function newBall() {
var geo = new THREE.SphereGeometry(1, 20, 20);
var mat = new THREE.MeshLambertMaterial({color: 0x7777ff});
var ball = new THREE.Mesh(geo, mat);
ball.position.x = 0;
ball.position.y = 2;
ball.position.z = 0;
ball.castShadow = true;
return ball;
}
function newLight() {
var spotLight = new THREE.SpotLight(0xffffff);
spotLight.position.set(-40, 60, -10);
spotLight.castShadow = true;
return spotLight;
}
function newCamera(lookAt) {
var camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.x = -30;
camera.position.y = 40;
camera.position.z = 30;
camera.lookAt(lookAt);
return camera;
}
function render() {
window.requestAnimationFrame(render);
renderer.render(scene, camera);
moveBall();
}
function moveBall() {
var size = getPlaneSize();
if (ball.position.x < size.width / -2.0
|| size.width / 2.0 < ball.position.x) {
dx = -dx;
}
if (ball.position.z < size.height / -2.0
|| size.height / 2.0 < ball.position.z) {
dz = -dz;
}
ball.position.x += dx;
ball.position.z += dz;
}
setupScene();
render();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment