0

I want to create a struct which is like a CGPoint, but with 3 coordinates instead of 2.

I create it in the following way:

typedef struct {CGFloat x;CGFloat y;CGFloat z;} CG3Vector;

CG_INLINE CG3Vector CG3VectorMake(CGFloat x, CGFloat y, CGFloat z)
{
  CG3Vector p; p.x = x; p.y = y; p.z = z; return p;
}

It works fine. But I now want to improve this struct so that it has the constants like for CGPoint: CGPointZero

Also what is the way to introduce the limits for particular components of the struct, like it is for the CGSize, where components are never lower than 0?

Thanks.

BartoNaz
  • 2,743
  • 2
  • 26
  • 42

1 Answers1

2

You could create constants like this:

const CG3Vector CG3VectorZero = { 0, 0, 0 };

If you want limits, I suppose you can do some checking like this:

CG_INLINE CG3Vector CG3VectorMake(CGFloat x, CGFloat y, CGFloat z)
{
    // normalize the values
    x = fmod(x, 360);
    y = fmod(y, 360);
    z = fmod(z, 360);

    x = (x < 0) ? 360 + x : x;
    y = (y < 0) ? 360 + y : y;
    z = (z < 0) ? 360 + z : z;

    return (CG3Vector) { x, y, z };
}
Richard J. Ross III
  • 55,009
  • 24
  • 135
  • 201
  • 1
    Probably worthwhile to put `const` on the zero struct. – jscs Apr 04 '12 at 16:54
  • Thanks, sounds really logical. Don't understand why I haven't come up with this idea myself. Actually I can put any code between curly brackets, right? For example changing to some default value if it exceeds the limit. But I have another question then. If I want a struct representing a vector through 3 angles in degrees that means x=(0;360), I can put the transformation of the angle value to a new one inside the limit. But how to do it for a setter of a single component like in this example: CG3Vector a=CG3VectorMake(120,70,80); a.z=-20; //Should be transformed to 360-20=340 – BartoNaz Apr 04 '12 at 18:58
  • Thanks. But the line const CG3Vector CG3VectorZero = { 0, 0, 0 }; doesn't work. I get the linker error when compiling. I think that some different syntax must be used for this purpose. – BartoNaz Apr 04 '12 at 20:05
  • and also the limiting method works when creating the CG3Vector variable, but it doesn't apply any limit when setting only one component explicitly: vector.z=-20; Then -20 stays -20, not 340. – BartoNaz Apr 04 '12 at 20:11
  • @BartoNaz that is a limitation of C-structs, what you are looking for is a C++ struct, or an Objective-C object. As far as the CGVectorZero is concerned, you may want to look into extern variables, as described here: http://stackoverflow.com/questions/2190919/mixing-extern-and-const – Richard J. Ross III Apr 04 '12 at 20:13