I need help detecting collisions between my dynamic cards and the screen boundaries.
Currently, when the cards go out of view, I want them to bounce back upon hitting the screen edge.
How can I identify these collisions in my code?
As of now, the cards move across the screen and rotate, but they disappear once reaching the border.
I can adjust the speed for negative direction movement, but need assistance with collision detection.
Below is the snippet of my implementation:
const camera = new THREE.PerspectiveCamera( 75, screenWidth / screenHeight, 0.1, 1000 );
const renderer = new THREE.WebGLRenderer();
const renderCard = async (card) => {
const cardFile = `./src/assets/img/${card.asset}`
const geometry = new THREE.BoxGeometry(1, 1.5, 0);
const texture = await new Promise((resolve) => {
const loader = new THREE.TextureLoader();
loader.load(cardFile, (texture) => {
resolve(texture);
});
});
const material = new THREE.MeshBasicMaterial({
map: texture
});
return new THREE.Mesh(geometry, material);
};
async function prepareScene() {
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
camera.position.z = 5;
}
function getCardPosition(card, position = 'x') {
if (!card.model.speed) {
card.model.speed = {};
card.model.speed['x'] = 0.05;
card.model.speed['y'] = 0.05;
}
return card.model['position'][position] + (card.model.speed[position]);
}
async function animate() {
cards = await Promise.all(cards.map(async card => {
if (!card.speed) {
card.speed = {
x: 0.01,
y: 0.01
}
}
if (!card.model) {
const box = new THREE.Box3();
card.model = await renderCard(card);
card.model.geometry.computeBoundingBox();
card.box = box;
scene.add(card.model);
}
card.model.position.x = getCardPosition(card, 'x');
card.model.position.y = getCardPosition(card, 'y');
card.box.copy(card.model.geometry.boundingBox).applyMatrix4(card.model.matrixWorld);
card.model.rotation.x += 0.01;
card.model.rotation.y += 0.01;
return card;
}
));
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
window.onload = async () => {
await prepareScene();
await animate();
};