0

嗨,我正在尝试使用 Rect.intersects 在两个矩形图像之间进行碰撞检测,但我总是得到错误的结果。如果可能的话,请尽快帮助我。我的代码如下。

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

提前致谢

4

2 回答 2

0

use this function

/**
 * 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);
}

and also see this link

于 2014-05-26T11:47:14.190 回答
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));


            }
        });
于 2013-10-21T09:22:30.047 回答