ShotEngine – all bullets in one place

29 01 2009

In the same way all units will be controlled in the same engine, the bullets fired by the units will be moved into their own engine and controlled from there. First let’s create a “blueprint” for the shots as well (yes an Interface).

package interfaces
{
	import units.AUnit;

	public interface IShot
	{
		// How will we check the collision? Is it a big radius or just a point check?
		function checkUnitCollision():IUnit;
		function checkStaticCollision():void;

		// What happens if the shot hits something (damage? explosions?)
		// returns TRUE if shot will be removed.
		function onUnitCollision(unit:AUnit):Boolean; 

		// What happens if the shot hits something static in the world (like a wall or other obstacle)
		// returns TRUE if shot will be removed.
		function onStaticCollision():Boolean;

		// update movement, rotation, scale, animation etc
		function transform():void;
	}
}

Now we’re getting used to the above view so with a little time looking at the code I believe that in the end you could tell me that the shots flying around (or behaving in other ways) will have a few basic functions that will be called apon. checkUnitCollision() checkStaticCollision() onUnitCollision()  onStaticCollision() and transform().  Good. I don’t even care about creating a real implemented class of this interface, instead I want to start with the whole shotEngine that will control all shots.

I think we will take this class in parts as it might contain a few new things to the new actionscript coder. First you can start with creating a new folder besides the rest of the folders and name it “engine“. And then create a new class starting like this:

package engine
{
	import interfaces.IShot;

	import units.AUnit;

	public class ShotEngine
	{

		static private var instance:ShotEngine
		private var aShots:Array

		// ************ SINGLETON CLASS *************
		public function ShotEngine()
		{
			init()
		}

		public static function getInstance():ShotEngine
		{
			if (ShotEngine.instance == null)
			{
				ShotEngine.instance = new ShotEngine();
			}
			return ShotEngine.instance;
		}

For you who are familiar with these kinds of Singleton-classes, skip this section. For you who is not:   “WHOOOOAA!!” WTF was that??

Above is my favourite code experience of the year (yes I’m new to this as well). I’ve always had problems with the whole capsulating thing when it comes to OOP as I just don’t get how people work with global variables. I always found myself coding in a small component class deep down in a hierachy tree and suddenly need an instance of a class that’s in a toal other place, unreachable for me. The quick, dirty solution back then was to make more and more variables public and static so I could reach them from wherever I wanted to in the project. Not that OOP’ish… right.

The wonderful solution is a class called a Singleton-class. With this type of class, you can create one and only one single instance. Whenever you try to create another one you will only recieve the same instance you created from the start and it will contain the same variables and data as that first instance has. If you look at the code above you will see that it has a function called getInstance()

To use a singleton class, ALWAYS call the getInstance() function to get the instance of the class. Never ever create a new instance using the constructorname. Always call getInstance(). This way you assure yourself that you will have only one single instance of the class and in this way you can have access to the same data and methods wherever you need in a project.

Another very important thing is that a lot of classes in a gameproject can only have one single instance! You maybe want to have only one gameengines running at the same time.Noramlly you want to use only one keyboard. Only one HUD? One highscorelist, one onlineLobby etc etc.  There are ways to control that the constructor cannot be directly called apon but I won’t bring that up here. Lets focus on our class instead. Continue….

        private function init()
        {
            aShots = new Array()
        }

        public function addShot(shot:IShot)
        {
            //Add a new shot into the shotlist
            aShots.push(shot);

            // code to put shot in the 3D scene will be implanted here

        }

        public function updateShots():void
        {
            var tempShot:IShot
            var tempUnit:AUnit
            var flagDelete:Boolean

            for (var i:int = aShots.length-1 ; i>-1 ; i--)
            {
                flagDelete = false    // reseting deleteflag.
                tempShot = aShots[i]

                // first make the shot move/rotate/animate/beam...
                tempShot.transform()

                // is it hitting anyone or anything?
                tempUnit = tempShot.checkUnitCollision()
                if (tempUnit != null)
                {
                    // returning 'TRUE' if that specific shot wants to remove itself on impact
                    flagDelete = tempShot.onUnitCollision(tempUnit);       
                }
                if (tempShot.checkStaticCollision()==true)
                {
                    // returning 'TRUE' if that specific shot wants to remove itself on impact
                    flagDelete = tempShot.onStaticCollision();
                }

                if (flagDelete == true)
                {
                    // code will be implanted here to remove the visual shot from the 3D scene
                    aShots.splice(i,1) // removing shot from the shot list.
                }
            }
        }
    }
}

This “engine” will handle all shots that are flying around on stage, update them, check if they hit things and then remove them on collision if they are coded that way( some shots, a lightingcloud for example, may not want to be removed on impact but draw damage over time as the unit stays in the cloud).
So, here you go. Another post without anything happening on the scene ;) remember, the more boring code we get done underneath, the faster the progress will get later on. Next post I promise we must create something visual. Like.. hmm, a gun?

Advertisements




The importance of being lazy!

29 01 2009

I will soon code a LOT, actually I’ve started already behind this scene but before I make it official and show it all to you I want to pull the breaks and look in the rear window so I got all of you with me. Why’s that? Because if you don’t get the structure that’s in my head, a big part of the next upcoming code will be just a copy and paste experience and you’ll probably learn nothing so let’s take a look and let me explain some things for you. (naah you’re all smart, I’m just repeating it to understand it myself!)

Lets start with an Image:

classstructure

If we start from the bottom we have actually already created some of these “components”. The interesting thing as that all the words down there but “MESH” starts with an ‘I’. It’s because we are focusing the Interface of that component. Creating an interface makes it so much easier to code a bigger project as I don’t have to worry about how many different “transformers” I need to make or how they will be implanted. I don’t even have to create fully functional classes. This is called to “code towards the interface”. For OOP-experienced coders this is basic material but somehow Actionscript has attracted a lot of designers into the coding world and haven’t until AS3 really faced this way of programming.

So, now lets say I create a lot of controllers, transformers, weapons and shots (which will be the physical ‘bullet’ fired from the gun) I can now extend the AUnit (abstract class) into a unique unit, eg. Defender and place one of each component types in there.

As AUnit now already have the public function transformUnit() and also checkCollisions() it means that I can have as many units on the scene as I want to, looking different, behaving differntly, is controlled differently but still will be exactly the same to handle for the main core engine. Eg. Lets create 3 different units:

var arUnits:Array = new Array()
var player:AUnit = new Defender()
var computer:AUnit = new Tank()
var LANgamer:AUnit = new Soldier()

arUnits.push(player)
arUnits.push(computer)
arUnits.push(LANgamer)

for each(tempUnit:AUnit in arUnits)
{
	tempUnit.transformUnit()
	tempUnit.checkCollisions()
}

This simple code above creates 3 different units but they are all typed AUnit (!) this means we can treat them exactly the same and loop through them but they will react differently depending on which components they have inside them. Great!  I don’t have to code a loop for each unit! I don’t have to code the management for each controller, nor for each weapon.  I just code how they will behave. Now that I feel that I’ve sorted this out a little more I will start working on those weapons and clean up the previous code so we can focus on the fun part in here.