How to solve this problem in the collision?

Asked

Viewed 96 times

-1

If I check the collision only horizontally, the program picks up the entire width of the scene and not just the div.

Code:

<html>
<style>
#dv{

border:1px solid red;
background-color:#344;
height:80px;
position:absolute;
}
#dv2{

border:1px solid black;
background-color:#f00;
height:80px;
position:absolute;

}




</style>
<body>
<div id = "dv"></div>
<div id = "dv2"></div>
<script>
var valor = 0;
var valor2 = 180;
var dv= document.getElementById("dv");
var div2 = document.getElementById("dv2");

var largura = dv.style.width = 80;
var lateral = div2.style.left = 180;
var largura2 = div2.style.width = 80;
var lateral2 = div2.style.top = 300;

function moverDiv(){
valor += 5;
dv.style.left = valor+"px";


if(valor+largura > lateral){
div2.style.backgroundColor = "blue";


}
}
dv.addEventListener("touchmove",moverDiv);





</script>
</body>
</html>

Execution:

inserir a descrição da imagem aqui

1 answer

0

The collision between squares and rectangles occurs when the left (coordinate where it starts to be drawn) from OBJECT TO is smaller than the left plus the width (width) of subject B and the left plus the width of OBJECT TO is greater than the left of subject B and the same with top and height.

if (A.x < B.x + B.w && A.x + A.w > B.x) {
     if (A.y < B.y + B.h && A.h + A.y > B.y) {
         // Está colidindo
     }
}

The x is the left, and the w is the width. If you have access to the property right, is equal to the sum of left with the width, and bottom amounts to some of top and height

In your example you are also not setting back the color red when there is no longer collision...

See this example on jsfiddle

  • blz,but the big case is that the black div is above the red div and even so when I pass to the side it indentify that collided.

  • @Danilosantos has to do the same for the y axis (vertical), see link example

  • Okay I’ll try that

  • So it checks y and not x and the path is open to use the two intendi coordinates.So use the two strings.

  • 1

    Thank you very much VIK

Browser other questions tagged

You are not signed in. Login or sign up in order to post.