When creating an instance, how do I randomly choose the class?


(Jacob) #1

Let’s say I have several different enemies, each one with it’s own class of course. I want to randomly choose one of those classes and instantiate it. Anyone know how this can be done?


(Bora Kasap) #2

if each one have their class

so you can use

FP.choose(FP.world.add(new Enemy1), FP.world.add(new Enemy2));


(Jacob) #3

AlobarNon, great idea. Thank you for the help. I’m going to try that. I was also thinking I could somehow do it with a Spritemap. If anyone else has any other ideas, please let me know!


(Jacob Albano) #4

That will actually not work.

What FP.choose() does is return a random value from the list given to it. However, in AlobarNon’s example, each enemy is being added to the world regardless of the choice. Here’s how you could do it instead:

var c:Class = FP.choose(Enemy1, Enemy2);
var e:Entity = new c();

You’ll have to be careful and make sure that each enemy type has the same constructor signature, or you’ll get errors. You can pass parameters into the call to new just like normal:

var e:Entity = new c(x, y);

Randomly choosing Entities/ Spawn Times
(Jacob) #5

Excellent, this works great. Thank you. However, this makes me wonder. Do you know if there’s a way list classes in an array & then randomly choose from the array?

  • var c:Class = new classArray[FP.rand(100)];

(azrafe7) #6

Taking a closer look at the FP.choose() function

public static function choose(...objs):*
{
	var c:* = (objs.length == 1 && (objs[0] is Array || objs[0] is Vector.<*>)) ? objs[0] : objs;
	return c[rand(c.length)];
}

you can see that it also accept an Array or Vector (as a single argument).

So, if you have a collection of classes in an Array you can use the same approach:

var enemyClasses:Array = [Enemy1, Enemy2, Enemy3, ...];
var c:Class = FP.choose(enemyClasses);
var e:Entity = new c(...);

Mmm… There’s something that makes me feel you’re asking for a slighlty different thing but I’m not quite sure.


(Jacob) #7

azrafe7, yes, that works. Thanks for the help. Funny thing is, I originally thought of storing the classes in an array & then choosing randomly from that array. But I assumed it wasn’t possible to store classes in an array.


(Jacob Albano) #8

Actionscript lets you do a lot of things that you wouldn’t think are allowed. :wink:


(Zachary Lewis) #9

I view it as allowing me to do a lot of things that I think should be allowed. Why can’t I store a reference to a class, or a function? Why can’t I call a function by name using a string?

High-level languages are hella’ dope.


(Jacob Albano) #10

Yeah definitely. A lot of the things I used to wish I could do using C++ are built right into as3.