title: How to sale a bitmap font in libGDX?

text:
# Question
Title: How to sale a bitmap font in libGDX?
I'm trying to create a Minecraft like quotes on the menu screen of my game.

I'm using `BitmapFont` to draw the text on screen but I don't know how to make that scale up scale down effect.

This is what I tried to do.

```
public class MenuQuotes extends Actor {
    private BitmapFont font16;
    private String     str;

    public MenuQuotes() {
        FreeTypeFontGenerator generator = new FreeTypeFontGenerator(Gdx.files.internal("fonts/minecraft.ttf"));
        FreeTypeFontGenerator.FreeTypeFontParameter parameter = new FreeTypeFontGenerator.FreeTypeFontParameter();

        parameter.size = 16;
        parameter.color = Color.WHITE;
        parameter.shadowColor = Color.BLACK;
        parameter.shadowOffsetX = 1;
        parameter.shadowOffsetY = 1;

        font16 = generator.generateFont(parameter);
        generator.dispose();
    }

    @Override
    public void draw(Batch batch, float alpha) {
        super.draw(batch, alpha);

        ScaleToAction scaleAction = new ScaleToAction();
        scaleAction.setScale(10, 10);
        scaleAction.setDuration(10);

        GlyphLayout glyphLayout = new GlyphLayout();
        str = "Chickens are the closest relative\nto Tyrannosaurus";
        glyphLayout.setText(font16, str);
        float w = glyphLayout.width;

        font16.draw(batch, str, (Chicken.V_WIDTH / 2) / 2 - w / 2, (Chicken.V_HEIGHT / 2) / 2 + 10);
        this.addAction(scaleAction);

    }

    @Override
    public void act(float delta) {
        super.act(delta);
    }
}

```

# Answer
> 0 votes
The Actor class provides attributes to apply transformation to entities like Textures or BitmapFonts. The ScaleToAction you added only modifies the attributes derived by the Actor class. To apply the Action to your BitmapFont you have to apply the scale of the Actor to your BitmapFont. This topic shows how to do that.

# Answer
> 0 votes
If you don't mind the pixelation due to scaling you can use `font.getData().setScale(float value)` with a interpolation value. I generally use Tween to set this kind of animations to scale up or down. Or you can use a counter to set scaling animation.

---
Tags: libgdx, fonts
---


# Question
Title: How to make a sprite jump up and return to original position?
I am just trying to make my game character, which is a texture (ball), to jump up in the air and then return back down to the position that it started at when the screen is pressed. I was just wondering if someone could give me a code example or help me to do this with my current code which is below. I have basically just drawn the background and the ball texture and positioned the ball where I want it to start the jump. The ball texture is what I want to make jump straight up.

```
    public class MyGdxGame extends ApplicationAdapter {
    SpriteBatch batch;
    Texture background;
    Texture ball;

    @Override
    public void create () {
        batch = new SpriteBatch();
        background = new Texture("gamebackground.png");

        ball = new Texture("ball2.png");
        ball.setFilter(Texture.TextureFilter.Nearest, Texture.TextureFilter.Nearest);
    }

    @Override
    public void render   () {
        batch.begin();
        float scaleFactor = 2.0f;
        batch.draw(background, 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight    ());
        batch.draw(ball, 80, 145, ball.getWidth() * scaleFactor, ball.getHeight() *     scaleFactor);
        batch.end();
    }

    @Override
    public void dispose () {
    }
}

```

# Answer
> 1 votes
Try keeping a `y` coordinate for your ball, and then manipulate this in the `render` method by adding a velocity to it.

Also, apply a gravity to the velocity to make the ball change direction at the 'top'.

There are many ways of achieving the above including (but not limited to using animated **libGDX** `Actor`s or by relying on a physics library (like **Box2D**, for example). Each different way will have some aspects that work well or not so well for your particular game.

A bare bones implementation could look something like this;

```
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;

public class MyGdxGame extends ApplicationAdapter {

    SpriteBatch batch;
    Texture ball;
    float x;
    float y;
    float vy = 0;
    float g = -64;

    @Override
    public void create () {
        batch = new SpriteBatch();
        ball = new Texture("ball2.png");

        Gdx.input.setInputProcessor(new InputProcessor() {
            public boolean keyDown(int keycode) { return false; }
            public boolean keyUp(int keycode) { return false; }
            public boolean keyTyped(char character) { return false; }

            public boolean touchDown(int screenX, int screenY, int pointer, int button) {
                // Only allow new jump if already at ground level;
                if (y == 0.0f) {
                    vy = 128; // Set an upwards velocity for the y position
                }
                return false;
            }

            public boolean touchUp(int screenX, int screenY, int pointer, int button) { return false; }
            public boolean touchDragged(int screenX, int screenY, int pointer) { return false; }
            public boolean mouseMoved(int screenX, int screenY) { return false; }
            public boolean scrolled(int amount) { return false; }

        });
    }

    @Override
    public void render () {
        Gdx.gl.glClearColor(1, 0, 0, 0);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        // Add the 'vy' velocity to the y position, scaled by how much time has elapsed
        // also make sure y is never smaller than 0, 0 representing the 'ground' in this example.
        y = Math.max(0, y + vy * Gdx.graphics.getDeltaTime());

        // Apply gravity, 'g', to the velocity so that it slows down and then turns around
        vy += g * Gdx.graphics.getDeltaTime();

        batch.begin();
        batch.draw(ball, x, y);
        batch.end();

    }

}

```

# Answer
> 0 votes
If you are using a ground as an initial position, i strongly suggest you to learn and use Box2D for LibGdx. It handles all physical interactions. Give an initial speed or apply force to your object and let Box2D handle the rest.

---
Tags: java, libgdx
---


# Question
Title: Libgdx: How to leave the dialog visible?
```
setBtn.addListener(new ClickListener() {
    @Override

    public void clicked(InputEvent event, float x, float y) {
        final Dialog dialog = new Dialog("Settings", skin, "dialog") {
            public void result(Object obj) {
                Preferences prefs = Gdx.app.getPreferences("My Preferences");

                if (obj.equals(2))
                    muteMusic = true;
                if (obj.equals(3))
                    muteMusic = false;

                prefs.putBoolean("music", muteMusic);
                prefs.flush();

            }

        };
        dialog.text("Do you want to play music");
        dialog.button("Yes", 2); //sends "true" as the result
        dialog.button("No", 3); //sends "false" as the result
        dialog.button("Ok", false);

        dialog.show(stage);
    }

});

```
* I want the ok button to be on an another row but if I do `dialog.row()` like with tables, it won't work, I can't add an empty row
* I want the dialog to stay visible on the screen until the ok button is touched, only then I want to call `dialog.hide()`

I can't do

```
if (obj.equals(false))
dialog.hide(); // IDE will suggest that i create a local variable called dialog

```

# Answer
Any specific reason you are using `dialog.button` to add buttons? In my experience this should just be used for the last button of the dialog that you wish to hide the dialog with, in your case 'ok'.

Did you try something like:

```
TextButton txtBtn = new TextButton ("yes", skin);
TextButton txtBtn2 = new TextButton ("no", skin);

dialog.getContentTable().add(txtBtn);
dialog.getContentTable().row();
dialog.getContentTable().add(txtBtn2);

dialog.button(new TextButton("ok", skin));

```
> 1 votes

---
Tags: java, android, libgdx, ios
---


title: Monogame shader distorts rendering

text:
# Question
Title: Monogame shader distorts rendering
I'm trying to apply a shader postprocessing effect to my rendered game.

Here is the game code:

```
namespace ShaderTestDesktop
{
    public class Game1 : Game
    {
        private GraphicsDeviceManager graphics;
        private SpriteBatch _spriteBatch;
        private Texture2D _alien;
        private RenderTarget2D _renderTexture;
        private Effect _shader;
        private float _angle;
        private Vector2 _position;

        private bool _isShaderApplied;
        private KeyboardState _keyboardState;

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }

        protected override void Initialize()
        {
            base.Initialize();

            _keyboardState = Keyboard.GetState();
        }

        protected override void LoadContent()
        {
            _spriteBatch = new SpriteBatch(GraphicsDevice);

            _shader = Content.Load<Effect>("nop");
            _alien = Content.Load<Texture2D>("alien");

            _renderTexture = new RenderTarget2D(
                GraphicsDevice,
                graphics.PreferredBackBufferWidth,
                graphics.PreferredBackBufferHeight
            );

            _position = new Vector2(
                GraphicsDevice.Viewport.Width / 2,
                GraphicsDevice.Viewport.Height / 2
            );
        }

        protected override void Update(GameTime gameTime)
        {
            _angle += 2f * (float)gameTime.ElapsedGameTime.TotalSeconds;

            var newState = Keyboard.GetState();

            if (!_keyboardState.IsKeyDown(Keys.Space) && newState.IsKeyDown(Keys.Space))
                _isShaderApplied = !_isShaderApplied;

            _keyboardState = newState;

            base.Update(gameTime);
        }

        protected override void Draw(GameTime gameTime)
        {
            // render the sprite to the intermediate texture
            GraphicsDevice.SetRenderTarget(_renderTexture);
            GraphicsDevice.Clear(Color.Transparent);

            _spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend);
            _spriteBatch.Draw(_alien, _position, null, Color.White, _angle, new Vector2(128, 128), 1, SpriteEffects.None, 0);
            _spriteBatch.End();

            // post-process
            GraphicsDevice.SetRenderTarget(null);
            GraphicsDevice.Clear(Color.CornflowerBlue);

            _spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, null, null, null, _isShaderApplied ? _shader : null);
            _spriteBatch.Draw(_renderTexture, Vector2.Zero, Color.White);
            _spriteBatch.End();

            base.Draw(gameTime);
        }
    }
}

```

The shader currently does nothing and is defined simply as:

```
sampler2D s0;

float4 MainPS(float2 coords: TEXCOORD0) : COLOR
{
    return tex2D(s0, coords);
}

technique BasicColorDrawing
{
    pass P0
    {
        PixelShader = compile ps_4_0_level_9_1 MainPS();
    }
};

```

Rendering without the shader looks like this (rotates clockwise):

When the shader is applied, the object is apparently moved, scaled and mirrored (rotates counter-clockwise):

The behaviour is consistent across platforms (at least Desktop and WP8). What am I doing wrong?

**UPDATE**:

As suggested in the comments, I modified the shader code to add a vertex shader too. Some articles suggested also creating a matrix to match the default transformation matrix from `SpriteBatch`.

Here's the new shader code:

```
matrix WorldViewProjection;

struct VertexShaderInput
{
    float4 Position : SV_POSITION;
    float4 Color : COLOR0;
};

struct VertexShaderOutput
{
    float4 Position : SV_POSITION;
    float4 Color : COLOR0;
};

VertexShaderOutput MainVS(in VertexShaderInput input)
{
    VertexShaderOutput output = (VertexShaderOutput)0;

    output.Position = mul(input.Position, WorldViewProjection);
    output.Color = input.Color;

    return output;
}

float4 MainPS(VertexShaderOutput input) : COLOR
{
    return input.Color;
}

technique BasicColorDrawing
{
    pass P0
    {
        VertexShader = compile vs_4_0_level_9_1 MainVS();
        PixelShader = compile ps_4_0_level_9_1 MainPS();
    }
};

```

New shader initialization code:

```
var halfPixel = Matrix.CreateTranslation(-0.5f, -0.5f, 0);
var offCenter = Matrix.CreateOrthographicOffCenter(0, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height, 0, 0, 1);
_shader = Content.Load<Effect>("nop");
_shader.Parameters["WorldViewProjection"].SetValue(halfPixel * offCenter);

```

New result (notice the 1px CornflowerBlue border at the right):

# Answer
> 1 votes
```
PixelShader = compile ps_4_0_level_9_1 MainPS();

```

It's illegal to have a pixel shader without a vertex shader in shader model 4.

# Answer
> 0 votes
The trouble was due to texture coordinates not being passed from vertex to pixel shader. Here is the correct version of the shader:

```
matrix WorldViewProjection;
sampler2D TextureSampler: register(s0); // added

struct VertexShaderInput
{
    float4 Position : SV_POSITION;
    float4 Color : COLOR0;
    float2 TexCoords: TEXCOORD0; // added
};

struct VertexShaderOutput
{
    float4 Position : SV_POSITION;
    float4 Color : COLOR0;
    float2 TexCoords: TEXCOORD0; // added
};

VertexShaderOutput MainVS(in VertexShaderInput input)
{
    VertexShaderOutput output = (VertexShaderOutput)0;

    output.Position = mul(input.Position, WorldViewProjection);
    output.Color = input.Color;
    output.TexCoords = input.TexCoords; // added

    return output;
}

float4 MainPS(VertexShaderOutput input) : COLOR
{
    return tex2D(TextureSampler, input.TexCoords);
}

technique BasicColorDrawing
{
    pass P0
    {
        VertexShader = compile vs_4_0_level_9_1 MainVS();
        PixelShader = compile ps_4_0_level_9_1 MainPS();
    }
};

```

Big thanks to @DMGregory for help!

---
Tags: c#, shaders, rendering, monogame, hlsl
---


title: Trying to subdivide an ISO tile

text:
# Question
Title: Trying to subdivide an ISO tile
I have code that calculates where the user clicked inside an iso tile in an isometric map. The tile has a width of 1 unit and a height of 0.5 units. My code calculates where they touched inside the tile in these same units. The goal is to then decide where that click falls if you sub-divided the iso tile into a 4x4 grid. The picture below shows how all this is supposed to look.

I have found ascreen co-ordinates to iso formula and it makes sense but for whatever reason, when I try to use it with my data above I get wrong outputs. When clicking from the top corner to the right corner, only the X iso output should change but both the X and the Y change.

I feel like this should be pretty simple but after hours of banging my head against this I can't figure out what I am doing wrong.

Source for screen to iso formula: How would I translate screen coordinates to Isometric coordinates?

Any help would be greatly appreciated.

```
float touchedX;
float touchedY;
//below 0.125 represents the tile height because the whole thing
// is 0.5 and its 4 tiles high so 0.125, 0.5 is 2*width which
//is (1 / 4.0) * 2
float gridPointLedftDown = (touchedY / 0.125f) + (touchedX / 0.5f);
float gridPointRightDown = (touchedY / 0.125f) - (touchedX / 0.5f);

```

# Answer
> 1 votes
It looks like the formula I had from that other site was just wrong. IsoY should be calculated as y / tileHeight - x/ tileWidth. The \*2 on tileWidth when removed made the values come out correctly.

---
Tags: 2d, graphics-programming
---


# Question
Title: Texture2D.SetPixel method behaving weirdly in game province creation
I have been trying to implement a province system in Unity. I am trying to read the provinces from an image file, store their coordinates in a province, and use those coordinates to generate a texture and a 2D sprite for the province to be displayed on the screen at its appropriate world coordinates. Games like Risk, and many strategy games that rely on world maps to function use this approach. So far, I have the following code to parse the image from the province.png file I have created.

```
public class ProvinceReader()
{
    public static void Read()
    {
        Texture2D provinces = MapImageCache.province_tex;
        for(int x = 0; x < provinces.width; x++)
        {
            for(int y = 0; y < provinces.height; y++)
            {
                Color32 color = provinces.GetPixel(x,y);
                ProvinceData province = null;
                if(MapInstance.ColorCodedData.TryGetValue(color, out province))
                {
                    province.AddPoint(x, y);
                    //TODO: Check if the neighboring pixels are of different colors. If so,
                    //add the pixel to the 'province border' pixels. The, get the province at
                    //the checked pixel position and store the x,y coordinate in a dictionary
                    //IDictionary<ProvinceData, List<Vector3>>.
                }
                else
                {
                    //MapInstance.Instance.ColorCodedData.Add(color, new ProvinceData());
                }
            }
        }
        foreach (ProvinceData prov in MapInstance.Instance.ColorCodedData.Values)
        {
            GameObject newProv = new GameObject();
            newProv.AddComponent<ProvinceScript>().SetData(prov);
            newProv.AddComponent<SpriteRenderer>().sprite = prov.GenerateSprite();
        }
    }
}

public class ProvinceData
{
    private List<Vector2> points = new List<Vector2>();
    private List<int> xPoints = new List<int>();
    private List<int> yPoints = new List<int>();
    private Sprite image;

    public Sprite GenerateSprite()
    {
        int minX = xPoints[0], minY = yPoints[0];
        int maxX = xPoints[0], maxY = yPoints[0];
        for(int i = 0; i < xPoints.Count; i++)
        {
            int xval = xPoints[i], yval = yPoints[i];
            if(xval < minX) minX = xval;
            else if(xval > maxX) maxX = xval;

            if(yval < minY) minY = yval;
            else if(yval > maxY) maxY = yval;
        }
        int width = (maxX - minX) + 1, height = (maxY - minY) + 1;
        Texture2D m_tex = new Texture2D(width, height);

        for(int i = 0; i < xPoints.Count; i++)
        {
            int xval = xPoints[i] - minX, yval = yPoints[i] - minY;
            m_tex.SetPixel(xval, yval, new Color32(0, 123, 20, 255)); //I want to display the province on screen in green
        }
        m_tex.Apply();
        this.image = Sprite.Create(m_tex, new Rect(0, 0, width, height), Vector2.zero, 1f);
        return image;
    }
    public void AddPoint(int x, int y)
    {
        xPoints.Add(x);
        yPoints.Add(y);
        points.Add(new Vector2((float)x, (float)y));
        //Also save whether it is a border point.
    }
}

```

I have a black (0,0,0) province in the center of the texture in my png file:

And I am trying to read it. I loaded it into my `MapInstance.Instance.ColorCodedData` and ensured the data is valid. I loaded the png into a Texture2D and ensured the image was set up properly.

I am getting the following on my screen when I start the game:

I did some experimenting, and used Debug.Log to record a list of points. The largest point in the province that matches the province color is (x,y) =\> (643, 290). The smallest is (x,y) =\> (627, 281). I recorded the final value of "width" and "height", in the ProvinceReader.Read() method using Debug.Log(); The value was 1 when I explicitly subtracted the minimum of each value from the maximum of each value. So, I should have gotten (width, height) =\> (16, 9), but when I record these values I get 1. Which is weird.

I then changed the width and height values arbitrarily to 200,200 to see what happens, and I just get a 200x200 version of the above sprite.

# What I am looking for:

**Why is the sprite doing this? How can I solve it? If you need any more information, please let me know and I will include it.**

# Answer
```
public Sprite GenerateSprite()
{
    int minX = xPoints[0], minY = yPoints[0];
    int maxX = xPoints[0], maxY = yPoints[0];

    for(int i = 0; i < xPoints.Count; i++)
    {
        int xval = xPoints[i], yval = yPoints[i];

        if(xval < minX) minX = xval;
        if(xval > maxX) maxX = xval;
        if(yval < minY) minY = yval;
        if(yval > maxY) maxY = yval;
    }
    int width = (maxX - minX) + 1, height = (maxY - minY) + 1;
    Texture2D m_tex = new Texture2D(width, height);

    for(int i = 0; i < xPoints.Count; i++)
    {
        //This is the modified code.
        int worldX = xPoints[i];
        int worldY = yPoints[i];
        int xval = maxX - worldX;
        int yval = maxY - worldY;

        m_tex.SetPixel32(xval, yval, new Color32(0, 123, 20, 255)); //I want to display the province on screen in green
    }
    m_tex.Apply();
    this.image = Sprite.Create(m_tex, new Rect(0, 0, width, height), Vector2.zero, 1f);
    return image;
}

```

This code fixes the error. For whatever reason, the `else` when I was setting my max and min values was screwing things up. I was also forgetting to convert the x and y values into the coordinates of the new texture.
> 0 votes

# Answer
**To find what color has been clicked by user on an UI image:**

Steps I've done on a **new** project:

* add PNG to your project
    + tick *Read/Write Enabled* in its *Import Settings*
    + Alpha Source -\> Input Texture Alpha
    + tick Alpha Is Transparency
    + apply changes
* add a *UI/RawImage* component (this adds a Canvas and a RawImage inside it)
    + set *Texture*
    + click *Set Native Size*
* in Canvas set *Pixel Perfect*
* in RawImage add the component below

Code:

```
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class FindColor : MonoBehaviour, IPointerClickHandler
{
    private Color _color;
    private RawImage _rawImage;

    #region IPointerClickHandler Members

    public void OnPointerClick(PointerEventData eventData)
    {
        // get the color of the pixel that has been clicked in image

        var rc = eventData.pointerCurrentRaycast;
        if (!rc.isValid)
            return;

        var rt = _rawImage.rectTransform;
        var sp = rc.screenPosition;
        var cam = eventData.pressEventCamera;
        Vector2 point;
        if (!RectTransformUtility.ScreenPointToLocalPointInRectangle(rt, sp, cam, out point))
            return;

        var d = _rawImage.mainTexture as Texture2D;
        if (d == null)
            return;

        var p = point + rt.rect.min;
        var x = (int) p.x;
        var y = (int) p.y;
        _color = d.GetPixel(x, y);

        // TODO do whatever you have to with the clicked color
    }

    #endregion

    private void Start()
    {
        _rawImage = FindObjectOfType<RawImage>();
    }

    private void OnGUI()
    {
        var color = GUI.color;
        GUI.color = _color;
        GUILayout.Label("Clicked color");
        GUI.color = color;
    }
}

```

So this will find the pixel color you've clicked, no matter where on your screen the map is, then do what you need to when the clicked color matches one you're watching.

(I assume your map is shown at 100% scale)

Result:

Original image:

**NOTE:**

Obviously for the technique to work your provinces should each have a distinct tone (no antialiasing)
> 0 votes

---
Tags: c#, unity, textures
---


# Question
Title: Why do we have to resize the screen in LibGDX
In a lot of the libgdx tutorials that I have took until now, I am told to resize the screen of the game using the SetToOrtho() of the orthographic camera. However, I don't get this part. Why do I have to resize the screen and make the sprites look bigger when I can just make the sprites themselves big at the first place?

# Answer
> 0 votes
You're not actually "resizing the screen" with `setToOrtho`. You're building an orthographic projection matrix that *takes into account* the size of the screen (note the source).

By doing this, you effectively map the world coordinates of your sprites to pixel coordinates on the screen, which lets you work more naturally in terms of pixel positioning and pixel sizes.

---
Tags: libgdx
---


# Question
Title: What are world coordinates and pixel coordinates in LibGDX
I searched the Internet for these two terms, but there is no reference to them. I just started learning LibGDX, so please explain in the simplest way possible

# Answer
These terms are not specific to libgdx, really.

"Pixel coordinates" are positions that correspond directly to pixels on a screen or in an image. They tend to be a natural fit for working and thinking in 2D: an object at (0,0) might be at the bottom-left of the screen. An object at (15, 0) would be 15 pixels to the right of that first object.

"World coordinates" have a less fixed reference. In 3D graphics, geometry (stuff you draw) tends to flow through a series of coordinate systems. Things start in model (or object) space, where they are defined, usually in such a way as to center the geometry around the origin of this coordinate space.

Geometry is then transformed from model space to world space, which is a coordinate system where the origin is at some defined central or logical location for the map/world/level/et cetera. This transformation into world space occurs for each model based on where that model should exist *in the world*.

There are further coordinate systems after this, but you didn't ask about them specifically and they don't have an additional bearing on the definitions. What remains that is important is that model and world space don't have fixed metrics. Pixel coordinates do: moving from (0,0) to (10, 0) moves you ten pixels.

But model and world space don't have fixed metrics, it's up to you and your program to assign values and meaning to the numbers. Moving from (0,0,0) to (10,0,0) in world space could mean moving ten feet, ten miles, ten meters, or ten pixels, depending on how you are choosing to interpret the values of the coordinates.
> 1 votes

# Answer
I will assume that it refers to coordinates in the same style as most other systems.

**World Coordinates**: Coordinates in respect to the larger world. These coordinates are relative to a global origin of the world, together with many other objects also placed relative to the world's origin.

**Pixel (Local) Coordinates**: Coordinates of your object relative to its local origin; they're the coordinates your object begins in.

**World Space**: If you import all your objects directly into the application they would all be stacked on each other around the world's origin of (0,0,0). The coordinates in world space are exactly what they sound like: the coordinates of all your vertices relative to a (game) world. This is the coordinate space where you want your objects transformed to in such a way that they're all scattered around the place (preferably in a realistic fashion). The coordinates of your object are transformed from local to world space; this is accomplished with the model matrix.

**The model matrix** is a transformation matrix that translates, scales and/or rotates your object to place it in the world at a location/orientation they belong to. Think of it as transforming a house by scaling it down (it was a bit too large in local space), translating it to a suburbia town and rotating it a bit to the left on the y-axis so that it neatly fits with the neighboring houses.

**Local Space**: Local space is the coordinate space that is local to your object, i.e. where your object begins in. Imagine that you've created your cube in a modeling software package (like Blender). The origin of your cube is probably at (0,0,0) even though your cube might end up at a different location in your final application. Probably all the models you've created all have (0,0,0) as their initial position. All the vertices of your model are therefore in local space: they are all local to your object.
> 0 votes

---
Tags: libgdx, terminology
---


# Question
Title: Unity - Exposing a function to the inspector
I wish to expose a script's function to the inspector, but I have no clue how to. I found something about `Invoke()` which was a start, but it isn't clear how to finish.

My code for the class:

```
 [System.Serializable]
     class MoveAction : UnityEvent<MonoBehaviour>, IUIAnimationEvent
     {
         #region Move
         public MoveAction()
         {

         }
         //to ensure only one mover coroutine can be active.
         IEnumerator moveRoutine = null;
         #region Solution 2: using fields and not parameters
         Transform from;
         Transform to;
         float overTime;
         public delegate void UIchain(MonoBehaviour mono);
         public event UIchain NEXT_FUNCTION;

         public MoveAction(Transform from, Transform to, float overTime, IUIAnimationEvent chain)
         {
             this.from = from;
             this.to = to;
             this.overTime = overTime;

         }
         public void Move(MonoBehaviour mono)
         {
             if (moveRoutine != null)
             {
                 mono.StopCoroutine(moveRoutine);
             }
             moveRoutine = _Move(from, to, overTime, mono);
             mono.StartCoroutine(moveRoutine);
             Invoke(mono);
         }
         IEnumerator _Move(Transform from, Transform to, float overTime, MonoBehaviour mono)
         {
             Vector2 original = from.position;
             float timer = 0.0f;
             while (timer < overTime)
             {
                 float step = Vector2.Distance(original, to.position) * (Time.deltaTime / overTime);
                 from.position = Vector2.MoveTowards(from.position, to.position, step);
                 timer += Time.deltaTime;
                 yield return null;
             }
             if(NEXT_FUNCTION != null)
             {
                 NEXT_FUNCTION(mono);
             }
         }

```

This is a lot of code, but the interesting part is the `Move(MonoBehaviour mono)` function. I want to expose that to the editor. How?

**EDIT:**

Something like this would be preferable:

# Answer
> 1 votes
what you are looking for is the Unity Event class. See this example below. This will appear in the editor exactly like your screenshot.

```
using UnityEngine;
using UnityEngine.Events;
using System.Collections;

public class InvokeOnAwake : MonoBehaviour {

    public UnityEvent invokeMethod;//set in editor

    void Awake(){
        invokeMethod.Invoke();
    }

}

```

---
Tags: unity, c#, events, editors
---


# Question
Title: GLES2-AnchorCenter branch has no org.andengine.util.color.Color
I am porting my game from GLES2 to GLES2-AnchorCenter branch. I am using

```
import org.andengine.util.HorizontalAlign;
import org.andengine.util.color.Color;
import org.andengine.entity.particle.modifier.ExpireParticleInitializer;

```

... but these aren't available in GLES2-AnchorCenter branch, it seems. Could anybody guide me on this?

# Answer
You import statement seems to be wrong because in GLES2 and GLES2-Anchor Centre branch contain Color class resides in different package.

In GLES2-AnchorCenter branch, you can found Color class in following package.

Color Class

So make change in your import statement as like above.
> 1 votes

# Answer
Here's an alternate package reference that worked for me:

`import org.andengine.util.adt.color.Color;`

thanks to: http://android.kul.is/2013/09/tutorial-andengine-extensions-and-examples.html
> 0 votes

---
Tags: opengl-es2, andengine
---


# Question
Title: What models am I allowed use when selling my game?
I have purchased models through Daz3D, and I have downloaded a lot, for free. The 3D models were downloaded as `.MMD` or `.FBX`.

How do I tell if I can edit or use any of these models, in my game? When I sell my game, will I need a license to include these models?

# Answer
First: I am not a lawyer, please contact a lawyer for actionable legal advice.

Use of the 3D models depends on the license the model maker provided. You should be able to read the license and see if it allows you to use them in a commercial project.

Commercial project means you intend to charge users for it.

Anytime you get content from the internet, make sure you identify the license, or if there is none, find the creator and ask them.
> 4 votes

# Answer
You can use models that you were granted the appropriate rights to use, via the licensing agreement you entered into during the purchase or acquisition of the model.

Beyond that there is no way to say, in general: you must review (or you must task a lawyer with reviewing) each model and how you use it in your game, and compare that to the license for that model. For example, it's possible you were granted a license that allows you to render out the model and use it for marketing purposes but not to actually distribute the model geometry or render it in real-time. It's possible you were granted the ability to use the model however, as long as you don't charge for the product you're selling. You may need to make certain disclaimers about where you got the model. Et cetera, et cetera, et cetera. The list of *possible* entanglements and requirements is too long to enumerate here.

If you do not have or cannot find a license for a model it's probably safe to assume you cannot use it.
> 1 votes

# Answer
I am not a lawyer, and you can be sued for anything. When you move into the *commercial* sector, you should contact an actual copyright lawyer. All that aside, you should always ensure that you have a license that permits your specific use of the assets, regardless of whether you originally paid for them or not.

---

Daz3D actually directly addresses these concerns in their Help Center.

> **Can I use Daz 3D's products in a video game that I am producing?**
>
> Only products for which there is a Game Developer License can potentially be used in a video game. You must have the pertinent Game Developer License for vendor. At the time this article was written, only DAZ Original Content products and Rawart content have available game licenses.
>
> Daz 3D (Daz Original) -- Commercial Game Developer License
> Daz 3D (Daz Original) -- Indie Game Developer License
> Raw Art -- Commercial Game Developer License
> Raw Art -- Indie Game Developer License

As of writing this answer, the website reports that the indie licenses are for "*Developers with Personal or Business income of LESS than $100,000.00 annually*" (currency is presumably in USD). While this sounds like it very well applies to the average user, here, this will still cost you 500-1000 USD (at 500 USD per license). The commercial licenses are 2000 USD a piece.
> 1 votes

---
Tags: models, legal, licensing
---


# Question
Title: Love2D and 'Tiled' - Detect if player is over certain tile/Collision
I created a 50x50 tile map with 32x32 tiles in Tiled and exported it as a Lua file so I can use it in Love2D. I have a player you can move around the world but I'm attempting to convert the player's x and y to where it is corresponding to the tile map and check if that position contains a wall. Tiled's exported map stores the map data in a 1 dimensional array like so...

```
data = {
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
  }

```

This makes it where I can't reference the data like `data[playerX][playerY]` So I just multiplied the values `data[playerX*playerY]` This is basically what I implemented (mapX and mapY are the player's x and y corresponding to the map)

