Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
480 views
in Technique[技术] by (71.8m points)

c# - Can't modify XNA Vector components

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...