How to detect if two divs are touching/ collision detection
There's probably a better way (this isnt very DRY) but it should work, simply replace "div1" and "div2" with your div IDs:
let div1 = document.getElementById('div1').getBoundingClientRect();
let div1Top = div1.top;
let div1Left = div1.left;
let div1Right = div1.right
let div1Bottom = div1.bottom
let div2 = document.getElementById('div2').getBoundingClientRect();
let div2Top = div1.top;
let div2Left = div1.left;
let div2Right = div1.right
let div2Bottom = div1.bottom
if ((div2Top > div1Top && div2Top < div1Bottom)||(div2Bottom > div1Top && div2Bottom < div1Bottom)) {
let verticalMatch = true
} else{
let verticalMatch = false
}
if ((div2Right > div1Left && div2Right < div1Right)||(div2Left < div1Right && div2Left > div1Left)) {
let horizontalMatch = true
} else {
let horizontalMatch = false
}
if (horizontalMatch && vertialMatch){
let intersect = true
} else {
let intersect = false
}
Javascript: Check collision between two divs
First, I'd suggest you check out the HTML5 canvas
element, as by the sounds of it, you want to make a game, and the canvas
is great for that ;)
But, to answer your question, you could create or get div elements with document.createElement()
or getElementById()
respectively, and get their style properties either by getting their JS-set values (element.style
) or use getComputedStyle if you'd prefer to set initial values in CSS.
Make sure that, however you get these CSS properties, they'll need to be parsed into something that JS can digest. For integer-based positions, parseInt()
usually does the trick.
Next, you do the math. In this case, you'd want to see if the character div's top, plus its height, is greater than the top position of the ground. If it is, it has collided.
To set the style back to the div, you can just set the style property.
Here's an example (copied from this fiddle):
var character = document.getElementById("character");
var ground = document.getElementById("ground");
//We could use getComputedStyle to get the style props,
//but I'm lazy
character.style.top = "10px";
character.style.height = "40px";
ground.style.top = "250px";
//For every 33ms (about 30fps)
setInterval(function(){
//Get the height and position of the player
var charTop = parseInt(character.style.top),
charHeight = parseInt(character.style.height);
//and the top of the ground
var groundTop = parseInt(ground.style.top);
//linear gravity? Why now?
charTop += 5;
//If the character's bottom is hitting the ground,
//Stop moving
if(charTop + charHeight > groundTop) {
charTop = groundTop - charHeight;
}
//Set the character's final position
character.style.top = charTop + "px";
},33);
#character {
position: absolute;
width: 40px;
height: 40px;
left: 50px;
background-color: #F00;
}
#ground {
position: absolute;
width: 300px;
height: 60px;
left: 0px;
background-color: #A66;
}
<div id="character"></div>
<div id="ground"></div>
Check collision between certain divs
Okay, I ended up using a modified version of this duplicate. The function which does the work is:
var overlaps = (function () {
function getPositions( elem ) {
var pos, width, height;
pos = $( elem ).position();
width = $( elem ).width() / 2;
height = $( elem ).height();
return [ [ pos.left, pos.left + width ], [ pos.top, pos.top + height ] ];
}
function comparePositions( p1, p2 ) {
var r1, r2;
r1 = p1[0] < p2[0] ? p1 : p2;
r2 = p1[0] < p2[0] ? p2 : p1;
return r1[1] > r2[0] || r1[0] === r2[0];
}
return function ( a, b ) {
var pos1 = getPositions( a ),
pos2 = getPositions( b );
return comparePositions( pos1[0], pos2[0] ) && comparePositions( pos1[1], pos2[1] );
};
})();
And it is called by using overlaps( div1, div2 );
(returns true or false).
Collision between two div vanillaJS no detection
You have a few issues..
getElementsByClassName
returns anHTMLCollection
, not a single element. You need to either iterate over these if you have more than one. Or if there's just one of each class, just usequerySelector
.- If you want to use the element's
x
,y
, you need to get it'sDOMRect
usinggetBoundingClientRect
.
Try this instead:
let rect1 = document.querySelector('.perso').getBoundingClientRect();
let rect2 = document.querySelector('.obstacle').getBoundingClientRect();
Collision detection with JavaScript. (Check if 2 Block Level elements are touching)
You can use the Jquery collision plugin like this:
var x = $("#div1").collision(".div2");
Javascript: Detect colliding divs
You need to loop through each div, and then compare with every other div in a nested loop. Then use logic like what you've written to compare each combination. Here is an example that simply prints out the overlapping divs to the output (note also that I changed the height
element to have a numerical value rather than text so that its value could be used in calculations):
var divs = [
{class:'A', top:0, left:0, height:60},
{class:'B', top:50, left:60, height:60},
{class:'C', top:30, left:10, height:60},
{class:'D', top:100, left:180, height:60},
{class:'E', top:80, left:50, height:60},
{class:'F', top:110, left:200, height:60},
{class:'G', top:55, left:80, height:60}
];
for (var i=0; i < divs.length - 1; i++)
for (var j=i+1; j < divs.length; j++)
{
var I=divs[i];
var J=divs[j];
if ( (I.top <= J.top && (I.top + I.height) >= J.top) ||
(J.top <= I.top && (J.top + J.height) >= I.top) )
document.writeln(
I.class + " collides with " + J.class + "<br />");
}
Output:
A collides with B
A collides with C
A collides with G
B collides with C
B collides with D
B collides with E
B collides with F
B collides with G
C collides with E
C collides with G
D collides with E
D collides with F
D collides with G
E collides with F
E collides with G
F collides with G
Sample working code: http://jsfiddle.net/QUrWM/
how can i check if two div touch each other in javascript
At the moment you're assigning the bounding rectangles of your game objects to the variables carRightBound & playerBound once before starting the interval.
That means it's values won't ever get updated anymore. You should update them inside the callback function.
Furthermore the interval of 5000ms is way too long. A lot of stuff can have happenend on screen during 5 seconds. Try reducing it to 50ms for example.
Lastly I'm not too sure about your collision detection anyhow. You aren't paying attention to the size of your objects.
Try this code:
setInterval(function() {
var playerBound = player.getBoundingClientRect();
var carsRight = document.querySelectorAll('.carRight');
var carRightBound;
for (var a = 0; a < carsRight.length; a++) {
carRightBound = carsRight[a].getBoundingClientRect();
if (playerBound.x > carRightBound.x - playerBound.width && playerBound.x < carRightBound.x + carRightBound.width && playerBound.y > carRightBound.y - playerBound.height && playerBound.y < carRightBound.y + carRightBound.height) {
console.log('The divs are intersecting!');
alert('on here')
} else {
console.log('The divs are not intersecting.');
}
}
}, 50);
Related Topics
Create React App Breaks After Deployment on Refresh 404 With Nginx
How to Show a Confirmation Dialog Box in Toastr
How to Change Iframe Src Without Reloading the Iframe
How to Change Image and Text Color When Clicking Using React-Native
React-Redux State Lost After Refresh
Prevent Any Form of Page Refresh Using Jquery/Javascript
Getting the Reason Why Websockets Closed With Close Code 1006
React: How to Inject React Component into Body
Bootstrap 4 Display Dropdown Submenu on the Right Side
Angular [Innerhtml]: How to Render Additional Elements Inside an Element With [Innerhtml] Directive
How to Get Width of (Dom) Element in Angular2
Check If a String Is HTML or Not
Failed to Execute Query Selector on Document, Id Is Not a Valid Selector
Calculate Distance Between Two Moving Elements
How to Stop All Ajax Process in the Page Using Jquery
How to Format a Float as Integer When .Tofixed(2) Gives Zeros After the Decimal Point