Question

I have the following function, which shall tell me when 2 sprites overlap on the x-axis:

public int getSecondObjectX(int secObjWidth)
    {
        int rndX = random.nextInt(AndroidApplication.getInstance().device_width - secObjWidth);

        Rect sObj = new Rect(rndX, 20, rndX + secObjWidth, 10);
        Rect droid = new Rect(myAnimation.getXcord(), 20, myAnimation.getXcord() + myAnimation.getCurrentImage().getWidth(), 10);

        Log.d("Compare Rect", "["+sObj.left+", "+sObj.right+"] ["+droid.left+", "+droid.right+"]");

        if(Rect.intersects(sObj, droid))
        {
            Log.d("INTERSECT", "INTERSECT");

            return getSecondObjectX(secObjWidth);
        }
        else
            return rndX;
    }

But I never get the intersect, here's the Logcat:

03-19 15:08:12.617: D/Compare Rect(631): [183, 231] [141, 189] <-- should be true
03-19 15:08:22.186: D/Compare Rect(631): [158, 206] [172, 220] <-- should be true
03-19 15:08:26.346: D/Compare Rect(631): [123, 171] [178, 226]
03-19 15:08:30.146: D/Compare Rect(631): [156, 204] [155, 203] <-- should be supertrue
03-19 15:08:32.617: D/Compare Rect(631): [84, 132] [172, 220]

What's the problem?

Was it helpful?

Solution

The way you construct the Rects is wrong. The public Rect (int left, int top, int right, int bottom) constructor does not perform range checking. You can find the following in the documentation:

Note: no range checking is performed, so the caller must ensure that left <= right and top <= bottom.

In your case, top > bottom.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top