Simple AI

I'm having some problems with implementing an AI. It should be just a simple AI that follows player. Here is the code that I got so far:

1
2
3
4
5
6
7
8
9
10
11
12

(float)DirectionX = Circle->GetX() - AI->GetX(); 
(float)DirectionY = Circle->GetY() - AI->GetY();

(float)Hyp = sqrt(DirectionX * DirectionX + DirectionY * DirectionY);
		
DirectionX /= Hyp;
DirectionY /= Hyp;

x += DirectionX * 3;
y += DirectionY * 3;


This is what I got so far. It creates a vector in a direction I want to move, then just normalizes the vector. Simple as that. But I'm having 2 problems..

AI moves towards player only when Im at like the end of screen and the AI is on the other side, I must keep a certain distance for it to be able to move towards me. Basically, its not constantly moving towards the player. I also tried it with trig, using atan2 for angle and sin / cos for speed. Also didn't work, same result.

The other problem is when I want to add i.e 5 more AIs. For each new AI it creates, it makes a new update.. So, to kinda clear it up. If I'm in middle of the screen and an AI is spawned above me, it will move towards me. But when after that one, 2nd AI spawns beneath me, both 1st and 2nd AI move up. Basically, previous AIs take the update from last one that is created.

For updating I'm using lists, objects and iters.

I'm making this game for some kind of project and a deadline is pretty soon, so any kind of answer that could help me would be appreciated a lot.
Last edited on
Lines 2, 3, and 5 cast the result of the assignment to float and then do nothing with it. You should use floating-point types for all your variables instead of just in intermediate calculations. Also, it is recommended to use double instead, as it is more precise - float is only used when you need to store millions of them and don't need the precision.

You only convert to integral types at the very last second to draw to the screen. Some graphics libraries actually take floating point types instead and do the integral conversion stuff for you.

Also, you may want to consider using atan2 to get the angle between the AI and the Player and then use a speed coefficient with cos and sin to move the AI.
Last edited on
So, what I should do is : switch to double from float, switch to trigonometry instead of using vectors ? Or I should just add atan2 / angle ? I'm using Allegro 5, not sure if it does the conversion. What about the update part ? You might know what the problem is ? Or actually.. How to use it properly ?
Try working it out with trigonometry. Unfortunately I don't have experience with Allegro but even if it doesn't do the conversion keep in mind what I said: don't cast to integral type until the last second.
Topic archived. No new replies allowed.