C# directx sprite origin

前端 未结 2 1185
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-22 01:05

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 i

相关标签:
2条回答
  • 2021-01-22 01:50

    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();   
        }
    
    0 讨论(0)
  • 2021-01-22 01:51

    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.

    0 讨论(0)
提交回复
热议问题