C# directx sprite origin

2019-02-26 06:08发布

i have this problem when my Sprite rotation origin is fixed at top left corner of window (same with sprite.Draw and sprite.Draw2D) Either way if i change rotation center it's still at top left. I need sprite to rotate around its Z axis.

Edit: I have tried this:

    hereMatrix pm = Matrix.Translation(_playerPos.X + 8, _playerPos.Y + 8, 0);
    sprite.Transform = Matrix.RotationZ(_angle) * pm;
    sprite.Draw(playerTexture, textureSize, new Vector3(8, 8, 0), new Vector3(_playerPos.X, _playerPos.Y, 0), Color.White);

But it does not seem to works well...

2条回答
不美不萌又怎样
2楼-- · 2019-02-26 06:59

When you draw it, is it in the correct place?

I believe that the multiplication order is reversed, and that you shouldn't be transforming by the players position in the transform.

// shift centre to (0,0)
sprite.Transform = Matrix.Translation(-textureSize.Width / 2, -textureSize.Height / 2, 0);

// rotate about (0,0)
sprite.Transform *= Matrix.RotationZ(_angle); 


sprite.Draw(playerTexture, textureSize, Vector3.Zero,
            new Vector3(_playerPos.X, _playerPos.Y, 0), Color.White);

Edit

You could also use the Matrix.Transformation method to get the matrix in one step.

查看更多
Anthone
3楼-- · 2019-02-26 07:04

I've got the solution for you, it's a simple method that you can use everytime you want to draw a sprite. With this method you will be able to rotate the sprite with your desired rotation center.

public void drawSprite(Sprite sprite, Texture texture, Point dimension, Point rotationCenter, float rotationAngle, Point position)
    {
        sprite.Begin(SpriteFlags.AlphaBlend);

        //First draw the sprite in position 0,0 and set your desired rotationCenter (dimension.X and dimension.Y represent the pixel dimension of the texture)
        sprite.Draw(texture, new Rectangle(0, 0, dimension.X, dimension.Y), new Vector3(rotationCenter.X, rotationCenter.Y, 0), new Vector3(0, 0, 0), Color.White);

        //Then rotate the sprite and then translate it in your desired position
        sprite.Transform = Matrix.RotationZ(rotationAngle) * Matrix.Translation(position.X, position.Y, 0);

        sprite.End();   
    }
查看更多
登录 后发表回答