2013-03-19 51 views
0

我有以下的功能,這會告訴我,當2個精靈在x軸重合:爲什麼矩形相交永遠不會是真的?

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; 
    } 

但我從來沒有得到過相交,這裏的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] 

什麼問題?

+0

閱讀*手冊,您正在使用Rect錯誤 – njzk2 2013-03-19 14:27:38

回答

3

你構建Rect的方式是錯誤的。 public Rect (int left, int top, int right, int bottom)構造函數不執行範圍檢查。您可以在文檔中的以下內容:

注:不執行範圍檢查,所以調用者必須確保左< =右側和頂部< =底部。

在你的情況,頂部>底部。

+0

啊,謝謝!頂部和底部混合;( – 2013-03-19 14:39:53

相關問題