Hello to everyone who’s reading!
I’m building a website in THREE.js where you can scroll through “cards” that are seen isometrically, and I’m currently adding an animation when hovering each card (which is just an array of Box Geometries).
The problem is that I’m animating the camera to move in the z axis to scroll through the array of boxes, but I think that since the raycasting works from the camera origin, when the objects get past the camera in the 3D space, but are still seen in the viewport, the intersection check doesn’t work anymore, this happens when the boxes are in the lower-left corner of the screen.
Since I don’t know what could be the problem I’ll post the whole code:
import { TextureLoader } from 'three';
import './style.css'
import * as THREE from 'three'
import gsap from 'gsap';
// Set up the scene
const canvas = document.querySelector('.webgl');
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xffffff); // Set background color to white
// Axis helper
const axesHelper = new THREE.AxesHelper(10);
scene.add(axesHelper);
// Create box geometry
const boxGeometry = new THREE.BoxGeometry(1, 1, 0.01);
// Create box material
const boxMaterial = new THREE.MeshStandardMaterial({
transparent: true,
opacity: 1,
});
// Box array
let currentlyHoveredBox = null;
function createBox(texture, positionZ) {
const aspect = texture.image.width / texture.image.height;
const boxGeometry = new THREE.BoxGeometry(1 * aspect, 1, 0.02);
const boxMaterial = new THREE.MeshStandardMaterial({
map: texture,
transparent: true,
opacity: 0.9
});
texture.colorSpace = THREE.SRGBColorSpace;
const box = new THREE.Mesh(boxGeometry, boxMaterial);
box.position.set(0, 0, -positionZ);
scene.add(box);
// Hover effect
const hoverGeometry = new THREE.BoxGeometry(1.2 * aspect, 1.2, 0.1);
const hoverMesh = new THREE.Mesh(hoverGeometry, new THREE.MeshBasicMaterial({ visible: false }));
hoverMesh.position.copy(box.position);
scene.add(hoverMesh);
box.userData.hoverMesh = hoverMesh;
box.userData.hover = {
enter: () => {
if (currentlyHoveredBox !== box) {
if (currentlyHoveredBox) {
currentlyHoveredBox.userData.hover.leave();
}
currentlyHoveredBox = box;
gsap.to(box.position, {
y: 0.2,
duration: 0.3,
ease: "power2.out"
});
}
},
leave: () => {
if (currentlyHoveredBox === box) {
currentlyHoveredBox = null;
gsap.to(box.position, {
y: 0,
duration: 0.3,
ease: "power2.out"
});
}
}
};
}
// Handle hover
function handleHover() {
const intersects = raycaster.intersectObjects(scene.children.filter(child => child.userData.hoverMesh));
if (intersects.length > 0) {
const hoveredBox = intersects[0].object;
console.log('Hover detected:', hoveredBox);
hoveredBox.userData.hover.enter();
} else if (currentlyHoveredBox) {
console.log('Hover ended');
currentlyHoveredBox.userData.hover.leave();
}
}
// Set up raycaster and mouse
const raycaster = new THREE.Raycaster();
const mouse = new THREE.Vector2();
// Add event listeners
window.addEventListener('mousemove', (event) => {
mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
raycaster.setFromCamera(mouse, camera);
handleHover();
});
// Add new images to the scene
const loader = new THREE.TextureLoader();
const imageUrls = [
'proj/1.png',
'proj/2.jpg',
'proj/3.jpg',
];
imageUrls.forEach((url, index) => {
loader.load(url, (texture) => {
createBox(texture, index * 1.5);
});
});
function addNewImage(url) {
loader.load(url, (texture) => {
createBox(texture, imageUrls.length * 1.5);
imageUrls.push(url); // Add the URL to the collection
});
}
// Add ambient light to the scene
const ambientLight = new THREE.AmbientLight(0xffffff, 2); // Soft white light
scene.add(ambientLight);
// Set up the renderer
const renderer = new THREE.WebGLRenderer({canvas: canvas, antialias: true});
renderer.setSize(window.innerWidth, window.innerHeight);
// Set up the camera
const zoom = 700; // Adjust this value to control the zoom
const sizes = {
width: window.innerWidth,
height: window.innerHeight
}; // Declares sizes value as window sizes
const aspect = window.innerWidth / window.innerHeight; // Set aspect ratio to the window's
const camera = new THREE.OrthographicCamera(
-sizes.width / zoom,
sizes.width / zoom,
sizes.height / zoom,
-sizes.height / zoom,
-100,
1000
);
// Scroll animation
window.addEventListener('wheel', onMouseWheel, {passive: false});
function onMouseWheel(event) {
const scrollSpeed = 0.1;
const targetZ = camera.position.z + event.deltaY * scrollSpeed;
gsap.to(camera.position, {
z: targetZ,
duration: 0.6,
ease: "power2.out",
onUpdate: () => {
camera.updateProjectionMatrix();
}
});
}
// Camera controls
camera.position.x = 0;
camera.position.y = 0;
camera.position.z = 0;
camera.rotation.order = 'YXZ';
camera.rotation.y = 0.5;
camera.rotation.x = - 0.4;
// Update camera aspect ratio and renderer size when the window is resized
window.addEventListener('resize', () => {
// Update sizes
sizes.width = window.innerWidth;
sizes.height = window.innerHeight;
// Update camera
camera.left = -sizes.width / zoom;
camera.right = sizes.width / zoom;
camera.top = sizes.height / zoom;
camera.bottom = -sizes.height / zoom;
camera.updateProjectionMatrix();
// Update renderer
renderer.setSize(sizes.width, sizes.height);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
});
// Update raycaster
function updateRaycaster() {
const cameraZPosition = Math.abs(camera.position.z);
raycaster.far = cameraZPosition + 10; // Adjust the value as needed
}
// Animate the hover
function updateHover() {
raycaster.setFromCamera(mouse, camera);
handleHover();
requestAnimationFrame(updateHover);
}
updateHover();
// Animate the scene
function animate() {
requestAnimationFrame(animate);
updateRaycaster();
raycaster.setFromCamera(mouse, camera);
handleHover();
renderer.render(scene, camera);
}
requestAnimationFrame(animate);
I’m thinking of adding a bounding box to the whole array, but that’s going to be difficult, because I’ve to update the bounding box size dynamically with the number of boxes and I’m kinda hitting a block here, so I think having the camera move is a better way to handle this, but I’m open to new ways of doing this.
Thank you in advance to anyone who takes the time to help!
jamfury is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.