How to manage multiple scenes / screens on AndEngine for Android - andengine

Do you know if there is any tutorial or example out there showing how to handle multiple screens / scenes of a game?
For example, imagine I have a game with this structure:
Cover
Main menu
Gameplay
Credits
To put allthe code in just one java file might be a nightmare... I'd like to use different classes and probably different scenes, but I don't know how to do it.
Thanks!

Extend Scene class for all of these scenes. Make a class called SceneManager, make a field of this class in your BaseGameActivity implementation. The scene manager has fields for all of the scenes, and you can make methods like SceneManager.getCreditsScene(), SceneManager.getMenuScene() and so on.
This way each scene has it's own file-class, while another classtakes care of all of the scenes and the game activity itself just calls simple methods to access these scenes.

This is the tutorial you are looking for, it's a plataform game, it has a scene manager class taht handles, spalsh, menu, loading and game scenes. It also privdes a Resources Manager that is used to load and unload resources according the scene you are at.
Main page: http://www.matim-dev.com/full-game-tutorial---part-1.html
Scene Manager page: http://www.matim-dev.com/full-game-tutorial---part-4.html

Related

How should I handle a multiple scenes project?

I'm trying to make this game using the approach of multiple scenes to make things more modular.
In my actual case I have an "Initialization" scene which holds some global state objects and the one to control the state machine of all the scenes in the game.
As for the other scenes, for now I divided them just in two: the base scenes (which for now contains everything besides UI) and its UI scenes (which basically have a Canvas and all the UI elements and UI-related scripts).
The confusion in my mind is simple though: as I tried to make the UI scenes as modular and independent as possible, there are a lot of points of interactions between the base scene and its UI scene.
For the sake of illustrating this question please take this problem I'm facing right now: I have camera animations that should be played as a response to user inputs to the UI (like the click of a button should trigger a specific camera animation). Thing is: that camera is not in the UI scene. The way I'm resolving this problem right now is creating a ScriptableObject which holds events for important actions triggered in the UI scene that are fired in the UI scene and subscribed in any other place. The same can occur in the opposite direction: the UI scene need to react to many actions that happens in other scenes.
Considering that the "camera animation" problem I explained above can happen with many other objects, if there is not a better way to handle that wouldn't splitting a game into multiple scenes be just too much of work just for the benefit of modularity? And by that I also asks: am I handling this problem the right way?
If you want to keep things consistent between scenes, there are a few ways to do it.
PlayerPrefs lets you keep variables consistent, I don't need to do a whole tutorial here, look it up.
DontDestroyOnLoad lets you take an object and make it consistent throughout the whole game. If you want, you can use DontDestroyOnLoad on one of your cameras and just delete the others in the other scenes if you want to keep a consistent camera.

Best way to switch UI in Unity3D

We are building a mobile app built in Unity3D, which involves a lot of UI switch. For example, from this page to the other page, it involves a lot of disabling the previous UI and activate new UI elements.
A common way to do is to set old UI inactive and new UI active. When switch back, just deactive/active again. But I read that this will cuase Rebuild problem (Canvas.SendWillRenderCanvases or BuildBatch). I wonder what is the alternative?
Will these two solutions work?
Instead of activate/deactivate UI element, apply it on the UI canvas.
Deactivae the UI element by moving it far away. Will it cause UI Rect rebuild?
Set in different layer, change its layer to invisbile layer when deactivate.
I would discourage you from using a state machine for your UI if you consider developing an application with many UI layers.
It will result in a scene hierarchy with hundreds of objects, some of them only been used when going deep down the app (like settings of a specific page) but they end up in memory at all time.
Also, it makes things harder to debug since you cannot really jump to a specific state without going through all the previous ones (except if you are already advanced prog and you defined your classes so they can work from anywhere).
The easy solution is to use scenes to separate your states, just like it is done in Android/iOS with Activity/Fragments or views.
This will clean you memory when needed, you can still keep scenes alive on the stack (like mobile OS does) using additive scene loading, since you won't have a lot of objects to create, the scene changes will seem seamless.
You can easily reuse code over scenes with inheritance and extension with scene name:
public class MyUIClassWithManyCommonCode:MonoBehaviour{}
public class FrontPage : MyUIClassWithManyCommonCode{}
public class CatalogPage : MyUIClassWithManyCommonCode{}
And finally since, you limit the amount of objects in a scene to only what should be seen, it is easy to find an object in the scene.

Understanding scenes in Unity3d

