Raycasting and Hover Effect

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!

New contributor

jamfury is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật