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
In stead of using new Vector2(...) to add 2 vectors, you can also use Vector2.UnitX:
ballSprite.Position.X += 1; // error
ballSprite.Position += Vector2.UnitX; // solution
It's very useful when you want to move directional. For example, if you want to move only horizontal:
Vector2 offset = new Vector2(2, 4);
ballsprite.Position += offset * Vector2.UnitX;
In this example, the value of speed.Y won't be added to the position of the sprite. Why?
offset == new Vector2(2, 4)
UnitX == new Vector2(1, 0)
--------------------------------
The above Vectors are multiplied
which results into the following
--------------------------------
offset * UnitX
(X: 2, Y: 4) * (X: 1, Y: 0)
(X: 2 * 1, ... Y: 4 * 0)
(X: 2, Y: 0) <-- result
Another advantage of doing it this way is readability. At least that is what I think. See it for yourself:
// multiple ways of incrementing ballspeeds X coordinate.
ballSprite.Position += Vector2.UnitX;
ballSprite.Position += new Vector2(1, 0);
ballSprite.Position = new Vector2(ballSprite.Position.X + 1, ballSprite.Position.Y);
Vector2 temp = ballSprite.Position;
temp.X++;
ballSprite.Position = temp;
Of course, there is also a Vector2.UnitY for vertical movement. Combine these static fields together with Vector2.Zero and Vector2.One, and you can write easy-to-understand code.
When I'm working with Vector2s and directions, I use the following table:
<--- X coordinate --->
-1 0 +1
| |
-Vector2.One | -Vector2.UnitY | -1
(X:-1, Y:-1) | (X: 0, Y:-1) |
| | ^
----------------+----------------+---------------- |
| |
-Vector2.UnitX | Vector2.Zero | +Vector2.UnitX 0 Y coordinate
(X:-1, Y: 0) | (X: 0, Y: 0) | (X:+1, Y: 0)
| | |
----------------+----------------+---------------- V
| |
| +Vector2.UnitY | +Vector2.One +1
| (X: 0, Y:+1) | (X:+1, Y:+1)
| |