We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hi all, I am having some trouble with this:
I am using the PVector class to define some moving elements in a sketch.
So an entity has:
PVector pos; //position
PVector vel; //velocity
PVector tar; //target position
PVector towardsTar; //direction from element to target
Basic calculations:
float heading = vel.heading(); //ok, I have the heading angle of my element
towardsTar.set(tar);
towardsTar.sub(pos); // pos + towardsTar = tar --> towardsTar = tar - pos so I have my desired direction
towardsTar.normalize();
Now I have these two vectors (heading and towardsTar) and I want to find the angle between them, inorder to know if the element has to turn clockwise or counterclockwise inorder to head towards the target.
If I use this:
float angle = PVector.angleBetween(heading, towardsTar);
I will get the right angle, but it will always be positive.
So I will not know if the entity has to turn the one or the other way.
I have managed to make a workaround for that, but my algorithm is not so good...
Is there a good and elegant way to do that? Perhaps something I have missed from the PVector class?
Please do not refer me to a library, I am just looking for a simple way to do that by defining a small function at most.
Thanks in advance, Kostas
Answers
Just check whether the dot product of towardsTar and the normal of heading is negative or positive:
And a small example sketch:
This would definately make sense, but unfortunately the PVector.angleBetween() function only returns positive values, and (I forgot to mention) also only values from 0 to PI. So if the anlge between them is 3*PI/2, then it will return PI/2 (instead of -PI/2). I dont know why that is, but this is my problem, actually... thanks anyway
Yeah, sorry - should test code before posting. :D I corrected my answer.
Very similar to the other solution but created a small function that accepts a heading and a target vector and calculates the 'nearest' side. Anyway play with the sketch it soon becomes obvious how it works.
I still have to figure out how (why) your answers work... even though they do! Thanks alot, guys!
@quark: Haha nice! :D
Even shorter:
Well, made my own shorter version too: >:)
And another 1: *-:)
Okay - the last one - I promise! :D
Additionally one little reference that explains the dot product quite well.
Sorry to bother again, but this doesn't work... Perhaps I am too tired to see why, but It has been a pain for sometime, so I thought to share once more...
ok, I found out what was wrong...
I was comparing vel to tar, while I should be coparing vel to towardsTar (tar-pos)...
fixed it for now... thanks for all the help again