I have two bitmaps which are being drawn onto a canvas using a matrix

canvas.drawBitmap(bitmap, matrix, paint);

first to work out if I need to check for a collision i am using eucilidean vectors as such

//vector between the bitmaps
float vx = bitmap2.x - bitmap1.x;
float vy = bitmap2.x - bitmap1.x;

//magnitude of the vector between the two bitmaps
float m = Math.sqrt( (vx*vx)+(vy*vy) );

if( m < bitmap1.getDiagonalWidth() + bitmap1.getDiagonalWidth())
    //pixel perfect collision detection required

Firstly, is this the best way to approach this part of the collision detection?

Secondly once I have found that a collision is possible, do I need to do anything before throwing the bitmaps into a method that runs pixel perfect collision detection? basically, is the issue complicated because of the rotation of the images?

edit* it is possible that the bitmaps will also be scaled by the matrix. i would imagine that this will complicate things further.


If you can generate proper matrices for the objects for translation & rotation, you can solve this pretty much straight-forwardly

Let's assume object A has the translation & rotation matrix mat_A and object B has translation & rotation matrix mat_B

You need to loop over pixels in A and if it has an alpha value > 0 (or a custom threshold you want) check which pixel of B is at this very position and check if this pixel also has a non-0 alpha channel

Using matrix mathematics, you can move the 2nd object into the first objects world space, to get the mapping between the pixels

You need to transform the global location to a local location in the space of object B. This is the inverse of mat_B. So, we have to transform the local position in A with the following matrix:

matrix fromAToB = mat_A * Inverse_Matrix(mat_B);
//now iterate over each pixel of A
for(int x = 0; x < width_A; ++x) {
    for(int y = 0; y < height_A; ++y)
        // check alpha channel
        if (alpha_value != 0) {
        //calculate the position in B
            Vector pos_in_A = new Vector2(x, y);
            Vector pos_in_B = Vector2.Transform(posInA, fromAToB);
            //use width_B & height_B to make sure the point is within the object
            if (point_inside_B) {
                //round posInB.X and posInB.Y to integer values
                //check if the pixel is transparent
                //if pixel is not transparent, you got collision

This is not really proper Java code, mostly pseduo-code, but I think it conveys the idea well

| improve this answer | |

Not the answer you're looking for? Browse other questions tagged or ask your own question.