ForumsProgramming ForumHow to make code apply for more than one instance of a movieclip?

4 3327
Katumi
offline
Katumi
9 posts
Nomad

Hello everyone

I'm making a rpg game in flash AS3.

I want to know more about classes, at least i think that's what i need to know. I'm having different enemy types in my game, and they act differently, but for now i can only have one instance of each. If i add more than one instance, only one of them will work, as they have the same instance name. I could give them different names, like for example enemytypeA1 and enemytypeA2 and apply the code for both, but this seems stupid as i know it can be done easier.

So, i was hoping anyone could tell me a way to make code apply for more than one instance of a movieclip.

  • 4 Replies
Katumi
offline
Katumi
9 posts
Nomad

Thanks in advance!

rjbman
offline
rjbman
215 posts
Nomad

Okay, well I'm assuming there's some sort of fighting portion of the game where multiple enemies come at you. So if you aren't then this may not work for you, it might anyway, I just don't know.

What you can do is put in the actual class file the stuff that makes them move, attack, etc; then in the document file (or whatever other file you're using) you can put an array of each kind of enemy.

Like, on a tick event, have a new enemy of kind normal spawn, by pushing the enemy into the array then adding the enemy. The reason you put it into the array and add it rather than just adding it is so that when you need to, say, remove them all, or do something else that acts on all of them, you can just use the array and a For...Each statement.

Good luck with your RPG. Hopefully this helps you.

PixelSmash
offline
PixelSmash
566 posts
Nomad

Well, I'm assuming you're using your document class to animate the instances, right? And you can only apply that code to one? Classes are your friend then

Classes are pretty simple. You've made a document class, and -as the name suggests- that too is a class.
So, the next step is port the code you have right now to that class.

document:
//you have an event listener added
enterFrameHandler(e:Event):void
{
instance.x += 1;
}

your new class (extends movieclip):
//add an event listener
this.addEventListener(Event.ENTER_FRAME, enterFrameHandler);
private function enterFrameHandler(e:Event):void
{
this.x += 5;
}

This is pretty basic, but it should give you some directions good luck!

TheInvidual
offline
TheInvidual
4 posts
Nomad

An easy way to solve problems is creating an array that contains all the enemies. Lets say this function is run every time an enemy is created:

var enemiesArray:Array = new Array();

function createEnemy ():void
{
var enemy:Enemy;
enemy = new Enemy();
enemiesArray.push(enemy);
addChild(enemy);
}

This way you can loop through the items in the array to, for example, check if they are colliding with the player, like so:

for each (var enemy in enemiesArray)
{
//Add collision detection code here
}

I hope this helps

Showing 1-4 of 4