K
K
Kirill Nesmeyanov2016-08-02 17:38:30
Algorithms
Kirill Nesmeyanov, 2016-08-02 17:38:30

How to solve the problem of vector rotation towards given coordinates?

Good day. There is a simple algorithm for finding the angle of rotation of a vector in the direction of given coordinates:

// class Unit

lookTo(x, y) {
        return Math.atan2(y - this.position.y, x - this.position.x);
}

Everything is calculated correctly, but the problem is that you need to find the minimum angle between the current and final. For example, the rotation angle delta between 3.14 (to the left) and -3.14 (also to the left) is PI * 2, although in fact the zero delta between PI and -PI is the same rotation angle. Just like between PI and -2.14 delta 5.14, although in reality it is equal to 1.
Because of this problem, objects when rotated to given coordinates (in the case of animation, for example) make a full rotation around their axis, instead of a small rotation.
Google helped only in obtaining information in which direction to rotate the object:
ccw(x, y) {
    return this.position.x * y - this.position.y * x;
}

But somehow it does not help much in solving the problem.
Can you please suggest a solution to this problem or keywords in Google, with the help of which I can find a solution or an idea for solving the problem? Thank you.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
Mercury13, 2016-08-02
@SerafimArts

sin(x^y) = x×y / (|x|·|y|) (1st year of the institute, but easily deduced independently)
cos(x^y) = (xy) / (|x|·| y|) (school)
x, y — vectors in 2D
x^y — angle between vectors
x×y — skew product of vectors
(xy) — scalar product of vectors
|x| is the Euclidean length (modulo, 2-norm) of the vector
Hence x^y = atan2( (xy), x×y ).
Perhaps somewhere I missed the sign and I got not x ^ y, but y ^ x.

G
GreatRash, 2016-08-02
@GreatRash

How to calculate the rotation angle of an object?

A
abcd0x00, 2016-08-04
@abcd0x00

But somehow it does not help much in solving the problem.

So what's the problem?
The angle lies between 0 and Pi. If the angle turned out to be greater than Pi, you need to take the rest and change its sign.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question