Time for action - player shot collisions

  1. Add the checkShotToEnemy() method to the CollisionManager class:
    private void checkShotToEnemyCollisions()
    {
    foreach (Sprite shot in playerManager.PlayerShotManager.Shots)
    {
    foreach (Enemy enemy in enemyManager.Enemies)
    {
    if (shot.IsCircleColliding(
    enemy.EnemySprite.Center,
    enemy.EnemySprite.CollisionRadius))
    {
    shot.Location = offScreen;
    enemy.Destroyed = true;
    playerManager.PlayerScore += enemyPointValue;
    explosionManager.AddExplosion(
    enemy.EnemySprite.Center,
    enemy.EnemySprite.Velocity/10);
    }
    }
    }
    }
    
  2. Add the checkShotToAsteroid() method to the CollisionManager class:
    private void checkShotToAsteroidCollisions()
    {
    foreach (Sprite shot in playerManager.PlayerShotManager.Shots)
    {
    foreach (Sprite asteroid in asteroidManager.Asteroids)
    {
    if (shot.IsCircleColliding(
    asteroid.Center,
    asteroid.CollisionRadius))
    {
    shot.Location = offScreen;
    asteroid.Velocity += shotToAsteroidImpact;
    }
    }
    }
    }
    

What just happened?

The structure of both of these methods is very similar. A foreach loop iterates over each active player shot, and a loop nested inside that loops through each enemy or asteroid. This way, every shot will be tested against every enemy and every asteroid in the game during each frame.

The Sprite class' CircleCollision() method is used to determine if the shot has impacted another object. In the case of enemies, a collision will move the bullet off screen, mark the enemy as destroyed, add to the player's score, and play an explosion effect. When the explosion is created, one tenth of the enemy's velocity is passed as the momentum parameter to the explosion, causing the explosion to drift in the direction that the enemy was travelling when it was destroyed.

For asteroid collisions, the shot is still moved off screen, but the asteroid is not destroyed by the shot. Instead, a small portion of the shot's velocity is added to the asteroid's velocity, allowing the player to nudge the asteroid onto a new course.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.15.160.43