Overlapping Divs and Colliding Elements

I am currently exploring the moment when my two yellow divs will overlap and make contact with each other. It seems that the collision detection is triggering true even when the divs are not intersecting.

If you'd like to take a look at the example, check out this link.

    var degree = 0;
var degreeSmall = 0;
var timer=30;
var $spin = $(".gear");
var $spinSmall = $(".gear-small");
var to;
var toSmall;

function detectCollision($div1, $div2) {
  var x1 = $div1.offset().left;
  var y1 = $div1.offset().top;
  var h1 = $div1.outerHeight(true);
  var w1 = $div1.outerWidth(true);
  var b1 = y1 + h1;
  var r1 = x1 + w1;
  var x2 = $div2.offset().left;
  var y2 = $div2.offset().top;
  var h2 = $div2.outerHeight(true);
  var w2 = $div2.outerWidth(true);
  var b2 = y2 + h2;
  var r2 = x2 + w2;

  if (b1 < y2 || y1 > b2 || r1 < x2 || x1 > r2) return false;
  return true;
}

$( document ).ready(function() {

    rotate();
});


function rotate() {
    degree++;
    $spin.css({ 'WebkitTransform': 'rotate(' + degree + 'deg)'});  
    $spin.css({ '-moz-transform': 'rotate(' + degree + 'deg)'});

    to = setTimeout(function() {
        rotate();
    }, timer);

    $('#result').text(detectCollision($('.gear .inner-gear.yellow'), $('.gear-small .inner-gear.yellow')));

}

Thank you.

Answer №1

Revision: Check out the updated demonstration below where both gears are shown rotating with polygon detection based on your request for dual gear rotation.

Initial Gear Rotation: I have modified your JSFiddle to function as per my understanding of your requirements here. The collision detection now displays "true" 25% of the time, which aligns with your expectations. However, I noticed some discrepancies in the calculation of your boxes. It seems necessary to exclude borders, so I adjusted the code to account for this by subtracting them from x1, y1, x2, and y2. Additionally, for border exclusion, employing innerWidth/innerHeight rather than outerWidth/outerHeight is more appropriate.

It is crucial to ensure that your rectangles do not encompass an extra pixel merely from adding the width or height. For instance, consider this line of 3 characters with positions:
0 1 2
a b c

The first character 'a' (x1) is located at position 0. The width is 3, yet 0+3 = 3, when character 'c' (r1) should correctly be positioned at 2. This inclusion of the additional pixel leads to erroneous left corner collision detection, making it seem like a collision occurs much sooner than it actually does. By subtracting 1 as demonstrated in the code below, this issue can be rectified:

function collision($div1, $div2) {
  var x1 = $div1.offset().left + parseInt($div1.css('borderLeftWidth'),10);
  var y1 = $div1.offset().top + parseInt($div1.css('borderTopWidth'),10);
  var h1 = $div1.innerHeight();
  var w1 = $div1.innerWidth();
  var b1 = y1 + h1 - 1;
  var r1 = x1 + w1 - 1;
  var x2 = $div2.offset().left + parseInt($div2.css('borderLeftWidth'),10);
  var y2 = $div2.offset().top + parseInt($div2.css('borderTopWidth'),10);
  var h2 = $div2.innerHeight();
  var w2 = $div2.innerWidth();
  var b2 = y2 + h2 - 1;
  var r2 = x2 + w2 - 1;

  return (r1 >= x2 && r2 >= x1 && b1 >= y2 && b2 >= y1);
}

Dual Gear Rotation: To achieve simultaneous rotation of both gears, comprehensive polygon detection is essential, considering the sides of polygons formed by the rotated corners. I have introduced corner divs to highlight yellow areas, incorporated go/stop/step buttons for debugging purposes, and made other divs translucent to enhance visibility. Reference the updated implementation JSFiddle here. Both gears exhibit rotation similar to your secondary example, displaying accurate collision detection results. The algorithm for polygon collision was sourced from a StackOverflow query.

Answer №2

The code provided for testing the intersection of axis-aligned bounding boxes seems to be correct. However, if you are encountering issues, it may be due to incorrect box coordinates being checked. While I won't make the corrections for you, I can guide you on how to troubleshoot this effectively:

One suggestion is to include a semitransparent overlay:

<div id="bb" style="background:rgba(0,0,0,0.5); position:absolute;"></div>

This will allow you to visually compare the elements:

$('#bb').offset({left:x1,top:y1}).width(w1).height(y1);

You can find an updated JSFiddle here.

Answer №3

Check out this demonstration:

To remove the border and make a width change, replace 49% with 50%

View demo

Alternatively, consider this solution

Modify the width & height to use calc(50% - 1px) instead of 49%, and adjust top & left positions from 149px to 148px

View demo

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

Utilizing CSS to position elements on a webpage

Currently, I am immersed in a CSS and HTML project aimed at honing my skills. The main challenge I face involves positioning a Google Maps image to the right of a paragraph. Despite several attempts, I have been unable to achieve the desired layout. Can an ...

