My question is, as there will be many, many bullets flying around at the same time, how do I make each one a separate instance, check collisions for each, move each, and draw each individually (arrays, I would presume, but could someone lend me some exact code)?
The way that I would solve your problem is as follows:
Firstly, you need create a class that contains bullet information, position, size, etc. And then have one copy of the image shared between them (IE: Use a static image that's allocated while it's loading). Using a static variable will save memory in the long run.
For example (I use C#, but the concept should be easy to see):
- Code: Select all
class Bullet
{
public System.Drawing.PointF Position {get;set;} // Center of the bullet.
public System.Drawing.PointF DrawStart {get;set;} // Drawing start point.
public System.Drawing.RectangleF Bounds {get;set;}
public void Move(float x, float y)
{
// Update Position and Bounds...
}
public static Image BulletImage; // Needs to be set to work.
};
List<Bullet> bullets;
To check whether or not a object is colliding with another object, you can either do a "Rectangle Intersects Check" or do it another say.
Let's say that I have a variable called unit, which has a property called Bounds, and I'm looking at a bullet called bullet.
- Code: Select all
if (bullet.Bounds.Intersects(unit.Bounds))
{
// Intersection.
}
Iterating over the list of bullets will allow you to do individual checks, but it can be time consuming when you have lots of units on the screen (It can be optimized as well).
Drawing is relatively simple, just iterate over the list and draw (You can get the bullets position from DrawStart).
I'll probably update this later on, but it should give you a rough idea of where to start.