Calling to objects

Monkey Forums/Monkey Beginners/Calling to objects

BradMangham(Posted January) [#1]
Hi,

This is less of a specific program problem but more of a query with OOP/Monkey in general. Is there a way to call to any object of a specific class instead of having to refer to them all individually?

For example, say if there was an 'enemy' class in a game, and within the OnUpdate method the programmer wanted a collision detection system, would it be possible to write code looking for if the player collides with ANY member of the enemy class?

Thank you, and my apologies for my inexperience, Monkey is really the first object oriented language I've messed around with.


Gerry Quinn(Posted January) [#2]
There are different ways of doing it. Generally, all the enemies will be stored in some kind of structure such as an array or list, so the usual approach is just something like:



The Kill function might initially just set the enemy to dead, and later on you might modify it to generate a cloud of particles or whatever.

It *would* be possible to have the enemies list hidden as a global variable of the Enemy class, in which case you could have a function to get each enemy individually - but that's not a good idea in general. They belong as a list or whatever in your Game or GameLevel class[*]. There might be several lists, after all, perhaps for example there is a fleet on incoming enemies that are not activated yet.

Why set the enemy dead instead of removing it? Answer: you don't want to be messing with your lists in the middle of doing other things. If lots of enemies are created and destroyed continuously, you might want to tidy up periodically. But in many cases it's fine to just make them dead and reset the list at the start of each level.

[*] Here you are obviously just placing the game in the App-derived class. For a simple game, that's perfectly fine, especially if you don't want to get in over your head with classes just yet.


Paul - Taiphoz(Posted January) [#3]
To add to this in Gerry's example enemies is an object of type LIST.. looks something like this.

Global MyBadGuysList:List<enemyClass> = new List<enemyClass>
..
..
Method MakeMoreStuffTRoKill:void(x,y,type)
  local newguy:enemyClass = new enemyClass 'make a new object of type enemyClass the same class used in the list.
          newguy.x=x ' fill its values
          newguy.y=y
          ...
          ...

          MyBadGuysList.AddLast(newguy) ' add this newguy object to the list of MyBadGuysList
End Method

Then you just iterate through the list as Gerry has shown.


BradMangham(Posted January) [#4]
Thanks for the responses guys,

I've seen a few examples of people making lists to handle multiple objects, I'll definitely give it a try!

I'll let you know if I have any success