how to make a collision of two squares?

0

I made this code, so that 2 squares passed by parameter collide. I try to make the collision based on the attributes of the squares

public boolean VerificarColisionCuadradoCuadrado(Cuadrado obj1, Cuadrado obj2) {
        if (obj1.x + obj1.w <= obj2.x) {
            return false;
        }
        if (obj1.y + obj1.h <= obj2.y) {
            return false;
        }
        if (obj1.x > obj2.x + obj2.w) {
            return false;
        }
        if (obj1.y > obj2.y + obj2.h) {
            return false;
        }
        return true;
    }

being square:

public class Cuadrado {

public int w, h;
public int x;
public int y;
public int color;

public void dibujarCuadrado(Graphics g, int posX, int posY, int base, int altura,int color) {
    Line.drawline(g, posX, posY, base + posX, posY, color);
    Line.drawline(g, base + posX, posY, base + posX, altura + posY,color);
    Line.drawline(g, base + posX, altura + posY, posX, altura + posY,color);
    Line.drawline(g, posX, altura + posY, posX, posY, color);
    this.w=base;
    this.h=altura;
    this.x=posX;
    this.y=posY;
    this.color=color;
}

I can not find the error, they do not collide

the error I think is in the function

  

CheckColisionCuadradoCuadrado

    
asked by hubman 12.11.2016 в 02:45
source

3 answers

0

The problem I see in your code is that you work without taking into account a certain margin of error at the time of the collision. You should keep this in mind when working with real simulation problems.

    
answered by 12.11.2016 в 03:23
0

it was just a code problem

public boolean VerificarColisionCuadradoCuadrado(Cuadrado obj1, Cuadrado obj2) {
        if (obj1.x + obj1.w < obj2.x) {
            return false;
        }
        if (obj1.y + obj1.h < obj2.y) {
            return false;
        }
        if (obj1.x > obj2.x + obj2.w) {
            return false;
        }
        if (obj1.y > obj2.y + obj2.h) {
            return false;
        }
        return true;
    }

eliminate the equality of the first 2 conditions and now it works !!!

    
answered by 12.11.2016 в 03:26
0

I do not know what you are using it exactly, but the Box2D library does the same for you. It has a lot of features and can save you a lot of work.

link

    
answered by 12.11.2016 в 09:29