//finds a spawning space for the player, trying the center first, with a minimum distance for spacing with asteroids public static Vector2 FindPlayerSpawnSpace(Asteroid[] Asteroids, double MinDistance) { bool TriedCenter = false; bool Successful = false; Vector2 Position = Vector2.Zero; do { if (!TriedCenter) { Position = new Vector2(GameEngine.Width / 2, GameEngine.Height / 2); TriedCenter = true; } else Position = new Vector2(GameEngine.Width / 2, GameEngine.Height / 2) + Vector2.RandomVector2(new Vector2(-100, -100), new Vector2(100, 100)); Successful = true; foreach (Asteroid asteroid in Asteroids) { double Distance = asteroid.Position.EuclideanDistance(Position); if (Distance < MinDistance) { Successful = false; break; } } } while (!Successful); return Position; }
//finds a spawning space for an asteroid with a minimum distance for spacing between asteroids public static Vector2 FindAsteroidSpawnSpace(Asteroid[] Asteroids, double MinDistance) { bool Successful = false; Vector2 Position = Vector2.Zero; do { Position = Vector2.RandomVector2(new Vector2(0,0), new Vector2(GameEngine.Width, GameEngine.Height)); Successful = true; foreach(Asteroid other in Asteroids) { double Distance = Position.EuclideanDistance(other.Position); if(Distance < MinDistance) { Successful = false; break; } } } while(!Successful); return Position; }
public Collision(Sprite playerSprite, Alien alien, BulletList bullets, Asteroid asteroids) { this.playerSprite = playerSprite; this.alien = alien; this.bullets = bullets; this.asteroids = asteroids; }
public void CreateAsteroidsAtPosition(Vector2D position, int sizeMod = 1, int howMany = 2) { for (int asteroidCount = 0; asteroidCount < howMany; asteroidCount++) { var asteroid = new Asteroid(this, sizeMod); asteroid.SetWithoutInterpolation(new Rectangle(position, asteroid.DrawArea.Size)); } }
public AsteroidManager( Settings settings, Asteroid.Factory asteroidFactory, LevelHelper level) { _settings = settings; _timeIntervalBetweenSpawns = _settings.maxSpawnTime / (_settings.maxSpawns - _settings.startingSpawns); _timeToNextSpawn = _timeIntervalBetweenSpawns; _asteroidFactory = asteroidFactory; _level = level; }
private void SpawnWave() { //Caps the asteroid count int asteroidCount = 4 + WavesSurvived; if (asteroidCount > MAX_ASTEROIDS) { asteroidCount = MAX_ASTEROIDS; } List<Asteroid>SpawnWave = new List<Asteroid>(); for (int i = 0; i < asteroidCount; i++ ) { Asteroid newAsteroid = new Asteroid(Game, FindAsteroidSpawnSpace(SpawnWave.ToArray(), 50), AsteroidSize.Large); SpawnWave.Add(newAsteroid); } foreach(Asteroid asteroid in SpawnWave) Game.SpawnAsteroid(asteroid); }
private void Form1_Paint(object sender, System.Windows.Forms.PaintEventArgs e) { Graphics g = e.Graphics; g.Clear(Color.Black); if (!bStarted) { String drawString = "Asteroids"; // Create font and brush. Font drawFont = new Font("Verdana", 48); SolidBrush drawBrush = new SolidBrush(Color.Red); PointF drawPoint = new PointF(this.ClientRectangle.Width / 4, this.ClientRectangle.Height - iTextHolder); // Draw string to screen. e.Graphics.DrawString(drawString, drawFont, drawBrush, drawPoint); drawString = "AURORA"; // Create font and brush. drawFont = new Font("TIMES NEW ROMAN", 14); drawBrush = new SolidBrush(Color.White); drawPoint = new PointF(this.ClientRectangle.Width / 4, this.ClientRectangle.Height - (iTextHolder - 90)); // Draw string to screen. e.Graphics.DrawString(drawString, drawFont, drawBrush, drawPoint); if (iTextHolder > this.ClientRectangle.Height + 25) { iTextHolder = 25; } else { iTextHolder = iTextHolder + 5; } return; } Bullet[] BulletArray = TheShip.BulletArray; // Move Ship if (TheShip.Active) { TheShip.Move(); // check ship is not out of bounds TheShip.InRectangle(this.ClientRectangle); } // Move Bullets for (int i = 0; i < BulletArray.Length; i++) { // check if bullet is still in scope if (BulletArray[i] != null) { if (BulletArray[i].Active) { BulletArray[i].Move(); // trim or reposition bullets if (BulletArray[i].InRectangle(this.ClientRectangle)) { BulletArray[i].Active = false; } // test ship & bullet collision if (TheShip.Active) { if (BulletArray[i].IntersectsWith(TheShip.GetBounds(), TheShip.ShipImage)) { BulletArray[i].Active = false; TheShip.Active = false; } } } } } // Move Asteroids foreach (Asteroid A in AsteroidList) { A.Move(); A.InRectangle(this.ClientRectangle); } // check for collisions for (int j = 0; j < AsteroidList.Count; j++) { Asteroid A = (Asteroid)AsteroidList[j]; // if exploding nothing to do if (A.Exploding == false) { // with bullets for (int i = 0; i < BulletArray.Length; i++) { if (BulletArray[i] != null) { if (BulletArray[i].Active) { if (BulletArray[i].IntersectsWith(A.GetBounds(), A.AsteroidImage)) { A.Exploding = true; spawnMoreAsteroids(A); BulletArray[i].Active = false; } } } } // with ship if (TheShip.Active) { if (TheShip.IntersectsWith(A.GetBounds(), A.AsteroidImage)) { A.Exploding = true; spawnMoreAsteroids(A); TheShip.Active = false; } } } } // trim any inactive asteroids for (int i = 0; i < AsteroidList.Count; i++) { Asteroid A = (Asteroid)AsteroidList[i]; if (A.Active) { A.Draw(g); } else { AsteroidList.RemoveAt(i); } } for (int i = 0; i < BulletArray.Length; i++) { if (BulletArray[i] != null) { if (BulletArray[i].Active) { BulletArray[i].Draw(g); } } } if (TheShip.Active) { TheShip.DrawShip(g); } }
public int LevelWinLose(Asteroid asteroid, Player player) { return(0); }
private void SpawnAsteroid(Asteroid typeToSpawn, Vector2 position) { typeToSpawn.SpawnAsteroid(position, Random.insideUnitCircle.normalized); typeToSpawn.OnDestroyedEvent = OnEnemyDestroyed; }
// clear all collisions associated with the specified asteroid private void clearCollisions(Asteroid a) { if(a == null) { return; } for(int i=0;i<m_asteroidSystem.size();i++) { Asteroid a2 = m_asteroidSystem.getAsteroid(i); if(a2.isCollidingWith(a)) { a2.removeCollision(a); a.removeCollision(a2); } } }
// Called when [collision with asteroid]. private void OnCollisionWithAsteroid(Asteroid asteroid) { asteroid.Collision(damage); OnEventDestroy(); }
public void SplitAsteroid() { // Asteroid has been marked for deletion so spawn smaller versions to fly off in random direction! (Don't split XS sprites) Random rand = new Random(); switch (asteroidSprite.Name) { case "Enemies/AsteroidS": // Split into 4 Asteroid[] xschildAsteroids = new Asteroid[4]; for (int i = 0; i < 4; i++) { Asteroid xstempAsteroid = new Asteroid(); xstempAsteroid.radius = 1; xstempAsteroid.speed = rand.Next(200, 400); xstempAsteroid.angle = rand.Next(361); xstempAsteroid.position = this.position; xstempAsteroid.offScreen = false; xstempAsteroid.asteroidSprite = AsteroidsGame.asteroidSprites[0]; xschildAsteroids[i] = xstempAsteroid; } Asteroid.childAsteroids.AddRange(xschildAsteroids); break; case "Enemies/AsteroidM": // Split into 3 Asteroid[] schildAsteroids = new Asteroid[3]; for (int i = 0; i < 3; i++) { Asteroid stempAsteroid = new Asteroid(); stempAsteroid.radius = 5; stempAsteroid.speed = rand.Next(150, 350); stempAsteroid.angle = rand.Next(361); stempAsteroid.position = this.position; stempAsteroid.offScreen = false; stempAsteroid.asteroidSprite = AsteroidsGame.asteroidSprites[1]; schildAsteroids[i] = stempAsteroid; } Asteroid.childAsteroids.AddRange(schildAsteroids); break; case "Enemies/AsteroidL": // Split into 2 Asteroid[] mchildAsteroids = new Asteroid[2]; for (int i = 0; i < 2; i++) { Asteroid mtempAsteroid = new Asteroid(); mtempAsteroid.radius = 12; mtempAsteroid.speed = rand.Next(100, 300); mtempAsteroid.angle = rand.Next(361); mtempAsteroid.position = this.position; mtempAsteroid.offScreen = false; mtempAsteroid.asteroidSprite = AsteroidsGame.asteroidSprites[2]; mchildAsteroids[i] = mtempAsteroid; } Asteroid.childAsteroids.AddRange(mchildAsteroids); break; default: break; } }
public void UpdateAsteroids(Asteroid asteroidSuper, GameTime theTime, List <SoundEffect> sounds) { Timer = theTime; theAsteroids[0].Visible = false; for (int i = 0; i < theAsteroids.Count; i++) { if (theAsteroids[i].Position.X < (0 - theAsteroids[i].Image.Width)) { theAsteroids[i].SetPositionX(Graphics.PreferredBackBufferWidth + theAsteroids[i].Image.Width); // thePosition.X = Window.ClientBounds.Width + image.Width; //thePosition = new Vector2(X,Y); } if (theAsteroids[i].Position.X > (Graphics.PreferredBackBufferWidth + theAsteroids[i].Image.Width)) { theAsteroids[i].SetPositionX(0 - theAsteroids[i].Image.Width); } if (theAsteroids[i].Position.Y < (0 - theAsteroids[i].Image.Height)) { theAsteroids[i].SetPositionY(Graphics.PreferredBackBufferHeight + theAsteroids[i].Image.Height); } if (theAsteroids[i].Position.Y > Graphics.PreferredBackBufferHeight + theAsteroids[i].Image.Height) { theAsteroids[i].SetPositionY(0 - theAsteroids[i].Image.Height); } theAsteroids[i].SpriteRectangle = new Rectangle((int)theAsteroids[i].Position.X, (int)theAsteroids[i].Position.Y, theAsteroids[i].Image.Width, theAsteroids[i].Image.Height); theAsteroids[i].SetPosition(theAsteroids[i].Velocity + theAsteroids[i].Position); theAsteroids[i].ImageCenter = new Vector2(theAsteroids[i].SpriteRectangle.Width / 2, theAsteroids[i].SpriteRectangle.Height / 2); //Colllision for (int w = 0; w < AccessWeapons.TheWeapons.Count; w++) { Weapon p = AccessWeapons; if (i != 0) { if (Collided(theAsteroids[i], p.TheWeapons[w], theAsteroids[i].Image)) { sounds[(int)Game1.Sounds.Boom].Play(); if (theAsteroids[i].TheType == (int)Asteroid.AsteroidType.Small) { Vector2 vtemp = theAsteroids[i].Velocity; Vector2 ptemp = theAsteroids[i].Position; theAsteroids.RemoveAt(i); --i; asteroidSuper.CreateAsteroids(asteroidSuper, ptemp.X, ptemp.Y, 2, (int)Asteroid.AsteroidType.ChunkSmall1, -VELOCITYE, VELOCITYE); AccessWeapons.TheWeapons.RemoveAt(w); --w; AccessPlayer.Score += 100; } else if (theAsteroids[i].TheType == (int)Asteroid.AsteroidType.Medium) { Vector2 ptemp = theAsteroids[i].Position; theAsteroids.RemoveAt(i); --i; asteroidSuper.CreateAsteroids(asteroidSuper, ptemp.X, ptemp.Y, 1, (int)Asteroid.AsteroidType.ChunkMedium1, -VELOCITYE, VELOCITYE); asteroidSuper.CreateAsteroids(asteroidSuper, ptemp.X, ptemp.Y, 1, (int)Asteroid.AsteroidType.ChunkMedium2, -VELOCITYE, VELOCITYE); asteroidSuper.CreateAsteroids(asteroidSuper, ptemp.X, ptemp.Y, 1, (int)Asteroid.AsteroidType.ChunkMedium3, -VELOCITYE, VELOCITYE); asteroidSuper.CreateAsteroids(asteroidSuper, ptemp.X, ptemp.Y, 1, (int)Asteroid.AsteroidType.ChunkMedium4, -VELOCITYE, VELOCITYE); asteroidSuper.CreateAsteroids(asteroidSuper, ptemp.X, ptemp.Y, 1, (int)Asteroid.AsteroidType.ChunkMedium5, -VELOCITYE, VELOCITYE); AccessWeapons.TheWeapons.RemoveAt(w); --w; AccessPlayer.Score += 200; } else if (theAsteroids[i].TheType == (int)Asteroid.AsteroidType.Large) { Vector2 ptemp = theAsteroids[i].Position; theAsteroids.RemoveAt(i); --i; asteroidSuper.CreateAsteroids(asteroidSuper, ptemp.X, ptemp.Y, 1, (int)Asteroid.AsteroidType.ChunkLarge1, -VELOCITYE, VELOCITYE); asteroidSuper.CreateAsteroids(asteroidSuper, ptemp.X, ptemp.Y, 1, (int)Asteroid.AsteroidType.ChunkLarge2, -VELOCITYE, VELOCITYE); asteroidSuper.CreateAsteroids(asteroidSuper, ptemp.X, ptemp.Y, 1, (int)Asteroid.AsteroidType.ChunkLarge3, -VELOCITYE, VELOCITYE); AccessWeapons.TheWeapons.RemoveAt(w); --w; AccessPlayer.Score += 300; } else if (theAsteroids[i].TheType == (int)Asteroid.AsteroidType.ExtraLarge) { Vector2 ptemp = theAsteroids[i].Position; theAsteroids.RemoveAt(i); --i; asteroidSuper.CreateAsteroids(asteroidSuper, ptemp.X, ptemp.Y, 1, (int)Asteroid.AsteroidType.ChunkExtra1, -VELOCITYE, VELOCITYE); asteroidSuper.CreateAsteroids(asteroidSuper, ptemp.X, ptemp.Y, 1, (int)Asteroid.AsteroidType.ChunkExtra2, -VELOCITYE, VELOCITYE); asteroidSuper.CreateAsteroids(asteroidSuper, ptemp.X, ptemp.Y, 1, (int)Asteroid.AsteroidType.ChunkExtra3, -VELOCITYE, VELOCITYE); asteroidSuper.CreateAsteroids(asteroidSuper, ptemp.X, ptemp.Y, 1, (int)Asteroid.AsteroidType.ChunkExtra4, -VELOCITYE, VELOCITYE); AccessWeapons.TheWeapons.RemoveAt(w); --w; AccessPlayer.Score += 400; } if (theAsteroids[i].TheType == (int)Asteroid.AsteroidType.ChunkSmall1) { theAsteroids.RemoveAt(i); --i; AccessPlayer.Score += 50; } if (theAsteroids[i].TheType == (int)Asteroid.AsteroidType.ChunkMedium1) { theAsteroids.RemoveAt(i); --i; AccessPlayer.Score += 100; } if (theAsteroids[i].TheType == (int)Asteroid.AsteroidType.ChunkMedium2) { theAsteroids.RemoveAt(i); --i; AccessPlayer.Score += 100; } if (theAsteroids[i].TheType == (int)Asteroid.AsteroidType.ChunkMedium3) { theAsteroids.RemoveAt(i); --i; AccessPlayer.Score += 100; } if (theAsteroids[i].TheType == (int)Asteroid.AsteroidType.ChunkMedium4) { theAsteroids.RemoveAt(i); --i; AccessPlayer.Score += 100; } if (theAsteroids[i].TheType == (int)Asteroid.AsteroidType.ChunkMedium5) { theAsteroids.RemoveAt(i); --i; AccessPlayer.Score += 100; } if (theAsteroids[i].TheType == (int)Asteroid.AsteroidType.ChunkLarge1) { theAsteroids.RemoveAt(i); --i; AccessPlayer.Score += 150; } if (theAsteroids[i].TheType == (int)Asteroid.AsteroidType.ChunkLarge2) { theAsteroids.RemoveAt(i); --i; AccessPlayer.Score += 150; } if (theAsteroids[i].TheType == (int)Asteroid.AsteroidType.ChunkLarge3) { theAsteroids.RemoveAt(i); --i; AccessPlayer.Score += 150; } if (theAsteroids[i].TheType == (int)Asteroid.AsteroidType.ChunkExtra1) { theAsteroids.RemoveAt(i); --i; AccessPlayer.Score += 200; } if (theAsteroids[i].TheType == (int)Asteroid.AsteroidType.ChunkExtra2) { theAsteroids.RemoveAt(i); --i; AccessPlayer.Score += 200; } if (theAsteroids[i].TheType == (int)Asteroid.AsteroidType.ChunkExtra3) { theAsteroids.RemoveAt(i); --i; AccessPlayer.Score += 200; } if (theAsteroids[i].TheType == (int)Asteroid.AsteroidType.ChunkExtra4) { theAsteroids.RemoveAt(i); --i; AccessPlayer.Score += 200; } //if (i > 0) // theAsteroids[i].Time = COLLISIONINTERVAL; Loop = theAsteroids[i].TheType; theAsteroids.TrimExcess(); } } } //check asteroid collisions for (int j = 0; j < theAsteroids.Count; j++) { if (Collided(theAsteroids[i], theAsteroids[j], theAsteroids[i].Image)) { theAsteroids[j].Time -= Timer.ElapsedGameTime.Milliseconds; if (theAsteroids[j].Time < 0) { // sounds[(int)Game1.Sounds.AsteroidCollsion].Play(); switch (theAsteroids[i].PlusOrMinus) { case 0: theAsteroids[i].SetVelocityX((-theAsteroids[i].Velocity.X) - (float)random.NextDouble()); theAsteroids[i].SetVelocityY((-theAsteroids[i].Velocity.Y) - (float)random.NextDouble()); theAsteroids[i].AngularVelocity = -theAsteroids[i].AngularVelocity; theAsteroids[j].SetVelocityX((-theAsteroids[j].Velocity.X) - (float)random.NextDouble()); theAsteroids[j].SetVelocityY((-theAsteroids[j].Velocity.Y) - (float)random.NextDouble()); theAsteroids[j].AngularVelocity = -theAsteroids[j].AngularVelocity; theAsteroids[i].PlusOrMinus = 1; break; case 1: theAsteroids[i].SetVelocityX((-theAsteroids[i].Velocity.X) + (float)random.NextDouble()); theAsteroids[i].SetVelocityY((-theAsteroids[i].Velocity.Y) + (float)random.NextDouble()); theAsteroids[i].AngularVelocity = -theAsteroids[i].AngularVelocity; theAsteroids[j].SetVelocityX((-theAsteroids[j].Velocity.X) + (float)random.NextDouble()); theAsteroids[j].SetVelocityY((-theAsteroids[j].Velocity.Y) + (float)random.NextDouble()); theAsteroids[j].AngularVelocity = -theAsteroids[j].AngularVelocity; theAsteroids[i].PlusOrMinus = 0; break; } theAsteroids[j].Time = COLLISIONINTERVAL; } } } theAsteroids[i].Angle += theAsteroids[i].AngularVelocity; // AngularVelocity*=AngularVelocityDecrement; if (theAsteroids[i].Angle > fullRotation) { theAsteroids[i].Angle -= fullRotation; } if (theAsteroids[i].Angle < 0) { theAsteroids[i].Angle += fullRotation; } // i.SetVelocityX(i.Velocity.X + (float)Math.Cos(Angle) * Speed); // i.SetVelocityY(Velocity.Y + (float)Math.Sin(Angle) * Speed); // SetVelocityX(Velocity.X * VelocityDecrement); // SetVelocityY(Velocity.Y * VelocityDecrement); // Speed } }
public static void Update() { for (int i = 0; i < stars.Length; i++) { if (stars[i] == null) { stars[i] = new Star(new Size(Rnd.Next(0, 5), Rnd.Next(0, 5)), true); } else { stars[i].Update(ref stars[i]); } if (stars[i].Position.X < 0) { stars[i] = null; } } for (int i = 0; i < ListAsteroid.Length; i++) { if (ListAsteroid[i] == null) { ListAsteroid[i] = new Asteroid(imageAsteroid); } ListAsteroid[i]?.Update(ref ListAsteroid[i]); if (BulletHits(ref ListAsteroid[i])) { continue; } if (ListAsteroid[i] != null && ship.Collision(ListAsteroid[i])) { Log("Корабль подбит"); timerBonus.Start(); ListAsteroid[i] = null; ship.Damage(); } } for (int i = 0; i < bullets.Length; ++i) { if (bullets[i] != null) { bullets[i].Update(ref bullets[i]); } } SystemSounds.Asterisk.Play(); ship.Update(ref ship); if (ship.Live <= 0) { ship?.Die(); } if (heart != null) { if (heart.Collision(ship)) { Log("Колличество жизней увеличено"); ship.Heal(); heart = null; } heart?.Update(ref heart); } GC.Collect(); }
public bool addCollision(Asteroid a) { if(a == null || m_activeCollisions.Contains(a)) { return false; } m_activeCollisions.Add(a); return true; }
public void handleCollisions() { if (m_projectileSystem == null || m_spaceShipSystem == null || m_asteroidSystem == null || m_explosionSystem == null || m_scoreSystem == null) { return; } // remove any collisions that have been handled and are no longer in collision for (int i = 0; i < m_asteroidSystem.size(); i++) { Asteroid a1 = m_asteroidSystem.getAsteroid(i); for (int j = 0; j < m_asteroidSystem.size(); j++) { Asteroid a2 = m_asteroidSystem.getAsteroid(j); if (i != j && (a1.isCollidingWith(a2) && !a1.checkCollision(a2)) || (a2.isCollidingWith(a1) && !a2.checkCollision(a1))) { a1.removeCollision(a2); a2.removeCollision(a1); } } } // check asteroid > asteroid collision for (int i = 0; i < m_asteroidSystem.size(); i++) { for (int j = i + 1; j < m_asteroidSystem.size(); j++) { if (i != j && m_asteroidSystem.getAsteroid(i).checkCollision(m_asteroidSystem.getAsteroid(j))) { handleCollision(m_asteroidSystem.getAsteroid(i), m_asteroidSystem.getAsteroid(j)); } } // check projectile > asteroid collision for (int j = 0; j < m_projectileSystem.size(); j++) { if (m_projectileSystem.getProjectile(j).checkCollision(m_asteroidSystem.getAsteroid(i))) { // [potentially] create a cluster of smaller asteroids if this was a big asteroid m_scoreSystem.addPoints(m_projectileSystem.getProjectile(j).getProjectileSource(), (m_asteroidSystem.getAsteroid(i).bigAsteroid) ? ScoreType.BigAsteroid : ScoreType.SmallAsteroid); if (m_asteroidSystem.getAsteroid(i).bigAsteroid) { m_asteroidSystem.spawnAsteroidCluster(m_asteroidSystem.getAsteroid(i)); } m_explosionSystem.spawnExplosion(m_asteroidSystem.getAsteroid(i)); clearCollisions(m_asteroidSystem.getAsteroid(i)); m_asteroidSystem.removeAsteroid(i); m_projectileSystem.removeProjectile(j); i--; j--; break; } } } // check ship > ship collision for (int i = 0; i < m_spaceShipSystem.size(); i++) { for (int j = i + 1; j < m_spaceShipSystem.size(); j++) { if (i != j && m_spaceShipSystem.getSpaceShip(i).checkCollision(m_spaceShipSystem.getSpaceShip(j))) { m_explosionSystem.spawnExplosion(m_spaceShipSystem.getSpaceShip(i)); m_explosionSystem.spawnExplosion(m_spaceShipSystem.getSpaceShip(j)); m_spaceShipSystem.getSpaceShip(i).reset(); m_spaceShipSystem.getSpaceShip(j).reset(); } } // check ship > asteroid collision for (int j = 0; j < m_asteroidSystem.size(); j++) { if (m_spaceShipSystem.getSpaceShip(i).checkCollision(m_asteroidSystem.getAsteroid(j))) { m_explosionSystem.spawnExplosion(m_spaceShipSystem.getSpaceShip(i)); m_spaceShipSystem.getSpaceShip(i).reset(); clearCollisions(m_asteroidSystem.getAsteroid(j)); m_asteroidSystem.removeAsteroid(j); j--; } } // check projectile > ship collision for (int j = 0; j < m_projectileSystem.size(); j++) { if (!m_projectileSystem.getProjectile(j).getProjectileSource().Equals(m_spaceShipSystem.getSpaceShip(i)) && m_projectileSystem.getProjectile(j).checkCollision(m_spaceShipSystem.getSpaceShip(i))) { m_scoreSystem.addPoints(m_projectileSystem.getProjectile(j).getProjectileSource(), ScoreType.SpaceShip); m_explosionSystem.spawnExplosion(m_spaceShipSystem.getSpaceShip(i)); m_spaceShipSystem.getSpaceShip(i).reset(); m_projectileSystem.removeProjectile(j); j--; } } } }
// spawn a random asteroid at a random location with random attributes public void spawnAsteroid() { int asteroidIndex; bool bigAsteroid; Random rand = new Random(); if(rand.Next(0, 99) < 30) { // spawn small asteroid (30% chance) asteroidIndex = rand.Next(0, 4) + 2; bigAsteroid = false; } else { // spawn big asteroid (70% chance) asteroidIndex = rand.Next(0, 2) % 2; bigAsteroid = true; } // if there are too many asteroids of this type, do not spawn it if(bigAsteroid && m_numberOfBigAsteroids >= m_maxBigAsteroids) { return; } if(!bigAsteroid && m_numberOfSmallAsteroids >= m_maxSmallAsteroids) { return; } bool isInsideOfAsteroid; bool isTooCloseToShip; Asteroid newAsteroid = new Asteroid(m_asteroidSprites.getSprite(asteroidIndex), bigAsteroid, m_settings); do { // make sure that the new asteroid is not too close to a space ship isTooCloseToShip = false; for(int i=0;i<m_spaceShipSystem.size();i++) { if(m_spaceShipSystem.getSpaceShip(i).checkExtendedCollision(newAsteroid)) { isTooCloseToShip = true; } } // also make sure that the asteroid is not stuck inside of another asteroid isInsideOfAsteroid = false; if(!isTooCloseToShip) { for(int i=0;i<m_asteroids.Count();i++) { if(m_asteroids[i].checkCollision(newAsteroid)) { isInsideOfAsteroid = true; } } } // if it is too close to a ship or inside of another asteroid, then re-randomize its position until it isn't if(isTooCloseToShip || isInsideOfAsteroid) { newAsteroid.randomizePosition(); } } while(isTooCloseToShip || isInsideOfAsteroid); // store the asteroid if(newAsteroid.bigAsteroid) { m_numberOfBigAsteroids++; } else { m_numberOfSmallAsteroids++; } m_asteroids.Add(newAsteroid); }
// handle a collision between two asteroids private void handleCollision(Asteroid a1, Asteroid a2) { if(a1 == a2) { return; } if(a1.isCollidingWith(a2) || a2.isCollidingWith(a1)) { return; } a1.addCollision(a2); a2.addCollision(a1); double v = a1.speed; double dx = Math.Abs(a2.x - a1.x); double dy = Math.Abs(a2.y - a1.y); double d = Math.Sqrt((dx * dx) + (dy * dy)); if(d == 0) return; double angle_b = Math.Asin(dy / d); double angle_d = Math.Asin(Math.Abs(a1.velocity.X) / v); double angle_a = (Math.PI / 2.0f) - angle_b - angle_d; double angle_c = angle_b - angle_a; double v1 = v * Math.Abs(Math.Sin(angle_a)); double v2 = v * Math.Abs(Math.Cos(angle_a)); double v1x = v1 * Math.Abs(Math.Cos(angle_c)); double v1y = v1 * Math.Abs(Math.Sin(angle_c)); double v2x = v2 * Math.Abs(Math.Cos(angle_b)); double v2y = v2 * Math.Abs(Math.Sin(angle_b)); if(a1.velocity.X > 0) { if(a1.x < a2.x) v1x = -v1x; else v2x = -v2x; } else { if(a1.x > a2.x) v2x = -v2x; else v1x = -v1x; } if(a1.velocity.Y > 0) { if(a1.y < a2.y) v1y = -v1y; else v2y = -v2y; } else { if(a1.y > a2.y) v2y = -v2y; else v1y = -v1y; } if(double.IsNaN(v1x) || double.IsNaN(v1y) || double.IsNaN(v2x) || double.IsNaN(v2y)) { return; } // update the asteroids with their new velocities a1.velocity = new Vector2((float) v1x, (float) v1y); a2.velocity = new Vector2((float) v2x, (float) v2y); }
public void spawnAsteroidCluster(GameObject o) { if(o == null || m_numberOfSmallAsteroids >= m_maxSmallAsteroids) { return; } Random rand = new Random(); // randomly choose how many small asteroids to spawn from a bigger asteroid int clusterSize = 0; int clusterSeed = rand.Next(0, 100); if(clusterSeed < 34) { clusterSize = 0; } // 34% chance no asteroids else if(clusterSeed < 76) { clusterSize = 1; } // 42% chance 1 asteroid else if(clusterSeed < 90) { clusterSize = 2; } // 14% chance 2 asteroids else if(clusterSeed < 96) { clusterSize = 3; } // 6% chance 3 asteroids else if(clusterSeed < 100) { clusterSize = 4; } // 4% chance 4 asteroids // create the corresponding number of mini-asteroids, and set their appropriate locations and directions // by rotating a pair of x/y co-ordinates around the origin of the original asteroid, randomized at equal // intervals and set their velocities so they are moving away from the origin of the original asteroid float angle = (float) (rand.NextDouble() * 359.0f); float angleIncrement = (360.0f / clusterSize); Asteroid newAsteroid; for(int i=0;i<clusterSize;i++) { newAsteroid = new Asteroid(m_asteroidSprites.getSprite(rand.Next(0, 4) + 2), false, m_settings); // calculate the velocities of the new asteroid float minVelocity = (float) (rand.NextDouble() * 0.3f) + 0.007f; float maxVelocity = (float) (rand.NextDouble() * 2.5f) + 0.8f; float xVelocity = (float) ( (((rand.Next(0, 2) % 2) == 0) ? 1 : -1) * (rand.NextDouble() * (maxVelocity - minVelocity) + minVelocity) ); float yVelocity = (float) ( (((rand.Next(0, 2) % 2) == 0) ? 1 : -1) * (rand.NextDouble() * (maxVelocity - minVelocity) + minVelocity) ); // set the velocities and locations of the new asteroid newAsteroid.position = new Vector2((float) (o.position.X + (o.offset.X * Math.Cos(MathHelper.ToRadians(angle)))), (float) (o.position.Y + (o.offset.Y * Math.Sin(MathHelper.ToRadians(angle))))); newAsteroid.velocity = new Vector2((float) (xVelocity * Math.Cos(MathHelper.ToRadians(angle))), (float) (yVelocity * Math.Sin(MathHelper.ToRadians(angle)))); // store the asteroid if(newAsteroid.bigAsteroid) { m_numberOfBigAsteroids++; } else { m_numberOfSmallAsteroids++; } m_asteroids.Add(newAsteroid); // increment to the next projection angle angle += angleIncrement; } }
public void Iteration() { iteration++; /// Fired by the form timer. This will Move and process all of the space objects. ship.Move(); // Move along the shots. // Delete any old ones. // Bullet Loop for (int i = bullets.Count - 1; i >= 0; i--) { Bullets bullet = bullets[i]; bullet.Move(); if (bullet.Iterations > bullet.life) { bullets.Remove(bullet); BullettsFired--; } // Check if we have hit an asteroid. for (int a = asteroids.Count - 1; a >= 0; a--) { Asteroid asteroid = asteroids[a]; if (asteroid.Area.Contains(bullet.point)) { // Add to score. PlayerScore += asteroid.Score; form2.playerScore.Text = PlayerScore.ToString(); // We have a hit. Remove this asteroid and create more smaller ones if appropriate. int createQty = 1; if (asteroid.Size == Asteroid.Sizes.Large) { createQty = random.Next(1, Level); for (int x = 0; x < createQty; x++) { Asteroid newAsteroid = new Asteroid(asteroid.point.X + 2, asteroid.point.Y, this, Asteroid.Sizes.Medium, asteroid.Colour); asteroids.Add(newAsteroid); } } if (asteroid.Size == Asteroid.Sizes.Medium) { createQty = random.Next(1, Level * 2); for (int x = 0; x < createQty; x++) { Asteroid newAsteroid = new Asteroid(asteroid.point.X + 2, asteroid.point.Y, this, Asteroid.Sizes.Small, asteroid.Colour); asteroids.Add(newAsteroid); } } if (asteroid.Size == Asteroid.Sizes.Small) { createQty = random.Next(1, Level * 3); for (int x = 0; x < createQty; x++) { Asteroid newAsteroid = new Asteroid(asteroid.point.X + 2, asteroid.point.Y, this, Asteroid.Sizes.Tiny, asteroid.Colour); asteroids.Add(newAsteroid); } } asteroids.Remove(asteroid); bullets.Remove(bullet); BullettsFired--; } } // Phase 2 Check if we have hit the enemy ship if (enemyShip1 != null && enemyShip1.Area.Contains(bullet.point) && bullet.Enemy != true) { // Add to score. PlayerScore += 50; form2.playerScore.Text = PlayerScore.ToString(); // Remove the object. enemyShip1 = null; soundPlayerGlass.Play(); EnemyShipActive = false; } // Phase 2 - See if the enemy ship has hit us. if (bullet.Enemy == true && ship.Area.Contains(bullet.point)) { // Oh dear we have been hit. Call the NewShip routine. NewShip(); ShowExplosion = 20; // Number of times to show explosion ExplosionPoint = bullet.point; break; } // See is all asteroids have gone. Need to start the next level. if (asteroids.Count <= 0) { Level++; NewLevel(Level); return; } } // End Bullet list loop. // Move the Asteroids. foreach (Asteroid asteroid in asteroids) { asteroid.Move(); // See if this has hit our ship. if (asteroid.Area.IntersectsWith(ship.Area)) { // Oh dear we have been hit. Call the NewShip routine. NewShip(); ShowExplosion = 20; // Number of times to show explosion ExplosionPoint = asteroid.point; break; } } // Phase 2 - Randomly start the enemy ship at the right hand side. if (EnemyShipActive == false) { int randy = random.Next(0, 500); if (randy == 250) { EnemyShipActive = true; int startPosX = FormSizeX - 2; int startPosY = random.Next(1, FormSizeY); enemyShip1 = new EnemyShip(startPosX, startPosY, this); enemyShip1.Angle = 270.0F; } } if (EnemyShipActive == true) { enemyShip1.Move(); if (iteration % 10 == 0) // Fire every ten iterations. { enemyShip1.Shoot(); } } // Fire the form paint event to paint the graphics. form1.Invalidate(); }
// remove an already existing asteroid public bool removeAsteroid(Asteroid a) { if(a == null) { return false; } return removeAsteroid(m_asteroids.IndexOf(a)); }
public bool HitsAsteroid(Asteroid asteroid) { return(this.posY > asteroid.GetY() && this.posY < asteroid.GetY() + asteroid.GetS() && this.posX > asteroid.GetX() && this.posX < asteroid.GetX() + asteroid.GetS()); }
public void Update() { if (IsUpButtonPressed) { if (player.Speed < 0) { player.Speed = 0; } if (player.Speed < player.MAX_SPEED) { player.Speed++; } } else { if (player.Speed > 0) { player.Speed--; } } if (IsDownButtonPressed) { if (player.Speed > 0) { player.Speed = 0; } if (player.Speed > -player.MAX_SPEED) { player.Speed--; } } else { if (player.Speed < 0) { player.Speed++; } } if (IsLeftButtonPressed) { player.Rotate(player.ROTATE_DEGREE_INCREMENT); } if (IsRightButtonPressed) { player.Rotate(-player.ROTATE_DEGREE_INCREMENT); } if (IsSpaceBarPressed) { App.soundPlayer.Play(); if (player.LastFired == player.FIRE_COOLDOWN && !player.IsDead()) { player.LastFired = 0; Bullet newBullet = new Bullet(VMath.AddVectors(player.Position, new Vector2(rand.Next(8) - 4, rand.Next(8) - 4)), player.UnitDirectionVector, 20, 3); gameObjects.Add(newBullet); } } if (rand.Next(1, 100) <= 1) //random asteroid spawn chance { Asteroid newAsteroid = new Asteroid(new Vector2(rand.Next(0, canvasWidth), 0), new Vector2(rand.Next(-180, 180), rand.Next(-180, 180)), rand.Next(1, 5), rand.Next(15, 100)); gameObjects.Add(newAsteroid); } foreach (var obj in gameObjects.Where((h => (h is HealthBar))).ToList()) { gameObjects.Remove(obj); } HealthBar gameHealthBar = new HealthBar(new Vector2(canvasWidth, canvasHeight), new Vector2(0, 0), 0, player.Health); gameObjects.Add(gameHealthBar); foreach (var obj in gameObjects.ToList()) { obj.Move(canvasWidth, canvasHeight); if (obj.IsDead()) { gameObjects.Remove(obj); } } foreach (var obj in gameObjects.Where((b => (b is Bullet))).ToList()) { if (obj.Position.X < 0 || obj.Position.X > canvasWidth || obj.Position.Y < 0 || obj.Position.Y > canvasHeight) { obj.Destroy(); } } foreach (var obj in gameObjects.Where((a => (a is Asteroid))).ToList()) { if ((obj.Position.X + obj.Radius > player.Position.X && obj.Position.X - obj.Radius < player.Position.X) && (obj.Position.Y + obj.Radius > player.Position.Y && obj.Position.Y - obj.Radius < player.Position.Y)) { if (!player.IsDead()) { player.AsteroidCollision(obj); obj.Destroy(); } } } foreach (var ast in gameObjects.Where((a => (a is Asteroid))).ToList()) { foreach (var bul in gameObjects.Where((b => (b is Bullet))).ToList()) { if ((ast.Position.X + ast.Radius > bul.Position.X && ast.Position.X - ast.Radius < bul.Position.X) && (ast.Position.Y + ast.Radius > bul.Position.Y && ast.Position.Y - ast.Radius < bul.Position.Y)) { gameObjects.Add((ast as Asteroid).Half()); bul.Destroy(); } } } if (player.Health <= 0) { gameOver = true; } }
public override void Update() { userInterface.UpdateUI(); spaceShipScore = Spaceship.GetSpaceshipScore(1); switch (createdSpaceShip) { case 0: { if (!regularSpaceship.IsSpaceshipAlive) { this.isGameOn = false; } else if (regularSpaceship.Shoot()) { Lazer lazer = new Lazer ( regularSpaceship.TriangleX, regularSpaceship.TriangleY, regularSpaceship.TriangleV, regularSpaceship.TriangleR, regularSpaceship.Damage, regularSpaceship.GetID ); } } break; case 1: { if (!scoutSpaceship.IsSpaceshipAlive) { this.isGameOn = false; } else if (scoutSpaceship.Shoot()) { Lazer lazer = new Lazer ( scoutSpaceship.TriangleX, scoutSpaceship.TriangleY, scoutSpaceship.TriangleV, scoutSpaceship.TriangleR, scoutSpaceship.Damage, scoutSpaceship.GetID ); } } break; case 2: { if (!heavySpaceship.IsSpaceshipAlive) { this.isGameOn = false; } else if (heavySpaceship.Shoot()) { Lazer lazer = new Lazer ( heavySpaceship.TriangleX, heavySpaceship.TriangleY, heavySpaceship.TriangleV, heavySpaceship.TriangleR, heavySpaceship.Damage, heavySpaceship.GetID ); } } break; case 3: { if (!sniperSpaceship.IsSpaceshipAlive) { this.isGameOn = false; } else if (sniperSpaceship.Shoot()) { Lazer lazer = new Lazer ( sniperSpaceship.TriangleX, sniperSpaceship.TriangleY, sniperSpaceship.TriangleV, sniperSpaceship.TriangleR, sniperSpaceship.Damage, sniperSpaceship.GetID ); } } break; } if (time[0] >= 10 * (4 - ButtonSeries.GetSelectedMultiplier(2))) { Asteroid asteroid = new Asteroid(); time[0] = 0; } else { time[0]++; } if (spaceShipScore >= 2000) { wave = 2; if (time[1] == 600) { MissileAsteroid missileAsteroid = new MissileAsteroid(); time[1] = 0; } else { time[1]++; } } if (spaceShipScore >= 4000) { wave = 3; if (time[2] == 1000) { ScatterAsteroid scatterAsteroid = new ScatterAsteroid(); time[2] = 0; } else { time[2]++; } } if (spaceShipScore >= 6000) { wave = 4; if (time[3] == 2000) { MissileScatterAsteroid missileScatterAsteroid = new MissileScatterAsteroid(); time[3] = 0; } else { time[3]++; } } if (spaceShipScore >= 8000 && ButtonSeries.GetSelectedButtonID(4) == 0) { wave = 5; if (time[4] == 2000) { LimitScreen limitScreen = new LimitScreen(); time[4] = 0; } else { time[4]++; } } if (spaceShipScore >= 10000) { if (ButtonSeries.GetSelectedButtonID(4) == 0) { wave = 6; } else { wave = 5; } if (time[5] == 4000) { MissileScatterAsteroidMissile missileScatterAsteroidMissile = new MissileScatterAsteroidMissile(); time[5] = 0; } else { time[5]++; } } if (spaceShipScore >= 20000) { if (time[6] == 0) { time[6] = 20000 - spaceShipScore / 10; } else { time[6]--; } if (ButtonSeries.GetSelectedButtonID(2) == 4) { wave = 7; } else { wave = 6; } int t = time[6]; switch (t) { case 1: { for (int i = 0; i < 200; i++) { Asteroid asteroid = new Asteroid(); } } break; case 2000: { for (int i = 0; i < 3; i++) { MissileAsteroid missileAsteroid = new MissileAsteroid(); } } break; case 4000: { for (int i = 0; i < 5; i++) { ScatterAsteroid scatterAsteroid = new ScatterAsteroid(); } } break; case 6000: { for (int i = 0; i < 3; i++) { MissileScatterAsteroid missileScatterAsteroid = new MissileScatterAsteroid(); } } break; case 8000: { for (int i = 0; i < 4; i++) { MissileScatterAsteroidMissile missileScatterAsteroidMissile = new MissileScatterAsteroidMissile(); } } break; } } base.Update(); }
private void StartNewGame() { ship = new Spaceship(Content); camera = new SpaceshipCamera(graphics.GraphicsDevice.Viewport, ship); int x, y, z, pos_x, pos_y, pos_z; Random random = new Random(); for (int i = 0; i < NUM_ASTEROIDS; ++i) { x = random.Next(2); z = random.Next(2); y = random.Next(2); pos_x = random.Next(-30, 31); pos_y = random.Next(-30, 31); pos_z = random.Next(-30, 31); asteroids[i] = new Asteroid(Content, new Vector3(x, y, z)); asteroids[i].Position = new Vector3(pos_x, pos_y, pos_z); } spriteDrawer = new SpriteDrawer(device, Content); spriteManager = new SpriteManager(device, Content); spFont = Content.Load<SpriteFont>(@"Arial"); spBatch = new SpriteBatch(graphics.GraphicsDevice); particleSystem = new ParticleSystem(spriteManager); jetParticleEffect = new JetParticleEffect(particleSystem, ship); points = 0; jetParticleEffect.MinXDirection = -0.3f; jetParticleEffect.MaxXDirection = 0.3f; jetParticleEffect.MinZDirection = 0.6f; jetParticleEffect.MaxZDirection = 0.8f; jetParticleEffect.MinYDirection = -0.2f; jetParticleEffect.MaxYDirection = 0.2f; jetParticleEffect.ParticlesPerSecond = 50.0; jetParticleEffect.ParticleLifetime = 400.0; jetParticleEffect.ParticleSize = 0.5f; jetParticleEffect.ParticleSpeed = 0.7f; jetParticleEffect.FinalColor = Color.Red; }
/// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { player = new Sprite(graphics, Content.Load<Texture2D>("playerShip")); alien = new Alien(Content, graphics, player); spriteBatch = new SpriteBatch(GraphicsDevice); background = new Background(graphics.GraphicsDevice, spriteBatch, Content); bullets = new BulletList(); asteroids = new Asteroid(Content, graphics); keyboard = new KeyBoardManager(Content); collision = new Collision(player, alien, bullets, asteroids); font = Content.Load<SpriteFont>("Font"); }
// Collisions public virtual void HandleCollision(Asteroid a) { }
//spawns a batch of asteroids independant from the game to be displayed on the background of the main menu public static List<Asteroid> SpawnAsteroids(int amount, int distance) { List<Asteroid> asteroids = new List<Asteroid>(); for (int i = 0; i < amount; i++) { Asteroid newAsteroid = new Asteroid(null, FindAsteroidSpawnSpace(asteroids.ToArray(), 50), AsteroidSize.Large); asteroids.Add(newAsteroid); } return asteroids; }
private void movement_Tick(object sender, EventArgs e) { // laser movement for (int i = 0; i < laser_list.Count; i++) { Shot s = new Shot(); s.graphic = laser_list[i].graphic; s.x = laser_list[i].x; s.y = laser_list[i].y - laser_speed; laser_list.RemoveAt(i); laser_list.Insert(i, s); } // asteroid movement for (int i = 0; i < asteroid_list.Count; i++) { Asteroid a = new Asteroid(); a.graphic = asteroid_list[i].graphic; a.x = asteroid_list[i].x; a.y = asteroid_list[i].y + asteroid_list[i].speed; a.speed = asteroid_list[i].speed; a.type = asteroid_list[i].type; a.hp = asteroid_list[i].hp; a.size = asteroid_list[i].size; asteroid_list.RemoveAt(i); asteroid_list.Insert(i, a); } // detect collisions // asteroid with ground for (int i = 0; i < asteroid_list.Count; i++) { Asteroid cur_asteroid = asteroid_list[i]; // COLLISION WITH SHIP if ((cur_asteroid.y > (800 - cur_asteroid.size - 100)) && (Math.Abs(cur_asteroid.x - spaceship.Location.X) < 50)) { // reduce lives numLives = 0; Debug.WriteLine("GAME OVER"); // remove all lasers and asteroids asteroid_list.Clear(); laser_list.Clear(); // disable timers movement_timer.Stop(); spawn_timer.Stop(); level_timer.Stop(); movement_timer.Enabled = false; spawn_timer.Enabled = false; level_timer.Enabled = false; // display game over message countdown_label.Text = "Game Over"; countdown_label.Show(); // set boolean GameOver = true; lives.Text = "Lives: 0"; } // COLLISION WITH FLOOR if (cur_asteroid.y > (800 - cur_asteroid.size)) { // reduce # lives Debug.WriteLine("LIFE LOST"); numLives--; String lives_text = "Lives: " + numLives.ToString(); lives.Text = lives_text; // remove graphic asteroid_list.RemoveAt(i); // end game if # lives == 0 if (numLives == 0) { Debug.WriteLine("GAME OVER"); // remove all lasers and asteroids asteroid_list.Clear(); laser_list.Clear(); // disable timers movement_timer.Stop(); spawn_timer.Stop(); level_timer.Stop(); movement_timer.Enabled = false; spawn_timer.Enabled = false; level_timer.Enabled = false; // display game over message countdown_label.Text = "Game Over"; countdown_label.Show(); // set boolean GameOver = true; } } // COLLISION WITH LASER for (int j = 0; j < laser_list.Count; j++) { Shot cur_laser = laser_list[j]; if ((Math.Abs(cur_asteroid.y - cur_laser.y) < cur_asteroid.size) && (Math.Abs(cur_asteroid.x - cur_laser.x) < cur_asteroid.size)) { // decrement asteroid HP cur_asteroid.hp = cur_asteroid.hp - 1; Debug.WriteLine(cur_asteroid.hp); // remove laser laser_list.RemoveAt(j); // increase points & redo label points = points + point_increment; String score_text = "Score: " + points.ToString(); score.Text = score_text; // reinsert asteroid if (cur_asteroid.hp != 0) { asteroid_list.RemoveAt(i); asteroid_list.Insert(i, cur_asteroid); } else { asteroid_list.RemoveAt(i); } } } } // redraw objects this.Invalidate(); }
public bool removeCollision(Asteroid a) { if(a == null) { return false; } return m_activeCollisions.Remove(a); }
private void spawn_Tick(object sender, EventArgs e) { Debug.WriteLine("Spawn Tick"); // generate an asteroid int type = rnd.Next(1,4); Debug.WriteLine(type); int size, hp; if (type == 1) { size = l1_asteroid_size; hp = l1_asteroid_hp; } else if (type == 2) { size = l2_asteroid_size; hp = l2_asteroid_hp; } else { size = l3_asteroid_size; hp = l3_asteroid_hp; } int placement_x = rnd.Next(size, 800 - size); System.Drawing.SolidBrush myBrush = new System.Drawing.SolidBrush(System.Drawing.Color.Red); System.Drawing.Graphics asteroid; asteroid = this.CreateGraphics(); asteroid.FillRectangle(myBrush, new Rectangle(placement_x, 0, size, size)); myBrush.Dispose(); Asteroid a = new Asteroid(); a.graphic = asteroid; a.x = placement_x; a.y = 0; a.speed = rnd.Next(1, 5); a.type = type; a.hp = hp; a.size = size; asteroid_list.Add(a); }
public bool isCollidingWith(Asteroid a) { if(a == null) { return false; } return m_activeCollisions.Contains(a); }
// handle a collision between two asteroids private void handleCollision(Asteroid a1, Asteroid a2) { if (a1 == a2) { return; } if (a1.isCollidingWith(a2) || a2.isCollidingWith(a1)) { return; } a1.addCollision(a2); a2.addCollision(a1); double v = a1.speed; double dx = Math.Abs(a2.x - a1.x); double dy = Math.Abs(a2.y - a1.y); double d = Math.Sqrt((dx * dx) + (dy * dy)); if (d == 0) { return; } double angle_b = Math.Asin(dy / d); double angle_d = Math.Asin(Math.Abs(a1.velocity.X) / v); double angle_a = (Math.PI / 2.0f) - angle_b - angle_d; double angle_c = angle_b - angle_a; double v1 = v * Math.Abs(Math.Sin(angle_a)); double v2 = v * Math.Abs(Math.Cos(angle_a)); double v1x = v1 * Math.Abs(Math.Cos(angle_c)); double v1y = v1 * Math.Abs(Math.Sin(angle_c)); double v2x = v2 * Math.Abs(Math.Cos(angle_b)); double v2y = v2 * Math.Abs(Math.Sin(angle_b)); if (a1.velocity.X > 0) { if (a1.x < a2.x) { v1x = -v1x; } else { v2x = -v2x; } } else { if (a1.x > a2.x) { v2x = -v2x; } else { v1x = -v1x; } } if (a1.velocity.Y > 0) { if (a1.y < a2.y) { v1y = -v1y; } else { v2y = -v2y; } } else { if (a1.y > a2.y) { v2y = -v2y; } else { v1y = -v1y; } } if (double.IsNaN(v1x) || double.IsNaN(v1y) || double.IsNaN(v2x) || double.IsNaN(v2y)) { return; } // update the asteroids with their new velocities a1.velocity = new Vector2((float)v1x, (float)v1y); a2.velocity = new Vector2((float)v2x, (float)v2y); }