New Method Question
BlitzMax Forums/BlitzMax Beginners Area/New Method Question
| ||
Hello, I have the following code,Type TGameObject Field OldX,X Field OldY,Y Method New AddListLast(List,Self) OldX=X OldY=Y End Method End Type Type TPlayer Extends TGameObject Function Create:TPlayer(X,Y) Local Player:TPlayer=New TPlayer Player.X=X Player.Y=Y Return Player End Function End Type This is obviously only part of it but what I am trying to do is to set the OldX and OldY values to the same as the X and Y values passed when creating the Player object. Is this possible? I can see why it is not working as the new method is called before the variables are assigned to the player but is there a way around this or another way to do it completely? I could call a separate function to set the old variable positions to the same as the new ones but I would like to know if there is a better way first. Hope this makes sense, it`s a little hard to explain. Many thanks for any advice. Jason. |
| ||
Makes sense, but ya, the only way is to use the create function to set the OldX and OldY fieldsType TGameObject Field OldX,X Field OldY,Y Method New AddListLast(List,Self) End Method End Type Type TPlayer Extends TGameObject Function Create:TPlayer(X,Y) Local Player:TPlayer=New TPlayer Player.X=X Player.Y=Y Player.OldX=X Player.OldY=Y Return Player End Function End Type |
| ||
Ok, so my first instinct was this, but it didn't work:Type tgameobject Field oldx,x Field oldy,y Function Create:tgameobject(_x,_y) o:tgameobject=aNewOne(_x,_y) o.oldx=o.x o.oldy=o.y Return o End Function Function aNewOne:tgameobject(_x,_y) Abstract End Type Type tplayer Extends tgameobject Function aNewOne:tgameobject(_x,_y) p:tplayer=New tplayer p.x=_x p.y=_y Return p End Function End Type p:tplayer=tplayer(tplayer.Create(1,1)) That didn't work because functions aren't as 'dynamic' in blitz as methods are, I don't think, so the create function doesn't know that aNewOne is no longer abstract when it's being used in the context of tplayer. So, I changed to using methods: Type tgameobject Field oldx,x Field oldy,y Global objects:TList=New TList Method Create:tgameobject(_x,_y) anewone(_x,_y) 'do the type-specific creation stuff 'do the stuff that happens to every tgameobject oldx=x oldy=y objects.addlast Self Return Self End Method Method aNewOne(_x,_y) Abstract End Type Type tplayer Extends tgameobject Method anewone(_x,_y) 'this is the method that does stuff particular to a tplayer x=_x y=_y End Method End Type p:tplayer=tplayer(New tplayer.Create(1,2)) Print "oldx: "+p.oldx Print "oldy: "+p.oldy Print "no. objects in list: "+tgameobject.objects.count() which works as you required, but the code to actually create a new object is pretty cumbersome. |
| ||
This is roughly how I would do it: |
| ||
Thanks for the replies. I now have several new ways that I can tackle the problem :) Jason. |