I want to rotate a 2-D image in the direction to where I click, to all quadrants. To do this, I need to calculate the angle relative to the object. I need 2 vectors.
I have tried to do this: one vector would be the "click" point, the other would be an "imaginary" horizontal vector departing from the object with the same X as the "click" point but with the Y of the object. That would serve as the second vector to where I would calculate the angle from the object.
I have made a test program with 3 objects to see if I can get those angles. b6
is the object, b7
is a "click point" approximately 45º from b6
, and b8
is another "click point" approximately 135º from b6
.
This is the code I'm using:
#define PI 3.14159265
int main(int argc, char** argv) {
Button b6(100,100);
Button b7(150,50);
Button b8(150,150);
int dot1 = b7.getX() * b7.getX() + b7.getY() * b6.getY();
int det1 = b7.getX() * b6.getY() - b7.getY() * b7.getX();
double angle1 = atan2(det1,dot1)* 180/PI;
int dot2 = b8.getX() * b8.getX() + b8.getY() * b6.getY();
int det2 = b8.getX() * b6.getY() - b8.getY() * b8.getX();
double angle2 = atan2(det2,dot2)* 180/PI;
}
The results don't correspond to the actual position of b7
and b8
. angle1
is 15.25, and angle2
is -11.31.
I'm a novice in this, and I don't know if what I'm doing is a total mess. Can anyone help me compute these angles?
As Sam already wrote in comment – not clear, what OP wants to achieve with dot
and det
. It sounds a bit like dot product but it's not necessary here.
A vector from one point to the other is simply the subtraction of points (point vectors).
Subtraction of point vectors is simply the subtraction of vector components.
Using the components of these vectors in atan2()
provides the slope of these vectors:
#include <iostream>
#include <cmath>
const double Pi = 3.14159265;
struct Vec2 {
const double x, y;
Vec2(double x, double y): x(x), y(y) { }
~Vec2() = default;
Vec2(const Vec2&) = default;
Vec2& operator=(const Vec2&) = delete;
};
int main()
{
const Vec2 b6(100, 100);
const Vec2 b7(150, 50);
const Vec2 b8(150, 150);
// vector b6->b7
const Vec2 b67(b7.x - b6.x, b7.y - b6.y);
// vector b6->b8
const Vec2 b68(b8.x - b6.x, b8.y - b6.y);
// slope b67
const double angle1 = atan2(b67.y, b67.x) * 180 / Pi;
// slope b68
const double angle2 = atan2(b68.y, b68.x) * 180 / Pi;
// output
std::cout
<< "angle1: " << angle1 << '\n'
<< "angle2: " << angle2 << '\n';
// done
return 0;
}
Output:
angle1: -45
angle2: 45
A Sketch of the Vec2
instances: