Can't modify XNA Vector components

前端 未结 4 1069
花落未央
花落未央 2020-12-20 16:57

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 c

4条回答
  •  死守一世寂寞
    2020-12-20 17:23

    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.

提交回复
热议问题