Tips for identifying collisions involving boxes in motion

I referenced an article on MDN for detecting collision between boxes and tested it out on this JSFiddle.

My goal is to move the red box and have the logs stop appearing once they are no longer colliding. However, I'm struggling with updating the Box3 (the bounding box of my box) to match the new position of the main box.

Currently, I am moving the box using keyboard keys like this:

checking if key is pressed

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

in my animate function:

if (moveForward) redBox.position.z -= .05;
if (moveBackward) redBox.position.z += .05;
if (moveLeft) redBox.position.x -= .05;
if (moveRight) redBox.position.x += .05;

I thought updating the Box3 position would be a simple solution, but it seems adding the Box3 to my scene is restricted... So I'm unsure how to proceed with updating it.

var scene, renderer, camera;
var redBox, blueBox, redBbox, blueBbox;
var controls;

init();
animate();

function init()
{
renderer = new THREE.WebGLRenderer( {antialias:true} );
var width = window.innerWidth;
var height = window.innerHeight;
renderer.setSize (width, height);
document.body.appendChild (renderer.domElement);

scene = new THREE.Scene();

camera = new THREE.PerspectiveCamera (45, width/height, 1, 10000);
camera.position.y = 50;
camera.position.z = 50;
camera.position.x = 50;
camera.lookAt (new THREE.Vector3(0,0,0));

  controls = new THREE.OrbitControls (camera, renderer.domElement);
  
  redBox = new THREE.Mesh(
    new THREE.BoxGeometry(3, 3, 3),
    new THREE.MeshBasicMaterial({color: 0xff00000})//RED box
  );
  redBox.position.set(3, 3, 3);
  redBbox = new THREE.Box3(new THREE.Vector3(), new THREE.Vector3());
  redBbox.setFromObject(redBox);
  const redBoxHelper = new THREE.BoxHelper(redBox, 0xFFFFFF);

  scene.add(redBox, redBoxHelper);

  blueBox = new THREE.Mesh(
    new THREE.BoxGeometry(3, 2, 5),
    new THREE.MeshBasicMaterial({color: 0x00000ff})//BLUE box
  );
  blueBox.position.set(3, 3, 3);
  blueBbox = new THREE.Box3(new THREE.Vector3(), new THREE.Vector3());
  blueBbox.setFromObject(blueBox);
  const blueBoxHelper = new THREE.BoxHelper(blueBox, 0xFFFFFF);

  scene.add(blueBox, blueBoxHelper);

window.addEventListener ('resize', onWindowResize, false);
}

function onWindowResize ()
{
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize (window.innerWidth, window.innerHeight);
}

function animate()
{
//controls.update();
  requestAnimationFrame ( animate );
  
  if(redBbox.intersectsBox(blueBbox)){
  console.log('intersection');
  }
  
renderer.render (scene, camera);
}
<script src="//cdnjs.cloudflare.com/ajax/libs/three.js/r83/three.min.js"></script>
<script src="https://dl.dropboxusercontent.com/u/3587259/Code/Threejs/OrbitControls.js">
</script>

Answer №1

Following the example in the MDN article, make sure to incorporate the following two lines within your animate() function before you proceed with the intersection check:

  greenBbox.setFromObject(greenBox);
  yellowBbox.setFromObject(yellowBox);

Check out this JSFiddle for a visual representation.

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

JavaScript Asynchronous Functions Not Handling Await Calls Correctly

The two fadeInList functions control the fading animation of a continuous list split into two lines. The typeOutText function displays text and is supposed to execute List1 first, wait for it to finish, and then proceed with List2. However, after adding ke ...

Ldap.js: exploring nested searches

