Time for action – positioning the asteroids

  1. Add methods to generate random locations and velocities to the AsteroidManager class:
    private Vector2 randomLocation()
    {
        Vector2 location = Vector2.Zero;
        bool locationOK = true;
        int tryCount = 0;
    
        do
        {
            locationOK = true;
            switch (rand.Next(0, 3))
            {
                case 0:
                    location.X = -initialFrame.Width;
                    location.Y = rand.Next(0, screenHeight);
                    break;
    
                case 1:
                    location.X = screenWidth;
                    location.Y = rand.Next(0, screenHeight);
                    break;
    
                case 2:
                    location.X = rand.Next(0, screenWidth);
                    location.Y = -initialFrame.Height;
                    break;
     } foreach (Sprite asteroid in Asteroids) { if (asteroid.IsBoxColliding( new Rectangle( (int)location.X, (int)location.Y, initialFrame.Width, initialFrame.Height))) { locationOK = false; } } tryCount++; ...

Get XNA 4.0 Game Development by Example Beginner's Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.