views:

484

answers:

2

I found some good resources for rotating a bitmap in android here and elsewher eon the net. I am close to getting my code to work but apparently I don't fully understand how the Matrix Translations work. The following is three main functions from my sprite class. THey worked great before I added things to facilitate the matrix rotation (namely in the onDraw I called the draw with just x,y and no matrix). I wrote some test code to add a sprite, and rotate it from 0 to 360 and back to 0 again repeatedly. It results it in rotating about like its orbiting some odd point. In reality I want it to just sit there and spin:

public void Rotate_Sprite(int transform, int deg)
    {
        int spriteCenterX = x+(width/2);
                int spriteCenterY = y+(height/2);
        mMatrix.setRotate(deg, spriteCenterX, spriteCenterY);
        }

public void Draw_Sprite(Canvas c) { 
//c.drawBitmap(images[curr_frame], x, y, null); //this worked great esp in move sprite
    c.drawBitmap(images[curr_frame], mMatrix, null);
}

public void Create_Sprite(blah blah) {

    ...
    ...
    mMatrix = new Matrix();
    mMatrix.reset();
}

public int Move_Sprite() {
    //with the matrix stuff, I assume I need a translate.  But it does't work right 
    //for me at all.
    int lastx=this.x;
    int lasty=this.y;
    this.x+=this.vx;
    this.y+=this.vy;
    mMatrix.postTranslate(lastX-x,lastY-y); //doesn't work at all
}

I did find this J2me like reference here. Though it seems to have all my sprites I call rotate on in orbit around one point.

+1  A: 

I haven't worked on the android, and It's been a while since I last worked with matrices, but it sounds like you're rotation is working properly and you just forgot to translate so the point to rotate around is at 0,0. What you're going to want to do if this is in fact the problem is translate the sprite so that it's world location is 0,0; rotate the sprite; then translate it BACK to wherever it was before. This should all occur before drawing that frame, so the translation itself will never be seen.

Hope this helps.

Lunin
Where would I do this translate, and are these translate coords in pixels?
Codejoy
+1  A: 

Try this:

mMatrix.setTranslate(objectX,objectY);
mMatrix.postRotate(Degrees, objectXcenter, objectYcenter);

Basically, you need to translate your bitmap to the location you want it first, set it there, then rotate it N Degrees around its center.

Ben Mc