2013-10-25 91 views
0

我想在沒有ImageView相互交叉的佈局上生成隨機ImageViews。我生成屏幕尺寸這樣內的隨機點:碰撞ImageViews不起作用

private Point generateRandomLocation(Point dimensions) { 
    Random random = new Random(); 

    // generate random x 
    int x = random.nextInt((dimensions.x - 0) + 1); 

    // generate random y 
    int y = random.nextInt((dimensions.y - 0) + 1); 

    Point location = new Point(x, y); 

    if(!collision(location)) { 
     return new Point(x, y); 
    } else { 
     return generateRandomLocation(dimensions); 
    } 

}

相撞方法包含下列方法來確定的閹羊碰撞ImageViews與否。 BubbleImage是ImageView的一個簡單擴展。

private boolean collision(Point location) { 
    // takes 100 as inital width & height 
    int x_1 = location.x; 
    int y_1 = location.y; 

    int x_2; 
    int y_2; 

    boolean collided = false; 

    // get all bubbleimages 
    for (int i = 0; i < mainLayout.getChildCount(); i++) { 
     View childView = mainLayout.getChildAt(i); 
     if (childView instanceof BubbleImage) { 
      x_2 = (int) childView.getX(); 
      y_2 = (int) childView.getY(); 

      // create rectangles 
      Rect rect1 = new Rect(x_1, y_1, x_1 + 100, y_1 - 100); 
      Rect rect2 = new Rect(x_2, y_2, x_2 + 100, y_2 - 100); 
      collided = Rect.intersects(rect1, rect2); 

     } 
    } 

    return collided; 

}

這裏有人察覺的錯誤的邏輯?

編輯:Rect.intersects()似乎返回false,即使圖像視圖相交。

回答

2

當創建新的Rect rect1 & rect2時,構造函數是Rect(左,上,右,下)。例如。 Rect(10,10,20,20),因爲android屏幕原點位於左上角。 您已經以錯誤的方式創建了Rects(如左圖,bottom,right,top)。嘗試在構造函數調用中切換第2個和第4個參數,或者將第4個參數增加爲大於2nd。 像這樣: Rect rect1 = new Rect(x_1,y_1,x_1 + 100,y_1 + 100);

+0

感謝這實際上工作! (切換參數) –