Scale texture to fit a circular body

100 views Asked by At

I have the following code in my MonoGame/Farseer Physics project:

_ball = BodyFactory.CreateCircle(World, 1f, 400f);
_ball.BodyType = BodyType.Dynamic;
_ballSprite = new Sprite(ScreenManager.Content.Load<Texture2D>("Common/ball"));

In my Draw method:

ScreenManager.SpriteBatch.Draw(_ballSprite.Texture, ConvertUnits.ToDisplayUnits(_ball.Position), null, Color.White, _ball.Rotation, _ballSprite.Origin, 1f, SpriteEffects.None, 0f);

The problem is that my texture is 120px by 120px, but when it renders on screen, the _ball body is larger than it in size. What can I do to resize the texture to fit exactly the width and height of the _ball body?

1

There are 1 answers

0
Alexandru On

I think I have solved this mystery at last. I needed to compute the scale (_ballTextureScale that is, which was the part that I was stuck on):

var radius = 1f;
_ball = BodyFactory.CreateCircle(World, radius, 400f);
_ball.BodyType = BodyType.Dynamic;
var rectangleTexture = ScreenManager.Content.Load<Texture2D>("Common/ball");
_ballTextureScale = ConvertUnits.ToDisplayUnits(radius * 2) / rectangleTexture.Width;

This converts the radius * 2 (total width of the circle) to display units which it seems the rectangle texture is already in. Then when I go to draw the body, I just needed to make use of this _ballTextureScale property:

ScreenManager.SpriteBatch.Draw(_ballSprite.Texture, ConvertUnits.ToDisplayUnits(_ball.Position), null, Color.White, _ball.Rotation, _ballSprite.Origin, _ballTextureScale, SpriteEffects.None, 0f);

If this is an incorrect approach, I am all ears to a better method for accomplishing this task, however it seems to work very well for my needs.