Basic Game GUI and layout

  ... tutorials on how to use AndEngine.

Basic Game GUI and layout

Postby kblood » Tue Feb 28, 2012 9:46 pm

Hi all,

I am going to make another tutorial. I already made this tutorial:
topic5652.html

But I will try to start from scratch and redo most of it. Mainly because its much easier to make simpler tutorials using my own projects instead of someone else's. But part of the focus was also on the difference from older versions of AndEngine compared to the newer versions. I am still not working completely in GLES2, because it still seems much easier to do stuff in the GLES1 version of AndEngine, and so far its much easier to import / export projects. And I like being able to test my projects on my HTC Hero phone as well just to see how well it performs. I do hope to support such phones from the early parts of the Android timeline as well. And I am pretty sure GLES2 targets Android 2.2+

What will the focus of this tutorial be? Well mostly what I do is I pick up the tutorials from other people, and implement them in projects of my own to see how well they work out. And I know from myself how much easier it is to understand when seeing it in a complete project, instead of just snippets of the source code. The focus will be on how to make a much more graphical UI and custom controls setup.

First off, I will just link the project I have made to show where it is now, and I will then begin explaining each part of it in different tutorials in this thread.

The newest versions of the APK and the project can be found here:
http://dionysus.dk/devstuff/downloads/
I put all the Android stuff I am testing there for development purposes.
Here is the most recent zip:
http://dionysus.dk/devstuff/downloads/a ... rejarl.zip
Most recent APK:
http://dionysus.dk/devstuff/downloads/a ... rejarl.apk

Have fun looking through the code. So far it has a scroll menu, a highscore (I will make a new highscore viewer), 3 demos, a splash screen and the on screen control setup which is what have kept me from making new tutorials for a few months I think it is now.

Its probably a bit much to take in all at once. I have not cleaned up the code much yet, but most of it should have helpful lines of text explaining what is going on since I already added those in the last tutorial. I will add more of those in newer versions, explaining what it all does.

I will add some credits as well, they are already in the code, but they will be added here as I go through the tutorial. I am picking up most of this from other tutorials / examples and they deserve credit as well of course.
Attachments
AndEngHardwareJarl.apk
The APK file, if you want to test this version on your device.
(3.31 MiB) Downloaded 242 times
AndEngHardwareJarl.rar
The complete project. Lets call it beta 1.
(9.59 MiB) Downloaded 432 times
Last edited by kblood on Wed Feb 29, 2012 1:30 pm, edited 1 time in total.
kblood
 
Posts: 333
Joined: Wed May 25, 2011 10:13 pm

Re: Basic Game GUI

Postby kblood » Tue Feb 28, 2012 10:26 pm

First off, I will try to explain the splash screen. For more basic Android setup, see:
tutorials/galaga-like-game-space-assault-t5652.html
Also that whole thread is about the game where I got this splash screen setup from. I just made it work with the more recent versions of AndEngine.

This splash screen is for making it possible to cycle through several splash screens, showing the game title, credits to AndEngine, the maker of the game and whatever you might want to be shown as a splash screen.