Tips for creating a more condensed materialized table with form elements

Currently, I am working on a timesheet table using Materialize CSS with form elements in cells. However, I find the height of the table rows to be too large for my liking. Is there any way to make the table more compact? If this is a limitation of Materi ...

What is the best way to target the nth-child() of a slotted element within a web component that utilizes multiple uniquely named slots?

I am struggling to select the second slotted item in a specific slot using slot[name=foo]::slotted(:nth-child(2)){, but it's not behaving as I anticipated. Even though the first foo slot is styled with green, the second one doesn't follow suit. ...

qunit timer reset

I have developed a user interface for manually launching qunit tests. However, I have noticed that the qunit test timer starts when displaying the interface, rather than when starting the actual test. For example: var myFunction = function (){ test ...

Enhancing the performance of your code by optimizing it using jQuery when a checkbox is either checked or

Looking for ways to optimize a jquery function that toggles a URL parameter based on checkbox status. Any suggestions on how to streamline this code? $('#mapControl').live('click', function(){ var thisUrl = $(location).attr(' ...

What is the best way to ensure my hover caption spans the entire size of the image?

I'm currently working on creating a hover caption that adjusts itself to fit the full width and height of an image even when it is resized. I attempted to implement a jQuery solution that I came across, but unfortunately, I am struggling to get it to ...

What steps are involved in establishing client-side AJAX polling?

I need some assistance with my app's functionality regarding Delayed::Jobs. Time to reach out for expert advice! My application generates Delayed::Jobs and I want to show users a visual indication of the job status as they progress. Let's assume ...

Steps for setting up an info window on a Google map with multiple markers

I'm having trouble getting the infowindow to pop up on the multiple custom markers I added using AJAX on Google Maps. Everything was working fine before I tried implementing the infowindow and adding the listenMarker() function. The icons were in the ...

Sort your Laravel pagination table effortlessly with just one click

Here is my current setup: <table class="table table-striped"> <tr> <th> Item Image </th> <th> Item Number </th> <th> Item Name </th> <th> Description </th> ...

Top method for individually choosing multiple selections from a foreach loop output

Need help with a loop: foreach ($userItems_get as $item => $value) { if ($value['prefab'] == 'wearable') { echo $value['name'] . "</br>"; echo "<img src=\"{$value['image_invent ...

Mastering the art of seamless navigation within a single page through the magic of

I have two HTML pages: "Login.html" and "index.html". Instead of a normal href linking, I want the user to navigate to "index.html" when they click on the login button. Furthermore, I want the index page to be displayed within the codes of login.html, cre ...

What is the best way to activate a function to control animation transitions?

My goal is to manually control transitions in my HTML using JavaScript code, such as a tween library like TweenMax. Instead of relying on CSS for transitions with classes like .ng-enter, I want to target a JavaScript function: function onEnter() { /* tra ...

Utilizing Twitter Bootstrap to populate form fields from a dropdown selection

I am currently using twitter bootstrap for my front end web development project. I have successfully implemented a text field with a dropdown menu right next to it: <div class="input-group"> <input type="text" class="form-control" name="ope ...

Solving the default font problem in Laravel

I've been working on a project using Laravel and Bootstrap 4. Recently, I decided to switch from the default Laravel font, Nunito, to Lato. So, I made the necessary changes in my app.css file: @import url(https://fonts.googleapis.com/css?family=Nun ...

Unveiling the search bar as it expands horizontally from the center, causing the submit button to slide to adjust

Wishes and Aspirations My goal is to design an .input-group with one input[type=text] and one button[type=button]. Initially, the text box should be hidden, leaving only the button visible at the center of the page. Upon activation, the text box should ...

The submit button is not reading the JavaScript file for validation and instead goes directly to my PHP file

**Hello, I'm new to Stack Overflow. My submit button is not reading the JavaScript file I created; instead, it goes straight to the PHP file without validating the input fields first in the JavaScript file. I've been stuck here for hours and can& ...

Issue with CakePdf unable to properly render CSS styling

I am having issues with the CakePdf Plugin (CakePdf.DomPdf) as it is not recognizing my stylesheet. Despite copying my /View/Layouts/default.ctp to /View/Layouts/pdf/default.ctp, the pdf file generated does not reflect the styling. Could this be due to t ...

Struggling to effectively use XPath to target LI elements that contain specific text

Below is the HTML code for the list item in question: <li class="disabled-result" data-option-array-index="1" style="">4" (0)</li> Here is my attempt at using JavaScript to hide this list item, but it's not working as expected: var xpat ...

Is there a way to eliminate the "x" in the upper right corner of a Foundation Joyride?

Edit 7/16/15: I decided to place the following code between the <li> tags within the joyride that required the removal of the "x" button: <script>$('.joyride-close-tip').remove();</script> While not the most elegant solution ...

When JQuery is written in a separate file, it does not get applied in the HTML file

I've encountered an issue that seems to have similarities to others, but despite trying various solutions and writing JQuery code in a JS file, I can't seem to get it to work properly. When I include the path for the JS and JQuery version in the ...