Detecting collisions with varying dimensions in Three.js

I have successfully created a collision detection system that allows users to place objects at the raycaster/mouse position on a floor. By clicking on the 'Add object' button, a helper object is generated to follow the mouse and check for collisions with existing objects. When the user clicks on their desired position, the new object will only be placed if there are no collisions.

My collision detection system works perfectly when both objects in question are of the same size.

In the accompanying screenshot, you can see a large object and a small (red) helper. The red color indicates a collision, which then turns green when the mouse is moved to the right.

However, I am facing an issue where my collision detection system only works when two objects are of equal size. How can I make it work with objects of different sizes?

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

Below is the code snippet for displaying the big object upon a click event:

var geometry = new THREE.BoxGeometry(200, 200, 300);
var bigobject = new THREE.Mesh(geometry, new THREE.MeshBasicMaterial({
    color: 0xFBF5D7,
    opacity: 1
}));
bigobject.position.copy(intersects[0].point);
bigobject.position.y = 100;
objects.push(bigobject);
scene.add(bigobject);

Here is the code snippet for showing the helper when the 'Add object' button is clicked:

var geometry = new THREE.BoxGeometry(50, 50, 100 );
helper = new THREE.Mesh(geometry, new THREE.MeshBasicMaterial({ color: 0x00ff00, opacity: 1 }));
helper.name = 'helper';
scene.add(helper);

And here is the code snippet for detecting collisions in the MouseMove event:

if(scene.getObjectByName('helper')) {
    helper.position.copy(intersects[0].point);
    helper.position.y = 25;

    var helperWidth = helper.geometry.parameters.width;
    var helperLength = helper.geometry.parameters.depth;

    var validpositionObject = true;
    for (var i = 0; i < objects.length; i++) {

        var objectWidth = objects[i].geometry.parameters.width;
        var objectLength = objects[i].geometry.parameters.depth;

        // Checking for collision
        ...

    }

    if (validpositionObject === true) {
        helper.material.color.setHex(0x00ff00);
        validposition = true;
    } else {
        helper.material.color.setHex(0xff0000);
        validposition = false;
    }

}

I am struggling with the placement of objects when they have varying sizes. Any help or guidance would be greatly appreciated. Thank you.

Answer №1

Here is a custom collision detection function written in JavaScript:

function checkCollision(obj1, obj2) {
  if (Math.abs(obj1.position.x - obj2.position.x) > (obj1.geometry.parameters.width + obj2.geometry.parameters.width) / 2)
    return false;
  if (Math.abs(obj1.position.z - obj2.position.z) > (obj1.geometry.parameters.depth + obj2.geometry.parameters.depth) / 2)
    return false;
  return true;
}

var isValidPosition = true;
for (var j = 0; j < allObjects.length; j++) {
  if (checkCollision(helperObject, allObjects[j])) {
    isValidPosition = false;
    break;
  }
}

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

Selecting a unique element at random from an array in Javascript

I want the function to randomly select elements from the array without repetition function RandomSelect() { let names = ["Yazeed", "Ammar", "Marwan", "Othman", "Sameh", "Amro", "Ibraheem"]; let paragraph = document.getElementById("demo1"); l ...

Analyzing and inserting elements into an array of objects

The following code aims to: 1) iterate through the two arrays, 2) if an item exists in both arrays, add its value to the value of the matching item in the first array, 3) if the item is found in arr2 but not in arr1, add the item to arr1. The code funct ...

Steps to disable fancybox for a specific selector

I am facing an issue with unbinding fancybox associated with anchor links having a specific class. Here is an example: <a class="group">some code here</a> To bind fancybox to elements with the class 'group', I use the following code ...

Enhancing Communication between Sibling Components in Angular 2

I have a ListComponent where clicking on an item should display its details in DetailComponent without any routing involved. Both components are displayed simultaneously on the screen. How can I pass the information of the clicked item from ListComponent ...

Guide on deleting a record in a Mysql database using Codeigniter(3) without the need to refresh the page

