XNA Creators Club Online
Page 1 of 1 (3 items)
Sort Posts: Previous Next

Can't set Vector2

Last post 4/6/2009 8:31 PM by Rizman. 2 replies.
  • 4/6/2009 8:21 PM

    Can't set Vector2

    Hello,

    I have a question regarding Vector2. When I use Vector2 as a property, it wont let me set its X variable. Anyone know why that is? Below is the code I'm trying to get working.

    This is the property:

            /// <summary>
            /// Get and set the position of the paddle.
            /// </summary>
            public Vector2 Position
            {
                get
                {
                    return position;
                }
                set
                {
                    this.position = value;
                }
            }

    This is where I'm trying to set a different value to the property:

            private void CheckPaddleScreenCollisions()
            {
                if (paddle.Position.X <= 0)
                {
                    paddle.Position.X = 0;
                }

                if (paddle.Position.X >= gameResources.GameScreenWidth)
                {
                    paddle.Position.X = gameResources.GameScreenWidth;
                }
            }

    It won't let me do this the compile error I get is: Cannot modify the return value of CrazyBlocks.Logic.Paddle.Position because it is not a variable.

    I don't really understand how it is not a variable? If I use position.X = someValue in the Paddle class, it will work (I guess because I'm referring to the class level variable and not the property?

    If anyone can give me any help on how to fix this problem, or explain to me why its not working, that would be greatly appreciated. Thanks.

  • 4/6/2009 8:28 PM In reply to

    Re: Can't set Vector2

    If were referring to the class level variable, you would have to reference position (not capitalized).  By referencing Position, you are calling the method.

    Is gameResources.GameScreenWidth a value of type float?
    Try running the code omitting

    if (paddle.Position.X >= gameResources.GameScreenWidth)
    {
    paddle.Position.X = gameResources.GameScreenWidth;
    }

    to see if it works. 

  • 4/6/2009 8:31 PM In reply to

    Re: Can't set Vector2

    Vector2 is a value type. Therefore, when using Vector2 as a property, the setter will only return a copy of the Vector2 you want to modify. Every change made to it will directly be discarded, hence the compiler will not allow you to modify properties of a value type through a Property. You will have to set the Vector2 this way:

    paddle.Position = new Vector2(x, y);

    There are a lot of threads on the forums which explain the difference between reference types and value types. Just search for it.

Page 1 of 1 (3 items) Previous Next