碰撞检测没有发生?

时间:2013-10-21 09:07:12

标签: android

您好我正在尝试使用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();
        }
    });

先谢谢

2 个答案:

答案 0 :(得分: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));


            }
        });

答案 1 :(得分: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

相关问题