Convert between vectors and angles

Is there an equivalent to processings’s Vector.heading?

https://processing.org/reference/PVector_heading_.html

which calculates the angle of a vector? (and also a way to create a vector from an angle)? Basically the equivalent of processing vector.fromAngle?

https://processing.org/reference/PVector_fromAngle_.html

I am still using ofVec3f, and I see: getRotatedRad() but its not clear to me if that is the same.

mike

hi,
for the heading you can use ofVec2f::angle(…) although you will need to provide a reference vector, which I guess is ofVec2f(1,0)
so you can do something like

ofVec2f v1(1,0);//the vector from which you want to get its heading
float angle = v1.angle({0,1}); // angle is 90 

The last line would be equivalent to

float angle = v1.angle(ofVec2f(0,1));

but you write less using the curly brackets as an initializer list. :slight_smile:

For the PVector.fromAngle equivalent you can use

ofVec2f v = ofVec2f(1,0).getRotated(0.001);// pass an angle

https://openframeworks.cc//documentation/math/ofVec2f/#!show_getRotated
hope this helps.

2 Likes

Hi, will glm::vec2 replace ofVec2f?

Hi @hamoid, I think that the intention is to eventually deprecate ofVec*f and then remove it in favor of glm. When this happens none of the ofVec*f stuff will work.

To remove some mystery:


heading is a synonym for atan2. Maybe that’s the reason why there is no such function.

float angle = std::atan2(y, x);

or

float angle = glm::atan2(y, x);

fromAngle(a) is a call to cosf() and sinf() away.

ofVec2f myvec(cosf(a), sinf(a));

or

glm::vec2 myvec(cosf(a), sinf(a));

I think it does become more readable when using heading and fromAngle

@roymacdonald I was wondering if it’s better to avoid ofVec examples then?

1 Like

@hamoid, certainly it would be better to avoid ofVec examples, but the original question was about ofVec and not glm. As ofVec is still there I think that it is still valid to answer on how to use it.
Thanks for the glm version to this answer. :smiley:
cheers