sprite rotation around center?

This topic is 1925 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

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

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

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.

1. 1
2. 2
Rutin
21
3. 3
JoeJ
18
4. 4
5. 5

• 14
• 40
• 23
• 13
• 13
• Forum Statistics

• Total Topics
631722
• Total Posts
3001892
×