Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't modify XNA Vector components

Tags:

c#

xna

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.

like image 259
Matthew H Avatar asked Mar 28 '10 21:03

Matthew H


3 Answers

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.

like image 172
Michael Madsen Avatar answered Oct 31 '22 09:10

Michael Madsen


You can do

 Position = new Vector2(Position.X + 1, Position.Y );

or

 Position += new Vector2( 1.0f, 0.0f );

or

 Position.X += 1.0f;
like image 20
Maynza Avatar answered Oct 31 '22 08:10

Maynza


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

like image 38
Lincoln Reiss Avatar answered Oct 31 '22 09:10

Lincoln Reiss