How to detect collision between two squares/rectangles

Asked

Viewed 2,694 times

5

Who provide an answer that explains all the necessary nuances for this in javascript will earn the points.

  • If you did not understand a user’s code, you should have posted comments there on the original question requesting clarification from him (after all, no one better than the author to explain what was done). In other words, opening a new question is not the way to do it on this site. I just don’t vote to close as duplicate (or even out of scope) because of active reward.

  • Hi Luiz thank you so much for the tips and remarks, as for the user of the other post I am myself, including requested that the author of the solution algorithm make comment on the code itself and also clarify an excerpt of the code, the comment in the code he made, but the question of the code excerpt he did not answer, after that I deleted the post I had posted asking myself. Another detail Luiz if you allow me is that despite the similarity of the title the algorithm will be different because the objectives are other despite the similarity.

  • Finally, if I was as smart as you are Luiz, I could have understood from the first time and clearly the logic he made and the excerpt of the coding.

  • Thank you for the compliment, but I don’t think it’s a question of being more or less intelligent. If this is another problem and will be really different, it is another reason not to have connection with the original code (because then you do not send the solution of this problem). About what you mentioned about the other colleague not having answered you, you could have put the reward on that same question if your question was understanding. Anyway, I’m just arguing that the way the question is she’s complicated, because this site is not a forum. But good luck to you! :)

  • Let’s do what is right then Luiz, you help me to do it the right way? What do I need to change to make the question simpler? close this post and redo the other post?

  • To begin with, in the future try to be more pragmatic. About your doubt, in the title you say "collision detection". Then, in his original question, he asked about "left alignment" and this about "above alignment". Do you realize you’re asking the question about your idea of a solution, rather than asking about the real problem (which is collision detection)? Read later about the XY problem.

  • 2

    For this question, and to take advantage of its reward, I would suggest asking directly "How to detect the collision between two squares/rectangles". Who provides an answer that explains all the nuances necessary for such, as you deem appropriate, is to whom you grant the reward. It’s better than asking for parts based on "alignment" (which isn’t exactly the ideal concept for what it looks like you want to do).

  • I even made an answer here simulating two rectangles like walls and a box that hits home one changing direction at the time of the collision, but the explanation ta half bad so I will not post. = P

  • 1

    Hello @Ack do you remember that Tetris game where different geometric shapes come down to base to be fitted? I would like to understand precisely that principle, when one square leans against another and it stops moving, because it would like to send multiple squares up (one square at a time) and when it touches another it stops moving.

  • @user31050 the question itself is clear, but when I read about the Tetris principle is that I really saw that I understood what you want, I will do a search and try to form something, if it becomes clear and can explain well put here.

  • @Mathias blz Mathias, I answered your post about clicking on input.

Show 6 more comments

1 answer

8


To show how the collision detection between two objects works I will use two div's square in a plane 2D, but collision detection can be applied to any form of object, provided we have the dimensions of the objects in question and this concept also serves for planes in 3D, the difference between 2D and 3D is that in 3D we work with three dimensions (x,y,z) while in 2D there are only two (x,y), which makes the process much simpler.

inserir a descrição da imagem aqui

The two objects (div’s) will have the following dimensions, the first div(blue) has 100px high and 100px wide, the second div(red) is half the size of the first, so 50px high and 50px wide.

inserir a descrição da imagem aqui

Position

To get the position of the element we have two options .position() or .offset(), the method .position() returns the location relative to the nearest ancestor, while the .offset() returns the position relative to the document. I will not explain in depth the methods if you want to understand more about them click here, in the example in question makes no difference as the parent or ancestor element is the document itself.

Collision

The collision in this context that we create, considering only these two elements, will happen when the following conditions are true:

Horizontally:

When the right end of the leftmost element(A2) is greater than or equal to the left edge of the rightmost element(V1) and less than or equal to the right end of the rightmost element(V2).

V1<=A2<=V2

