We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hi,
In this situation, I am trying to calculate the angle between a stick and a ball. However, first off, the angle is only between 0 and 180 degrees when using a PVector for the points and the angleBetween() function. Secondly, the degrees don't correspond to my expectations, since 180 degrees is more like northwest than straight, and zero degrees is southeast etc.
Calculating a precise angle is important because I am creating this pool game, and I am using the angle between the stick and pool ball to calculate the x and y components of velocity using cos and sin respectively. I've been trying to do a myriad of things but it just doesn't work.
This is a slightly modified version of the "VectorMath" example provided on Porcessing's website. While this isn't my pool program, it uses the exact same processes as this example. So the fixes to this program to get it to work will be directly applicable to my code. What can be done to get the angles to correspond properly to conventional direction? (180 degree is west, 90 is south for processing... etc. ), and just in general, how can I get cos and sin in this situation to get the exact results that would be needed in a pool program, when calculating the x component with cos and y component with sin? Would atan2() offer a better solution?
float angle;
void setup() {
size(640,360);
}
void draw() {
background(0);
// A vector that points to the mouse location
PVector mouse = new PVector(mouseX,mouseY);
// A vector that points to the center of the window
PVector center = new PVector(width/2,height/2);
// Subtract center from mouse which results in a vector that points from center to mouse
mouse.sub(center);
// Normalize the vector
mouse.normalize();
// Multiply its length by 150 (Scaling its length)
mouse.mult(150);
angle = PVector.angleBetween(center,mouse);
println(degrees(angle));
translate(width/2,height/2);
// Draw the resulting vector
stroke(255);
strokeWeight(4);
line(0,0,mouse.x,mouse.y);
}
Thank you!
Answers
@MyName -- Don't use
mouse.angleBetween()
. Instead usemouse.heading()
. Rather than returning two ranges 0-180, this will return 0-180 (clockwise) or negative 0-180 (counter-clockwise). This will also correct your offset error.You can test simple heading output by adding the heading to your printout line:
If you wish to convert your negative headings to 181-360, then simple say "if negative, invert and add 180." Now you are getting 0-360.
@jeremydouglass Thank you! Your a lifesaver!!