I have a tower and 10 enemies. now if an enemy get in the tower range, the tower will shoot a bullet and the bullet will keep following the enemy until it hits him.
Now if the first enemy get in the tower range, the tower will shoot a bullet and the bullet class will calculate the enemy position and keep following him. However if the second enemy get in range while the bullet didn't reach the first enemy, the bullet will leave the first enemy and calculate the second enemy position.
I want if the tower shoot a bullet, the bullet should keep following the first enemy even if another enemy get in the tower range. and If the second enemy get in range the tower should shoot a new bullet with the second enemy position.
Here is the code:-
class Bullet
{
public void ShootAt(GameTime gameTime, Vector2 SourcePosition, Vector2 TargetPosition)
{
if (Alive)
{
ElapsedGameTimeSpeed = (float)Speed * (float)gameTime.ElapsedGameTime.TotalSeconds * 10.0f;
DeltaPosition.X = SourcePosition.X - TargetPosition.X;
DeltaPosition.Y = SourcePosition.Y - TargetPosition.Y;
double VectorLength = Math.Sqrt((DeltaPosition.X * DeltaPosition.X) + (DeltaPosition.Y * DeltaPosition.Y));
Direction.X = (float)DeltaPosition.X / (float)VectorLength;
Direction.Y = (float)DeltaPosition.Y / (float)VectorLength;
}
}
}
class Tower
{
int ShootAtEnemyIndex;
public void IsInRange(List<enemy> enemies)
{
for (int i = 0; i < enemies.Count; i++)
{
Distance.X = enemies[i].Position.X - TowerPosition.X;
Distance.Y = enemies[i].Position.Y - TowerPosition.Y;
DistanceSquare = (Distance.X * Distance.X) + (Distance.Y * Distance.Y);
if (DistanceSquare <= Radius * Radius)
{
ShootAtEnemyIndex = i;
InRange = true;
}
else
InRange = false;
}
}
public void Update(GameTime gameTime,List<enemy> enemies)
{
IsInRange(enemies);
if (InRange)
{
bulletManager.Fire(gameTime, enemies[ShootAtEnemyIndex], Damage, AttackSpeed);
}
//Calculate the distance between the bullet position and the enemy position.
for (int i = 0; i < bulletManager.Bullets.Count; i++)
bulletManager.Bullets[i].ShootAt(gameTime,enemies[ShootAtEnemyIndex].Position, bulletManager.Bullets[i].GetPosition() + bulletManager.Bullets[i].GetVelocity());
bulletManager.Update();
}
Edited by FantasyVII, 26 October 2012 - 11:00 PM.






