2013-10-21 80 views
0

嗨我想碰撞检测使用Rect.intersects两个矩形图像之间,但我总是得到结果false.If尽可能尽快帮助我。我的代码如下。碰撞检测不开心?

img1 = (ImageView) findViewById(R.id.imgLeft); 
    img2 = (ImageView) findViewById(R.id.imgRight); 

    bmp1 = BitmapFactory.decodeResource(getResources(), 
      R.drawable.ic_launcher); 
    bmp2 = BitmapFactory.decodeResource(getResources(), 
      R.drawable.ic_launcher); 
    Drawable d1 = new BitmapDrawable(getResources(), bmp1); 
    img1.setBackgroundDrawable(d1); 
    Drawable d2 = new BitmapDrawable(getResources(), bmp2); 
    img2.setBackgroundDrawable(d2); 

    rec1 = new Rect(0, 0, img1.getWidth(), img1.getHeight()); 

    tw = ObjectAnimator.ofFloat(img2, "translationX", 20, -550f); 
    tw.setDuration(6000); 
    tw.addUpdateListener(new AnimatorUpdateListener() { 

     @Override 
     public void onAnimationUpdate(ValueAnimator animation) { 
       Rect recTest1 = new Rect((int)img1.getX(), (int)img1.getY(),rec1.width(), 
         rec2.height()); 
      Rect recTest2 = new Rect((int)img2.getX(), (int)img2.getY(),rec2.width(), 
        rec2.height()); 
      System.out.println("Test : "+Rect.intersects(recTest1, recTest2)); 


     } 
    }); 

    tw.start(); 

    tw_One = ObjectAnimator.ofFloat(img1, "translationX", 0, 550f); 
    tw_One.setDuration(6000); 
    tw_One.start(); 

    tw_One.addUpdateListener(new AnimatorUpdateListener() { 

     @Override 
     public void onAnimationUpdate(ValueAnimator animation) { 
      img_one_CurrentX = img1.getX(); 
     } 
    }); 

由于提前

回答

0

尝试这种方式

tw.addUpdateListener(new AnimatorUpdateListener() { 

      @Override 
      public void onAnimationUpdate(ValueAnimator animation) { 
       Rect recTest1 = new Rect(); 
       img1.getDrawingRect(recTest1); 
       Rect recTest2 = new Rect(); 
       img2.getDrawingRect(recTest2); 


       System.out.println("Test : "+recTest1.intersect(recTest2)); 


      } 
     }); 
+0

以上代码给出的结果总是正确的。我只需要在碰撞时 –

0

使用此功能

/** 
* Check if two rectangles collide 
* x_1, y_1, width_1, and height_1 define the boundaries of the first rectangle 
* x_2, y_2, width_2, and height_2 define the boundaries of the second rectangle 
*/ 
boolean rectangle_collision(float x_1, float y_1, float width_1, float height_1, float x_2, float y_2, float width_2, float height_2) 
{ 
    return !(x_1 > x_2+width_2 || x_1+width_1 < x_2 || y_1 > y_2+height_2 || y_1+height_1 < y_2); 
} 

,也看到这个link