```
mapX = math.floor(player.x / 32)
mapY = math.floor(player.y / 32)

```

and then before I get player input I check if the player's location in regards to the map contains '2' because that resembles a wall in the map data

```
if map.layers[3].data[mapX*mapY] ~= 2 then
...check input

```

The player's mapX and mapY do not seem to be correct because it's values never seem to be actually corresponding accurately with the map. Any ideas on doing this a different way or fixing this? If you need more detailed code, please ask.

# Answer
Indexing a 2D array represented as a 1D array is done like this:

```
index = x + y * width

```

Where `width` is sometimes known as *stride*.

For more information see https://opengamingalliance.org/wiki\_2/index.php/Indexing\_into\_2D\_arrays
> 1 votes

---
Tags: tilemap, lua, tiled, love2d
---


# Question
Title: Retrieving text from a text file and inputting it to a Text component
I had a suspicion I would come across this problem. I know how to write to the file and read from it, but the following snippet isn't allowing me to input it into a text component.

```
public class EventHandler : MonoBehaviour
{
    string _text;
    Text text;
    private void Awake()
    {
        text = FindObjectOfType<Text>();
    }
    public string Read(string path)
    {
        _text = "";
        StreamReader reader = new StreamReader(path);
        while (!reader.EndOfStream)
        {
            _text += reader.ReadLine();
        }
        reader.Close();
        return _text;
    }
    public void chapter_one()
    {
        text.text = Read("Assets/Chapters/chapter_one.txt");
    }
}

```

I'm sure you guys can explain why this isn't working. I already got the reference to the Text component as well.

**Edit**

No errors, file exists, its filled, color is white on black background, chapter\_one is the file name and yes chapter\_one is called, and I put Debug.Log right in the while loop and out\_side of it and I received those logs. My only thoughts are that the string is not getting returned for god knows what reason, or the text component isn't appending the text.

# Answer
After an extensive amount of research over the last two day, the help of all you wonderful people, and a little bit of ingenuity and sacrifice I managed to create a solution. As some reference, it turns out that `chapter_one` was not being called properly, however, even when it was being called properly it wasn't working. So, I ended up using `File.ReadAllText(path)` to get the text in my `.txt`. This is when I found out `chapter_one` wasn't being called correctly. I ended up doing a lot of migrating of various things away from my `EventHandler` and using multiple scripts to achieve what I was doing with just my `EventHandler`. The following code being placed on the Text Component in the scene achieved what I set out to do in the first place:

```
public class Chapter_one : MonoBehaviour
{
    string _text;

    private void Awake()
    {
        chapter_one();
    }
    public void Read(string path)
    {
        _text = File.ReadAllText(path);
    }
    public void chapter_one()
    {
        Read("Assets/Chapters/chapter_one.txt");
        gameObject.GetComponent<Text>().text = _text;
    }
}

```

Such simple things like this situation, where all that needed to be done was change methods or changing the style of retrieving a particular thing makes things so annoying. Especially when it takes days to figure out the most simplest of problems.
> 0 votes

# Answer
Testing your solution, I find that the script works. You confirm that the text is being *set* from your `StreamReader`, but not transferring to your `Text` component. I can only find two reasons why this might be happening, and both generally fall under how you actually *set up* your initial `Text` component.

---

### `FindObjectOfType<t>()` will only work if you can *guarantee* that you only have one instance of that `t Type`, or otherwise, do not care about *what* instance you will retrieve.

As per official documentation, `FindObjectOfType<>()` will return *the first active object* of that `Type` that has been loaded in to the scene. In my experience, you can not always reliably assume *what* instance will return, unless you *only* have a single instance of that `Object` in your scene.

That said, there is a much easier way to do this. If your script is attached to the same `GameObject` that holds your intended `Object`, use `GetComponent<Component>`, instead. That way, we look for the `Component` inside the specific `GameObject`. We can have a lot more control over referencing the right `Object`, in this way.

An easier method is to simply link the reference via the Inspector. You can do this by making your `Text` reference `public`, or by using either the `[SerializeField]` or `[ShowInInspector]` tags. The below script will look for a `Text` component *local* to the host `GameObject`, providing it has not already been linked via the Inspector.

```
public class EventHandler : MonoBehaviour
{
    [SerializeField]Text text;
    // ...

    private void Awake()
    {
        if(text == null)
        {
            text = (Text)GetComponent<Text>();
        }
    }
}

```

### To be visually displayed, `Text` must be attached to a `Canvas`

`Text` will not display if it does not have a `Canvas` to display to. `Canvas` is a separate `Component`, and is used to display UI. The `Text` `GameObject` must be attached to the `Canvas` `GameObject`, via the Hierarchy. They *can* simply be attached to the same `GameObject`, if preferred.
> 1 votes

---
Tags: unity, c#, text
---


# Question
Title: Libgdx: How to replace texture with shaperenderer?
I have a method that creates rectangles, it takes a texture

```
 for (Rectangle rect : rect) {
            game.batch.draw(rectImage, rect.x, rect.y);
        }

```

The texture is simple, I could just draw it instead. I created for example

```
shapeRenderer.set(ShapeRenderer.ShapeType.Filled);
shapeRenderer.rect(
        rect.x,
        rect.y,
        rect.width,
        rect.height,
        Color.DARK_GRAY,
);

```

Now what? `game.batch.draw` doesn't accept `shapeRenderer` instead of `rectImage` and doesn't accept only `rect.x, rect.y`

I'm just wondering how to call it?

# Answer
To draw Shapes over sprites and textures:

1. Make a *shape renderer*

```
ShapeRenderer shapeRenderer = new ShapeRenderer();

```
2. *Define* your shape(s)

```
Rectangle rect = new Rectangle(x, y, width, height);

```
3. *Open* your batch and *draw* all the stuff which needs to be UNDER your shape. Then *close* your batch.

```
batch.begin();
// Draw your stuff
batch.end()

```
4. *Draw* your shape(s)

```
shapeRenderer.begin(ShapeType.Line);
shapeRenderer.setColor(yourColor);
shapeRenderer.rect(rect.x, rect.y, rect.width, rect.height);
shapeRenderer.end();

```

If you want gradients and stuff for your shape, `ShapeRenderer.rect()` also has a method where you can put to four colors in (one by top of rectangle).

If you want border for your shape (which can also be gradients) it's also possible with ShapeRenderer

So if you want a specific shape with gradient and stuff, i'll recommend you to build a class which is very similar to sprite, but where the draw method look like the .4 above.
> 3 votes

# Answer
Why you are using shapeRenderer if you want to draw rect type object having different color.

Draw Rectangle using Pixmap. create Texture with given method and use

```
Texture texture=getPixmapTexture(Color.WHITE);

    Sprite sprite=new Sprite(texture); //Used for drawing 2D sprites.
    or
    Image image=new Image(texture);  //2D scene graph node.

    public static Texture getPixmapTexture(Color color){
       return new Texture(PixmapBuilder.getPixmapRectangle(1, 1, color));
    }

   public static Pixmap getPixmapRectangle(int width, int height, Color color){
       Pixmap pixmap=new Pixmap(width, height, Pixmap.Format.RGBA8888);
       pixmap.setColor(color);
       pixmap.fillRectangle(0,0, pixmap.getWidth(), pixmap.getHeight());
       return pixmap;
   }

```
> 2 votes

---
Tags: java, android, libgdx, rendering, ios
---


title: How to update void show?

text:
# Question
Title: How to update void show?
`getMusicPlaying` is set to false whenever someone touches the button, but libgdx runs `show` method only once, at the start of the game, hence the music will keep playing forever.

I tried to use the `render` and `batch.begin` instead of `show()` same result.

```
private boolean musicPlaying = true;

button.addListener(new InputListener() {
public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
 return true;
}

public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
 setMusicplaying(!musicplaying);
}
});

}
});
}

public void show() {
 if (getMusicPlaying ==true)
  music.play();
}

```

# Answer
In your setMusicplaying function, you should add something like music.stop() whenever the argument is false.
> 1 votes

---
Tags: java, libgdx
---


title: Register Enemies in game development

text:
# Question
Title: Register Enemies in game development
I'm working on a game to learn the basic for game concepts. I end up with the following problem. I got a class called enemy, but now I want different types of enemies. These enemies extend from this class enemy. So I can have different enemies with that share different properties. The problem is that I want to spawn a different enemy each time. But to do this I need to know all the enemies available to choose on randomly.

I have been thinking and I got two approaches to solve this. The first one I end up is to have an enum with different enemies, and get a random value from the enum and spawn that enemy, but for this, I need to hard code all the enemies into the enum. And another one is to have a GameRegister class, that have a register for all available enemies, like when you do modding in Minecraft for example. I can have a registered class to register enemies or objects. And if I want to select a random enemy I know all the enemies available. I think is the best approach because if I want to add more enemies or anything, I only need to register for that class.

I don't have any idea at all to how to implement this pattern, and I didn't find anything on the internet. Can someone give some tips or clarify what I want to do? Because I have the main idea but I get completely lost when I need to design this.

I'm working on Java using libGDX, if is useful for some reason.

# Answer
> 1 votes
I would go a bit further than SpacemanSpiff and use the Abstract Factory Pattern.

Create an interface `IEnemyFactory` with a method `public Enemy createEnemy()`.

Then for each class of Enemy, also create a corresponding factory class (like `GoblinEnemyFactory`) which implements that interface by returning a newly created enemy of that type.

You can now register a new type of enemy by creating an EnemyFactory object and putting it into your collection of all available `IEnemyFactory`s.

The nice thing about this pattern is that you can theoretically have multiple enemy types which are actually implemented by the same enemy class. This is useful when you have enemies which behave identical but just have different stats. You can do that by creating different factory classes or by creating multiple instances of the same factory-class and then set some different variables on those instances. Here is an example which mixes both approaches by having two variants of goblins generated by two instances of the same factory-class and one variant of bat generated by an instance of a different factory-class:

```
EnemyFactory goblinFactory = new GoblinEnemyFactory();
goblinFactory.setName("Goblin");
goblinFactory.setHp(40);
goblinFactory.setAttack(10);
EnemyFactory eliteGoblinFactory = new GoblinEnemyFactory();
eliteGoblinFactory.setName("Elite Goblin");
eliteGoblinFactory.setHp(80);
eliteGoblinFactory.setAttack(20);
EnemyFactory batFactory = new BatEnemyFactory();
batFactory.setName("Bat");
batFactory.setHp(20);
batFactory.setAttack(10);

enemyFactories.add(goblinFactory);
enemyFactories.add(eliteGoblinFactory);
enemyFactories.add(batFactory);

```

By the way, in the long run you might want to put all the different properties of your enemies into a config file, so you can easily tweak them and add more enemies.

# Answer
> 0 votes
You could look into the Factory Design Pattern. Using this your enemy factory class is the only place where you need to store the list of available choices.

From your description you would be fine with just a single generate method for random enemies. But if you want to make it more complex later you could also give your factory additional methods or have it take optional input and generate different results based on it. For example:

```
//Gives a random enemy
Enemy enemy1 = enemyFactory.getEnemy();

//Gives a goblin enemy
Enemy enemy2 = enemyFactory.getEnemy("goblin");

//Gives a troll, bat or something else classed as cave monster
Enemy enemy3 = enemyFactory.getEnemyCave();

```

Maybe you sometimes want to generate more of whatever enemy is first generated to create small groups of similar enemies, which you can do without your calling class knowing the full list of choices by just looking at the type of the first one generated and use as input for the next one. Or you may want specific types of enemies to be more common on certain levels. But this is just examples you may not need for your game.

---
Tags: java, libgdx, design-patterns
---


# Question
Title: Implementing a game loop with interpolation
I am trying to implement the Game Loop interpolated found in this website http://www.gameprogblog.com/generic-game-loop/. Here is my implementation:

```
long frameRate = 50000000;
int maxUpdates = 3;
boolean yield = true;

private long time =0;

private long lastTime;
private long currentTime;

public static float interpolation;

public void gameLoop() {

    long nanoElapsed = tick();

    System.out.println(time + "\t Framerate: " + frameRate + "\t"
            + "Nanoelapsed: " + nanoElapsed + "\t Interpolation: "
            + interpolation);

    time += nanoElapsed;
    int updateCount = 0;

    while (time >= frameRate && updateCount < maxUpdates) {
        game.update();
        updateCount++;
        time -= frameRate;
    }

    interpolation = getInterpolation();
    game.render();

}

long tick() {
    lastTime = currentTime;
    currentTime = TimeUtils.nanoTime();
    return currentTime - lastTime;
}

float getInterpolation() {
    return (float) ((double) time / (double) frameRate);
}

```

However I cannot figure out the problem I am having. I am logging most of the variables and for some reason the time variable is very big and does not stay in an acceptable range. It also decreases over time. I have spent a long time trying to figure out why and I'm now stuck. Any suggestions and help would be appreciated. Thanks

# Answer
> 1 votes
edit: **If you are reading this and are experiencing bizarre results with your physics bodies or gameloop in general** \- I highly recommend that you read as many articles on this page as you can handle. Its also highly advised to continue further reading on the topics mentioned, most notably integration techniques and interval arithmetic.

---

Maybe a bit late to answer this question, but I guess I will give some insight.

Firstly I'm noticing that you are not using a fixed timestep correctly, instead you have coupled the FPS with each update.

The problem comes from the following line

```
 while (time >= frameRate && updateCount < maxUpdates) {

```

Every update you are comparing your accumulated delta time against a frame rate of 500000, the delta time will never be this high for a start.

Instead you want to define a TIMESTEP which is based on a maximum fps (50000 if you want) and compare your accumulated frame time against this value.

```
TIMESTEP = 1000/MAX_FPS;

```

Have a look at this quick javascript loop implementation

```
 var start = function(){

    this.gameLoop = requestAnimationFrame((t)=>{interval(t)});

}

const MAX_FPS = 60;
const TIMESTEP = 1000/MAX_FPS;

var lastFrame = performance.now();
var accumulator = 0;

var gameLoop;

function interval(t){

    var frameTime = t - lastFrame;
    lastFrame = t;

    //add frame times to an accumulator to make up for any excess time
    //for example if the last frame only took 2ms out of a 16ms - we will want to account for this - otherwise the simulation will start to fall behind
    accumulator += frameTime;

    //if the accumulator has enough time to warrant a timestep then we will want to simulate this
    //if the accumlator is greatly over the timestep, then we will want to simulate all the excess time in discrete time steps
    if(accumulator > TIMESTEP){
        update(TIMESTEP) //note the fixed timestep used to ensure every update is consistent

        accumulator -= TIMESTEP

    }

    requestAnimationFrame((t) => {interval(t)});
}

```

Finally in your update you will need to take into account the timestep for any motion integration.

```
    velocity.x += acceleration.x * dt //this dt is a fixed value to ensure consitent movement

```

Also note that this is a basic Euler integration, there are countless other integration techniques for use in an update, Euler is the most simple but it has many shortcomings.

---
Tags: java, libgdx, game-loop
---


title: Rotation 2d top-down view in 3d game

text:
# Question
Title: Rotation 2d top-down view in 3d game
I have a game in top-down view, with little ants who can walk up/down, left/right and diagonal (and all direction with Joystick).

My little player can move, but I can't rotate it properly... See what i mean in the youtube video of 7 seconds i made: https://www.youtube.com/watch?v=1mGMPhJ-u4s&feature=youtu.be

See the code:

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Move : MonoBehaviour
{
public float lookSpeed = 10;
private Vector3 curLoc;
private Vector3 prevLoc;

void Update()
{
    InputListen();
    transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.LookRotation(transform.position - prevLoc), Time.fixedDeltaTime * lookSpeed);
}

private void InputListen()
{
    prevLoc = curLoc;
    curLoc = transform.position;

    if (Input.GetKey(KeyCode.S))
        curLoc.y -= 1 * Time.fixedDeltaTime;
    if (Input.GetKey(KeyCode.Z))
        curLoc.y += 1 * Time.fixedDeltaTime;
    if (Input.GetKey(KeyCode.D))
        curLoc.x += 1 * Time.fixedDeltaTime;
    if (Input.GetKey(KeyCode.Q))
        curLoc.x -= 1 * Time.fixedDeltaTime;

    transform.position = curLoc;

}

```

}

I have tried a LOT of ways, but nothing worked... I have also an animator with a stylesheet (ants walking):

thanks !

EDIT: i try another aproch for moving:

```
transform.Translate(Input.GetAxis("Horizontal") * speed * Time.deltaTime, Input.GetAxis("Vertical") * speed * Time.deltaTime, 0);

```

and for rotating:

```
transform.up = gameObject.GetComponent<Rigidbody>().velocity;

```

It move well.. but it doen't rotate when i move... BUT when i collide with another object, my player get some velocity, and then rotate correctly without touching any input, see in the video: https://www.youtube.com/watch?v=AS3agqJbVtI&feature=youtu.be

# Answer
I Made it ! Thanks yo \_TOM First, I draw guizmo to help me visualized the transform.up vector:

```
void OnDrawGizmos()
{
    Color color;
    color = (nb_player == 1) ? Color.blue : Color.red;
    // local up
    DrawHelperAtCenter(this.transform.up, color, 2f);
}

private void DrawHelperAtCenter(
                    Vector3 direction, Color color, float scale)
{
    Gizmos.color = color;
    Vector3 destination = transform.position + direction * scale;
    Gizmos.DrawLine(transform.position, destination);
}

```

Then I made my function of movement, called in Update():

```
void MoveNew()
{
    //I don't want any angular velocity when i don't move !
    gameObject.GetComponent<Rigidbody>().velocity = Vector3.zero;
    gameObject.GetComponent<Rigidbody>().angularVelocity = Vector3.zero;

    if (nb_player == 1)//I have keyboard input ZQSD for player 1, and arrow key for player 2
    {
        float heading = Mathf.Atan2(Input.GetAxis("Horizontal") * speed * Time.deltaTime, Input.GetAxis("Vertical") * speed * Time.deltaTime);
        //if not, the rotation will go back to 0 when no input happened, note the use of "GetAxisRaw" very important, because returning 0 when not moving
        if (Input.GetAxisRaw("Horizontal") != 0 || Input.GetAxisRaw("Vertical") != 0)
            transform.rotation = Quaternion.Euler(0f, 0f, -heading * Mathf.Rad2Deg);

        transform.Translate(((this.transform.up * Input.GetAxis("Vertical")) * speed) * Time.deltaTime);
        transform.Translate(((-this.transform.right * Input.GetAxis("Horizontal")) * speed) * Time.deltaTime);

    }
    else if (nb_player == 2)
    {
        float heading = Mathf.Atan2(Input.GetAxis("Horizontal2") * speed * Time.deltaTime, Input.GetAxis("Vertical2") * speed * Time.deltaTime);
        if (Input.GetAxisRaw("Horizontal2") != 0 || Input.GetAxisRaw("Vertical2") != 0)
            transform.rotation = Quaternion.Euler(0f, 0f, -heading * Mathf.Rad2Deg);

        transform.Translate(((this.transform.up * Input.GetAxis("Vertical2")) * speed) * Time.deltaTime);
        transform.Translate(((-this.transform.right * Input.GetAxis("Horizontal2")) * speed) * Time.deltaTime);
    }
}

```

I havn't try it wet With Joystick, but i believe the result is the same...
> 0 votes

---
Tags: c#, rotation, quaternion
---


# Question
Title: How is the render() method called in libGDX?
I know that the project generator in libGDX finds the `render(deltatime)` method in my Game project and make it into a game loop so that it repeats itself on an average of 60 times per second. But I want to know how exactly the project generator finds the `render()` method.

Let me give you an example:

In my game, in the Main class, I declared a SecondClass with its own `render()` method using its constructor in the `create()` of the Main class. Then, I didn't have any render() method in the MainClass. When I did this, the `render()` in the SecondClass worked. However, when I created the `render()` method in the MainClass, the `render()` from the MainClass worked but not the `render()` method in the SecondClass. Does that mean that the project generator access the first `render()` it can see as the GameLoop?

# Answer
> 3 votes
The project generator isn't doing any work here, this is all handled by the source code, using dynamic dispatch (virtual functions) and basic programming logic. Reading the source code is a good way to understand how things like this work.

The `Game` base class you inherit from in libGDX is itself an implementation of `ApplicationListener`, which mandates the `render()` function.

The `Game` class implements `render()` by checking to see if the game has a screen, and if it does, it calls that screen's `render()` method.

If you inherit from `Game` and provide `render()` there, you override the `Game` class's render method and yours gets called *instead*. If you don't override `render`, the `Game` class's method gets called, and it forwards along a call to the `render` method of any active screen object.

This is just how dynamic dispatch/virtual functions work in Java. There's no magic examination of your source code by any project generator going on to implement this.

The generator is only used to generate a stub set of files that just replace your class and package names into the source code at the right points to ensure an instance of your class is created. It doesn't do much else relevant to this operation, and it's entirely unnecessary; you could write that bootstrapping code yourself quite easily if you wanted.

---
Tags: java, libgdx
---


title: How to change mute/unmute button?

text:
# Question
Title: How to change mute/unmute button?
I'm saving music in libgdx preference, the following code works perfectly but if you enter the settings again you'd see the initial `button up` regardless if the sound is muted or not.

```
TextureAtlas buttonsAtlas = new TextureAtlas("ui/dialogButtons.pack");
textButtonStyle.up = skin.getDrawable("music.down");
textButtonStyle.checked = skin.getDrawable("muteMusic.up");
button.addListener(new InputListener() {
 public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
  return true;
 }
 public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
  setMusicplaying(!musicplaying);
  if (getMusicplaying() == false)
   playMusic.stop();
  else playMusic.play();
 }
});

```

I tried to do this, it works perfecly but doesn't switch the button, when the user is clicking on it, it only switches when the user closes the dialog

```
if (getMusicplaying() == true) {
textButtonStyle.up = skin.getDrawable("music.down");
textButtonStyle.down = skin.getDrawable("muteMusic.up");}
if (getMusicplaying() == false) {
  textButtonStyle.up = skin.getDrawable("muteMusic.up");
  textButtonStyle.down = skin.getDrawable("music.down");}

```

# Answer
> 0 votes
I'm posting this answer since it may help someone, i got it from libgdx forums

```
if (getMusicplaying() == false)
 button.setChecked(true)

```

no need for more code, that's it.

---
Tags: java, android, libgdx, ios
---


# Question
Title: what makes render() and update() change frame 60 times every second in LibGDX
Whenever we declare the render(float deltatime) or update(float deltatime), in any class, it automatically become a method that is repeated 60 times per second. But what makes this method repeat itself 60 fps? What makes the method do that? In some classes, I am not implementing any other interface or expending any abstract class but that still makes the render(float deltatim) and update(float deltatime) work. Also, even though I *do* expend a interface like Game, how does the render(float deltatime) work? I mean, there is no special code within the render() in the Game interface class as well.

# Answer
Libgdx will do that. Part of the arguments passed to the project generator is `--mainClass MyGame`. The libgdx will then look for the methods in that class (either using reflection or by creating it's own class during project generation that refers to that class directly).

After that it's a standard gameloop buried somewhere inside the libgdx code.
> 0 votes

# Answer
One has to write code that does this. libGDX happens to generate this code for you using its project generator tool, to avoid making you build that boilerplate. All it is doing is producing a set of stub source files based on your target platform. For example, this is the file used for desktop platforms. `%PACKAGE%` and `%MAIN_CLASS%` are replaced, by the generator, with the names of your package and game class.

You can see that all this code does is create a new `LwjglApplication` and pass it an instance of your class. When constructed, `LwjglApplication` calls `initialize()`, which in turn starts a thread to call the `mainLoop` function.

`mainLoop` simply runs until the game is done. Within that loop, it does work related to gathering input and updating state and ultimately calls `render()` on the listener (your game instance) provided to it.

You can follow a similar path of execution for different platforms you may be interested in; there's nothing magic here. The project generator is just saving you some typing by instantiating the correct things for you, but ultimately all it is doing is copy-pasting some code on your behalf. It does not introspect your source code at all.
> 0 votes

---
Tags: libgdx
---


# Question
Title: Unity. C# help with arrays and letter placement
Think about this like "Guess the word" game: W _ _ _ _

I have a word that i separate in index - letters like this:

```
public static string[] splitWord;
word = "WORLD";

string[] splitWord = new string[word.Length];
for(int i = 0; i < splitWord.Length; i++)
    {
        splitWord[i] = word[i].ToString();
    }

```

This way when i print the splitWord variable

```
for(int i = 0; i < splitWord.Length;i++)
    {
         print(splitWord[i] + " " + i);
    }

```

i get this;

```
 W 0
 o 1
 r 2
 l 3
 d 4

```

In my Ui i have letters, when i choose one i check if the letter is in the word, this part is done.

```
public static void SetWord (string letter)
{
    if (GameController.word.Contains (letter)) {
        word.text += letter; ------>setting the word NOT in order
    } else {
        Debug.Log("Letter is not in the word");
    }

}

```

What i´m having problems with is to place the letter in the correct place of the word. What i want to do is, based on this:

```
 W 0
 o 1
 r 2
 l 3
 d 4

```

Is to check "ok this letter is on the word, what index in the Word does this letter has?, place the letter in the correct place". That is the idea. but because im pretty new to code in general i m having problems with this. The idea is to convert that array of stings into a hole string and use Insert() to place the letter in the correct spot.

Any ideas?

Thanks in advance for the help.

# Answer
I believe the easy way is to keep 2 char arrays

* First one contains the word
* Second one contains the first letter and the `_` char otherwise

What you display to the player is the second array of course.

When you check if the user guessed correctly, find at which index it was in the 1st array, and replace `_` by that letter in the second array at the same index.

In order to do that, you should not use the `Contains` method in order to know if the letter is in the word, but rather parse the array yourself to find **where** the letter matches.

It could look like this

```
void CheckInputLetter(array1, array2, letter)
{
    int i = 0;
    while (array1[i] != '\0') //parse the whole array
    {
         if (array1[i] == letter)
             array2[i] = letter;
         i++;
    }
}

```
> 1 votes

# Answer
Alternatively, using LINQ gives you one liner:

```
string displayWord = string.Concat(word.Select(c => guessed.Contains(c) ? c : '_'));

```

where `word` and `guessed` are `List`s of `char`s, first one is the correct word while the latter is list of all guesses(keeping them also gives you option to prevent player guessing a character twice).
> 0 votes

---
Tags: unity, c#
---


# Question
Title: What happens if I make more than $100k with the free Unity license?
If an indie game developer makes more than $100,000 using the free version of Unity, what happens to the money that goes over $100k? How will Unity people come to know how much money they are making?

What precautions should I take just in case a game is a great success?

# Answer
> **Update:** In June 2016, Unity revised their business model. They no longer offer permanent licenses, only subscriptions. However, they now offer a cheaper plus-version without the unprofessionally-looking Unity splash screen but with a revenue limit of $200,000. They also made some changes to the license agreement which required an update to this answer.

---

The Unity software terms regarding the differences between the personal, plus and pro version are pretty clear: When your company makes a gross revenue (not profit!) of more than $100,000 per year, you need to subscribe to the plus-version ($200,000 limit), pro version (no limit) or enterprise version (no limit):

> Unity Personal may not be used by:
>
> * a Commercial Entity that has either: (a) reached annual gross revenues in excess of US$100,000, or (b) raised funds (including but not limited to crowdfunding) in excess of US$100,000, in each case during the most recently completed fiscal year;
> * a Non-Commercial Entity (this means academic and governmental entities as defined below) with a total annual budget in excess of US$100,000 (for the entire Non-Commercial Entity (not just a department)) for the most recently completed fiscal year; or
> * an individual (not acting on behalf of a Legal Entity) or a Sole Proprietor that has reached annual gross revenues in excess of US$100,000 from its use of the Unity Software during the most recently completed fiscal year, which does not include any income earned by that individual which is unrelated to its use of the Unity Software.

The upgrade becomes required at the end of the fiscal year, because that's the way revenue is calculated according to the license conditions. As long as you don't subscribe to licenses for all your Unity users, you are obligated to stop using Unity. You are still allowed to sell your games, but you are no longer allowed to update them, even when you don't need the Unity editor to make updates:

> During the term of this Agreement, you expressly acknowledge and agree that if you are a Unity Personal or Unity Plus user and the above thresholds are exceeded, then you may no longer use that tier of the Unity Software, and you must either: (a) purchase Unity Plus (if eligible) or Unity Pro; or (b) destroy all copies of the Unity Software in your possession or control, and cease updating Your Project Content. Unity will monitor your compliance with and enforce these restrictions and requirements including but not limited to monitoring the number of downloads of Your Project Content and any available revenue estimate data.

What happens when you don't? When your games are that successful, you will likely not stay under the radar. When Unity Technologies suspects that you make more than $100,000 with the free version of their product they might sue you. During that lawsuit you might be forced to show your books to prove how much revenue you made and how many people you had working.

The court will decide what happens with any of the money above $100,000 you received from sales. Depending on the jurisdiction in which you are sued and their interpretation of the applicable laws and the EULA they might rule that you are entitled to it, that Unity Technologies is entitled to it, or that the sales are void and you need to refund it to your customers. Ask your lawyer what they consider the most likely outcome (don't tell us you can't afford one when you make over $100,000 a year).
> 54 votes

# Answer
> What precautions should I take just in case a game is a great success?

Document all of your income so you can show your revenue and when you earned it if a lawyer asks for it. Not just a spreadsheet you made up, but also statements from Steam or whoever is selling your game for you, or bank account transactions if you're selling it yourself. Save copies of these documents on your machine (don't just rely on the bank/vendor/etc. making them accessible), and print them out too if reasonable.

If you're a small company or lone developer, keep a separate bank account for your business. Using the same account for both business and personal finances leads to nightmares when financial records are necessary (e.g. if Unity sues, or if you're audited for taxes, etc.). Separate bank accounts are easier to show how money moves around.

If your game is an overnight success and you wake up in the morning with $100k+ revenue from its sales, get a version built in Pro and released as an update immediately. Even if you own Pro licenses for all of your developers, if Unity sees a version of your game built with the Free edition of their engine has thousands of sales, they'll likely audit or sue you for your records and you'll have a lot more hassle to go through even though you're legit.

Otherwise, upgrade all of your developers to Pro *well before* hitting the $100k mark if possible. If your game makes $50k or more, it's probably a good idea to upgrade. Upgrade as early as you can. If you make a nice game and can expect to make even nearly $100k off of it, upgrade to pro before you ever start selling. The less time a Free-built version of your game is on the market, the less likely there will be speculation and concern from Unity.
> 6 votes

# Answer
if you are 100% confident you are going to exceed 100k dollars, then take out a small business loan and purchase the Unity license required before launching the game... If you are 99% confident, then launch the game, make 100k overnight, go to the bank and get a small business loan...

There is zero reason for you to have to wait any length of time to get the proper license.
> -3 votes

---
Tags: unity, licensing
---


# Question
Title: Create Bezier curves with random heights that connect
In unity, I am trying to create several curved platforms that connect using bezier curves, however I am having issues. I understand the basics of genertating a bezier curve and I have something working well

My goal is to generate a series of forward moving Bezier curves, that are all connected to each other, while also having varying lengths and points. I have something working, however I am having issues connecting the curves, while retaining random Y values for different heights in the 4 points.

Below is my attempt:

Below is a Sketch I did in MS Paint to help explain goal:

From the sketch you can see that there is a diffrence in height between gameobject 0 and 1 but they are still connected. How can I generate the next points with random Y values, while still accounting for the previous curve? Any help would be greatly appreciated,

Thank you for your time.

# Answer
Let's start by declaring a few variables:
-**p1** is the y value of "Gameobject-0"
-**p2** is the y value of "Gameobject-1"
-**t1** is the height of the last point on the first curve(Gameobject-0)
-**t2** is the height of the first point on the second curve(Gameobject-1)

Having said all this, you should use equation:

```
p2 = p1 + t1 - t2

```
> 0 votes

---
Tags: unity, procedural, curves, beziers
---


# Question
Title: What is a good budget ratio for computation time?
What sort of budgets do they put on computation time?

For example, lets say a football game needs to run at 50 frames per second. That means that each frame can only be 20 milliseconds long. How is that 20 milliseconds divvied up? For example, it could be:

* Pathfinding - 3ms limit
* Ball Physics - 8ms limit
* Particle Effects - 2ms limit
* Animations - 7ms - limit
* **Total - 20ms**

However, I just made those numbers up without any idea what I was doing.

Is there a rule of thumb or a standard practice used? I know every game is different depending on art-style, game genre, etc. I am looking for as generic as an answer that can be had; however, if specifics are needed, then Madden Football 2017 can be used as the example game.

What percentage of milliseconds should be allowed for each aspect of game development?

# Answer
> 4 votes
Allocate the most frame time for the most important things. Allocate less frame time for less important things.

What is more or less important will vary significantly based on the game. Not just on the genre of the game, but the very specific desired style, feel and features of that game.

* A football game focusing on extreme realism of the simulation, both of player dynamics, flight physics of the ball, play tactics, et cetera will likely want a significantly more robust AI and simulation engine, and thus will be willing to sacrifice more frame time there.
* A more arcade-y, less serious football game might not care so much about any of that simulation and might want more time spent on rendering fancy particle effects and graphics to get across more *action*, or whatever.

Most games will probably fit into those kinds of buckets: either they'll have complex game simulations, and want to dedicate the lion's share of frame time to those, or they won't and will instead prefer to dedicate that time to graphics.

As a rule of thumb it seems unlikely to want to permit any one chore from consuming more than 50% of the frame, but in some cases that might be acceptable and when you start allowing for concurrent operation of certain tasks that becomes much more flexible (as does the definition of what constitutes percentage of frame time).

---
Tags: performance
---


title: Pre rendered 3d

text:
# Question
Title: Pre rendered 3d
I am so confused on how to create isometric buildings ( like the ones in Clash of clans ) so I can use them in my project in Unity..What I've understood ( I think ) is the buildings are actually 3d models but rendered as 2d images..I have created lots of 3d models in Blender and I want them to look as the ones in the pic.. How can I do this?

(Image source)

# Answer
You render them as a png/preferred image format from the angle you want from your 3d program. Shadows and everything is baked into your sprite. Then in Unity you import them as regular sprites and use that in 2d.

There's not really much more to it. I guess, you have to texture it etc, but that's not something you do in Unity anyway.
> 1 votes

# Answer
Check out this site here.

You can do this as 2D images, not 3D models being rendered 2D. They are actually 2D sprites that are just made in such a way with appropriate proportions and tools to make them appear as though they are 3-Dimensional. That's the point of isometric - "having equal dimensions".

The tutorials on that site use Illustrator so if you don't have that and intend to legitimately make these, then it's definitely a great tool to get, but there are free, lower quality, tools that do essentially the same stuff.
> 1 votes

# Answer
Probably what you need is orthographic projection. Orthographic projection maintains the distance between points and usually used for generation of minimaps in games. Blender should be able to render pictures with this mode. Please try it and tell if it helped your case
> 0 votes

---
Tags: unity, rendering
---


# Question
Title: Error using Physics Body Editor for LibGDX
In my game, I've been trying to use the physics body editor for libgdx, but I kept on getting an error. So I thought there was probably something wrong with my code so I took the example off of the website (http://www.aurelienribon.com/blog/projects/physics-body-editor/), and tried running that. But I got the same exact error on the same line of code.

The line of code from the website's example that's creating the error is

```
BodyEditorLoader loader = new BodyEditorLoader(Gdx.files.internal("data/test.json"));

