Problem with detecting collisions in Three.js

Currently, I am developing a simple game where players can add objects (cubes) to the scene at the position of a raycaster (mouse) click on a large ground plane. To prevent cubes from overlapping with each other, I have implemented basic collision detection. While I acknowledge that this may not be the most efficient method, it aligns with my current understanding as a beginner.

In the code snippet below, I check the positions of both the new object and existing objects. By calculating the distance between them, if it is less than 4096 (64*64), the new cube is added to the scene.

function onDocumentMouseDown( event ) {
    // Event handling logic here
}

One of the limitations I have encountered is that the current implementation only works effectively for square objects. Can anyone assist me in adapting this logic to accommodate rectangle objects like THREE.BoxGeometry( 64, 64, 400)?

Answer №1

A while ago, I created a modern version of the classic frogger game from C64. The main goal was to ensure that my frog didn't collide with any cars on the road.

var img1_x1 = parseInt(idImg.style.left);
var img1_x2 = img1_x1 + idImg.width - 1;
var img1_y1 = parseInt(idImg.style.top);
var img1_y2 = img1_y1 + idImg.height - 1;

img2_x1 = parseInt(idImg2.style.left);
img2_x2 = img2_x1 + idImg2.width - 1;
img2_y1 = parseInt(idImg2.style.top);
img2_y2 = img2_y1 + idImg2.height - 1;

if (((img2_x1 <= img1_x2 && img1_x2 <= img2_x2) || (img2_x1 <= img1_x1 && img1_x1 <= img2_x2) || (img1_x1 <= img2_x1 && img2_x1 <= img1_x2)) 
    && ((img2_y1 <= img1_y2 && img1_y2 <= img2_y2) || (img2_y1 <= img1_y1 && img1_y1 <= img2_y2) || (img1_y1 <= img2_y1 && img2_y1 <= img1_y2)))
{
    alert('boom');
}

Take a look at my code, it might have some useful insights for you. I start by determining the position of my frog (img1) and then iterate through all test objects using a for loop (here not shown). Within this loop, I calculate the position of the object (img2) and perform collision detection.
In your case, you would need to add a third dimension to the conditions which wasn't necessary for me.

Note: For img2, I declare the variable outside the for-loop within the function.

I've only included excerpts from my code here, removing any confusing parts.

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

Set the minimum date for the jQuery datepicker

Having trouble with jQuery datepickers for selecting from and to dates? Currently, the code restricts the selection in the second datepicker to dates after the one selected in the first datepicker. However, what if you need to set the to datepicker to allo ...

What steps can be taken to execute a function when a button remains unclicked?

