I notice that in the platformer example as well as the templates, the player behavior is coded directly in the gameplay ui state (ie, the code handling input and setting velocity of the player, etc). I usually like to encapsulate all of that player behavior in it’s own class…and maybe even separate out the player controller as another separate class that can be applied to the player (to be able to switch control modes, for example, if a player morphs from a fish to a walking animal or something like that, i can swap out its player controller)
I was able to do this, but would love some feedback if my approach sounds reasonable or if there is a better way to handle this. Here is what I did:
Created a TCastleScene ScenePlayer in the editor and assigned a png file to the URL.
Created a new class TPlayer descended from TCastleBehavior with a TCastleScene field called ScenePlayer
In TPlayer I override ParentChanged and set a reference to the ScenePlayer field there.
This is when I realized in order to handle input in the player class as I’m used to doing, I’d need a reference to the Container object of the UIState. I wasn’t sure if there is a way to get that from this context, so I added an argument to my TPlayer constructor to allow the gamestate to pass the container to TPlayer. That way in TPlayer.update I can check the input state and move my player as necessary.
The only catch is that when I was expecting to create my TPlayer object in the start procedure of the UI State, the container is nil at that point. I made kind of an ugly workaround which leads me to believe I’m not doing things the right way. Basically, in the update of the UIState, I do this to create my player once the container exists:
if not assigned(Player) and assigned(Container) then begin
Player := TPlayer.Create(nil, Container);
ScenePlayer.AddBehavior(Player);
end;
This works fine, but is ugly to do that in the update procedure.
If there is a better approach or suggestion to separating out player behavior and perhaps player control behavior from the main UIState class, I’d love know. I’d like to be able to get my bearings and try out most of the usual stuff I like to do in a game to see how to approach it in CGE.
thanks!