I have some confusion with scenes in Unity3d and I was not able to find any resources about them.
When should scenes be used? For example in a platformer would every level have to be a different scene? Would the main menu be a scene?
Can one overlay scenes?
How do assets work between scenes? Are they attached to each individual scene and have to be reloaded every time. Can one specify when an asset is no longer needed?
How does one send data between scenes/interface between scenes?
I understand that this is a broad topic, but I didn't want to spam with multiple questions.
When should scenes be used? For example in a platformer would every
level have to be a different scene? Would the main menu be a scene?
There are no general rules about that. In theory you may have just one scene for the whole game.
How you organize your scenes is entirely up to you and often depends on the type of game you are creating.
I think that there are at least 3 features to be considered of using scenes:
they are a logical container for all pre-instantiated objects that might be useful to divide your game into multiple levels/sections.
You can serialize cross references between GameObjects and Components inside a scene (if GO A needs a ref to GO B, and they belong to the same scene, the reference can be serialized and you no longer need to find the referenced object at runtime)
When you load (not in an additive way) another scene, the resources already loaded into memory are automatically released
Can one overlay scenes?
Yes you can using LoadAdditive. Unfortunately, once 2 scenes are both loaded into memory there is no automatic way of distinguish objects belonging to one or the other. So if you load additive a second level environment, it's up to you to keep track of the previous environment and explicitly destroy it if you need to.
How do assets work between scenes? Are they attached to each
individual scene and have to be reloaded every time. Can one specify
when an asset is no longer needed?
As defaults every GameObject of a scene will be destroyed once the new scene is loaded (unless you use an additive scene loading). A way to make a GameObject survive across scenes is to mark it using DontDestroyOnLoad.
If you need to share a particular "configuration" of a GameObject, you can store it as a prefab, and reference it across scenes (but remember that once in a scene it's a prefab instance, so the GO shares with the prefab the initial serialized and not overriden properties, but 2 instances of the same prefab are different objects).
How does one send data between scenes/interface between scenes?
Several ways, depending on what kind of persistent data you want to share.
For a particular GameObject instance let the object survive using DontDestroyOnLoad.
If you have some configuration data that doesn't need to be attached to a specific GameObject you can consider storing a ScriptableObject inside the AssetDatabase and reference it.
If you have data that must persist across different game sessions you can consider storing them into PlayerPrefs.
There are 2 other ways that I don't like, but just to cite them:
Using a static field can sometimes help you in doing that, but it has several problems from my point of view
Save and load from disk (could be useful in several situations, but often it's a platform dependent way and you can have some trouble especially on different mobile platforms)
This is a broad topic btw, I hope this answer can be a quite decent overview.
When should scenes be used? For example in a platformer would every level have to be a different scene? Would the main menu be a scene?
There is no rule as to how many scenes you need to have in your game. However, scenes allow you to logically separate out parts of your game from the rest of it. You have to have a minimum of one scene.
By main menu, if you are referring to a canvas with your UI elements, it will be IN a scene and not a scene itself. Canvas is just another GameObject, that we mostly happen to use for showing game menus. I mostly create a Canvas GameObject, put a script by the name of "UIManager" and put DontDestroyOnLoad on it, so I have access to it in all scenes. Make it Singleton and I ensure that it is not duplicated.
Can one overlay scenes?
Yes, there is no restriction as to how many scenes you can load at a time. What purpose do you plan to overlay scenes though? Maybe there is a better way than loading additively.
How do assets work between scenes? Are they attached to each individual scene and have to be reloaded every time. Can one specify when an asset is no longer needed?
Assets are what you see in your 'project' hierarchy. I think you meant "GameObject"s in the scene, and if so, think of your gameobjects as entities with components (Entity-Component System). All entities in a scene get destroyed when its parent scene is destroyed until explicitly stated not to, using DontDestroyOnLoad in some component (a monobehavior in case of unity). The destroyed ones will get garbage collected.
So how they are loaded (or reloaded) depends on your implementation, on whether you are instantiating/destroying them time an again or if you put their instantiated prefabs in a cached object and retrieving later from it.
How does one send data between scenes/interface between scenes?
Heisen covered the ones I could think of. Just to add a little bit to it, it also depends on how you want to the architect your project. So if you had an underlying data structure to e.g. hold Commands, you are free to use it in any part of your project
Most games would be organised to have scenes for every level(including the main menu) but that is entirely up to you.
You can use the data from one scene to another if you save it in a text file or binary. There are a lot of tutorials on how to do this. I find documentation helps a lot.
Assets are universal in a project.
You can not overlay scenes.
When should scenes be used? For example in a platformer would every level have to be a different scene? Would the main menu be a scene?
When to use a scene is up to you. If you are just starting I would recommend using a different scene for each section of your game.
Can one overlay scenes?
Yes, using LoadSceneMode.Additive(). (LoadAdditive() is obsolete)
How do assets work between scenes? Are they attached to each individual scene and have to be reloaded every time. Can one specify when an asset is no longer needed?
By default, assets are deleted when using SceneManager.LoadScene(). However, if you use DontDestroyOnLoad(), the object will not be destroyed when entering new scenes. If you want to only keep an object through a few scenes instead of all, use Destroy() with some boolean logic.
How does one send data between scenes/interface between scenes? I understand that this is a broad topic, but I didn't want to spam with multiple questions.
You can send data through scenes by using the aforementioned DontDestroyOnLoad(), referencing the data on different scripts, using ScriptableObjects, using JSON Serialization, using StreamWriter(), using PlayerPrefs (Don't use for important information), the list goes on. I would personally recommend using ScriptableObjects for their accessibility, and StreamWriter() for it's encryption capabilities.

Which design pattern to use for a 2D iPhone game?

To give a little background about the game: falling items float from the top, and the objective is to flick/slide another object to hit them. If an item hits the ground, you lose a life, and gain points for hitting falling items.
Here is where I'm a little confused. In O'Reilly's iPhone game development. They state have the AppDelegate inherit a game state machine object, and have the main game loop in the App Delegate. Nothing about MVC.
I was going to use MVC. I have all the objects identified for the models, and was going to use one controller to update each model and their corresponding view. Then have a navigation controller in the App Delegate, and push certain controllers (Play, instructions, stats) from the home screen. Then have the game loop run in my gameViewController. I am using Chipmunk as a physics engine by the way.
This is my first game so I'm little confused. I would greatly appreciate any advice on how to proceed. I would like to get the object orientated design right from the start before jumping into code.
I don't think MVC is really what you want here. MVC could apply to your overall application state - ie a view for the menu, a view for the gameboard etc. It doesn't fit well WITHIN the game play - at least just thinking off the top of my head.
Take a look at this post on gameDev. Lots of useful patterns from people smarter about this than I.
https://gamedev.stackexchange.com/questions/4157/what-are-some-programming-design-patterns-that-are-useful-in-game-development
My MVC goes something as follows. Each Game Object that is create is just a single Model. Empty data with no logic attached. When the object is created it also gets a Brain or controller attached to it. Each created Brain is added to the Brain list. The Brain List updates each brain and the brains change the Model.
To show something on screen the Brain adds the Model to the Scene. The scene keeps a list of all the models it is rendering. The Scene is also Updated from the Game Loop. Each update the Scene looks at each Model, any model without a View, is given a view (a new view is created based on data in the model). The Scene then tracks the view until the Model's data says it no longer needs it.
When I have been working on the iPhone I like to break the game loop out onto its own thread. Those folks over at O'Reilly are pretty smart though so take what I've got to say with a grain of salt.
[NSThread detachNewThreadSelector:#selector(GameLoop:) toTarget:self withObject:nil];
Then the game loop itself is updating first the Brains (or "Controller List"), then the Scene (or "view list").
The final piece that ties it all together is the input. For iPhone I use a full screen View. In the touchesBegan and touchesEnd of the view I generate Events which I pass off to the InputManager. The InputManager will send events to different models as needed.
Do you not consider that game state machine to be a kind of data model? I don't have the O'Reilly book you mention, but the description you give sounds to me very much like MVC.
The main point of MVC is to separate an application's content from the way that content is represented on the screen. The "model" in MVC doesn't have to consist of dumb data objects that you read from a file or a web server... it could just as easily be a simulation, a connection to another device, etc. The way I think of it is that the model is the part that you'd keep if you were going to throw out app's GUI and replace it with a script, a command line interface, or maybe a web service. A game state machine could certainly fit that description.
It's not uncommon in an iOS app to have the application delegate instantiate the model. You then have view controllers that know how to talk to the model and translate the data that it provides into something that can be displayed in the view(s). If some of the data that the model provides are graphic elements like textures or meshes, that's okay... those are the data that the game operates on, after all.

How to organize multiple xna game components?

I am programming in XNA and need help on organizing my classes and code:
I have a button class and a button manager.
I also have a scene class and a scene manager.
The button manager handles the different buttons that would be drawn on different screens since almost all screens would have a button.
The scene manager does the same thing except instead of handling buttons it handles background scene objects that just need to be drawn.
Both managers depend on the current game state to determine which buttons or scene objects to draw.
How should I organize my code so that both managers know what the current game state is? (Both managers are instantiated inside of the main game class and both managers are game components)
The keyword you are looking for that describes your problem is "Game state management" The XNA website has a few good articles on it, be sure to read this one: http://create.msdn.com/en-US/education/catalog/sample/game_state_management
Now to answer your question more directly. Say you have 2 different states
-Menu
-Game
First create a class called State with methods to setup draw and update the correct UI elements.
Now create a class MenuState deriving from State and override the setup, draw and update methods. In the setup method put all the code to generate the correct menu. (Like Scene.MenuItems.Clear(); Scene.MenuItems.Add(new Label(..)); etc..). Do the same for the update and draw methods (update and draw each control, capture events given by clicks on buttons etc...)
Do the same for GameState.
Now in your Scene code make a field "State state". When a user presses escape set state to (a new) MenuState. When a user returns to game set state to (a new) GameState. In the scene's update and draw methods place a call to state.Update(..) and state.Draw(..). Because you've overriden these methods in GameState and MenuState the correct actions will be performed.
This approach solves the issue of having a gazzillion controls that do checks like "if(scene.StateEnum == StateEnum.SomeState){DoThis();}". You will find this way easier to manage.
Also think about building other conceptual classes. Like the MenuState could have a substate, "Options menu". Maybe think up a form class, etc...
SInce GameComponent has a Game property, you can use this to cast to the Game class, or alternatively to get a Service exposing the Game Status.