I try to work on a Force based 2D ship game.
I have Forces, that a stored in a Dictionary, for ‘Jets’ on a ship. So I just have to say the name, the amplitude and let the engine do the acceleration/rotation.
For that I have to rotate the force into the local coordinates of the ship, before I can apply it, but instead only rotating the new force, it also rotates the force stored in the Dictionary. What causes the Force to spin around.
Force f1 = new Force();
f1 = Player.JetsDict["RearRight"];
f1.Position = Vector2.Transform(f1.Position, Matrix.CreateRotationZ(Player.Rotation));
while this code dose not change the instance stored in the dictionary (but I don’t want to use it, as its longer, and I got many forces to handle):
Force f1 = new Force();
f1.Position = Player.JetsDict["RearRight"].Position;
f1.Vector = Player.JetsDict["RearRight"].Vector;
f1.Position = Vector2.Transform(f1.Position, Matrix.CreateRotationZ(Player.Rotation));
Why?
Greg the Mad
Since
Forceis defined as a class (class Force), when you get the copy out of the Dictionary, you’re just getting a reference to a Force instance – the same Force instance that’s stored in the Dictionary. Making a change to members within that reference will be reflected everywhere in your program that uses it.The only option here is to make a new instance. This is what you’re doing in the second case.
However, if the Force is nothing but a Position and a Vector, I would consider making this a struct instead of a class. Structs are always copied by value instead of by reference, which would cause your original code to work the way you expect. If there is more to it, however, a class may still be the best option, in which case the second option is the best potential solution.
You could shorten it, though, by adding a new constructor that took a Force as an argument, and copied the Position + Vecotr. That would let you write: