Hi there
I am writing a game with some basic AI elements. The enemies know there position and the players position and so are able to rotate and follow the player around etc.

The idea is that when an enemy gets within a radius of the player they calculate a new random angle and move that way for 3 seconds then continue following the player. The effect with a single enemy works fine and looks OK.

The next thing I need to do is if two enemies are near each other they produce a random angle and move away from each other for a small amount of time. If I don't do this then it is possible to have all the enemies running into each other and acting the same.

I foolishly haven't got my code with me but I am doing something like

``````for(int i = 0; i<numberOfEnemies; i++)
{
if(tooCloseToEnemy)
time = 3.0;

if(timeFactor >0.0)
float newAngle = rand()%90+45;

if(enemy[i].angle > newAngle)
{
enemy[i].angle -= 80*timeFactor
}
}``````

I think the problem is that all the enemies behave the same and so always collide and run into each other continuously once it first occurs.

Is there an easy or better way of doing a random variable within a for loop so that the two colliding enemies will have a different angle???

Many thanks sorry if its a bit of a vague question

## All 4 Replies

What is `timeFactor` for, and under what circumstances is it less than or equal to zero?

Also, have you considered making this part of the AI part of the enemy objects themselves, rather than part of the overall code? (I am assuming that Enemy is a class rather than a structure).

timeFactor counts the time between frames being drawn and is decreased to be able to distinguish when a certain amount of time has passed. It is also used to allow everything to happen within the same time frame such as walking, running, shooting etc.

in the enemy class it resets to 0 when nothing is happening to the enemies. When the enemy collides with either the player or another enemy it sets its self to 3.0 then decreases when the 3 seconds is done.

The enemy is a class I haven't thought about that, if I assign a different rand to each enemy class would that generate different numbers or would it still generate the same number for each?

I can put up more of my full code tomorrow(I'll have to edit it as it is quite long) all help appreciated

Many thanks

Sounds like you might have your `srand()` call in the wrong place. It should be called only once a the start of `main()`

many thanks for the help
Moving srand did help :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.