I am thinking about adding a skip button to it. Seems like a useful thing to have.

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. package dk.dionysus.hjarl; // Change this to your own package if you are adding it to your own project.
  2.  
  3. import org.anddev.andengine.engine.Engine;
  4. import org.anddev.andengine.engine.camera.Camera;
  5. import org.anddev.andengine.engine.options.EngineOptions;
  6. import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation;
  7. import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
  8. import org.anddev.andengine.entity.IEntity;
  9. import org.anddev.andengine.entity.modifier.AlphaModifier;
  10. import org.anddev.andengine.entity.modifier.DelayModifier;
  11. import org.anddev.andengine.entity.modifier.IEntityModifier.IEntityModifierListener;
  12. import org.anddev.andengine.entity.modifier.LoopEntityModifier;
  13. import org.anddev.andengine.entity.modifier.LoopEntityModifier.ILoopEntityModifierListener;
  14. import org.anddev.andengine.entity.modifier.SequenceEntityModifier;
  15. import org.anddev.andengine.entity.scene.Scene;
  16. import org.anddev.andengine.entity.scene.background.ColorBackground;
  17. import org.anddev.andengine.entity.sprite.Sprite;
  18. import org.anddev.andengine.opengl.texture.TextureOptions;
  19. import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
  20. import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
  21. import org.anddev.andengine.opengl.texture.atlas.bitmap.source.IBitmapTextureAtlasSource;
  22. import org.anddev.andengine.opengl.texture.region.TextureRegion;
  23. import org.anddev.andengine.ui.activity.BaseGameActivity;
  24. import org.anddev.andengine.ui.activity.BaseSplashActivity;
  25. import org.anddev.andengine.util.modifier.IModifier;
  26. import org.anddev.andengine.util.modifier.LoopModifier;
  27.  
  28. import android.app.Activity;
  29. import android.content.Intent;
  30. import android.widget.Toast;
  31.  
  32. public class GameSplashActivity extends BaseGameActivity {
  33.         private static final int CAMERA_WIDTH = 470;
  34.         private static final int CAMERA_HEIGHT = 270;
  35.        
  36.         private Camera camera;
  37.         private BitmapTextureAtlas texture;
  38.         private TextureRegion pictureRegion;
  39.         //private final String backgroundImage = "gfx/AndEngineText.png"; // from the original script
  40.        
  41.         @Override
  42.         public Engine onLoadEngine() {
  43.                 this.camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
  44.                 final EngineOptions engineOptions = new EngineOptions(true,
  45.                                 ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy( // you need to set this to PORTRAIT  instead of LANDSCAPE if you want to change the orientation.
  46.                                                 CAMERA_WIDTH, CAMERA_HEIGHT), this.camera);
  47.                 return new Engine(engineOptions);
  48.         }
  49.  
  50.         @Override
  51.         public void onLoadResources() {
  52.                 texture = new BitmapTextureAtlas(512, 512, TextureOptions.BILINEAR); // For storing the splash screen texture
  53.                 BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); // We will expect all images to be be in the assets/gfx folder
  54.                 pictureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.texture, this, "startbox.png", 0, 0); // The first splash screen image is added here.
  55.                 mEngine.getTextureManager().loadTexture(this.texture); //Loading the texture into memory. Easy to forget when adding new textures for new graphics. You can load several textures at once if you use loadTextures instead, and then put a , between each texture to load.
  56.         }
  57.  
  58.         @Override
  59.         public Scene onLoadScene() {
  60.                 final Scene scene = new Scene(1); // The scene where our camera viewpoint will focus on, and were we will be placing our splash screen.
  61.                 scene.setBackground(new ColorBackground(0, 0, 0)); // Change the scenes background color to contain no red, green or blue. Making it black.
  62.  
  63.                 final int x = (CAMERA_WIDTH - this.pictureRegion.getWidth()) / 2;
  64.                 final int y = (CAMERA_HEIGHT - this.pictureRegion.getHeight()) / 2;
  65.                 // ^^ A little math trick for centering our picture region on the camera.
  66.  
  67.                 final Sprite picture = new Sprite(x, y, this.pictureRegion); // Make a sprite with the picture region as its graphic.
  68. // A sprite is a game object, and makes it for us to add modifiers to it.
  69. // The sprite is what we use to show our splashscreen image and move it.
  70.                 picture.setAlpha(0); // makes our picture sprite transparent
  71.  
  72.                 // I took this entity modifier code from the AndEngineExamples (because the original was old AndEngine code)
  73.                         final LoopEntityModifier entityModifier =
  74.                                 new LoopEntityModifier(
  75.                                                 new IEntityModifierListener() {
  76.                                                         @Override
  77.                                                         public void onModifierStarted(final IModifier<IEntity> pModifier, final IEntity pItem) {
  78.                                                                 GameSplashActivity.this.runOnUiThread(new Runnable() {
  79.                                                                         @Override
  80.                                                                         public void run() {
  81.                                                                                 // Any code here will run at the same time as the splash screen runs, or at least the first modifier.
  82.                                                                                
  83.                                                                                 // Toast for debugging
  84.                                                                                 // Toast.makeText(GameSplashActivity.this, "Sequence started.", Toast.LENGTH_SHORT).show();
  85.                                                                         }
  86.                                                                 });
  87.                                                         }
  88.  
  89.                                                         @Override
  90.                                                         public void onModifierFinished(final IModifier<IEntity> pEntityModifier, final IEntity pEntity) {
  91.                                                                 GameSplashActivity.this.runOnUiThread(new Runnable() {
  92.                                                                         @Override
  93.                                                                         public void run() {
  94.                                                                                 // Any code here will run at the same time as the splash screen finishes
  95.                                                                                
  96.                                                                                 // Toast for debugging
  97.                                                                                 // Toast.makeText(GameSplashActivity.this, "Sequence finished.", Toast.LENGTH_SHORT).show();
  98.                                                                                 Intent menu = new Intent(GameSplashActivity.this, ScrollMenu.class); // Creates an intent in this activity, to prepare the next class
  99.                                                                                 startActivity(menu); // Runs the menu activity
  100.                                                                                 finish(); // Ends this activity to stop it from hogging precious Android memory.
  101.                                                                         }
  102.                                                                 });
  103.                                                         }
  104.                                                 },
  105.                                                 2, // Loop count. Want more loops to add more splash screens or something else? Just change this number.
  106.                                                 new ILoopEntityModifierListener() {
  107.                                                         @Override
  108.                                                         public void onLoopStarted(final LoopModifier<IEntity> pLoopModifier, final int pLoop, final int pLoopCount) {
  109.                                                                 GameSplashActivity.this.runOnUiThread(new Runnable() {
  110.                                                                         @Override
  111.                                                                         public void run() {
  112.                                                                                 // Do something while the loop is rolling
  113.                                                                                
  114.                                                                                
  115.                                                                                
  116.                                                                                 // A toast message that is useful for debugging.
  117.                                                                                 //Toast.makeText(GameSplashActivity.this, "Loop: '" + (pLoop + 1) + "' of '" + pLoopCount + "' started.", Toast.LENGTH_SHORT).show();
  118.                                                                         }
  119.                                                                 });
  120.                                                         }
  121.  
  122.                                                         @Override
  123.                                                         public void onLoopFinished(final LoopModifier<IEntity> pLoopModifier, final int pLoop, final int pLoopCount) {
  124.                                                                 GameSplashActivity.this.runOnUiThread(new Runnable() {
  125.                                                                         @Override
  126.                                                                         public void run() {
  127.                                                                                 // Toast.makeText(GameSplashActivity.this, "Loop: '" + (pLoop + 1) + "' of '" + pLoopCount + "' finished.", Toast.LENGTH_SHORT).show();
  128.                                                                                 if (pLoop == 0) { //pLoop is the number of times this modifier has been loop.
  129.                                                                                         texture.clearTextureAtlasSources(); // Clear the first splash screen from our texture
  130.                                                                                         BitmapTextureAtlasTextureRegionFactory.createFromAsset(texture, GameSplashActivity.this, "AndEngineText.png", 0, 0); // Load the second splash screen onto the texture instead
  131.                                                                                 }
  132.                                                                                 if (pLoop == 1) { //pLoop is the number of times this modifier has been looped.
  133.                                                                                         texture.clearTextureAtlasSources(); // Clear the splash screen from our texture
  134.                                                                                         BitmapTextureAtlasTextureRegionFactory.createFromAsset(texture, GameSplashActivity.this, "startbox2.png", 0, 0); // Load this splash screen onto the texture instead
  135.                                                                                 }
  136.                                                                                 if (pLoop == 2) { //pLoop is the number of times this modifier has been looped.
  137.                                                                                         texture.clearTextureAtlasSources(); // Clear the splash screen from our texture
  138.                                                                                         BitmapTextureAtlasTextureRegionFactory.createFromAsset(texture, GameSplashActivity.this, "startbox3.png", 0, 0); // Load this splash screen onto the texture instead
  139.                                                                                 }
  140.                                                                                 if (pLoop == 3) { //pLoop is the number of times this modifier has been looped.
  141.                                                                                         texture.clearTextureAtlasSources(); // Clear the splash screen from our texture
  142.                                                                                         BitmapTextureAtlasTextureRegionFactory.createFromAsset(texture, GameSplashActivity.this, "AndEngineText.png", 0, 0); // Load this splash screen onto the texture instead
  143.                                                                                 }
  144.                                                                                 if (pLoop == 4) {
  145.                                                                                         // You could do something here which would happen after the fourth loop. If you change the loop count this could become the third loop.
  146.                                                                                 }
  147.  
  148.                                                                         }
  149.                                                                 });
  150.                                                         }
  151.                                                 },
  152. // These are the modifiers added to each splash screen. Making them fade in and out.
  153.                                                 new SequenceEntityModifier(
  154.                                                         new DelayModifier(1),
  155.                                                         new AlphaModifier(0.5f, 0, 1),
  156.                                                         new DelayModifier(2),
  157.                                                         new AlphaModifier(0.5f, 1, 0),
  158.                                                                         new DelayModifier(0.5f)
  159.                                                                
  160.                                                 )
  161.                                 );
  162.                return scene;
  163.         }
  164.        
  165.         @Override
  166.         public void onLoadComplete() {}
  167.  
  168. }
  169.  
Parsed in 0.059 seconds, using GeSHi 1.0.8.4


The descriptions are mostly in the code. Feel free to ask any questions if you have any problems.
Last edited by kblood on Sun Mar 04, 2012 5:55 pm, edited 1 time in total.
kblood
 
Posts: 333
Joined: Wed May 25, 2011 10:13 pm

Re: Basic Game GUI

Postby kblood » Tue Feb 28, 2012 10:51 pm

Well, I think it would be nice to be possible to just skip the splash screen. The user will probably notice it the first 2-3 times before finding it possible to skip it with the back key anyway. Add this code to make it possible to skip past the splash screens:

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.             @Override
  2.                 public boolean onKeyDown(final int pKeyCode, final KeyEvent pEvent) {
  3.                 // Maybe the user decides to use Android buttons instead? Lets try to stop the user from quitting with the back button, by accident.
  4.                 // And in this case, let him skip the splashscreen and go directly to the ScrollMenu.
  5.  
  6.                         if (pKeyCode == KeyEvent.KEYCODE_BACK
  7.                                         && pEvent.getAction() == KeyEvent.ACTION_DOWN) { // Check if the back button is being pressed
  8.                                 Intent menu = new Intent(GameSplashActivity.this, ScrollMenu.class); // Creates an intent in this activity, to prepare the next class
  9.                                 startActivity(menu); // Runs the menu activity
  10.                                 finish(); // Ends this activity to stop it from hogging precious Android memory.
  11.                                 return true;
  12.                         }
  13.                        
  14.                         return super.onKeyDown(pKeyCode, pEvent);
  15.                 }
Parsed in 0.033 seconds, using GeSHi 1.0.8.4


Add it after the
public Scene onLoadScene() {
}
part of the script. Or at least outside of other functions. Or whatever they are called in Java / AndEngine. I learned it all from the web, so I am lacking lots of basic knowledge about what the actual things are called. Hopefully you will figure that out before you get too deep into Android and might get laughed at by pro coders ;)

Hope it was was useful so far. I want to do much more with the onKeyDown stuff later on, but there is still quite a lot of things to go through. Feel free to ask questions or make requests, add ideas and so on. Or add suggestions even, I am very open to them. I am a bit pressed time wise though, as most of us probably are.
kblood
 
Posts: 333
Joined: Wed May 25, 2011 10:13 pm

Re: Basic Game GUI and layout

Postby kblood » Sun Mar 04, 2012 6:26 pm

Next thing is the scroll menu. It has a complete tutorial of its own:

tutorials/menu-scroll-example-t5740.html
written by myfknoll.

But I made a few changes to it, and made it a working example. It should help making it easier to see how it works.
http://dionysus.dk/devstuff/downloads/scrollmenu.java - The full source of the changes I made.

I added a background, my own images and links to games and menus.

I used
http://cooltext.com/
to make some of the graphics.

The background is from the "Hardware Jarl" game that is one of the demo games which is still an ongoing progress. It was originally made by my brother and one of his friends as a school project, and I thought I might as well make it into an Android game, since its quite simple and should be able to teach some of the basics in Android.
My brothers website:
http://rendse.net/ - He made all the graphics for Hardware Jarl. I think the background was partly made with 3D Studio Max. And if I remember correctly Paint Shop Pro for most the 2D graphics.

And in case it is not obvious, I tried making the text look like graffiti on the planks :)

This is what I used to make it load another part of my project:

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.                                         if (iLevel == 1) {
  2.                                                                 Intent game = new Intent(ScrollMenu.this, HjarlGameActivity.class); // When clicked, run HjarlGameActivity
  3.                                                                 startActivity(game); // runs the game intent, which targets the HjarlGameActivity
  4.                                         }
Parsed in 0.035 seconds, using GeSHi 1.0.8.4


I used intents, which seem the common way of opening new game activities. You might notice how there is no
finish();
command after beginning the game activity. That is because I would like us to be able to return to this menu when closing the activity we just clicked into. It will stay in the memory, but I doubt it will be too much of a memory stealer. Optimizing is not something I have looked into much yet.

I also added the game title and the background. To make sure that these two new sprites did not follow all the menu imagines, I added these lines of code:

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.                 //set the arrows for left and right
  2.                 menuright.setPosition(mCamera.getCenterX()+CAMERA_WIDTH/2-menuright.getWidth(),menuright.getY());
  3.                 menuleft.setPosition(mCamera.getCenterX()-CAMERA_WIDTH/2,menuleft.getY());
  4.                 background.setPosition(mCamera.getCenterX()-background.getWidth() / 2,background.getY());
  5.                 title.setPosition(mCamera.getCenterX()-title.getWidth() / 2,title.getY());
Parsed in 0.037 seconds, using GeSHi 1.0.8.4


So that their X position changes, but the the Y position. Just like the menu left and right arrow.

And I added all this at the end to stop users from closing the app by accident:

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.             @Override
  2.                 public boolean onKeyDown(final int pKeyCode, final KeyEvent pEvent) {
  3.                 // Maybe the user decides to use Android buttons instead? Lets try to stop the user from quitting with the back button, by accident.
  4.  
  5.                         if (pKeyCode == KeyEvent.KEYCODE_BACK
  6.                                         && pEvent.getAction() == KeyEvent.ACTION_DOWN) { // Check if the back button is being pressed
  7.                                 showExitDialog(); // Run the showExitDialog.
  8.                                 return true;
  9.                         }
  10.                        
  11.                         return super.onKeyDown(pKeyCode, pEvent);
  12.                 }
  13.            
  14.             public void showExitDialog() { // Here a showExitDialog is prepared. Its a kind of submenu, but since it is very simple its all done without XML
  15.                 AlertDialog.Builder builder = new AlertDialog.Builder(ScrollMenu.this); // Making an AlerDialog, its an Android feature
  16.                         builder.setMessage("Are you sure you want to exit?")
  17.                                         .setCancelable(false)
  18.                                         .setTitle("EXIT")
  19.                                         .setPositiveButton("Yes",
  20.                                                         new DialogInterface.OnClickListener() {
  21.                                                                 public void onClick(DialogInterface dialog, int id) {
  22.                                                                         ScrollMenu.this.finish(); // if yes is clicked, close this class. If this class had been opened by another class, we would return to that class.
  23.                                                                 }
  24.                                                         })
  25.                                         .setNegativeButton("No", new DialogInterface.OnClickListener() {
  26.                                                 public void onClick(DialogInterface dialog, int id) {
  27.                                                         dialog.cancel(); // Of the NO choice is clicked, we cancel the AlertDialog and go back to Menuactivity2
  28.                                                 }
  29.                                         });
  30.  
  31.                         AlertDialog alert = builder.create(); // This takes the AlertDialog and prepares it
  32.                         alert.setIcon(R.drawable.icon); // Puts the application icon in the drawable folder into the dialog
  33.                         alert.show(); // shows the alert dialog
  34.            
  35.             }
