C# directx sprite origin

六月ゝ 毕业季﹏ 提交于 2019-12-31 03:32:29

问题


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...


回答1:


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.




回答2:


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();   
    }


来源:https://stackoverflow.com/questions/3390437/c-sharp-directx-sprite-origin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!