I'm currently trying to delete a record from a MySQL database table using jQuery with Codeigniter(3). Despite it being a simple task, I am facing some challenges as I am new to both Codeigniter and jQuery. This is a section of the view where I need t ...

Code is not running in ReactJS

My challenge is to use canvas and script to draw a rectangle with one diagonal line. However, when I try to do so, only the rectangle appears on my browser. It seems like the script is not being executed. Here's the code: import React, { Component } ...

Preventing duplication of code execution in recycled PHP elements

Currently, I have implemented a generic toolbar that is used on multiple pages of my web application by using PHP include. This toolbar contains log in/log out functionality and checks the log in status upon loading to update its UI accordingly. Initially ...

Different Angular 2 components are resolved by routes

Consider this scenario: Upon navigating to the URL /product/123, the goal is to display the ProductComponent. This is how it's currently configured: RouterModule.forRoot([ { path: 'product/:productId', ...

Struggling with generating forms using AJAX, Javascript, and HTML depending on the selection made from a drop-down menu

I am in need of a simple web form for work submissions within my organization. These submissions will fit into 4 Categories, each requiring unique information. Currently, I have a basic form set up with fields such as Requested Name, Requested Date, Acquis ...

The distinction between using document.getElementById and document.getElementsByClassName in JavaScript

One thing that stands out is why does document.getElementsById function as expected here <div id="move">add padding</div> <button type="button" onclick="movefun()">pad</button> <script> function movefun() { document.get ...

Direct your attention to the cursor problem in Internet Explorer

Here is a snippet of code that automatically changes background images: function changeBackground() { currentBackground++; if(currentBackground > 3) currentBackground = 0; $('body').fadeOut(0, function() { $('body&ap ...

Is it possible for invoking a web service recursively in JavaScript to lead to a stack overflow issue

I am currently working on a migration procedure that may last between 2 to 3 days to complete. My concern is that the implementation I have in place could potentially result in a StackOverflow exception due to its recursive nature. I am questioning wheth ...

What is the most efficient way to modify the variables for numerous images within a JavaScript canvas?

I'm a newcomer to using Javascript in a canvas, and coding with javascript overall. My primary goal is the following: Create numerous fireballs (images) that spawn randomly with each having a fixed y-value and random x-value. The fireballs should t ...

Javascript variable decrement failure

One of the challenges I am facing is with a button in HTML that is set by AJAX to create a new tr element. I have successfully built a function (code provided below) to add it, but now I want to include a counter to keep track of how many rows I have. The ...

React and Rails are not playing nice when it comes to AJAX POST requests - all

I'm currently facing an issue while setting up this AJAX POST request in my react component to interact with my rails api controller. The browser console shows a 404 error and I am unable to trigger the pry debugger. react/src/pages/HomeIndex.js ge ...

Activate the fadetoggle function to smoothly transition and fade in

Is there a way to implement jQuery fading in when an element becomes visible? Check out this code snippet for reference: http://jsfiddle.net/IntelandBacon/nWscz/ $('.expand').click(function () { $(this).next().css("visibility", "visible"); ...

Steps for triggering a click event on a div with a button role within a class containing multiple elements

Can anyone help me figure out how to auto-click every button in Instagram's "hide story from" settings using console? I tried the following code: for (let i = 0; i < 300; i++) { document.getElementsByClassName('wbloks_1')[i] ...

Looking to detect and notify the presence of duplicate values within an array

I am encountering an issue where I can view an array in the console, but cannot check if it contains duplicate values. $('.tab2field').each(function () { PackageName.push($('.span2', this).val() ); PackageCount.push($(&apo ...

Utilizing eval properly in JavaScript

One method I am using is to load a different audio file by clicking on different texts within a web page. The jQuery function I have implemented for this purpose is as follows: var audio = document.createElement('audio'); $(".text_sample ...

Instructions for importing a CSV file into PostgreSQL with Node.js

Just dipping my toes into the world of node js. I've got a csv file sitting on my local system that I'm eager to upload to my local PostgreSQL Database using node js. Here's what I've been experimenting with: var csv = require(' ...