Lasonic
Lasonic

Reputation: 901

How to check if two CGVectors are equal in Objective-C?

I have two CGVectors:

CGVector vector1 = CGVectorMake(1,2);
CGVector vector2 = CGVectorMake(1,2);

How can I check if vector1 is equal to vector2?

Upvotes: 0

Views: 256

Answers (2)

coryknapp
coryknapp

Reputation: 69

if( (vector1.dx == vector2.dx)&&(vector1.dy == vector2.dy) )

but be careful when comparing floats, because the comparison may be false because of rounding errors, so you may want to check to see if the differance of each component is very close to zero instead.

if( (abs(vector1.dx - vector2.dx) < verysmallnumber) && (abs(vector1.dy - vector2.dy) < verysmallnumber) )

where abs is an absolute value function

Upvotes: 2

matt
matt

Reputation: 535491

It's not an easy question. What do you think "equal" should mean here?

In one sense, they are equal if their dx values are equal and their dy values are equal.

But in another sense, perhaps what you want to know is whether the ratio between their dx and dy values are equal, because this is, after all, supposed to be a vector - that is, perhaps CGVectorMake(1,2) and CGVectorMake(2,4) are, in a very real sense, the same vector, because qua vector they point the same way.

In other words, in some contexts, both magnitude and direction must be equal, but in other contexts, direction alone must be equal. You need to make a decision about this.

There are some useful CGVector utilities here: https://github.com/KoboldKit/KoboldKit/blob/master/KoboldKit/KoboldKitExternal/External/CGPointExtension/CGVectorExtension.m

Upvotes: 0

Related Questions