Jump to content
  • Advertisement
Sign in to follow this  
fathom88

Silly Obvious Question On Angles

This topic is 4329 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi, I have a silly question on angles. I know it's just a trig formula but I can't seem to remember it. I have three points (x1,y1), (x2,y2), and (x3,y3). One point is always at the origin. Hence, I get two connected lines. For example, my points could be 0,3, 0,0, 3,0 and my resulting angle would be 90 degrees. If my points were 0,3, 0,0 0,-3, my angle would be 180 degrees. You get the idea. I seem to remember having to find the dot product 1st. Thanks. Sorry for asking such a lame question.

Share this post


Link to post
Share on other sites
Advertisement
First of all, substract the coordinates of the "origin" from the other two points, so now you actually have two vectors, (x1,y1) and (x2,y2). Now compute the dot product of the two vectors (x1*x2,y1*y2) and divide it by the length of each vector. The result is the cosine of the angle (this is a common definition of "angle", actually).

The same approach works for vectors in higher dimension.

#include <iostream>
#include <cmath>

const double Pi=std::atan(1.0)*4;

struct Vector2D {
double x,y;

Vector2D(double x, double y):x(x),y(y){
}

double dot(Vector2D const &v) const{
return x*v.x+y*v.y;
}

double length() const{
return std::sqrt(this->dot(*this));
}
};

struct Point2D {
double x,y;

Point2D(double x, double y):x(x),y(y){
}

Vector2D operator-(Point2D const &p) const{
return Vector2D(x-p.x,y-p.y);
}
};

int main(){
Point2D x1(0,3),x2(0,0),x3(3,0);
Vector2D v1=x1-x2;
Vector2D v2=x3-x2;

double cosine=v1.dot(v2)/(v1.length()*v2.length());
double angle=std::acos(cosine);
std::cout << angle*180/Pi << std::endl;
}

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!