My current task involves using ldapjs to conduct a search where the filter is dependent on the outcome of a preceding search. ldapClient.search(base1, opts1, (err1, res1) => { res1.on("searchEntry", entry => { const myObj = { attr1: entr ...

Working with JSON data and extracting specific information within the grades

Here is a JSON data structure that contains information about a student named Alice and her grades in various courses: { "student": [{ "cert_id": "59826ffeaa6-b986fc04d9de", "batch_id": "b3d68a-402a-b205-6888934d9", "name": "Alice", "pro ...

Forgetting variable after utilizing jQuery ajax in php

I am facing an issue with PHP not retaining variables when I use jQuery ajax. Can you provide me with guidance on how to ensure that it remembers its variables? Attached at the bottom of this message are the code files. Firstly, question.php sends a quest ...

Retrieving all options from a dropdown list in HTML using ASP.net C#

I am currently working with a select list that looks like this: <select name="Section" id="Section" size="5"> <option>Section1</option> <option>Section2</option> <option>Section3</option> <option>Section4< ...

Sorting through a table based on the name of the element

I am currently working on filtering an HTML table using a search form. It's working great, but I'm facing an issue where the filtered elements are trying to fill the entire width of the table instead of maintaining their original width (which is ...

Experiencing issues with retrieving undefined values from a JavaScript object

Attempting to access a specific property value from a JavaScript object, I have written the following code: for (key in map.regions) { console.log(key); console.log(states); console.log(states.key); } The key variable will contain something l ...

attempting to utilize jQuery to call a controller method, but encountering an issue where the method is failing to

In one of my pages, called "GetData.cshtml", I have a requirement to input data into some textboxes and send it to a controller method using jQuery. Here is the code snippet: //GetData.cshtml $(document).ready(function () { $('#btn_sbmt_recommenda ...

What is the best approach to implement a basic image upload functionality?

I have a vision for my new website where users can upload an image with the click of a button, store it locally on one page and then retrieve its absolute URL to share on forums or other websites for preview purposes. While I've managed to create a fu ...

Issue with Angular: event.key doesn't register as shft+tab when pressing Shift+Tab key

Our website features a dropdown menu that can be opened and closed by clicking, revealing a list of li items. However, we are currently experiencing an issue with keyboard focus navigation. When the Tab key is pressed, the focus properly moves from one li ...

Align a div in the center when an anchor link is clicked

Is there a way to create an anchor link that not only scrolls down to a specific div on the page, but also centers it on the screen rather than positioning it at the top? While I have been able to achieve a similar effect by using absolute positioning in ...

"Unleashing the Power of Effortless Object Unwr

Looking for a better way to convert a raw json snapshot from Firebase into a JS class. My current method is lengthy and inefficient. Does anyone have a more optimal solution? Class: class SuggestedLocation { country_slug region_slug slug marker_ty ...

If the option of "none" is chosen, I would like to deactivate all checkbox selections

Struggling with disabling all checkboxes in a PHP form when the NONE option is selected. <h5>HEALTH OF STUDENT</h5> <p>Any physical, emotional, or other difficulties to be aware of?</p> <table> <td>Hearing ...

Customizing ArrowDownwardIcon within MuiTableCell in Mui v5

I am attempting to modify the default color of the ArrowDownIcon within a TableCell using global theming in the following manner: MuiTableSortLabel: { styleOverrides: { root: { '&&.MuiTableSortLabel-icon': { ...

What is the best way to eliminate query parameters in NextJS?

My URL is too long with multiple queries, such as /projects/1/&category=Branding&title=Mobile+App&about=Lorem+ipsum+Lorem+. I just want to simplify it to /projects/1/mobile-app. I've been struggling to fix this for a week. While I found so ...

Styling Input elements with a unified border in Bootstrap

[Issue Resolved] I have been working on setting a single border between multiple inputs inside a form-group in Bootstrap. Currently, the border is only visible when the input is not focused and it is the last one. However, my expectation is for the bo ...

Struggling with error management while using react-redux during the SignUp process

https://i.sstatic.net/OD2fl.pngWithin my component code, I handle user sign up and error checking. Initially, the error value is null. let error = useSelector((state) => state.authReducer.error); const checkErrorLoading = () => { ...

Unable to locate the _app.js file within my Next.js project

After using "npx create-next-app" to set up my NextJs project, I came across a situation where I needed to define TransactionContext in _app.js. However, I encountered the issue that this file is not included in my project. Any assistance would be greatly ...

React Js: Data not being properly updated in the application state

Presenting App.js - import './App.css'; import { connect } from 'react-redux' import { ActionChangeName } from "./Actions/Action"; function App(props) { return ( <div className="App"> <div> ...

Leveraging React Native to position a view absolutely in the center of the screen without obstructing any other components

How can I center an image inside a view in the middle of the screen using position: "absolute"? The issue is that the view takes up 100% of the width and height of the screen, causing all components underneath it (such as input fields and buttons ...