I have a class called Sprite, and ballSprite is an instance of that class. Sprite has a Vector2 property called Position.
I'm trying to increment the Vector's X component like so:
ballSprite.Position.X++;
but it causes this error:
Cannot modify the return value of 'WindowsGame1.Sprite.Position' because it is not a variable
Is it not possible to set components like this? The tooltip for the X and Y fields says "Get or set ..." so I can't see why this isn't working.
The problem is that ballSprite.Position
returns a struct, so when you access it, it creates a copy of it due to the value semantics. ++ attempts to modify that value, but it'll be modifying a temporary copy - not the actual struct stored in your Sprite.
You have to take the value from reading the Position and put it into a local variable, change that local variable, and then assign the local variable back into Position, or use some other, similar way of doing it (maybe hiding it as some IncrementX
method).
Vector2D v;
v = ballSprite.Position;
v.X++;
ballSprite.Position = v;
Another, more generic solution, might be to add another Vector2 to your Position. The + operator is overloaded, so you could create a new vector with the change you want, and then add that to the vector instead of updating the indiviudal components one at a time.
You can do
Position = new Vector2(Position.X + 1, Position.Y );
or
Position += new Vector2( 1.0f, 0.0f );
or
Position.X += 1.0f;
An easy alternative is this:
instead of: sprite.Position.X = 10;
use: sprite.Position = new Vector2(10, sprite.Position.Y);
instead of: sprite.Position.Y = 10;
use: sprite.Position = new Vector2(sprite.Position.X, 10);
instead of: sprite.Position.X += 10;
use: sprite.Position += new Vector2(0, 10);
instead of: sprite.Position.Y += 10;
use: sprite.Position += new Vector2(10, 0);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With