Click here to Skip to main content
15,905,427 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
I am making a asteroids type game, where i have enemies and bullets in two array lists. I need to loop through my enemies and bullets and write an if statement too see if the bullet is equal to the location of the enemy.

C#
public partial class frmGame : Form
    {
        Background backgroundItem = new Background();
        MobileObject mobileItem = new MobileObject(200, 300, "Object");
        Bitmap enemyView = new Bitmap("images\\Enemy.png");
        HUD hudItem = new HUD();
        Camera cameraItem;
        bool Up = false;
        bool Down = false;
        bool Left = false;
        bool Right = false;
        Point Speed = new Point(0,-40);
        Random rnd = new Random(System.DateTime.Now.Millisecond);
        ArrayList enemies = new System.Collections.ArrayList();
        ArrayList bullets = new System.Collections.ArrayList();

C#
private void timGame_Tick(object sender, EventArgs e)
       {
           mobileItem.Move(Up, Down, Left, Right);



           //loop through enemies

           //if (bullet location == enemy location
           //HIT

           this.Refresh();
       }
Posted
Comments
Ankit Rajput 28-May-12 13:39pm    
I think you forgot to mention the question.....

1 solution

First off, don't use an ArrayList - use a Generic structure instead. An ArrayList is not strongly typed, whereas a List (or similar) is. This means that you do not need to cast it to get the object, and you can only store the appropriate objects in there (which is why you don't need to cast it).

Secondly, I would start by defining a class for my Asteroid, which contains a region (or a rectangle if you are feeling lazy) which describes the bound of the current size of asteroid. (You could also do this for a bullet, but a Point, a Direction and a Speed of movement is probably all you need there.)

Then for a rectangle, it is easy: Rectangle.Contains[^] comes in Point and Rectangle versions.

For the more accurate Region there is IsVisible[^] which does much the same job.
 
Share this answer
 
Comments
fjdiewornncalwe 28-May-12 14:17pm    
+5. Sound Advice

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900