How can I get if an object is facing another in degrees if one has 0 and the other one has 360?

56 Views Asked by At

I'm developing a model for the collision for two ships.

First, I have the angle that the first ship would be pointing if it was to directly point at the second ship. I'll call the angle between the two ships $\phi$.

Next, I have the measured angle of the first ship's trajectory, which I'll call $\theta$.

The problem is, I check if $\theta$ is greater or less than $45^{\circ}$ from $\phi$. This is fine if the $\phi$ is, say, $180^{\circ}$, and $\theta$ is, say, $170^{\circ}$. This is fine until I hit the problem of $0^{\circ}$. If $\phi$ is $10^{\circ}$, and $\theta$ is $357^{\circ}$, it would still be within that $45^{\circ}$ radius. However, it would not be detected.

What is an easy/simple way to solve it so that if $\phi = 10^{\circ}$ and $ \theta = 357^{\circ}$ would still be detected as within the $45^{\circ}$ radius?

2

There are 2 best solutions below

17
On BEST ANSWER

If your angles are within $[0,360]$, the cyclic distance is given by $$d_\text{cyc}(\alpha_1,\alpha_2) = \min (|\alpha_1 - \alpha_2|, 360^\circ - |\alpha_1 - \alpha_2|)$$ You want to check if $d_\text{cyc}(\alpha_1, \alpha) \le 45^\circ$.

Here's a step-by-step evaluation of $d_\text{cyc}(10,357)$:

$$\min(|10-357|,||10-357|-360|) = \min(|-347|,360 - |-347|) = \min(347, 360-347) = \min(347,13) = 13$$

3
On

A solution to the problem would be to calculate all angles modulo $360$. That is, instead of working with the angles itself you always reduce them to their remainder when dividing by $360$. For instance, $$357 \equiv -3 \,(\mathrm{mod}\, 360)$$ In C or C++, for example, this action is done by the % operator (assuming this is for a programming context).

Edit: The "three line equal sign" is just a symbol saying "is equivalent to". You don't need to worry about that though. What the modulo operation does is very simple (as long as you know integer division!).

For example, the hours of the day are calculated modulo 24. Otherwise, we'd say that we're (roughly) at hour 17,550,000 C.E. so instead, after every 24 hour time period we start counting over again (as far as hours go).

Mathematically, this means doing integer division, but discarding everything except the remainder.

Having said this, what you actually need is more complicated (just a bit), because in most (programming) languages, $357$ modulo $360$ is still $357$. What you actually need is not just the remainder, but the smallest possible remainder in absolute value. Essentially, this is AlexR's function. Also, modulo only works for integers, so all in all my solution is quite limited. I hope you gained some understanding anyway.