Cant get Rect.intersects(rec, rec2) to work

2019-09-01 08:53发布

问题:

For some reason my program won't get through Rect.intersects(re,hitcore). If I use System.out.println()re.flattenToString(), I see that the two rectangles intersect but it won't return true.

I also tried using re.intersect(hitcore), but still nothing. Help?

import android.graphics.Rect;   

public class Enemy {
public Rect re, hitCore;

private boolean hit = false;


public Enemy() {
    re = new Rect(0, 0, 0, 0);
    hitCore = new Rect(0, 0, 0, 0);

}

public void update() {

    re.set(centerX + leftX, centerY + topY, rightX, botY); // these are set by another class                  
    hitCore.set(ship.getCenterX() + 3, ship.getCenterY() + 10, 93, 20);

            //System.out.println(re.flattenToString() + " rect1");
    //System.out.println(hitCore.flattenToString() + " rect2");

    checkHit(hitCore);

}

private void checkHit(Rect hitCore) {
    if (Rect.intersects(hitCore, re)) {
        hit = true;
    }
}
}

回答1:

I figured it out. I was setting up rectangle using x,y and width,height. The actual parameters are the top left corner coordinate and bottom right corner coordinate.

 rect.set(x1,y1,x2,y2);