Saturday, September 26, 2015

c# - In Monogame, why does Rectangle.Offset not work?


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?



Answer



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);
}

No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...