Accessing class 1 fields from class 2 fields
Monkey Forums/Monkey Programming/Accessing class 1 fields from class 2 fields
| ||
Hello. I am in the process of rewriting my code, which at the moment uses loads of external functions, into using just classes as fields on the game main class. It seems that i don't understand how to access fields. What i want is to create a class with 2 variables that are based of what is contained into another class. As you can see i made a comment where i want the class to grab the other class fields. Everything works if i use external functions and variables declared globals. Hope it make any sense... |
| ||
The only ways are to connect via MyApp containing field inside the bullet class or you store ship inside the bullet app too. Or store ship as a global. |
| ||
I would do it like this: [monkeycode] #rem 31/3/2013 #end Import mojo Global ma:MyApp Function Main() ma = New MyApp End Function Class MyApp Extends App Field ship:= New player 'declaration for the player class which is a class Field bull:=New bullet 'declaration for the bullet class which is a class Method OnCreate() ship.init() SetUpdateRate(60) End Method OnRender() Cls ship.render() bull.render() End Method OnUpdate() ship.update() bull.update() If KeyHit(KEY_1) Then bull.init() End '---------- extra functions '---------- end extra functions End Class Class actor Field posx:Int Field posy:Int Field speed:Int Field life:Int Field Lbound:Int Field Rbound:Int Field Ubound:Int Field Dbound:Int Field size:Int Field power:Int End Class player Extends actor '---------- Method init() posx=300 posy=300 speed=5 size=60 End '---------- Method update() End '---------- Method render() DrawCircle(posx,posy,size) 'draw ship End End Class bullet Extends actor '------------------------------- Method init() power=1 size=5 posx=222 'what i want here is to be able to access x and y of the player class 'Access the ship like this ma.ship.posx = 100 posy=222 'to be able to create the new class x and y based on the player one speed=5 End '-------------------------------- Method update() posy=posy-speed 'start the movement upward End '----------------------------- Method render() DrawCircle(posx,posy,size) 'draw bullet End End [/monkeycode] |
| ||
this would do what you want and make it a bit flexible. |
| ||
So basically in the initialisation method's brackets i have to put the name of the class i want to get the values from? Interesting. Thank you! |
| ||
It's just one way to do it. The important thing is that anything that wants to know about an instance of anything else must have a way of finding it. |