Search code examples
javaandroidmatrixrotationtranslate-animation

Translate and rotate matrix via old matrix values


I am trying to rotate and translate my bitmap with a matrix where I use the following code (I tried making it plain english):

playerX = playerValues[Matrix.MTRANS_X];
playerY = playerValues[Matrix.MTRANS_Y];

if (fingerx1 > playerX) {
    xspeed = 1;

}
if (fingerx1 < playerX) {
    xspeed = -1;
}
if (fingery1 < playerY) {
    yspeed = -1;
}
if (fingery1 > playerY) {
    yspeed = 1;
}

//playerX and playerY are checked in Log.d, returns correct values

playerMatrix.setRotate(rotation, bitmap.getWidth()/2, bitmap.getHeight()/2);
playerX += xspeed;
playerY += yspeed;
playerValues[Matrix.MTRANS_X] = playerX;
playerValues[Matrix.MTRANS_Y] = playerY;
playerMatrix.setValues(playerValues);

This does not work :P It flashes back and forth between the start and current x and y values. Could anyone tell me what the right way of doing this translation?

(rotation works fine alone)


Solution

  • Using Matrix.setXXX() will replace the previous matrix transformations. Instead of setValues, you can use:

    playerMatrix.postRotate(rotation, bitmap.getWidth()/2, bitmap.getHeight()/2);
    playerX += xspeed;
    playerY += yspeed;
    playerValues[Matrix.MTRANS_X] = playerX;
    playerValues[Matrix.MTRANS_Y] = playerY;
    playerMatrix.postTranslate(playerX, playerY);