[5SD033]Potato Pirates, Week Two – How to code an AI

So this past week I spent most of the time having a cold while also trying to wrap my head around a trigonometric problem of mine. As the AI  needed to turn to fly towards the player, I took it upon myself to write the code that would let it do just that. I let the player plane be my guinea pig while trying this.

bloggbild
The function used to find the angle between the player and mouse pointer

I had gotten it working to use the setRotation function in SFML to have the player plane turn itself towards the mouses position. It worked roughly the same way that the AIs field vision from last weeks post did, but instead of the result being a distance, this time it was an angle. First I got the difference in X and Y positions of the player and mouse pointer. Then by dividing the two values I got the tangent of the angle and with the atan function of the cmath library I got the rough angle. bloggbild2

There was however a problem with my code, the way I had coded it it now caused the angle to be  0° while the mouse and planehad the same Y position and the angle became 90° while the mouse and plane were on the same X position.(See picture on the right)

I did get around this by a large amount of If statements that changed the angle depending on if the mouse pointers X and Y values where greater or less than the planes X and Y values. This only brought out a new problem that I still haven’t found a solution to. The plane will turn to face the mouse pointer but it will not turn around the top of the Y axis. Picture the mouse pointer positioned in the red square in the image to the right and the plane turned along the green line. The plane would in this case not turn the 20° degrees to the left, instead it would turn the 340° to the right. I sat for some time trying to find a solution to the problem, I even tried rebuilding the code from the start which did not work. I had to leave the code the way it was as it had to implemented, and we had several things left to complete before the Alpha.

If anyone could find a solution to this; your help would be very welcome.

About Bengt Hagnelius

2015 Programming