Search code examples
c#monogame

C# cannot convert from 'float' to 'Microsoft.Xna.Framework.Point'


I'm Trying to make a rougelike in C# using Monogame and RogueSharp.

here is some of the code I have in Draw()

protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            _spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend);

            int sizeOfSprites = 64;
            float scale = .25f;
            foreach (Cell cell in _map.GetAllCells())
            {
            // error in the line below    
            Microsoft.Xna.Framework.Rectangle position = new Microsoft.Xna.Framework.Rectangle(cell.X * sizeOfSprites * scale, cell.Y * sizeOfSprites * scale);
                if (cell.IsWalkable)
                {
                    _spriteBatch.Draw(floorSprite, position, null, Color.White, 0f, new Vector2(scale, scale), 0.0f, 0f);
                }
                else
                {
                    _spriteBatch.Draw(wallSprite, position, null, Color.White, 0f, new Vector2(scale, scale), 0.0f, 0f);
                }
            }

            _spriteBatch.End();

            base.Draw(gameTime);
        }

Returns:

Argument 2: cannot convert from 'float' to 'Microsoft.Xna.Framework.Point'

Argument 1: cannot convert from 'float' to 'Microsoft.Xna.Framework.Point'


Solution

  • The Rectangle constructor either takes (Point location, Point size) or (Int32 x, Int32 y, Int32 width, Int32 height) but not (Float, Float) (what would that even mean?) - See docs.

    So, two issues here:

    • You need four values to uniquely specify a rectangle in 2D space, not two. Rectangle does that using X and Y of the top-left corner as well as width and height.
    • The Rectangle constructor expects those values as integers and not floats.

    Looking at your code, I'm guessing that you want to create a rectangle that has sizeOfSprites * scale as length of both sides, in which case you'd need to specify the size as follows:

    int scaledSize = (int)(sizeOfSprites * scale);
    Microsoft.Xna.Framework.Rectangle position = new Microsoft.Xna.Framework.Rectangle(
      cell.X * scaledSize,
      cell.Y * scaledSize,
      scaledSize,
      scaledSize
    );
    

    I noticed Cell also has integer coordinates and you only use floats for the 0.25 part, so you can simply store the size as integer too. If you don't intend to later make these variables dynamic, the fastest way would be to use const int scaledSize = 16; in the first place.