```

and the error is

Exception in thread "LWJGL Application" com.badlogic.gdx.utils.GdxRuntimeException: java.lang.NoSuchMethodError: com.badlogic.gdx.utils.JsonReader.parse(Ljava/lang/String;)Ljava/lang/Object; at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:118) Caused by: java.lang.NoSuchMethodError: com.badlogic.gdx.utils.JsonReader.parse(Ljava/lang/String;)Ljava/lang/Object; at aurelienribon.bodyeditor.BodyEditorLoader.readJson(BodyEditorLoader.java:179) at aurelienribon.bodyeditor.BodyEditorLoader.(BodyEditorLoader.java:41) at com.Jon.App.App.createBottle(App.java:129) at com.Jon.App.App.create(App.java:76) at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:132) at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:112)

Any ideas on how to fix this?

# Answer
Apparently the JSON API has changed recently, but there is a maintenance problem with the physics body editor.

More details at https://code.google.com/p/libgdx/issues/detail?id=1418.
> 0 votes

# Answer
The problem is that, with newer versions of libGDX, their API's have changed. That is why you get the errors like `java.lang.NoSuchMethodError`.

The solution is to use an updated version of the `BodyEditorLoader` class. The original author, *Aurelien Ribon*, did not have enough time to update and replace the repository; others have made the changes.

This code should work with libGDX version 1.9.5. Just reference this class when you want to use the `BodyEditorLoader`, like you would with any other class.

---

Here is an updated version of the `BodyEditorLoader` class. Minor revisions include the new `readJson` method and replacing `mul(scale)` is changed to with `scl(scale)`. You can copy paste this code, or find it at it's source, on GitHub.

```
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.CircleShape;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.PolygonShape;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.JsonReader;
import com.badlogic.gdx.utils.JsonValue;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BodyEditorLoader {

// Model
private final Model model;

// Reusable stuff
private final List<Vector2> vectorPool = new ArrayList<Vector2>();
private final PolygonShape polygonShape = new PolygonShape();
private final CircleShape circleShape = new CircleShape();
private final Vector2 vec = new Vector2();

// -------------------------------------------------------------------------
// Ctors
// -------------------------------------------------------------------------

public BodyEditorLoader(FileHandle file) {
    if (file == null) throw new NullPointerException("file is null");
    model = readJson(file.readString());
}

public BodyEditorLoader(String str) {
    if (str == null) throw new NullPointerException("str is null");
    model = readJson(str);
}

// -------------------------------------------------------------------------
// Public API
// -------------------------------------------------------------------------

/**
 * Creates and applies the fixtures defined in the editor. The name
 * parameter is used to retrieve the right fixture from the loaded file.
 * <br/><br/>
 *
 * The body reference point (the red cross in the tool) is by default
 * located at the bottom left corner of the image. This reference point
 * will be put right over the BodyDef position point. Therefore, you should
 * place this reference point carefully to let you place your body in your
 * world easily with its BodyDef.position point. Note that to draw an image
 * at the position of your body, you will need to know this reference point
 * (see {@link #getOrigin(java.lang.String, float)}.
 * <br/><br/>
 *
 * Also, saved shapes are normalized. As shown in the tool, the width of
 * the image is considered to be always 1 meter. Thus, you need to provide
 * a scale factor so the polygons get resized according to your needs (not
 * every body is 1 meter large in your game, I guess).
 *
 * @param body The Box2d body you want to attach the fixture to.
 * @param name The name of the fixture you want to load.
 * @param fd The fixture parameters to apply to the created body fixture.
 * @param scale The desired scale of the body. The default width is 1.
 */
public void attachFixture(Body body, String name, FixtureDef fd, float scale)    {
    RigidBodyModel rbModel = model.rigidBodies.get(name);
    if (rbModel == null) throw new RuntimeException("Name '" + name + "' was not found.");

    Vector2 origin = vec.set(rbModel.origin).scl(scale);

    for (int i=0, n=rbModel.polygons.size(); i<n; i++) {
        PolygonModel polygon = rbModel.polygons.get(i);
        Vector2[] vertices = polygon.buffer;

        for (int ii=0, nn=vertices.length; ii<nn; ii++) {
            vertices[ii] = newVec().set(polygon.vertices.get(ii)).scl(scale);
            vertices[ii].sub(origin);
        }

        polygonShape.set(vertices);
        fd.shape = polygonShape;
        body.createFixture(fd);

        for (int ii=0, nn=vertices.length; ii<nn; ii++) {
            free(vertices[ii]);
        }
    }

    for (int i=0, n=rbModel.circles.size(); i<n; i++) {
        CircleModel circle = rbModel.circles.get(i);
        Vector2 center = newVec().set(circle.center).scl(scale);
        float radius = circle.radius * scale;

        circleShape.setPosition(center);
        circleShape.setRadius(radius);
        fd.shape = circleShape;
        body.createFixture(fd);

        free(center);
    }
}

/**
 * Gets the image path attached to the given name.
 */
public String getImagePath(String name) {
    RigidBodyModel rbModel = model.rigidBodies.get(name);
    if (rbModel == null) throw new RuntimeException("Name '" + name + "' was not found.");

    return rbModel.imagePath;
}

/**
 * Gets the origin point attached to the given name. Since the point is
 * normalized in [0,1] coordinates, it needs to be scaled to your body
 * size. Warning: this method returns the same Vector2 object each time, so
 * copy it if you need it for later use.
 */
public Vector2 getOrigin(String name, float scale) {
    RigidBodyModel rbModel = model.rigidBodies.get(name);
    if (rbModel == null) throw new RuntimeException("Name '" + name + "' was not found.");

    return vec.set(rbModel.origin).scl(scale);
}

/**
 * <b>For advanced users only.</b> Lets you access the internal model of
 * this loader and modify it. Be aware that any modification is permanent
 * and that you should really know what you are doing.
 */
public Model getInternalModel() {
    return model;
}

// -------------------------------------------------------------------------
// Json Models
// -------------------------------------------------------------------------

public static class Model {
    public final Map<String, RigidBodyModel> rigidBodies
        = new HashMap<String, RigidBodyModel>();
}

public static class RigidBodyModel {
    public String name;
    public String imagePath;
    public final Vector2 origin = new Vector2();
    public final List<PolygonModel> polygons = new ArrayList<PolygonModel>();
    public final List<CircleModel> circles = new ArrayList<CircleModel>();
}

public static class PolygonModel {
    public final List<Vector2> vertices = new ArrayList<Vector2>();
    private Vector2[] buffer; // used to avoid allocation in attachFixture()
}

public static class CircleModel {
    public final Vector2 center = new Vector2();
    public float radius;
}

// -------------------------------------------------------------------------
// Json reading process
// -------------------------------------------------------------------------

private Model readJson(String str) {
    Model m = new Model();

    JsonValue map = new JsonReader().parse(str);

    JsonValue bodyElem = map.getChild("rigidBodies");
    for (; bodyElem != null; bodyElem = bodyElem.next()) {
        RigidBodyModel rbModel = readRigidBody(bodyElem);
        m.rigidBodies.put(rbModel.name, rbModel);
    }

    return m;
}

private RigidBodyModel readRigidBody(JsonValue bodyElem) {
    RigidBodyModel rbModel = new RigidBodyModel();
    rbModel.name = bodyElem.getString("name");
    rbModel.imagePath = bodyElem.getString("imagePath");

    JsonValue originElem = bodyElem.get("origin");
    rbModel.origin.x = originElem.getFloat("x");
    rbModel.origin.y = originElem.getFloat("y");

    // polygons
    JsonValue polygonsElem = bodyElem.getChild("polygons");
    for (; polygonsElem != null ;polygonsElem = polygonsElem.next()){

        PolygonModel polygon = new PolygonModel();
        rbModel.polygons.add(polygon);

        JsonValue vertexElem = polygonsElem.child();
        for (; vertexElem != null; vertexElem = vertexElem.next()) {
            float x = vertexElem.getFloat("x");
            float y = vertexElem.getFloat("y");
            polygon.vertices.add(new Vector2(x, y));
        }

        polygon.buffer = new Vector2[polygon.vertices.size()];

    }

    // circles
    JsonValue circleElem = bodyElem.getChild("circles");

    for (; circleElem != null; circleElem = circleElem.next()) {
        CircleModel circle = new CircleModel();
        rbModel.circles.add(circle);

        circle.center.x = circleElem.getFloat("cx");
        circle.center.y = circleElem.getFloat("cy");
        circle.radius = circleElem.getFloat("r");
    }

    return rbModel;
}

// -------------------------------------------------------------------------
// Helpers
// -------------------------------------------------------------------------

private Vector2 newVec() {
    return vectorPool.isEmpty() ? new Vector2() : vectorPool.remove(0);
}

private void free(Vector2 v) {
    vectorPool.add(v);
}
}

```
> 2 votes

---
Tags: java, box2d, libgdx
---


title: Lag in Destroy() method

text:
# Question
Title: Lag in Destroy() method
I have a script that destroys the player object when a collider with that script touches it. The thing is that, even if there is no time specified in the script, it takes couple seconds before it destroys the player. Why does this happen, and how do I get around it?

```
public class DestroyScript : MonoBehaviour
{
    public GameObject player;

    void OnTriggerEnter(Collision otherObj)
    {
        if (otherObj.gameObject.tag == "Player")
            Destroy(player);
    }
}

```

# Answer
`Destroy()` does not have an immediate affect on a `GameObject`. As *m.rogalski* points out, `Destroy()` ensures that the `GameObject` is destroyed *safely*. There are a couple of ways around this. If we want the `GameObject` to be immediately invisible to the game, we can use `SetActive()`. If we really need to, we can use `DestroyImmediate()`, though usage is unadvised.

### Making the `GameObject` invisible as we `Destroy()` it

If you want the `GameObject` to be immediately invisible to the player, when you call `Destroy()`, you should also call `SetActive(false)`. This will deactivate the `GameObject`, and remove it from play, while letting it idle in the background until it's `Destroy()` method completes.

```
public class DestroyScript : MonoBehaviour
{
    public GameObject player;

    void OnTriggerEnter(Collision otherObj)
    {
        if (otherObj.gameObject.tag == "Player")
        {
            player.SetActive(false);
            Destroy(player);
        }
    }
}

```

### Using `DestroyImmediate()`

If you just want to immediately `Destroy()` a `GameObject`, call `DestroyImmediate()`, instead. Be advised: `DestroyImmediate()` is extremely unsafe. It is advised that this method is used *sparingly*, and only for *editor* tasks; I typically use an `#if UNITY_EDITOR` to ensure that an actual build still uses `Destroy()`, instead.

```
public class DestroyScript : MonoBehaviour
{
    public GameObject player;

    void OnTriggerEnter(Collision otherObj)
    {
        if (otherObj.gameObject.tag == "Player")
        {
            #if UNITY_EDITOR
            DestroyImmediate(player);
            #else
            Destroy(player);
            #endif
        }
    }
}

```

It is ***very important*** to note the *overload* for `DestroyImmediate()`; while you provide an `Object`, much like `Destroy()`, you can also provide a `bool` to permit *asset deletion*. This `bool` defaults to `false`, but it is important to know that the functionality there can *permanently delete* assets.

```
public class DestroyScript : MonoBehaviour
{
    public GameObject player;

    void OnTriggerEnter(Collision otherObj)
    {
        if (otherObj.gameObject.tag == "Player")
        {
            // I am now permitting permanent asset deletion.
            // This can be real bad, mmkay?
            #if UNITY_EDITOR
            DestroyImmediate(player, true);
            #else
            Destroy(player);
            #endif
        }
    }
}

```
> 1 votes

---
Tags: unity
---