0
\$\begingroup\$

I have the following code in a default Monogame Game project:

protected override void Update(GameTime gameTime)
{
    if (Keyboard.GetState().IsKeyDown(Keys.Left))
    {
        paddle.Box.Offset(-10, 0);
        Debug.WriteLine(paddle.Box);
    }
    if (Keyboard.GetState().IsKeyDown(Keys.Right))
    {
        paddle.Box.Offset(10, 0);
        Debug.WriteLine(paddle.Box);
    }
    base.Update(gameTime);
}

paddle.Box is a normal XNA Rectangle.

The problem is that the location of paddle.Box does not change after calling any of the Offset() overloads, as debugging confirms. If I just assign a new Rectangle, it works, but Offset (and Inflate(), FWIW) seems to be broken.

What am I doing wrong?

\$\endgroup\$
3
\$\begingroup\$

This is because Rectangle is a struct, which causes this to be a bit of tricky case. Since structs are passed and returned by value in C#, calling Paddle.Box will return a copy of Paddle.Box. After that, you call Offset on this fresh copy of Paddle.Box, but it's the copy, not the rectangle you were trying to change! The copy did change however, but it is discarded straight after that line. This is why calling '= new Rectangle...' does work.

You will encounter similar things with built-in Vectorn types.Assigning a new object ('... = new ...') is generally what you should do in these scenarios. (On a side-note, I believe that C# even prevents you from doing this on properties and member variables).

Edit: A more of an actual answer: if you want to use offset, you can do something like this instead:

protected override void Update(GameTime gameTime)
{
    if (Keyboard.GetState().IsKeyDown(Keys.Left))
    {
        Rectangle box = paddle.Box;
        box.Offset(-10, 0);
        paddle.Box = box;
        Debug.WriteLine(paddle.Box);
    }
    if (Keyboard.GetState().IsKeyDown(Keys.Right))
    {
        Rectangle box = paddle.Box;
        box.Offset(10, 0);
        paddle.Box = box;
        Debug.WriteLine(paddle.Box);
    }
    base.Update(gameTime);
}
|improve this answer|||||
\$\endgroup\$
  • \$\begingroup\$ Or more succinctly: paddle.Box = paddle.Box.Offset(10, 0); \$\endgroup\$ – JonBee Dec 14 '15 at 16:42
  • \$\begingroup\$ That won't work unfortunately. Offset does not return a new rectangle. \$\endgroup\$ – Athos vk Dec 14 '15 at 21:43
  • \$\begingroup\$ Ah yes, correct. Sorry. \$\endgroup\$ – JonBee Dec 16 '15 at 15:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.