Search code examples
xna-4.0

XNA choosing a subgroup of Game.Components


G'day All,

My little game has 5 bouncing balls and 1 player. Initially I wrote the code for the bouncing balls first and each ball has a collision detection method:

 foreach (Bouncer bouncer in Game.Components) //For each bouncer component in the game...
        {
            if (bouncer != this)// Don't collide with myself
            {
                if (bouncer.collisionRectangle.Intersects(this.collisionRectangle))
                {
                    // How far apart of the positions of the top right hand corners of the sprites when they hit?
                    int deltaX = Math.Abs((int)this.position.X - (int)bouncer.position.X);
                    int deltaY = Math.Abs((int)this.position.Y - (int)bouncer.position.Y);

                    // This is the width and height of a sprite so when two sprites touch this is how far the corners are from each other.
                    int targetWidth = 80;
                    int targetHeight = 80;

                    // The following determins the type of collision (vert hit vs horiz hit)
                    // Because the app is driven by a game based timer the actual amount of sprite overlap when the collision detection occurs is variable.
                    // This bit of simple logic has a 10 pixel tollerance for a hit.
                    // If target - delta is > 10 it will be interpreted as overlap in the non-colliding axis.
                    // If both if statements are triggered it is interpreted as a corner collision resulting in both sprites rebounding back along the original paths.

                    if (targetWidth - deltaX < 10) // The hit is a side on hit. 
                    {
                        this.velocity.X *= -1;
                    }

                    if (targetHeight - deltaY < 10) // The hit is a vertical hit
                    {
                        this.velocity.Y *= -1;   
                    }

                    this.numberOfCollisions = this.numberOfCollisions + 1;
                }
            }
        }

        base.Update(gameTime);
    }

Then I added my player component and the wheels fell off. The app compiles OK but when I run it I get an InvalidCastException and the message:

Unable to cast object of type 'Bounce2.Player' to type 'Bounce2.Bouncer'.

I don't want to include the player object in this collision detector.

Is there a way I can enumerate my way through the Bouncer objects and exclude any other objects?

Thanks, Andrew.


Solution

  • You can use this:

    foreach (Bouncer bouncer in Game.Components.OfType<Bouncer>()) 
    

    Note that you can store the Bouncer instances in other list too.