How to create an Android 2D game? - android

I'm an dev still learning in Android, I've created two apps so far, an alarm clock, a widget and a pass manager using databases, I have a little bit of experience, but I'd like to create a 2D side scroller game, I check on the web and there are different tutorials, but, what's the best way to start working on it? I've read about libgdx but I'm not sure if it's outdated.
I've seen that all the games are made in Java, and then ported to Android, is this correct? I would appreciate some guidance, thanks!

You have multiple options, you can either go for AndEngine (which to me seemed extremely underdocumented and random), make your own "native" Android game with extending from a SurfaceView (which isn't impossible but it certainly doesn't make your life easy, especially when handling images and especially sound, but here's a setup for it: Using a custom SurfaceView and thread for Android game programming (example)), and there's LibGDX.
I personally recommend LibGDX, I even made a fairly simple 4-player multiplayer game in it and it certainly was not difficult. I'd recommend the following tutorial on how to get to it: http://www.gamefromscratch.com/page/LibGDX-Tutorial-series.aspx
And the basics are the following:
When you create a project, the first thing you want to do is change the ApplicationAdapter to Game so you'll have access to the setScreen(Screen) delegation function, so that you can seperate the display and logic of your game into Screens.
You want to handle elapsed time in your Screen, which is done as the following: How to track time in Libgdx(android)
You probably want to make a menu, which of course can be done with pretty pictures and BitmapFonts, but I'll point you to the official wiki ( https://github.com/libgdx/libgdx/wiki ) with that. You can use Scene2D, although I found it slightly difficult, so I personally made a menu made of rectangles, it worked fairly well: LibGDX - Custom Click Listener?
A bit more "click oriented" guide on how I handled touch events using LibGDX: https://stackoverflow.com/a/24511980/2413303
Afterwards, it's literally just implementing game logic, timers, data models, behavior.
The way I solved the stretching rather than using a StretchingViewport or the in-built cameras was the following:
public class Resources
{
public static Texture texture;
public static SpriteBatch batch;
public static Matrix4 normalProjection;
public static BitmapFont bitmapFont;
public static ShapeRenderer shapeRenderer;
....
}
public static void initialize()
{
int width = Gdx.graphics.getWidth();
int height = Gdx.graphics.getHeight();
Resources.bitmapFont = new BitmapFont();
Resources.shapeRenderer = new ShapeRenderer();
Gdx.gl.glLineWidth((width < 640 && height < 480) ? 2.5f : 6f);
//camera = new OrthographicCamera(1, h / w); //I didn't use this at all
Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
loadTextures();
Resources.batch = new SpriteBatch();
Resources.normalProjection = new Matrix4().setToOrtho2D(0, 0, 480, 320); //model is 480x320
Resources.batch.setProjectionMatrix(Resources.normalProjection);
Resources.shapeRenderer.setProjectionMatrix(Resources.normalProjection);
}
public class InputTransform
{
private static int appWidth = 480;
private static int appHeight = 320;
public static float getCursorToModelX(int screenX, int cursorX)
{
return (((float)cursorX) * appWidth) / ((float)screenX);
}
public static float getCursorToModelY(int screenY, int cursorY)
{
return ((float)(screenY - cursorY)) * appHeight / ((float)screenY) ;
}
}
Make sure to dispose resources that need disposing, in the Game's dispose() callback.

Libgdx is not outdated and is, IMHO, the best way to program for android. The reason ist, that you can develop 99% on desktop (ofc think about the controlls, which won't be a keyboard on android) and then you have a working android app with a few lines only.
If you instead develop for android directly, you need to use the verry slow emulator or you have to send the app to a testphone, just to debug your code. This is a lot slower then debuging on desktop directly.
Libgdx is verry efficient, easy to use (as soon as you understan how it works) and has a verry good documentation.
For tutorials: I wrote an answer here on SO, which seemed to help some people. It is a short "tutorial" which shows only the verry basics and i have added the links to some tutorials which helped me learning it. So i hope it helps you to^^

Related

how i can remove lagging in my unity android game?

I am adroid proggrammer,because of many object in scene my game has lagging
i have theory for remove lagging in my game.
if i can control rendering in unity i can remove lagging.
using UnityEngine;
using System.Collections;
public class Enemy : MonoBehaviour {
void Update(){
void Start(){
GetComponent<Renderer>().enabled = false;
}
object2 = GameObject.Find("TR");
var distance = Vector3.Distance(gameObject.transform.position, object2.transform.position);
print (distance);
if(distance <= 80){
GetComponent<Renderer>().enabled = true;
}
}
}
Don't work.how can i have boolean render that when have collision will render
else remove.
i want have zone that all object in my zone rendered and allthing outside do not render.
void OnTriggerEnter(Collider collision)
{
if(collision.gameObject.tag == "zone")
{
GetComponent<Renderer>().enabled = true;
}
else{
GetComponent<Renderer>().enabled = false;
}
don't work
void OnTriggerEnter(Collider collision)
{
if(collision.gameObject.tag == "zone")
{
gameObject.SetActive(false);
}
else{
gameObject.SetActive(true);
}
This is either implemented in Unity or implementing it is a bad idea because raycasts are expensive and you need a lot of them. Try finding other problems which cause lagging in your game, disable feature by feature and write how many frames you have, this will get you best overview of what's the problem. Look online which methods are expensive (Instantiating, Destroy, try merging all models you have, smaller amount of shaders, fast shaders, less textures to load, FindGameObjectByName (or tag...)).
Here you will find a great document about optimization. It's preapared for mobile devices but i hope you will find what you need: Unity Optimization Guide for x86 Android
I would recommend having your blue blobs in an object pool, and the ones leaving your screen getting disabled.
You know your position and you know the position of the objects in the pool, you can math your distance in one direction, for instance behind you and disable after x amount.
Raycasting or collisions are abundant.
On your terrain generation scripts, check for disabled pool objects and if one exist, it should be put ahead in the level and repositioned or w/e logic you have there.
Don't instantiate and destroy unless you really need it, do it on level-load instead of on the fly.
(It's expensive.)
There's some really good tutorials on the unity page, have a look there.
They cover things like endless-runners.

Understanding outdated Libgdx code

Am trying to understand the following piece of code. According to the author,
he is trying to reset the camera position based on the gutter width and height. By gutter, I take it the author means the black bars on the screen.
The problem is that I cant seem to find the methods
setViewport(int,int,boolean) and getGutterWidth() and getGutterHeight() on the Stage class. I think this code was written with an outdated Libgdx API. What am looking for is the equivalent code that will perform the same task as this outdated code:
private Stage stage;
public void resize(int width, int height){
stage.setViewport(MyGame.WIDTH, MyGame.HEIGHT, true);
stage.getCamera().translate(-stage.getGutterWidth(),
-stage.getGutterHeight(), 0);}
These black bars are now handled by the viewport classes, see https://github.com/libgdx/libgdx/wiki/Viewports for a overview and short description.
In our case I would suggest a FitViewport:
Viewport viewport = FitViewport(MyGame.WIDTH, MyGame.HEIGHT, camera);
Stage stage = new Stage(viewport);

Android AndEngine two circles collision perfectly

Android AndEngine two circles collision perfectly. I have two circle and a collision method for them, I want when they touch each other the collision happens, currently when they near each other the collision happens.
I think that it is because of the transparent free space in the .png file of each circle.
In the picture you can see that now they collide from a distance, I want when both touch each other.
My collision method:
if (circle1.collidesWith(circle)){
Score += 1;
}
I am almost sure you are right that transparent places in png causes it. You probably creating BoxBody. In your case you should use circle body like this:
Body circleBody = PhysicsFactory.createCircleBody(pWorld, pSprite, BodyType.StaticBody, FixtureDef);
If it doesn't help there is method overload where you can provide position and size of the body. I can recommend you using DebugRender which you only have to attach to scene:
new DebugRenderer(physicsWorld, vbom)
When u use this you will see how helpful it can be:) Just remember that it may slowdown your phone when you have a lot of bodies on the scene.
PS. You didn't give us a lot of information but you should use contactListener to check colisions. There are plenty of tutorials in the internet for it
PS2. If you don't use Box2D extension - do it. This is great feature of AndEngine and it's pointless to implement that for yourself. It will be hard to detect circle shape collision of 2 objects without Box2D.
If you are not in Box2d , You must use Pixel-Perfect Collision library. Well default AndEngine Library, Does not support pixel perfect collision. To get this support, you need to import this library in eclipse and add this to your project uses library.
Here, I Demonstrate how to use this library. When you define Texture and Atlas for your sprite write as below.
private BitmapTextureAtlas lifeAtlas;
public PixelPerfectTiledTextureRegion life_Texture;
PixelPerfectTextureRegionFactory.setAssetBasePath("gfx/game/");
lifeAtlas = new BitmapTextureAtlas(textureManager, 1280, 128,
TextureOptions.BILINEAR);
life_Texture = PixelPerfectTextureRegionFactory.createTiledFromAsset(
lifeAtlas, activity, "heart_tiled.png", 0, 0, 10, 1, 0);
lifeAtlas.load();
For your custom sprite class,
public class Plane extends PixelPerfectAnimatedSprite {
public Plane(float pX, float pY,
PixelPerfectTiledTextureRegion pTiledTextureRegion,
VertexBufferObjectManager pVertexBufferObjectManager) {
super(pX, pY, pTiledTextureRegion, pVertexBufferObjectManager);
setColor(Color.GREEN);
}
}
You also need some adjustment with your AndEngine library to use it. Follow this thread to go.

android libgdx bitmap fonts turn to black rectangles after a while

I'm using gdx-freetype library in android to generate BitmapFont from TrueType font which is in assets/fonts/arial.ttf
This is the way I use to show some text on screen
generator = new FreeTypeFontGenerator(Gdx.files.internal("fonts/arial.ttf"));
font30 = generator.generateFont(60 , "ConectigTsrv" , false);
generator.dispose();
Label l = new Label("Connecting to server...", new LabelStyle(font30 , Color.BLUE));
l.setX(400 - l.getWidth()/2f);
l.setY(480 - l.getHeight() - 10);
stage.addActor(l);
text will be printed to screen very well
But after a while or when I push Home button and then come back to application all characters turn to black rectangles
Any idea about whats going on?
The problem is that the textures created by FreeTypeFontGenerator were not managed until this recent commit. The fact that textures are unmanaged means that they have to be reloaded following a loss of the OpenGL context, which occurs in scenarios such as the one you described.
If you upgrade libgdx to the latest nightlies then the problem will probably go away.
For more information, the problem with unmanaged textures is described very well in this article.
In case anyone is still having this problem. Using LibGDX 1.9.2, I had this problem as well:
Run the game, navigate 'back' to Android home screen, go back to the game and fonts would be black rectangles.
Turned out I was loading all textures in a static way, which only loads them once at game start and never again:
//THIS IS WRONG
public class Styles {
public static final BitmapFont HEADER_FONT;
public static final FreeTypeFontGenerator _freeTypeFontGenerator = ...
static {
FreeTypeFontGenerator.FreeTypeFontParameter params = ...
HEADER_FONT = freeTypeFontGenerator.generateFont(params);
}
}
This causes trouble when the game is reloaded in memory. As far as I understand, the final fields now refer to non-existent texture data. To fix that, I got rid of the final properties and load them in the create() function, recreating all assets each time the game is reloaded in memory:
public void onCreate() {
Styles.loadAssets();
}
And in Styles:
//STATIC RESOURCES CAN CAUSE TROUBLE, KEEP IT IN MIND
public class Styles {
public static BitmapFont HEADER_FONT;
public static FreeTypeFontGenerator FONT_GENERATOR = ...
public static void loadAssets() {
FreeTypeFontGenerator.FreeTypeFontParameter params = ...
HEADER_FONT = FONT_GENERATOR.generateFont(params);
}
}
I prefer my read-only assets to be static to be memory friendly. However, the use of static resources may still create problems I'm not aware of, as per the manual.

How load a lot of textures in andengine

I am trying to load textures as follows:
private Texture mTexture;
...
public Textures(final BaseGameActivity activity, final Engine engine) {
this.mTexture = new Texture(2048, 1024,
TextureOptions.BILINEAR_PREMULTIPLYALPHA);
this.mBackgroundTextureRegion = TextureRegionFactory.createFromAsset(
this.mTexture, activity, "img/back.png", 0, 0);
this.mSwingBackTextureRegion = TextureRegionFactory.createFromAsset(
this.mTexture, activity, "img/player.png", 836, 0);
...
I want to load more than 200 textures. However, the current method that I am using is too long.
Are there faster methods to complete it?
I am working in GLES1.
The easiest way to do it is with Texture Packer, found here
This allows you to add multiple image files in to one easy to load spritesheet. The engine loads this spritesheet in to a texture and creates a class that lets you easily reference each image from that spreadsheet. Turn 200 TextureRegions in to 1 TexturePack.
I'm using GLES2 and I'm not sure where the source files are for GLES1. Poke around the forums and you should be able to find out how to use them. There has been plenty of talk about it.
There is a texture packer built in AndEngine which does this automagically. Try searching the AndEngine forum.
http://www.andengine.org/forums/

Categories

Resources