$("#RunCode").click(function(){ var $this = $(this); if($this.data('clicked')) { console.log("Is clicked"); $(".documentWrite").text("Is clicked"); } else { $this.data('clicked', true); consol ...

I encountered an issue while attempting to establish a connection to an API using WebSocket. Specifically, I received an error message stating: "Uncaught ReferenceError

Guide on Installing the API from GitHub; const WebSocket = require("ws"); const DerivAPI = require("@deriv/deriv-api/dist/DerivAPI"); // Use your own app_id instead of 1089 for testing // Register your own app at api.deriv.com to get a ...

What is preventing me from displaying my paragraph?

I have some content that I want to show a paragraph with the class paragraphtoggle when clicked, but it's not working as expected. Here is what I have tried: https://example.com/jsfiddle HTML <div class="enzimskiprogramindex herbaprogramindex he ...

Utilize Server Side Includes in your JavaScript code

When the query string is parsed, a specific section of code SSI is included in the footer page. Here are some examples of query strings: ?headId=520&genderType=2 ?headId=600&genderType=1 function GetQueryStringParams(sParam){ var sPageURL ...

Creating a Star Rating System Using HTML and CSS

Looking for help with implementing a Star rating Feedback on articles in Visualforce page. Came across some code that seems to fit the bill but facing issues with getting it to work when placed in a file and executed, particularly in Firefox. Any assistanc ...

The persistentFilter in the Tabulator is failing to verify for the headerFilterEmptyCheck

Using Tabulator version 4.4.3 When filtering the checkbox in the usual way, everything works fine. If I set a filtered checkbox to true on a column, it functions correctly: headerFilterEmptyCheck: function (value) { return !value; }, Howev ...

Leveraging Vuetify on a standalone .html document

I am currently working on a personal project where I am experimenting with avoiding a full npm build process. Instead, I am trying to work within a single .html file that utilizes Vue 3 and Vuetify. Below is the complete HTML code which can be simply dropp ...

filtering an array based on a specific property will result in the original array remaining

Working on filtering an array of objects based on a certain property using the following code snippet: if (payment == Payment.CREDIT_CARD) { this.currenies.filter((currency: Currency) => currency.isFromEurope === true); console.log(this.currencies) ...

Learn how to run a Linux bash command by clicking a button, where the command is generated from user input

HTML: I am presenting two inputs here <input id="range3" type="range" min="0" max="255" value="0" /> <input id="num3" min="0" max="255&q ...

Creating three functions with the same name, one with a callback, another with a promise, and the third with async/await, can

I am looking to create a versatile function that can be used in 3 different ways to handle npm dependencies Using Promises Using callbacks Using async/await For Instance 1) Using async/await var mongoose = require('mongoose'); async fu ...

What is the best way to track and display the window.scrollY value in the console using Next.js

Unfortunately, my ScrollToTop component is not functioning correctly within my app. I have exhausted all possible debugging methods but am still unable to determine why the scrollY value is not being logged as expected. Even after moving the snippet to a ...

Determine the class name of an element when it is clicked on

For various reasons, I am unable to use $('.class').click or on('click', function..) Therefore, I must utilize the onclick="" event from the html element. Is there a way to determine the class of the element where the onclick event oc ...

Executing a background.js function in response to an event trigger within the active tab in a Chrome extension

I am facing an issue where I am getting an error saying "resetTime is not defined" when running the code below. I have tried passing the function as an argument, but that did not solve the problem. Do I need to come up with a new logic to reset the time ...

Utilize inline scripts within the views of Yii2 for enhanced functionality

I stumbled upon a jQuery code online that allows for the integration of Google Maps, and I'm looking to implement it in my application to ensure accurate address retrieval. You can find the jQuery code here. Currently, I am working with yii2 Advanced ...

Maintaining active navigation state in JQuery/JavaScript after clicking a link: tips and tricks

While many resources discuss adding the active class to a nav link using jquery, there is less information on maintaining the active state after the nav link has been clicked. After experimenting with code from various sources, I have attempted to set ses ...

Learn how to increase a value with each dynamically clicked button in JavaScript

Whenever I try to increment the value by clicking the like button, it seems to be increasing but not in sync with the actual button count. How can I fix this issue? index.html <div class="row"> <div class="col-md-4"> ...

What is the best way to create a selection input using buttons and save the chosen option in the state?

Check out this snippet showcasing 3 buttons const [role, setRole] = React.useState('') const [active, setActive] = React.useState(false) <Grid container spacing={1}> <Grid item xs={4}> <Button variant='plain&apos ...

Create a function to produce a list of dates within two specified date ranges using JavaScript

Looking for assistance as a beginner in JavaScript. Can anyone guide me on how to generate a list of dates between dateA and dateB? For instance: dateA = 07/01/2013 dateB = 07/01/2014 Desired outcome: 07/01/2013, 07/02/2013, 07/03/2013, 07/04/2013...a ...

Performing CRUD operations with mongoose and express

My express app is currently being developed with mongoose, and the goal is to integrate it with React for the front end. In my customer controller, I have outlined some CRUD operations, but there are aspects of this approach that I find unsatisfactory. W ...