I'm currently working on developing a straightforward app that allows me to move a cube either to the left or right. The movement part has been successfully implemented, and now I am faced with the challenge of ensuring that the cube stays within the bounds of the plane. What would be the most efficient way to achieve this?
Here is the code snippet that I have been working on:
<html>
<head>
<title>Time Car</title>
<style>
body {
width: 100%;
height: 100%;
margin: 0;
padding 0;
}
</style>
</head>
<body>
<script src="js/three.min.js"></script>
<script src="js/Detector.js"></script>
<script>
var scene, camera, renderer, object, raycaster, board1, board2, board3, board4;
var vy = 0,
vx = 0,
direction = "",
gravity = 0.3;
function init() {
if (!Detector.webgl) Detector.addGetWebGLMessage();
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
renderer = new THREE.WebGLRenderer({
antialias: true
});
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor(0xCCFFFF);
document.body.appendChild(renderer.domElement);
var light = new THREE.DirectionalLight(0xffffff, 2);
light.position.set(1, 1, 1).normalize();
scene.add(light);
var light = new THREE.DirectionalLight(0xffffff);
light.position.set(-1, -1, -1).normalize();
scene.add(light);
var geometry = new THREE.BoxGeometry(20, 10, 10);
object = new THREE.Mesh(geometry, new THREE.MeshLambertMaterial({
color: 0x3333FF
}));
scene.add(object);
var geometry = new THREE.PlaneGeometry(5000, 800, 800);
var plane = new THREE.Mesh(geometry, new THREE.MeshLambertMaterial({
color: 0x99FF66
}));
plane.rotation.x = -Math.PI / 2;
plane.position.set(0, -20, 0);
scene.add(plane);
camera.position.set(0, 100, 100);
raycaster = new THREE.Raycaster();
raycaster.ray.direction.set(0, -1, 0);
render();
}
function render() {
requestAnimationFrame(render);
if (direction == "left") {
vx = -2;
}
if (direction == "right") {
vx = 2;
}
object.position.x += vx;
vx = vx * 0.95;
camera.lookAt(object.position);
camera.position.x += (((object.position.x - 20) - camera.position.x)) * 0.03;
camera.position.y += (((object.position.y + 50) - camera.position.y));
renderer.render(scene, camera);
}
window.addEventListener('keydown', function (e) {
switch (e.keyCode) {
case 65: //left
direction = "left";
break;
break;
case 68: //right
direction = "right";
break;
};
}, false);
window.addEventListener('keyup', function (e) {
switch (e.keyCode) {
case 65: //left
direction = "";
break;
case 68: //right
direction = "";
break;
};
}, false);
init();
</script>
</body>
</html>