Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collision Between 2 views in android

I have 2 views in android and they are dragable.I want to detect collision between them. Currently I am using this code to detect collision but I don't think its working .Please suggest what need to check the collision.

public boolean onTouch(View view, MotionEvent event) {
    final int X = (int) event.getRawX();
    final int Y = (int) event.getRawY();
    switch (event.getAction() & MotionEvent.ACTION_MASK) {
    case MotionEvent.ACTION_DOWN:
        RelativeLayout.LayoutParams lParams = (RelativeLayout.LayoutParams) view
                .getLayoutParams();

        _xDelta = X - lParams.leftMargin;
        _yDelta = Y - lParams.topMargin;
        break;
    case MotionEvent.ACTION_UP:
        break;
    case MotionEvent.ACTION_POINTER_DOWN:
        break;
    case MotionEvent.ACTION_POINTER_UP:
        break;
    case MotionEvent.ACTION_MOVE:
        RelativeLayout.LayoutParams ParamsA = (RelativeLayout.LayoutParams) view
                .getLayoutParams();
        ParamsA.leftMargin = X - _xDelta;
        ParamsA.topMargin = Y - _yDelta;
        ParamsA.rightMargin = -250;
        ParamsA.bottomMargin = -250;

        for (int i = 0; i < balls.size(); i++) {
            if (balls.get(i).getTag() != view.getTag()) {
                RelativeLayout.LayoutParams ParamsB = (RelativeLayout.LayoutParams) balls
                        .get(i).getLayoutParams();

                Rect b = new Rect(ParamsB.leftMargin,ParamsB.topMargin,ParamsB.rightMargin,ParamsB.bottomMargin);
                Rect a = new Rect(ParamsA.leftMargin,ParamsA.topMargin,ParamsA.rightMargin,ParamsA.bottomMargin);


                if(a.intersect(b))
                {
                    Toast.makeText(getApplicationContext(), "Collision Detected", Toast.LENGTH_SHORT).show();
                }
            }

        }

        view.setLayoutParams(ParamsA);
        break;
    }
    // _root.invalidate();
    return true;
}

"balls" is array of type "View" which are laying in the screen.

like image 747
Ali Avatar asked Jan 09 '23 17:01

Ali


1 Answers

I just found solution myself it works perfect in all case.

public boolean CheckCollision(View v1,View v2) {
    Rect R1=new Rect(v1.getLeft(), v1.getTop(), v1.getRight(), v1.getBottom());
    Rect R2=new Rect(v2.getLeft(), v2.getTop(), v2.getRight(), v2.getBottom());
    return R1.intersect(R2);
}
like image 155
Ali Avatar answered Jan 16 '23 05:01

Ali