Parsed in 0.041 seconds, using GeSHi 1.0.8.4


I am planning on making a close app button on the menu screen as well. I already have the graphics for one. What all of this does is making a dialogue come up and ask the user if he or she wants to quit the application, with a yes and no option. Its native Android stuff, and later on I hope to make a custom dialogue pop-up.

The "onKeyDown" part is the part that is checking whether the back button has been pressed or not, and if it has, it brings up the exit dialogue.

As always, if I am not clear enough about something feel free to ask. I am trying to make this tutorial a bit shorter and simpler than the last one. Since it became a lot of text, and not so much programming, to go through.

Here is an alternative tutorial about making a splash screen + scroll menu out of the same ScrollMenu.
*There should have been a link here but I lost it :( It was a single scene version of the scrollMenu.*
kblood
 
Posts: 333
Joined: Wed May 25, 2011 10:13 pm

Re: Basic Game GUI and layout

Postby kblood » Mon Apr 09, 2012 8:37 pm

Next topic is how to make an options menu, or just changing options in your game in general. It was requested in my other tutorial thread, and I am sorry for the delay, but I wanted to have a good example of it where I could explain each detail. The first example used xml and native android UI layout. I want it to be something that can be controlled, and easily blend in with the theme of the game.

So I took the scroll menu I just linked, and made a menu to change preferences, and made it text based as well. It also scrolls vertically now instead of horizontally. Or maybe its the other way around.

The APK to test it:
http://dionysus.dk/devstuff/downloads/a ... rejarl.apk

And the full source:
http://dionysus.dk/devstuff/downloads/a ... rejarl.zip

Its in a zip file, and its using the GLES1 version to avoid any confusion with versions of AndEngine and such. If you use the files in the zip file, you should be sure that it works. I have not tried using GLES2 much yet, but from what I have been told, its not that difficult to use my code with GLES2, somewhat small changes needed.

But how to change the preferences in Android and AndEngine? Here is what I do to make it possible:

public static Options options;
public static Controls controls;

I set this up first of all. What these do is prepare the classes we need. Lets look at how the Options class look, I have cut most of it off, to make it simple to look at:

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. package dk.dionysus.hjarl;
  2.  
  3. import android.app.Activity;
  4. import android.content.SharedPreferences;
  5. import android.preference.PreferenceManager;
  6.  
  7. public class Options {
  8.        
  9.         SharedPreferences options;
  10.        
  11.         public Options(Activity activity){
  12.                 options = PreferenceManager.getDefaultSharedPreferences(activity);
  13.         }
  14.        
  15.         public boolean getSprite(){
  16.                 return options.getBoolean("chkSprite",true);
  17.         }      
  18.        
  19.         public boolean getSoundEffects(){
  20.                 return options.getBoolean("chkSound",false);
  21.         }
  22.        
  23.         public boolean getMusic(){
  24.                 return options.getBoolean("chkMusic",false);
  25.         }
  26. }
Parsed in 0.038 seconds, using GeSHi 1.0.8.4


This adds some "Options" functions that can be used to check the states of the preferences. I made the Controls class because I wanted a separate one to manage the game controls, but it works much the same way.

public boolean getMusic(){
return options.getBoolean("chkMusic",false);
This one makes it possible to do a "if (options.getMusic()) { play music commands} since options.getMusic will return a boolean, that is true or false. chkMusic is the string under which the data should have been saved in SharedPreferences. The default value is false, if the option has not been set at all.

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. package dk.dionysus.hjarl;
  2.  
  3. // Imports here
  4.  
  5. public class OptionsActivity2 extends BaseGameActivity implements IScrollDetectorListener, IOnSceneTouchListener, IClickDetectorListener {
  6. //other variables here removed
  7.         private int MenuValue[];
  8.         private int MenuItemValue[];
  9.  
  10.         private AnimatedSprite ToggleButton[];
  11.         private List<String> MenuItem = new ArrayList<String>();
  12.         private List<String> MenuType = new ArrayList<String>();
  13.  
  14.         // ===========================================================
  15.         // Methods for/from SuperClass/Interfaces
  16.         // ===========================================================
  17.        
  18.         public static Options options; // Adding options as a function in our actvity
  19.         public static Controls controls; // And adding controls as well
  20.  
  21.         public Engine onLoadEngine() {
  22.                 options = new Options(OptionsActivity2.this); // Initializing options in this activity.
  23.         @Override
  24.         public void onLoadResources() {
  25.                
  26.                 options = new Options(OptionsActivity2.this);
  27.  
  28. // skipping some texture and variable preparation here as well. And here comes the data we want to change with data from Options:
  29.                         /* The data for the menu
  30.                          * MenuValue is to determine the highest possible value of the slider, the onoff type is either 0 or 1 (false or true).
  31.                          * MenuItem is the description text for the menu
  32.                          * MenuType is to set different types of menu items.
  33.                         */
  34.  
  35.                         MenuValue = new int[10];
  36.                         ToggleButton = new AnimatedSprite[10];
  37.                         MenuItem.add("Options");                MenuType.add("Title");
  38.                         MenuItem.add("Sprite");                 MenuType.add("OnOff");MenuValue[MenuItem.size()-1] = 0;
  39.                         MenuItem.add("Music");                  MenuType.add("OnOff");MenuValue[MenuItem.size()-1] = 0;
  40.                         MenuItem.add("Music Volume");   MenuType.add("Slider");MenuValue[MenuItem.size()-1] = 100;
  41.                         MenuItem.add("Sound");                  MenuType.add("OnOff");MenuValue[MenuItem.size()-1] = 0;
  42.                         MenuItem.add("Sound Volume");   MenuType.add("Slider");MenuValue[MenuItem.size()-1] = 100;
  43.                         MenuItem.add("Controlpads");    MenuType.add("Slider");MenuValue[MenuItem.size()-1] = 4;
  44.                         MenuItem.add("buttons");                MenuType.add("Slider");MenuValue[MenuItem.size()-1] = 6;
  45.                         MenuItem.add("Vibration");              MenuType.add("OnOff");MenuValue[MenuItem.size()-1] = 0;
  46.                         MenuItem.add("");                               MenuType.add("Empty");
  47.  
  48.  
  49.                         // Check if any of these settings are not the default setting and change it if so.
  50.                         if (options.getSprite()) MenuValue[1] = 1;
  51.                         if (options.getMusic()) MenuValue[2] = 1;
  52.                         if (options.getSoundEffects()) MenuValue[4] = 1;
  53.                         if (options.getVibration()) MenuValue[8] = 1;
  54.  
  55. //loadings textures part skipped
  56. }
  57.  
  58.         private void CreateMenuBoxes() {
  59.                
  60.                 MenuItemValue = new int[MenuItem.size()];
  61.                 // Here we get the slider bar settings:
  62.                 MenuItemValue[3] = options.getMusicVolume();
  63.                 MenuItemValue[5] = options.getSFXVolume();
  64.                 MenuItemValue[6] = options.getControlPads();
  65.                 MenuItemValue[7] = options.getButtons();
  66.               // They are all integer values.
  67. }
  68.  
Parsed in 0.050 seconds, using GeSHi 1.0.8.4


I added some more functions to options to make it possible to get these settings from options:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.         public int getMusicVolume(){
  2.                 return options.getInt("chkMusicVol",80);
  3.         }
  4.        
  5.         public int getControlPads(){
  6.                 return options.getInt("chkControlPads",4);
  7.         }
  8.         public int getButtons(){
  9.                 return options.getInt("chkButtons",6);
  10.         public int getSFXVolume(){
  11.                 return options.getInt("chkSoundVol",100);
  12.         }
Parsed in 0.038 seconds, using GeSHi 1.0.8.4


So that is how to retrieve the current preferences. We also want to be able to change them though.

So we will add another function to options:

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.         public boolean save(boolean sfx, boolean music, boolean sprite, boolean vibrate, int controlpads, int buttons, int sfxvol, int musvol) {
  2.                 // Save the changes made to options
  3.                 SharedPreferences.Editor editor = options.edit();
  4.                         editor.putBoolean("chkSprite", sprite);
  5.                         editor.putBoolean("chkSound", sfx);
  6.                         editor.putBoolean("chkMusic", music);
  7.                         editor.putBoolean("chkVibration", vibrate);
  8.                         editor.putInt("chkSoundVol", sfxvol);
  9.                         editor.putInt("chkMusicVol", musvol);
  10.                         editor.putInt("chkControlPads", controlpads);
  11.                         editor.putInt("chkButtons", buttons);
  12.                 editor.commit();
  13.                 return true;
Parsed in 0.039 seconds, using GeSHi 1.0.8.4

Now we are able to save all the settings made. Now we just need to add something that uses this function on our options menu:

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.                                                                         boolean sfx = false; boolean music = false; boolean sprite = false; boolean vibrate = false;
  2.                                                                         int controlpads = MenuItemValue[6]; int buttons = MenuItemValue[7]; int sfxvol = MenuItemValue[5]; int musvol = MenuItemValue[3];
  3.                                                                         if (MenuItemValue[1] == 1) sprite = true;
  4.                                                                         if (MenuItemValue[2] == 1) music = true;
  5.                                                                         if (MenuItemValue[4] == 1) sfx = true;
  6.                                                                         if (MenuItemValue[8] == 1) vibrate = true;
  7.  
  8.                                                                         options.save(sfx, music, sprite, vibrate, controlpads, buttons, sfxvol, musvol);
Parsed in 0.038 seconds, using GeSHi 1.0.8.4


I added it to a "when the back key was pressed" function, so the options are saved, when going back the the menu.
kblood
 
Posts: 333
Joined: Wed May 25, 2011 10:13 pm

Re: Basic Game GUI and layout

Postby Molkobain » Sat Apr 21, 2012 5:37 pm

Hi kblod,

thank you for your thread, I used it to build my own SplashScreen and as I beginning with Andengine it was very useful.
Molkobain
 
Posts: 106
Joined: Wed Apr 18, 2012 4:16 pm
Location: France

Re: Basic Game GUI and layout

Postby kblood » Sat Apr 21, 2012 5:42 pm

Molkobain wrote:Hi kblod,

thank you for your thread, I used it to build my own SplashScreen and as I beginning with Andengine it was very useful.


Good to know. I hope to add how to implement a highscore and some more customizable UI. There is already one highscore example I went through in my other guide, but like the menu, I want the layout to be within Android itself, instead of having to use XML layout and AndEngine, seems to be easier to control that way and do more with it. Like adding animations to the menu, or special buttons.
kblood
 
Posts: 333
Joined: Wed May 25, 2011 10:13 pm

Re: Basic Game GUI and layout

Postby ahmedayyad89 » Sun Apr 29, 2012 1:09 pm

i had this exception when i tried to run your src

04-29 03:22:06.193: E/AndroidRuntime(1711): FATAL EXCEPTION: main
04-29 03:22:06.193: E/AndroidRuntime(1711): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{dk.dionysus.hjarl/dk.dionysus.hjarl.GameSplashActivity}: java.lang.ClassNotFoundException: dk.dionysus.hjarl.GameSplashActivity
04-29 03:22:06.193: E/AndroidRuntime(1711): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1880)
04-29 03:22:06.193: E/AndroidRuntime(1711): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
04-29 03:22:06.193: E/AndroidRuntime(1711): at android.app.ActivityThread.access$600(ActivityThread.java:123)
04-29 03:22:06.193: E/AndroidRuntime(1711): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
04-29 03:22:06.193: E/AndroidRuntime(1711): at android.os.Handler.dispatchMessage(Handler.java:99)
04-29 03:22:06.193: E/AndroidRuntime(1711): at android.os.Looper.loop(Looper.java:137)
04-29 03:22:06.193: E/AndroidRuntime(1711): at android.app.ActivityThread.main(ActivityThread.java:4424)
04-29 03:22:06.193: E/AndroidRuntime(1711): at java.lang.reflect.Method.invokeNative(Native Method)
04-29 03:22:06.193: E/AndroidRuntime(1711): at java.lang.reflect.Method.invoke(Method.java:511)
04-29 03:22:06.193: E/AndroidRuntime(1711): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
04-29 03:22:06.193: E/AndroidRuntime(1711): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
04-29 03:22:06.193: E/AndroidRuntime(1711): at dalvik.system.NativeStart.main(Native Method)
04-29 03:22:06.193: E/AndroidRuntime(1711): Caused by: java.lang.ClassNotFoundException: dk.dionysus.hjarl.GameSplashActivity
04-29 03:22:06.193: E/AndroidRuntime(1711): at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:61)
04-29 03:22:06.193: E/AndroidRuntime(1711): at java.lang.ClassLoader.loadClass(ClassLoader.java:501)
04-29 03:22:06.193: E/AndroidRuntime(1711): at java.lang.ClassLoader.loadClass(ClassLoader.java:461)
04-29 03:22:06.193: E/AndroidRuntime(1711): at android.app.Instrumentation.newActivity(Instrumentation.java:1023)
04-29 03:22:06.193: E/AndroidRuntime(1711): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1871)
please help if you can
ahmedayyad89
 
Posts: 1
Joined: Sun Apr 29, 2012 1:06 pm

Re: Basic Game GUI and layout

Postby kblood » Sun Apr 29, 2012 10:36 pm

Difficult to say just from that.

I cannot find anything specific in those errors. You can run the APK when you run it directly, right?

APK
http://dionysus.dk/devstuff/downloads/a ... rejarl.apk

How did you take my source? Did you unpack everything and add it as a project? Did you include all of the source in the lib folder? Sometimes you also need to make it use another Java Compliance level? It should be 1.6.

I hope those questions help. Otherwise I might be able to help if you can answer them.
kblood
 
Posts: 333
Joined: Wed May 25, 2011 10:13 pm

Re: Basic Game GUI and layout

Postby kblood » Fri Jun 01, 2012 4:48 am

I will try to explain my key-binding customization now.

As some might have noticed, I have made part of my app an UI to set up keybindings for the few apps I put in.

http://dionysus.dk/devstuff/downloads/o ... setup.java

Is the file with all the coding for the setup UI. It stores the data just like the options I made a guide for above. That is under app preferences, which is something a default database for Android apps that they can use, a bit like SQLite which is more advanced and can store more data as far as I know, but just another method of data handling. I actually made this control setup first, but just wanted to do more with it before I added the tutorial, but it has the essentials and I have tested it enough.

Just like in the options, I do not use native Android like in the Space Assault tutorial for changing the preferences. It has its uses, but I just find it annoying having so little control of the looks, and having to conform, especially when using AndEngine which makes it much easier to make the layout myself. Also, for this purpose of making these controls, it certainly is not enough with using native Android and XML for layouts maybe unless you really know what you are doing and in native Android.

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.         private static final int CAMERA_WIDTH = 320;
  2.         private static final int CAMERA_HEIGHT = 192;
  3. // The resolution is a bit arbitrary. But when I save the layout of these controls, I have done it in a way that ensures that your app can use a different resolution and still be located at the same place on the screen. More on that later, but I did some math that place it relative to the height and width of the screen when we save the setup.
  4.  
  5.         // ===========================================================
  6.         // Fields
  7.         // ===========================================================
  8.  
  9.         private Camera mCamera; // The Camera we use to view the controls UI setup
  10.  
  11.         private BitmapTextureAtlas mOnScreenControlTexture;
  12.         private TextureRegion mOnScreenControlBaseTextureRegion;
  13.         private TextureRegion mOnScreenControlKnobTextureRegion;
  14.         private TextureRegion sliderTextureRegion;
  15.  
  16. // I am using the most common AndEngine textures for as much as possible. Except I made my own texture for the slider to make it easier to find its center and such.
  17.  
  18.         private Scene mScene;
  19.        
  20.         private Sprite control[];
  21.         float ControlX[];
  22.         float ControlY[];
  23.         float scale[];
  24. // All of these are arrays which is why they have the [] on them. This is to be able to use several of them at once and use them in loops to go through all the UI elements.
  25.  
  26.         private Sprite sliderbar;
  27.         private Sprite sliderknob;
  28.         private int f = 0;
  29.         private float C1X = 0;
  30.         private float C1Y = 0;
  31.         private float C1TX = 0;
  32.         private float C1TY = 0;
  33. // Some basic sprites and variables used to the setup I will go into them some more later.
  34.        
  35.         // HUD Text and HUD
  36.     private BitmapTextureAtlas mFontTexture;
  37.     private BitmapTextureAtlas mFontTexture2;
  38.     private Font mFont;
  39.     private Font mFontTiny;
  40. // Fonts and textures, mostly to be able to setup a debug HUD area which I like to use to easier debug my apps while running them, and try to figure out what the stuff on the screen is doing and why it is not always what I hoped it would do.    
  41.  
  42.  
  43.     //private BitmapTextureAtlas mFontTexture2[];
  44.     //private Font mFont2[];
  45.     // I hoped to make text for each UI element, each control and each button. But I never got it working. Its something to do with using arrays inside a button and such. I think I found a solution when I made the Options but I just havent gotten around to test it.
  46.    
  47.     HUD hud = new HUD();
  48. // A HUD. Heads up display. Its very useful when you need to move the camera around the scene, but have stuff like health, score or other UI elements that you want to follow the camera instead of staying put on the screen.
  49.  
  50. // I use it to for debug text as explained earlier.
  51.         // ===========================================================
  52.         // Constructors
  53.         // ===========================================================
  54.  
  55.         // ===========================================================
  56.         // Getter & Setter
  57.         // ===========================================================
  58.  
  59.         public static Options options; // This is to load settings from Options.java, to see how many controls to display and buttons.
  60.         public static Controls controls; // This loads settings from controls.java and uses the commands there to help setup the layout and save the key-bindings as preferences.
  61.  
  62.  
Parsed in 0.043 seconds, using GeSHi 1.0.8.4


The UI setup. I added some more explanations to it here.

This is another important file
http://dionysus.dk/devstuff/downloads/controls.java

As explained in the code above, it makes a Controls function that is used to handle these control UI elements.
kblood
 
Posts: 333
Joined: Wed May 25, 2011 10:13 pm

Next

Return to Tutorials

Who is online

Users browsing this forum: Dudi, iamthenewking, jorginhopc, mr.stormcs and 37 guests