Artificial Intelligence can be implemented in many different ways, but today I will be covering an form of AI that will allow you to calculate distinctions between sets of objects, which can be useful for whether or not an NPC is given permission to shoot an enemy or the player.
The geometry we will be covering is largely consistent of Analytical geometry following the basic principles of the Cartesian coordinate system. We will modify the 2D Distance Geometrical Distance formula to calculate the distances of 3D Objects later on in the tutorial …
Our first step will be to write our basic C ++ code. Then our next step will be to implement the formulas into our code and then calculate the distances and preform the set routines. Please note: I am not covering ways to retrieve the X, Y, Z values of your game objects so that is up to you.
First, to understand the code itself let us take an look at the geometric 2D Distance formula …
distance = DeltaX2 – DeltaX1 sqrd + DeltaY2 – DeltaY1 sqrd SQRT
If you read the formula, you should understand the code I wrote with no problem at all.
Demonstration Code: (* Full Source *)
// ** NOTE: You need to include iostream and math.h, EzineArticles removs include syntax.
long calculate_2D (long x1, long x2, long y1, long y2);
long sqrd (value);
using namespace std;
int main ()
Using the basic primitives of the 2D Distance formula I implement the X, Y variables and calculation routines.
OK, so we could write some IF statements to check whether or not our player is in the X, Y range of our NPC. And if so, we could have the NPC attack right?
returned_ai_value = calculate_2D (X1, X2, Y1, Y2); // returned_ai_value will have the return value of calc_2D
if (returned_ai_value> = 5 && npc_settokill)
// npc does something to the player here …
Please note, returned_ai_value is an variable that contains the distance calculated from our formula.!
That is all for this tutorial, I hope you enjoyed it and learned something new. If you liked it, please leave commentary or or feedback and I will write the sequel to this article which will include 3D AI …