2
\$\begingroup\$

I need the rendered dimensions of a sprite, I'm calling Draw in the class below:

public class Ship
{
    public Ship(Texture2D texture)
    {
        Width = texture.Width;
        Height = texture.Height;

        Texture = texture;
    }

    public int Width { get; set; }

    public int Height { get; set; }

    public float Scale { get; set; }

    public Vector2 Position { get; set; }
    
    public Texture2D Texture { get; }

    public Rectangle Rectangle => new Rectangle((int)Position.X, (int) Position.Y, Width, Height);

    public void Draw(SpriteBatch batch)
    {
        var origin = new Vector2(Texture.Width / 2, Texture.Height / 2);
        var scale = new Vector2(Scale, Scale);
        var rotation = GetRotationInRadians();

        batch.Draw(Texture, Position, null, Color.White,
            rotation,
            origin,
            scale, 
            SpriteEffects.None, 0f);
    }
}

The problem is Width and Height are based off the source (see the constructor) Texture size, so after drawing they are not actual dimensions. Is there away to determine the scaled sprite size?

Side note: I'm using these dimension to detect if an sprite was clicked on by the mouse. Maybe there is a better way to detect clicks?

\$\endgroup\$
3
  • \$\begingroup\$ It's actually not the most trivial thing to do to be honest. Quite some time ago I solved this problem in the MonoGame.Extended Sprite class which you're welcome to borrow the code from. \$\endgroup\$ Commented Jul 3, 2020 at 22:27
  • \$\begingroup\$ @craftworkgames I actually discovered that (your?) library last night, its saving me a ton of time, thanks! \$\endgroup\$
    – mxmissile
    Commented Jul 4, 2020 at 4:36
  • \$\begingroup\$ It's unclear to me how Texture.Width * Scale (and likewise for height) differs from what you need in this situation. Can you clarify what other effects are modifying the rendered size of your asset? It doesn't look like you have 3D perspective to contend with here... \$\endgroup\$
    – DMGregory
    Commented Jul 7, 2020 at 21:47

1 Answer 1

1
\$\begingroup\$

I'm now using Monogame.Extended, Camera and Sprite classes to detect mouse collision:

public RectangleF GetBoundingRectangle()
{
    return Sprite.GetBoundingRectangle(_transform);
}
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .