How can I save an XML file with Unity on the Android platform?

| | August 18, 2015

I am writing a game that has a save function which looks like this

    public void Save()
    {

        System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(this.GetType());
        System.IO.StreamWriter file = new System.IO.StreamWriter(("Assets/Resources/Save");
         ser.Serialize(file, this);
        file.Close();
    }
}

This will work fine in the editor and on Windows machines, but when we build to Android the saving no longer works. Why is that?

Framerate and game loop on mobile

| | August 18, 2015

I’m searching how to manage game framerate on mobiles devices, here is my problem:

On a computer with got something like that:

void main()
{
    while(game.isRunning())
    {
        event.handle(eventInfos);
        game.update(dt);
        graphic.render();
    }
}

On a mobile device with got something like that:

void update()
{
    game.update(dt);
}

void render()
{
    game.render(dt);
}

void event()
{
    game.handle(eventInfos);
}

When I search on internet, I found something like that everytime:

-> GameLoop

-> Fix your time step

I’m using IOS (With GLKViewController) and Android (with the NDK), and I’ve that rendering method is call from another thread

Thanks for your help!

AndEngine Font Issue

| | August 18, 2015

I am learning AndEngine. I am displaying Hello world using this code:

public class myactivity extends SimpleBaseGameActivity
{

 private final int CAMERA_WIDTH = 320;
 private final int CAMERA_HEIGHT = 480;

 private Camera  m_Camera;
 private Scene  m_Scene;

 private Font  font;
 private Text  text;

 @Override
 public EngineOptions onCreateEngineOptions()
 {
  m_Camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
  EngineOptions en = new EngineOptions(true, ScreenOrientation.PORTRAIT_FIXED, new RatioResolutionPolicy(
    CAMERA_WIDTH, CAMERA_HEIGHT), m_Camera);

  return en;
 }

 @Override
 protected void onCreateResources()
 {
    //determine the density
 WindowManager windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
 Display display = windowManager.getDefaultDisplay();
 DisplayMetrics displayMetrics = new DisplayMetrics();
 display.getMetrics(displayMetrics);
 int density = (int)(displayMetrics.density);

 //scale desired size 25 by density
     int fontSize = (int) (25 * density);
  font = FontFactory.createFromAsset(this.getFontManager(), this.getTextureManager(), 1024, 1024, this.getAssets(),
    "times.ttf", fontSize, true, android.graphics.Color.BLACK);
  font.load();



//Texture fontTexture = new BitmapTextureAtlas(1024, 1024, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
//font = new Font(fontTexture, Typeface.create(Typeface.DEFAULT, Typeface.NORMAL), fontSize, true, Color.WHITE);
//mEngine.getTextureManager().loadTexture(fontTexture);
//mEngine.getFontManager().loadFont(font);

 }

 @Override
 protected Scene onCreateScene()
 {
  m_Scene = new Scene();
  m_Scene.setBackground(new Background(Color.WHITE));

  text = new Text(0, 0, font, "Hello Android", this.getVertexBufferObjectManager());
  m_Scene.attachChild(text);

  text.setPosition(CAMERA_WIDTH/2 - (text.getWidth()/2), CAMERA_HEIGHT/2 - (text.getHeight()/2));
  return m_Scene;
 }

}

It is displaying the font like this:
Hello Android displayed but with pixelated edges

As you can see that pixels are stretching and font is looking ugly with too much pixelation. How do I display proper font text with no pixelation or add anti-aliasing to the font?

Alpha Value at 0 Shows Black for Android Canvas Bitmap

| | August 18, 2015

There have been a few questions similar to this but none seem to give a straight answer. If I am creating a Bitmap from a .png image and want to set a color (i.e. true pink) to transparent, the color turns black instead. I am using get and set pixel methods, iterating through an array of pixel colors.

The method I wish to accomplish this in is as follows:

public Bitmap getFormattedBitmap(Bitmap bm, int newHeight, int newWidth, int r, int g, int b, int a) {
int width = bm.getWidth();
int height = bm.getHeight();
int pixNum = width * height;
int[] pixels = new int[pixNum];
int scaleWidth =  newWidth * width;
int scaleHeight = newHeight * height;

bm.getPixels(pixels, 0, width, 0, 0, width, height);

for(int k = 0; k < height; k++) {
   for(int j = 0; j < width; j++ ) {
        int red   = Color.red(bm.getPixel(j, k));
        int green = Color.green(bm.getPixel(j, k));
        int blue  = Color.blue(bm.getPixel(j, k));
        int alpha = Color.alpha(bm.getPixel(j, k));
        int index = k * width + j;

        if(red == 0 && green == 0 && blue == 0 && alpha == 255) {
            pixels[index] = Color.argb(a, r, g, b);
        }
        else {
            pixels[index] = Color.argb(0, 255, 255, 255);
        }
    }
}

bm.setPixels(pixels, 0, width, 0, 0, width, height);

Bitmap resizedBitmap = Bitmap.createScaledBitmap(bm, scaleWidth, scaleHeight, true);
return resizedBitmap;

}

As you can see, I am using the Color.argb() method to set the alpha to 0, but in reality, it just shows those parts as black on the screen. I recognize bitmaps don’t take kindly to alpha channels (unless you configure it to ARGB_8888), but this has me stumped. It is also interesting to note that I do have SOME control of alpha via the Color.argb() method, it is just if it is too close to 0 it turns black anyway. Something in that method or whatever I am doing does not like full transparency apparently.

How to rotate just the object being touched in Unity?

| | August 18, 2015

For my first steps in Unity I am just trying to rotate some squares when I touch them.

 using UnityEngine;
using System.Collections;

public class testskript2 : MonoBehaviour {

    // Use this for initialization
    void Start () {
        //transform.Rotate(Vector3.forward * 2 * 100);
    }

    // Update is called once per frame
    void Update () {
        if (Input.touchCount == 1) {
            Ray r = camera.ScreenPointToRay(new Vector3(Input.GetTouch(0).position.x, Input.GetTouch(0).position.y));
            RaycastHit hit0;
            if (Physics.Raycast(r, out hit0, 100f)) {
            transform.Rotate(Vector3.forward * Time.deltaTime * 100);
        }
    }
}
}

It isn’t working this way. Any tips?

translating canvas for rotating sprites that shoot

| | August 18, 2015

I am trying to align bullets to my different sprites guns (top down 2D for android). Right now Im using this method to draw my bullets:

public void draw(Canvas canvas){    
    update();
    canvas.save();
    canvas.rotate(angle, x + width / 2, y + height / 2);
    canvas.translate(translaterX, translaterY);
    canvas.drawBitmap(bitmap, x, y, null);
    canvas.restore();
}

The problem here is the translater, Im always having to add or substract from it to make the bullets spawn from my gun when my sprites rotate and I cant figure it out, is there any standard value for this, like translaterX = bitmap.getwidth()/2? I dont really understand how the translater works and I feel like Ive tried everything, what am I missing? For the examples sake lets say that my gun is always in the middle of the bitmap.

Or is there even another way to do this that is simpler?

LibGDX Drawing sprites when moving orthographic camera

| | August 18, 2015

I’ve been having this problem for a long time and I just can’t seem to find the exact problem. I have a game where the map is 480×1600 and my camera has a view of 480×800. I have a button that when pressed, allows the user to place a platform on the map, and since the map is too big to fit on the screen, I made it so the user can move the camera up and down the map by dragging.

@Override
public boolean touchDragged(int screenX, int screenY, int pointer) {
    Vector3 pos = new Vector3(screenX, screenY, 0);
    cam.unproject(pos);
    cam.position.y = pos.y;
    return true;
}

Method that controls when the user tries to put a platform down

@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
    Vector3 pos = new Vector3(screenX, screenY, 0);
    cam.unproject(pos);
    Gdx.app.log(Game.LOG, "X Coordinate: " + pos.x + " Y Coordinate: " + pos.y);

    if (GameScreen.createPlatform == true) {
        world.setPlatform(new Vector2(pos.x - 0.6f, pos.y - 0.1f), 1);
        GameScreen.createPlatform = false;
        return true;
    }

    ...
}

Where I render the platform sprites

public void render(float delta) { 
    ...
    spriteBatch.setProjectionMatrix(cam.combined);
    spriteBatch.begin();
    for (Sprite platformSprite: world.getPlatformSprites()) {
        platformSprite.draw(spriteBatch);
    }
    spriteBatch.end();
    ... 


}

The game works fine when I don’t move the camera. But when I do, the platforms aren’t placed where I click, they’re always either higher or lower where I actually clicked. Also, the platforms are always placed somewhere where the camera was originally looking before anything has been moved.

I think it’s doing this is because for some reason, the coordinates never actually change. So wherever I am on the map, the top of the screen is always 120 and the bottom is always 90. This also causes objects on the map to have different coordinates if I move the camera.

This problem has me completely lost and I would appreciate any help.

Recording and playing back sounds with LibGDX

| | August 18, 2015

How do I record a sound to PCM format and replay it from there?

libgdx game process dies on loading texture atlases

| | August 18, 2015

I try to load a lot of texture atlases (10) with approximately 5 (~2048x~2048)(not using PoT) .pngs each. I’m using AssetManager and there is no trouble with it on my pc but when I try it on my tablet the app just dies without any error messages or crash reports and there aren’t any outOfMemoryExceptions.

Here’s my log:

DropBox link

the max memory: 67 is

Runtime().getRuntime().maxMemory() / 1000000

I’m running out of ideas of what to do. Maybe I don’t fully understand the way mobile games work: is that a lot of atlases (I have other textures not atlases apart from these atlases)? because everything looks quite fine in the memory segment as much as I know. Anyway I’m open to suggestions and maybe some tips. And I’d really like to keep these atlases in my game.

EDIT: the game loads on my tablet but not phone when I use 1 png per atlas (8192×8192) but my tablet doesn’t show images larger than 2048×2048 for some reason oh and the images in the atlas aren’t even 1024×1024 so idk why it doesn’t show them must be because the atlas is 8192×8192.

EDIT #2: I load only atlases now, no separate .png files and I am now using PoT (2048×2048). 17 atlases some have 2 pngs some even have 1 png but there are some that have 5+ and that’s my level plus player animations plus I’m using a gradient for my whole level that is ~10000px in width combined and I use FBO to do a Lighten shader on the level and my level has animations. Is that too much? Anyway this time the game died @ 94% on my phone(Galaxy S2) and @ 58% on my tablet(Lenovo IdeaTab A2109) and here’s my new log but this time from my phone:

DropBox link log_new

I’m confused because there aren’t any outOfMemory exceptions and I’m disposing every possible thing there is to dispose. btw my app in the logs is com.comraz.slashem
Is theree something I can do? f.e. downscale textures or use mipmaps or something? my level textures are 1024×768 when zoomed in and 1024×1536 when zoomed out. If you have any ideas or any questions please do ask or tell me. Oh and my camera size is 1280×768

Android local multiplayer

| | August 18, 2015

I am working on a FPS game for Android and I want to make a support for local multiplayer with no additional devices or server required. One of the player’s devices would serve as a server, getting and distributing all the messages, OR every device broadcasts messages to everyone inside the group.
First I was thinking bluetooth or wifi direct, but I am running into many problems with both. The plan was to support up to 10 players, so I am not sure bluetooth can handle that (broadcast messages and similar). If it is possible, let me know.
Also, I heard of an option to make a wifi hotspot on one device, and connect all other devices to it that way, but I have no idea how that would work.
Does anyone have any real experience with this, or any advice on how to implement it?
Thanks in advance.

PS. yes, I’ve ran through everything on android developers site, but their wifi direct example is kinda bad and only supports 1-way data transfer.

Page 1 of 141234567891011121314