Rectangles in collision: A mathematical analysis

After numerous attempts, I have developed a small "game" that incorporates collision detection.

Unfortunately, I have encountered a persistent issue where objects sometimes pass through each other. The root cause of this problem eludes me completely.

Initially, I crafted my own detection mechanism, which I have since commented out. I then resorted to using the following approach:

Access the code sample on fiddle

function rectanglesIntersect( minAx, minAy, maxAx, maxAy, minBx, minBy, maxBx, maxBy ) {
    var aLeftOfB = maxAx < minBx;
    var aRightOfB = minAx > maxBx;
    var aAboveB = minAy > maxBy;
    var aBelowB = maxAy < minBy;

    return !( aLeftOfB || aRightOfB || aAboveB || aBelowB );
}

Answer №1

Fortunately, when your rectangles are in motion, they exhibit these simplifying characteristics:

  • They only move vertically (up or down).
  • They all move at a consistent rate of 30 pixels per move.

This allows you to easily determine if and where a pair of rectangles will collide:

  1. At the beginning of the motion, assess whether a pair of rectangles could potentially collide by checking if they are aligned vertically.

    rect1.x > rect2.x && rect1.x < rect2.x + rect2.width;
    
  2. If the rectangles are moving towards each other, check if they are within 60 vertical pixels of each other. The value 60 is significant because each rectangle can move 30 pixels per move, allowing them to close in on each other by 30 + 30 = 60 pixels per move.

    var willCollideThisMove = Math.abs(rect1.y - rect2.y) <= 60;
    
  3. If a collision is imminent, it will occur at the midpoint of the vertical distance between the two rectangles:

    var collisionY = Math.min(rect1.y, rect2.y) + Math.abs(rect1.y - rect2.y) / 2;
    

Repeat these 3 calculations for all pairs of rectangles.

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

Screen the embedded array depending on the criteria

Here is an example of an object I have: data = { "suites": [ { "status": "fail", "testcases": [ { "status": "pass" }, ...

Advanced JavaScript function invocation

I have been learning JavaScript and I am struggling to understand the coding style I see in the code I read. I am familiar with the "old" way of writing JavaScript but I haven't come across any resources that explain this new way of creating and calli ...

What steps should I follow to generate a table using Ajax and Javascript when a button is clicked?

After spending hours following various tutorials and exploring previously asked questions, I am struggling to make this work. My HTML page looks like this: <!DOCTYPE html> <html> <head> <link type="text/css" rel="styleshee ...

How to highlight all the text within a 'pre code block' when double-clicked using JavaScript

Is there a way to make code blocks on my blog automatically selected when double-clicked without using jQuery? Here is the code I have so far: I apologize if this is a silly question, I am still learning! <script type="text/javascript" src="https://c ...

Display solely the initial row in the tbody segment of a table. Is there a method to obscure subsequent 1st rows?

The initial row of each tbody acts as the row header, containing the column names. Subsequent rows in each tbody are unnecessary and should be hidden. Classes utilized: toprowHeader = first row containing column names recordsRow = holds additional recor ...

Is there a way to retrieve postmessage data from React?

I am attempting to embed a React URL within an iframe in my JSP project. Here is the code snippet from the sender side: <iframe id="eda" style="display: none;" src="http://myhost:3000/" width="100%" heig ...

submitting a form including a file through ajax communication

For the past two weeks, I've been trying to find a solution to my unique problem. I've created a custom form that I need to upload along with one or more files. Our backend is running ruby on Rails, and the data must be formatted into a specific ...

How can a controller configure an AngularJS provider by passing options?

How can I pass configuration options to a provider from a controller? Below is an example of how to pass options/configurations to a provider from the controller: provider.js file: app.provider('contactProvider', function() { this.name ...

What steps can I take to resolve the issue of item display in the dropdown menu?

My objective is to have a dropdown list with "title 1234" appearing first. When this option is selected, its value should be 1234. How can I achieve this? Here is the desired outcome: https://i.sstatic.net/CqWgn.png Currently, the list looks l ...

Sorting elements to the beginning of each nested array

Looking to rearrange the elements in the given nested array, moving the element with the id 'cat_spc_my_special_id' to the top of the list using the keyword 'special'. There are 4 items currently in the above array, and the goal is to ...

Troubleshooting: Jquery show effects not functioning as expected

Currently, I am facing an issue where I am attempting to display a fixed div using the show function of jQuery. Although the show function itself is working properly, when I try to include an effect from jQuery UI, it does not seem to work as expected. Bot ...

Determine the name of the Java exception class using JavaScript

Here is the code I am using to call a Java web API: m$.ajaxq({ url: contextPath + "/updateElapsedTime", type: "POST", data: params, contentType: "application/json; charset=utf-8", dataType: 'text', async: optionalRunAsync, success: ...

Understanding the Contrast between Relative Paths and Absolute Paths in JavaScript

Seeking clarification on a key topic, Based on my understanding, two distinct paths exist: relative and absolute. Stricly relative: <img src="kitten.png"/> Fully absolute: <img src="http://www.foo.com/images/kitten.png"> What sets apart R ...

Is it possible to utilize the same Context in multiple forms within React?

Is it possible to utilize React Context to store the state of multiple forms, or should each form have its own unique Context? Below is a snippet of code that showcases the use of React Hooks API: In FormContext.js ... import {FormReducer} from './ ...

Expanding Text Area in AngularJS

I came across this directive and I want to integrate it into my project, but I need the text area to expand as soon as the content is loaded. Angular-Autogrow.js: (function(){ 'use strict'; angular.module('angular-autogrow', [ ...

In React and Node Js, the setState function will return a value of NULL

My Node Js API utilizes a find function to retrieve data from the database, which works flawlessly and returns the results. However, when I pass this data into setState using React and Axios, it ends up returning null. Below is my API's find() functi ...

I am looking to enhance my JSON output using JavaScript

My JSON output appears as follows: {"intent":"P&P_Purchase","value1":{"date1":"30-Dec-19","prd_desc":"NEEM UREA OMIFCO (45 KG)","qty":"18MT","inv_no":"NRKT07003160"},"value2":{"date1":"25-Dec-19","prd_desc":"NEEM UREA IMP (45 KG)","qty":"18MT","inv_no ...

Issue with Object.keys printing in an abnormal manner

My goal is to extract only the keys from an object, but instead of getting the desired output with the keys, I am seeing numbers. Here is the code snippet: data = {"property" : "{\"animalID\": \"12345\" ...

Forming a BoxBufferGeometry using the dimensions from Box3

I'm looking to generate a box mesh within a three.js scene, with the points of the box mesh matching the bounding box of an existing object in the scene. I attempted to create the box mesh from box3 using the method outlined below, but I'm not a ...

Vue's watch function failing to trigger

Experiencing issues with Vue watch methods not triggering for certain objects even when using deep:true. Within my component, I am passed an array as a prop containing fields used to generate forms. These forms are dynamically bound to an object named cru ...