Currently, I am developing a simple breakout/arkanoid game using threeJS. The game features a paddle and a bouncing ball on the screen. My main focus right now is to make the collision detection work correctly so that when the ball hits the paddle, it bounces away. I have been attempting to use bounding boxes for this purpose, but I am facing an issue where the .intersect/.intersectsBox methods are not detecting the collision as expected. Below is the code snippet that I have been working on -
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
const geometry = new THREE.BoxGeometry(5, 1, 1);
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
const cube = new THREE.Mesh(geometry, material);
var cubeBoxHelper = new THREE.BoxHelper(cube, 0xff0000);
var boundingBoxPaddle = new THREE.Box3().setFromObject(cubeBoxHelper);
cubeBoxHelper.update();
const geometrySphere = new THREE.SphereGeometry(1, 32, 32);
const materialSphere = new THREE.MeshBasicMaterial({ color: 0xffff00 });
const sphere = new THREE.Mesh(geometrySphere, materialSphere);
var sphereBoxHelper = new THREE.BoxHelper(sphere, 0xff0000);
var boundingBoxBall = new THREE.Box3().setFromObject(sphereBoxHelper);
sphereBoxHelper.update();
scene.add(cube, cubeBoxHelper, sphere, sphereBoxHelper);
sphere.position.y = 5;
camera.position.z = 15;
camera.position.y = 10;
var xSpeed = 0.0005;
var dx = 0.1;
var dy = 0.1;
function bounce()
{
if (sphere.position.x < -19 || sphere.position.x > 18.5)
{
dx = -dx;
}
if (sphere.position.y < -5 || sphere.position.y > 19)
{
dy = -dy;
}
sphere.position.x += dx;
sphere.position.y += dy;
sphereBoxHelper.update();
}
function intersect()
{
if (boundingBoxBall.intersect(boundingBoxPaddle) == true)
{
console.log("Intersection Detected");
}
}
const animate = function ()
{
requestAnimationFrame(animate);
document.addEventListener("keydown", onDocumentKeyDown, false);
function onDocumentKeyDown(event)
{
var keyCode = event.which;
if (keyCode == 65 && cube.position.x >= -18.5)
{
cube.position.x -= xSpeed;
}
else if (keyCode == 68 && cube.position.x <= 18)
{
cube.position.x += xSpeed;
}
cubeBoxHelper.update();
};
bounce();
intersect();
sphereBoxHelper.update();
renderer.render(scene, camera);
};
animate();
Currently, the intersect function simply logs to the console for debugging purposes. Any assistance on resolving this issue would be greatly appreciated as I am unsure of where the problem lies.