# sprite rotation around center?

## Recommended Posts

cozzie    5029

Hi,

I'm working through the Game programming book of Jonathan S. Harbour. Currently getting into d3dx sprites.

My question is, how can I rotate and scale a sprite around it's own center?

Rotation works fine until I combine it with scaling.

Here's the (relevant) code I have, any help is appreciated.

void Sprite_Transform_Draw(LPDIRECT3DTEXTURE9 image,
int x,
int y,
int width,
int height,
int frame,
int columns,
float rotation,
float scaling,
D3DCOLOR color)
{

// create a scale vector
D3DXVECTOR2 scale(scaling, scaling);

// create a translate vector
D3DXVECTOR2 trans((float)x, (float)y);

// set center by dividing scaled width and height by 2
D3DXVECTOR2 spritecenter((float)(width * scaling)/2, (float)(height * scaling)/2);

// create 2D transformation matrix
D3DXMATRIX mat;
D3DXMatrixTransformation2D(&mat, NULL, 0.0f, &scale, &spritecenter, rotation, &trans);

//	D3DXMatrixTransformation2D(&mat, &spritecenter, 0.0f, &scale, &spritecenter, rotation, &trans); TESTED, NOT OK

// tell sprite object to use the transformation matrix
spriteobj->SetTransform(&mat);

// calculate frame location in source image
int fx = (frame % columns) * width;
int fy = (frame / columns) * height;
RECT srcrect = { fx, fy, fx + width, fy + height };

// draw the sprite image
spriteobj->Draw(image, &srcrect, NULL, NULL, color);
}

The second parameter of 3dx transformation function is the sprite center for rotation, I tried both NULL as well as the scaling center of the sprite.

##### Share on other sites
cozzie    5029

I got it, the function works fine. I was passing through incorrect X and Y as input to the function, not depending on the scale.

Old/ not OK:

Sprite_Transform_Draw(sunflower, SCREENW/2-width/2, SCREENH/2-height/2, width, height, frame, columns, r, s, color);

Now OK:

Sprite_Transform_Draw(sunflower, SCREENW/2-((width*s)/2), SCREENH/2-((height*s)/2), width, height, frame, columns, r, s, color);

##### Share on other sites
Dave Hunt    4872

By the way, SCREENW / 2 - ((width * s) / 2) == (SCREENW - (width * s)) / 2.

Not a big deal, but saves a bit of typing and is easier to read. Also, depending on how SCREENW and SCREENH are defined, it could result in fewer instructions, though I'm not recommending this solely as an optimization. Just for readability.

## Create an account

Register a new account