inserir a descrição da imagem aqui

Upright:

When the bottom end of the element above(A4) is greater than or equal to the top end of the element further down(V3) and less than or equal to the lower end of the lower element(V4).

V3<=A4<=V4

inserir a descrição da imagem aqui

Extremities

var posAzul = $(".azul").position();
A1 = posAzul.left;
A2 = posAzul.left + $(".azul").width();
A3 = posAzul.top;
A4 = posAzul.top + $(".azul").height();

In the same way we get the ends of the red block.

If these two conditions are met simultaneously we can say that there was a collision between the objects. There are n ways to do this check, follows a very practical example that checks for collision between two objects, I hope it helps.

$("#dir").click(function() {
  $(".azul").animate({
    "left": "+=50px"
  }, "fast", checkCollisions);
});

$("#esq").click(function() {
  $(".azul").animate({
    "left": "-=50px"
  }, "fast", checkCollisions);
});

$("#cima").click(function() {
  $(".azul").animate({
    "top": "-=50px"
  }, "fast", checkCollisions);
});

$("#baixo").click(function() {
  $(".azul").animate({
    "top": "+=50px"
  }, "fast", checkCollisions);
});

function getPositions(vermelho) {
  var $vermelho = $(vermelho);
  var pos = $vermelho.position();
  var width = $vermelho.width();
  var height = $vermelho.height();
  return [
    [pos.left, pos.left + width],
    [pos.top, pos.top + height]
  ];
}

function comparePositions(p1, p2) {
  var x1 = p1[0] < p2[0] ? p1 : p2;
  var x2 = p1[0] < p2[0] ? p2 : p1;
  return x1[1] > x2[0] || x1[0] === x2[0] ? true : false;
}

function checkCollisions() {
  var vermelho = $(".vermelho")[0];
  var pos = getPositions(vermelho);

  var pos2 = getPositions(this);
  var horizontalMatch = comparePositions(pos[0], pos2[0]);
  var verticalMatch = comparePositions(pos[1], pos2[1]);
  var match = horizontalMatch && verticalMatch;
  if (match) {
    $("body").append("<p>Colisão!</p>");
  }
}
.azul {
  position: absolute;
  background-color: blue;
  left: 50px;
  width: 100px;
  height: 100px;
  margin: 30px;
}

.vermelho {
  position: absolute;
  background-color: red;
  left: 300px;
  width: 50px;
  height: 50px;
  margin: 30px;
  top: 70px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="cima" style="width:150px;">Cima</button>
<br>
<button id="esq" style="width:75px;">Esquerda</button>
<button id="dir" style="width:75px;">Direita</button>
<br>
<button id="baixo" style="width:150px;">Baixo</button>

<div class="azul"></div>
<div class="vermelho"></div>

  • @user31050 Look at this fiddle I made by changing the code of the first answer of the topic you sent me, what did you need? https://jsfiddle.net/mathiasfcx/crboo2hz/

  • @user31050 It was fairly simple, rather than changing the . left of each element, the . top, compare the two methods you easily identify the changes.

  • @user31050 I can explain to you yes, I am on the street at the moment but as soon as possible I leave a brief explanation.

  • @user31050 hahaha, sorry face to half full of stuff at work, I am in debt to you, let’s do the following, you have the fiddle link with the code, today I still update there the code with the explanation in a comment.

  • @user31050 https://jsfiddle.net/mathiasfcx/crboo2hz/7/

  • The line 44 to 55 that is hard to understand @Mathias, I really wanted to know that part there of the logic that he did.

  • @user31050 really, there is more confusing, but do the following, first ignore the comments that are there, they are referring to the algorithm that moved left, second creates one . html on your pc itself and a debug in that code, specifically in that part of the 44 to 55, then maybe it’s clearer, there are all the checks that it does p/ no collision, that arrays manipulation that leaves the business tense kk.

Show 2 more comments

Browser other questions tagged

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