Strange viewport issue

Sep 3, 2012 at 5:42 AM

Hello again,

Once again, I want to thank you for your very helpful tool, it's beyond amazing. I'm having a pretty strange issue, I took some time to straighten out some of my code and tidy a few things up and started experiencing an issue where calling a method to modify a viewport's location seems to be entirely ignored, but if I copy the code from the method and place it directly into the Update() method, it works fine.

Code in question...


private void keepCameraInBounds(xTile.Dimensions.Rectangle viewport)
            viewport.Location.X = Math.Max(0, viewport.X);
            viewport.Location.Y = Math.Max(0, viewport.Y);
            viewport.Location.X = Math.Min(
                map.DisplayWidth - viewport.Width, viewport.X);
            viewport.Location.Y = Math.Min(
                map.DisplayHeight - viewport.Height, viewport.Y);


this ^ for some reason does nothing when called as-is. But when placed into the Update() method...

public override void Update(GameTime gameTime, bool otherScreenHasFocus, bool coveredByOtherScreen)
            if (active)
                foreach (GameObject entity in entities.ToList())

                Camera1.Location += repositionCameraToObject(James, Camera1);

                Camera1.Location.X = Math.Max(0, Camera1.X);
                Camera1.Location.Y = Math.Max(0, Camera1.Y);
                Camera1.Location.X = Math.Min(
                    map.DisplayWidth - Camera1.Width, Camera1.X);
                Camera1.Location.Y = Math.Min(
                    map.DisplayHeight - Camera1.Height, Camera1.Y);

This works properly^. I'm utterly baffled as to why? Could you perhaps shed any light on the matter?

Thanks for taking the time to read this.


Sep 3, 2012 at 9:17 AM

Viewport is of type Rectangle which is a struct not a class. Hence, when you pass it as a parameter in keepCameraInBounds(...), a local copy will be made in the method's scope and any changes to it will be lost.

I can think of two solutions:

1) keep the Viewport variable as a class field and make keepCameraInBounds() parameterless.

2) Pass Viewport as a ref type so you can modify it within the method.

Hope that helps.

Sep 3, 2012 at 10:24 PM

Thank you very much, I figured it had to be relatively simple. I'm trying to structure things so that I can easily set up two viewports for splitscreen play, hence why I am trying to use a method that uses a rectangle parameter. Now that I understand why it's behaving that way better, I should be able to streamline this.

Thank you again for the help!