AI is annoying, even when rudimentary

So the latest week I have been working on an rudimentary AI for our game(AI being short for Artificial Intelligence, meaning something made to mimic intelligence) although all it does is follow the player and attack him/her a certain distance away. This time I didn’t copy any code for the AI itself, although I needed a bit of help, AI is tricky even when it barely qualifies(the reason you don’t see better AI in games I suspect).

AIGameplay1 AIGameplay2 AIGameplay3

Some simple images showing the AI at work(the enemies are place-holders since I did not need the proper sprites for this).

The code works by creating a triangle between the player, an enemy and a third spot where the Y-axis meets the X-axis. You can then get everything from distance through the Pythagorean theorem to the angle through some trigonometry. And with the angle you can use the unit circle to get an direction that the program can use, therefore allowing an enemy to constantly move towards the players position. On the other hand these guys can’t realise that there is stuff in the way and might get stuck(can be solved with A* Pathfinding). Then there is a timer to limit how often the enemies can attack(the timer causes a delay between getting in range and the attack itself and disallows the enemy from just attacking every update, in which case it can get a bit silly really quickly).

The reason I wrote this code was so that the player would have a challenge, without any AI it’s fully possible to survive forever if you really tried to. The reason I chose this type of AI is because I lack the experience to do an more elaborate and elegant one and we simply didn’t need one better. One of my bigger hurdles was figuring out how to get the direction of the player. I figured I needed the unit circle but did not know how. Luckily I got help from a more seasoned programmer who showed me the atan2 function that takes the difference between y coordinates(known as delta y in math terms) and the difference between x coordinates(likewise known as delta x, delta meaning the Greek letter Δ) and gives you the angle. Then you can use sinus to get the y coordinate on the unit circle(in code written as sin(angle)). Then you can use cosine to get the x coordinate on the circle(written as cos(angle)) then you also need to invert the values or they will be running away from the player. Then I had a little trouble with getting the attacking to work properly. That solved itself when I checked the value on the timer and realising it was an int variable, meaning it didn’t accept the decimal values I were using to set it.