I’m trying to program an agent to avoid barriers that it hits. I have access to the heading of the agent as it meets the barrier, which are recorded in positive and negative degrees up to 180 (as shown here, with example headings of agent). I also have access to the coordinate points of the barriers, and thus can also calculate the ‘heading’ of the barrier as well.
My aim is to calculate the angles in which the barrier and agent meet, so that I know how much to change the heading of the agent so that it moves along the barrier in the direction of the largest supplementary angle, like shown here - the new heading is obtained by adding sometimes negative or positive numbers on to the original heading.
I’ve currently been using the inverse tan of the start and end coordinates of the barrier (to get its heading and get the theta angle), getting the theta angle of the agent meeting the barrier, and then calculating the angle that needs to be added to the heading for the agent to start travelling along the barrier, however, obviously since this is being implemented in a program, I can’t seem to come up with one universal maths formula which can account for all the combinations of headings of the barrier and agent meeting? And was, therefore, wondering if anyone had any advice on how to deal with these calculations when using headings that are on a positive/negative scale of 180 degrees?
atan2(y,x)instead ofatan(y/x)to calculate the angles. Most computer languages have it, and it gets rid of a lot of problems. Secondly, if $a$ is your heading, and $b$ is the barrier's heading (in either direction), then I think the heading change you need is $(b-a+360+90)%180 - 90$. The addition of $360$ is to make sure it becomes an equivalent positive angle for the rest to work, and the rest then cuts it down by multiples of $180$ degrees to the range $[-90,90)$, so it is the least change needed to follow the barrier. – Jaap Scherphuis Aug 12 '17 at 19:05atan(y1-y2,x1-x2). The signs of those two arguments makes sure that atan2 returns an angle in the right quadrant. It uses the convention that 0 radians is along the x-axis (i.e. east) and increasing the angle turns anti-clockwise. To convert this angle $a$ to a heading in degrees (i.e. 0=north, positive is clockwise), I think the formula $(360-a180/\pi + 90+180)%360-180$ works. The first $360-a180/\pi$ changes $a$ to degrees and flips the direction, the $+90$ shifts it to make 0=North, and the rest cuts it down to the range $[-180,180)$ by multiples of $360$ degrees. – Jaap Scherphuis Aug 13 '17 at 21:22