I’m making a vector graphics game in XNA. I’ve designed a Line class to rotate around a central point to help draw specific shapes. In order to maintain a single point of truth, is there a way to pass a reference to the center of the shape to all of the lines I create, so that updating the center’s position will also update the lines’ positions? I thought something like this would work:
class Line
{
private Vector2 start;
private double length;
private double angle;
public Line(ref Vector2 start, double length, double angle){
this.start = start;
this.length = length;
this.angle = angle;
}
}
class Obj
{
private Vector2 center;
private Line[] lines;
public Obj(){
center = new Vector2(50,50);
lines = new Lines[5];
for (int i = 0; i < 5; i++){
lines[i] = new Line(ref center,30, (i/5 * 2 * Math.PI));
}
}
}
but the lines do not update when I move the center. What am I doing wrong?
Although the
structis correctly passed by reference toLine, when you assign it internally:You are actually taking a copy of the
struct.If you ever find yourself needing reference type semantics of
structbeyond passing it to a single method then you likely need to reconsider usingclass.You can either re-implement the type in a class or wrap the
Vector2in a class and use that:Be aware that you are still working against a copy, but if you share the class you’ll all be working on the same copy.
Personally, I would avoid the wrapper and make my own class for representing “centre”. This is supported by the largely accepted idea that
structtypes should be immutable, but you seem to need to mutate the values to keep the representation true.This only lets you share the data, it doesn’t actually notify the lines that the centre has changed. For that you would need some sort of event.