The intersectsBox function unexpectedly returns true instead of false

I recently came across a tutorial on MDN that discussed the intersection of bounding boxes. Intrigued, I decided to try out the code snippet provided:

  const testBoxGeometry = new THREE.BoxGeometry(3, 3, 3);
  const testBoxMaterial = new THREE.MeshBasicMaterial({color: 0x00ff00});
  testBox = new THREE.Mesh(testBoxGeometry, testBoxMaterial);
  testBox.geometry.computeBoundingBox();
  testBoundingBox = new THREE.Box3(
    testBox.geometry.boundingBox.min,
    testBox.geometry.boundingBox.max
  );
  testBox.position.set(5, 0, 5);
  scene.add(testBox);

  const cameraBoxGeometry = new THREE.BoxGeometry(3, 3, 3);
  const cameraBoxMaterial = new THREE.MeshBasicMaterial({color: 0x00ff00});
  cameraBox = new THREE.Mesh(cameraBoxGeometry, cameraBoxMaterial);
  cameraBox.geometry.computeBoundingBox();
  cameraBoundingBox = new THREE.Box3(
    cameraBox.geometry.boundingBox.min,
    cameraBox.geometry.boundingBox.max
  );
  scene.add(cameraBox);

However, when I tested for intersection in my animate function:

  if (testBoundingBox.intersectsBox(cameraBoundingBox)) {
    console.log(`intersection`);
  }

I encountered an issue where the green boxes appeared not to intersect, yet the console logged the opposite result. Can anyone offer guidance on what might be going wrong here or suggest ways to debug this situation?

https://i.sstatic.net/W3mZ0.png

EDIT

Following a suggestion by Hectate, I added setFromObject() which resolved the initial problem. However, a new challenge emerged as the first box represents my camera. I aim to create a scenario where the camera, simulating a first-person view, collides with objects in the environment. To achieve this, I have hidden a square within an Object3D() to serve as a collision boundary.

Due to my translation of the player Object3D (for performance reasons), the original position remains unchanged, leading to either constant or absent intersection detection. Any thoughts on how to address this issue?

Here is the code snippet I use to control the player Object3D:

Keypress detection:

switch (e.key) {
case `z`:
  moveForward = true;
  break;
case `s`:
  moveBackward = true;
  break;
case `q`:
  moveLeft = true;
  break;
case `d`:
  moveRight = true;
  break;
}

In the animate function:

if (moveForward) player.translateZ(- .05);
if (moveBackward) player.translateZ(.05);
if (moveLeft) player.translateX(- .05);
if (moveRight) player.translateX(.05);

EDIT 2

Presented here is my full script.js:

import sets from './data/sets';

import ColladaLoader from 'three-collada-loader';

import BufferLoader from './modules/sound/BufferLoader';
import SpawnObject from './modules/render/SpawnObject';
import Controls from './modules/util/Controls';

import io from 'socket.io-client';
import {isEmpty} from 'lodash';

// Other imports...

// Main initialization function and event handlers...

animate();

Answer №1

The linked article contains the following important note:

Note: The boundingBox property is based on the Geometry itself, not the Mesh. This means that any transformations like scale or position applied to the Mesh will not be considered when calculating the box.

Keeping that in mind, I utilized the setFromObject() method to adjust the position of the testBoundingBox, which resulted in the expected/unexpected intersection behavior. Below is the code snippet for reference, along with a demonstration on jsfiddle. Feel free to modify the box position and run it again to observe the intersections.

https://jsfiddle.net/87wg5z27/122/

  const testBoxGeometry = new THREE.BoxGeometry(3, 3, 3);
  const testBoxMaterial = new THREE.MeshBasicMaterial({color: 0x00ff00});
  testBox = new THREE.Mesh(testBoxGeometry, testBoxMaterial);
  testBox.geometry.computeBoundingBox();
  testBoundingBox = new THREE.Box3(
    testBox.geometry.boundingBox.min,
    testBox.geometry.boundingBox.max
  );
  testBox.position.set(5, 0, 5);
  testBoundingBox.setFromObject(testBox); //This line was added
  scene.add(testBox);

  const cameraBoxGeometry = new THREE.BoxGeometry(3, 3, 3);
  const cameraBoxMaterial = new THREE.MeshBasicMaterial({color: 0x00ff00});
  cameraBox = new THREE.Mesh(cameraBoxGeometry, cameraBoxMaterial);
  cameraBox.geometry.computeBoundingBox();
  cameraBoundingBox = new THREE.Box3(
    cameraBox.geometry.boundingBox.min,
    cameraBox.geometry.boundingBox.max
  );
  scene.add(cameraBox);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the method for selecting an element using CSS code in Protractor?

Having trouble clicking on the element with CSS Selector: <button _ngcontent-c16="" class="btn btn-flat btn-no-text btn-kebab-view"> <i _ngcontent-c16="" class="zmdi zmdi-more-vert"></i> </button> This is what I've t ...

The setState function in React.js fails to properly assign data

Recently, I've been using axios.get() to retrieve data from my database. The response is coming back correctly, but for some reason, when I attempt to update the state with this data, nothing seems to change. import React, { Component, useState, useE ...

Updating and deleting Firebase data from an HTML table: A guide

I am struggling to make the onClick function work in order to update and delete already retrieved data from an HTML table view. Despite trying different approaches, I can't seem to get it right. var rootRef = firebase.database().ref().child("prod ...

How to implement various middlewares in Express.js depending on the current environment using NODE_ENV?

My dilemma involves utilizing two different middlewares based on NODE_ENV: router1 for production and router2 for testing and development environments. I'm currently using the following code snippet: if( process.env.NODE_ENV === 'prod' ) { ...

Updating variable storage in React components

This is a project built with Next.js and React. Below is the folder structure: components > Navbar.js pages > index.js (/ route)(includes Navbar) > submitCollection.js (/submitCollection)(includes Navbar) The goal is to allow users to inpu ...

Discover the process of connecting a REST controller with AngularJS and Spring

I have a list of file paths stored in an array within the scope variable of an AngularJS Controller. My goal is to properly map these file paths to a Java REST controller for further processing. When I pass it as "/ABC/Scope-Variable," it successfully ma ...

Displaying information based on selection in AngularJSIn this tutorial

I am a beginner in Angularjs and currently working on developing a website. One of the tasks I have is to create a combo box that, when an option is selected, calls a method to load values into a Scope variable and update it. Below is the code I have so fa ...

Discover the best method for sending multiple API requests to Vuex store using Nuxt middleware

I am having trouble figuring out how to make multiple API calls to Vuex store from Nuxt middleware. I have successfully implemented it for a single API call, but I can't seem to get it working for multiple APIs. // middleware/log.js import axios fro ...

Updating the load context variable in Django template after making changes via an AJAX call: a step-by-step guide

Here is the code snippet for displaying table items in my customer_items.html page: <table id="tblData" style="width: 100% !important;" class="display table table-bordered table-striped table-condensed"> <thead> <tr> ...

Guide on dynamically displaying a page based on the response from express/mssql middleware

I have developed a full stack application that includes a registration feature which successfully adds data to the database. Now, I am looking for a way to conditionally display the home page based on whether the login credentials are correct. Within my l ...

What is the process for implementing token authentication within headers using an interceptor, especially when the token may be null?

In my Angular13 application with OAuth authentication, I am encountering issues when trying to add the token for all services. I have been unsuccessful in managing the undefined token. Despite trying various techniques to retrieve the token, I always enco ...

Error encountered: Difficulty rendering Vue 3 components within Google Apps Script

Currently delving into Vue and Vue 3 while coding an application on Google Apps Script. Following tutorials from Vue Mastery and stumbled upon a remarkable example by @brucemcpherson of a Vue 2 app functioning on GAS, which proved to be too challenging in ...

Error: Please provide the required client_id when setting up Google Sign-In with Next-Auth

I have been trying to implement the Sign in with Google option in my Next.js application using next-auth. Below is a snippet of my [...nextauth].js file located in the api/auth folder: import NextAuth from "next-auth"; import Google ...

Troubleshooting: Issue with incorporating libraries into my HTML code using Ionic framework and Angular

I am currently working on developing a hybrid app using Ionic and Angular. I attempted to incorporate jQuery UI for drag-and-drop functionality, but unfortunately, it did not work as expected. Despite testing simple examples, the feature still did not func ...

Unable to interact with options in a dropdown menu while utilizing selenium

As a newcomer to the world of web scraping with Python using Selenium, I am trying to extract information on tennis players from the website "https://www.itftennis.com/en/players/". The challenge I am facing is related to navigating a drop-down list of res ...

Insert half a million records into a database table using JavaScript seamlessly without causing the webpage to crash

I am facing an issue with my report system where running a single report query results in over 500,000 rows being returned. The process of retrieving the data via AJAX takes some time, but the real problem arises when the browser freezes while adding the H ...

Hidden Password Field Option in HTML

My HTML password textbox has the input type set as password, but I can still see what is being typed. This shouldn't happen as password inputs should be masked. Can someone please advise me on how to resolve this issue? To replicate, copy the code be ...

Establishing the default selection and deactivating the notification

I've been struggling for a while to make this function properly. My knowledge of jquery and javascript is limited, so I'm facing some challenges. What I'm aiming to do is to have a default option selected from the drop-down menu when the but ...

The element type 'x' in JSX does not offer any construct or call signatures

I have recently imported an image and I am trying to use it within a function. The imported image is as follows: import Edit from 'src/assets/setting/advertising/edit.png'; This is the function in question: function getOptions(row) { ...