title: game resuming stats password

text:
# Question
Title: game resuming stats password
i'm asking for a more clever encoding algorithm to retrieving game stats which generates a shorter and more clear password

for example i have this information's to be saved via a short CODE

---

**Health** 0 - 99
**Armor** 0 - 99
**Ammo** 0 - 999
**Shells** 0 - 99
**Rockets** 0 - 9
**Weapon1** 0 - 1 // picked or not (boolean)
**Weapon2** 0 - 1
**Weapon3** 0 - 1
**Weapon4** 0 - 1
**Level** 1 - 3

---

## what i did :

an inline example of above information's : **99 99 999 99 9 1111 3**

the encoded result with base64 as String : **OTkgOTkgOTk5IDk5IDkgMTExMSAz**

the encoded result with base64 as Decimal : **Y2PPp2MJ0ZcD** (good but long yet)

what i know is to handly encoding some part of the code for example for boolean part, there is only 16 states, **0000** 0001 **0010** 0011 ...etc

so it can be reduced to only 16, information could be reduced to: **99 99 999 99 9 16 3**

then result will be still same : **Y2PPp2MJEAM=** (ogly and long)

i used **this** website for decoding and encoding

# Answer
First, consider the alternatives. When this is a game running as an executable application, you should be able to create a savegame. When this is a web-based game where you don't have access to the user's filesystem, you could store the information in a database on the server or in the user's localstorage.

But if you really want a passcode solution, you need to look at how many bits of information you really need. `n` bits can store `2^n` different values. So the least number of bits you need to represent your game state is:

```
Variable Range     Required bits

Health   0 - 99    7
Armor    0 - 99    7
Ammo     0 - 999   10
Shells   0 - 99    7
Rockets  0 - 9     4
Weapon1  0 - 1     1
Weapon2  0 - 1     1
Weapon3  0 - 1     1
Weapon4  0 - 1     1
Level    1 - 3     2

Sum               41

```

41 bits encoded with base64 is just 7 characters. If you find base64 ugly, you can encode it using less characters, but then you will need longer passcodes. You could, for example, use hexadecimal, but then you will need at least 11 characters (might want to round that up to 12 by adding an additional character as checksum to prevent players from guessing passcodes).

For more information about how to get and set individual bits of data in byte-oriented data-types, look up the bit-operators of your programming language of choice, namely bitwise shift, binary-and and binary-or.
> 2 votes

# Answer
I'm not going to suggest a way to re-hash your hash in a shorter fashion. I'll suggest an alternative.

What you could do is extract *all* the possibilities, let's put them in the vector `SaveHashes`.

Then come up with a list of random *names*, such as \[Potato, Fire, Cloud, Mug, Wig\], and a similar list of random *adjectives*, such as \[Blue, Light, Frowning, French\].

You see me coming, right?

Then for each of the hashes in `SaveHashes`, generate a unique random 'new hash' by combining an adjective with a name.

Put that in an associative array, and your good to go! When a player enters "BlueMug" as their password, fetch the associated 'real' password **Y2PPp2MJEAM=**, and from there, reset the stats.

This has the advantage of making password easy to remember, and bring a smile on the face of your players, because the concept of a HairyPotato or DancingBanana is funny. *You* could even cheat as a game developer and add 'artificial' save games that would give you super-powers not available to normal players.

The only drawback of this technique is that it's potentially going to take up a lot of disk space.

---

*This alternative is based on comments from @Philipp and @RatchetFreak (thanks!).*

There is a way to reduce quantity of data used.

As calculated by @Philipp, you need 37 bits to encode the information.

You find a list of 2048 English words, and you link each of these words to a unique 11 bits value (2^11 = 2048).

To generate the 'password', you inspect the bits of the compressed data that you have, left-pad with zeros, split the bit string in four 11 bits parts, and find the word associated with each of these. This will generate a four words 'password'.

You can regenerate the savegame data by simply doing the steps in reverse order.
> 1 votes

---
Tags: savegame
---


# Question
Title: Publishing a game on Google Play with a fake name
I'm almost publishing my game to Google Play, but I wonder if I can use an fake name, I mean, not using a fake name with a real names, just some words like **Lazer Dude** or anything else, because I don't want to show who am I, I wanna keep my anonymously. There's no problem to use an fake name?

# Answer
You cannot hide your real name from *Google*. The distribution agreement you enter into is between you (or your company) and them, and they will require sufficient personal information from you in order to allow you to distribute (and in return, disburse your payments) that they'll be able to identify you.

The public-facing name you use doesn't have to be your own (as near as I've been able to tell), as long as you don't pick something that would be impersonating some other intellectual property or brand.

You can consider filing a DBA (doing-business-as) registration (or the equivalent outside the US). This is a fictitious name legally associated with your business entity (which would be a sole proprietorship in this case). It may provide some additional legitimacy.

You should consult a lawyer familiar with business law and practices to be 100% sure, as I am not.
> 4 votes

# Answer
Call them on a land line or cell phone and ask.
> -5 votes

---
Tags: publishing, google-play
---


# Question
Title: Do I really need an engine to make a great game?
I made one simple game, and now I'm working on a second version. I make games in Java, but everyone around me uses tools and engines. I do not understand some of the stuff that is in Unity.

In Java, I write all the code. I understand how it works, and I know how to make the code do what I want.

Is it true that I cannot make a great game without a tool?

# Answer
Of course you can make everything yourself if you want to. Game engines aren't magic. There is nothing they can do which you couldn't program on your own if you were willing to invest a lot of time and effort. But the question is *is it worth it?*

Using a premade engine means you have already solved a lot of the common problems every game needs to solve, like asset loading, rendering, collision detection, UI framework and many more. Doing all that stuff on your own requires a lot of studying algorithms and APIs, a lot of programming and testing, and in the end you will just have ended up reinventing the wheel. But if you use a game engine, all of that drudge work is already done and you can put all your time into what actually requires creativity: gameplay and content.

Sometimes you have game concepts which are so unique that they require special technical implementations no common engine can handle. For example, Minecraft with its up to 18 *million* of destructible blocks in the scene at once would never work in an engine not optimized for that. In such a case you need to invest the time to develop your own engine. But that's rather the exception than the norm.
> 4 votes

---
Tags: tools
---


# Question
Title: Get distance between two objects from an ortographic point of view
I want to be able to measure the distance from one object to another through the camera's orthographic projection.

**As shown here, the objects are away from each other**

**When I move the camera, they "appear" to be closer together:**

I want to be able to measure that blue line. How can I make this possible?

# Answer
Take both object centers and pass them through the `WorldToScreenPoint` or `WorldToViewportPoint` function of your camera then calculate the 2D distance (magnitude of the difference).

```
Vector3 screenPos1 = camera.WorldToScreenPoint(target1.position);
Vector3 screenPos2 = camera.WorldToScreenPoint(target2.position);
float distance = new Vector2(
        screenPos1.x-screenPos2.x, screenPos1.y-screenPos2.y
    ).magnitude;

```

https://docs.unity3d.com/ScriptReference/Camera.WorldToScreenPoint.html https://docs.unity3d.com/ScriptReference/Camera.WorldToViewportPoint.html

> Viewport space is normalized and relative to the camera. The bottom-left of the camera is (0,0); the top-right is (1,1). The z position is in world units from the camera.
> 6 votes

# Answer
When we get the normal distance between two game objects, we simply work out the distance based off the 3D coordinates.

When we change to an orthographic view, all we are doing is changing to a *2D* perspective. Distance works *in exactly the same way*, except we work it out based off *2D* coordinates.

We can convert our positions to `Vector2` and use the inbuilt `Vector2.Distance` method, or use Pythagoras's theorem to work it out, manually.

---

## Using `Vector2.Distance`

If we convert the 3D positions to 2D1, we can simply use the `Vector2.Distance` method. In context of an *orthographic* view, this means we only really need to ommit the `z` value in our game objects `Vector3` position.

Here is an example of a method that will determine the orthographic distance between two `Vector3` coordinates, and output the value as a `float`.

```
public float GetOrthographicDistance(Vector3 a, Vector3 b)
{
    return Vector2.Distance(
        new Vector2(a.x, a.y), new Vector2(b.x, b.y));
}

```

### Using Pythagoras's theorem

Pythagoras's theorem tells us that, in an equilateral triangle, the square of the longest side is equal to the sum of the squares of the other two sides.

> a2 = b2 \+ c2

Using this theorem, we can easily create a manual method to work out the distance, as follows.

```
public float GetOrthographicDistance(Vector3 vectorA, Vector3 vectorB)
{
    // a^2 = b^2 + c^2

    float b = vectorA.x - vectorB.x;
    float c = vectorA.y - vectorB.y;

    float a = Mathf.Sqrt((b * b)+ (c * c));

    return a;
}

```

---

1 I have read Unity tutorials that claim you can pass a `Vector3` freely into a `Vector2`, but I can not find an implicit cast overload, nor have I ever seen this actually done.
> 2 votes

---
Tags: unity
---


title: Not a Number error

text:
# Question
Title: Not a Number error
I am developping a little game with GameMaker Studio.

I am sorry if this is a silly question, but I keep getting NaN as a result of this equation :

```
    Team_Joueur.PVsRandom[Setup_Battle.PokemonAleatoire] -= (( 2 * Team_Joueur.Niveau[0] + 10) / 250 * (Team_Joueur.Attaque[0] *
(ModificateursSimples(Team_Joueur.Modificateurs[0, 0]) / 100)) / (Team_Joueur.DefenseRandom[Setup_Battle.PokemonAleatoire] *
(ModificateursSimples(Team_Joueur.ModificateursRandom[Setup_Battle.PokemonAleatoire, 1]) / 100)) * Team_Joueur.Puissance[0, Position] + 2)
* (STAB * Coup_Critique * round(random_range(0.85, 1.01)));

```

Here is the original equation :

And here is the equation with simpler variables' name :

```
HP[Pokemon] -= (( 2 * Level[0] + 10) / 250 * (Attack[0] *
(Modif(Modificators[0, 0]) / 100)) / DefenceOpponent[Opponent] *
(Modif(ModificatorsOpponent[Opponent, 1]) / 100)) * Power[0, Attack] + 2)
* (STAB * Critical * round(random_range(0.85, 1.01)));

```

I tried each argument and they are all numbers, not very large, and drawing the equation gave me the result...

```
draw_text(32, 224, string(Team_Joueur.PVsRandom[Setup_Battle.PokemonAleatoire] - (( 2 * Team_Joueur.Niveau[0] + 10) / 250 * (Team_Joueur.Attaque[0] *
(ModificateursSimples(Team_Joueur.Modificateurs[0, 0]) / 100)) / (Team_Joueur.DefenseRandom[Setup_Battle.PokemonAleatoire] *
(ModificateursSimples(Team_Joueur.ModificateursRandom[Setup_Battle.PokemonAleatoire, 1]) / 100)) * Team_Joueur.Puissance[0, 0] + 2)));

```

PS : The 'Modif' function returns a number based on another one.

I am deeply sorry for my code, I know it's messy.

# Answer
> 1 votes
Ok, the problem was in my function ModificateursSimples : I was returning a value in a switch, thus never reading the line `break;`, and when coming back to that function, the switch was never clearly closed before, thus buging.

The solution is to make a temp variable, changing in the switch, and returning it only AFTER the switch, once it is close.

---
Tags: game-maker
---


# Question
Title: How to create a tile map texture in Oxygine?
I started playing around with Oxygine and Ogmo last night when I stumbled upon this GitHub that read in the Ogmo level.

I ended up *fixing* the `doRender` method as it did not work (could just be due to it being an old version of Ogmo or something):

```
void OgmoLevel::doRender(const RenderState& rs) {
    auto tileLayers = this->tileLayers;
    Sprite sprite;
    for (size_t layerIndex = 0; layerIndex < tileLayers.size(); ++layerIndex) {
        auto tileLayer = &tileLayers.at(layerIndex);

        auto resAnim = project->resource->getResAnim(tileLayer->tileset->name);
        resAnim->getFrame(0).getDiffuse().base->setLinearFilter(false);

        sprite.setResAnim(resAnim);

        int gridXSize = tileLayer->definition->gridWidth;
        int gridYSize = tileLayer->definition->gridHeight;

        size_t columns = roomWidth / gridXSize;
        size_t rows = roomHeight / gridYSize;

        auto tiles = &tileLayer->tiles;
        size_t tilesSize = tiles->size();

        size_t i = 0;
        float yy = 0;
        for (size_t y = 0; y < rows; ++y) {
            float xx = 0;
            for (size_t x = 0; x < columns; ++x) {
                int tileID = tiles->at(i);
                if (tileID != OGMO_BLANK_TILE)
                {
                    int tWidth = tileLayer->tileset->tileWidth;

                    int actualRow = (tileID * tWidth / tWidth) / tWidth;
                    int actualColumn = (tileID - (actualRow * tWidth));

                    sprite.setColumnRow(actualColumn, actualRow);
                    sprite.setPosition(xx, yy);
                    sprite.render(rs);
                }

                xx += tileLayer->definition->gridWidth;
                ++i;
            }
            yy += tileLayer->definition->gridHeight;
        }
    }
}

```

The issue I see with this, is that the same exact rendering is happening every single frame. Normally for the tile maps, there are checks to determine whether or not the tile is on the screen. Now that is fine and all, but this time around, I know it is fully static 99% of the time and I want to render it to a texture and just continue to render that.

I've looked at the `MemoryTexture` and `ImageData` classes, but there wasn't really anything online I could find to tell me how to properly use them. Does anyone have any idea how I can achieve caching this?

*(not enough rep to create proper tags)*

# Answer
> 0 votes
Thanks to the helpful admin over at the Oxygine forum, I was able to figure out how to programmaticly create textures. Below is sample code on how to do it:

```
oxygine::file::read(fileName, fb, oxygine::error_policy::ep_show_error);

oxygine::Image tileSheetImage;
tileSheetImage.init(fb);
Rect r(0, 0, 16, 16);

oxygine::Image myMap;
myMap.init(1024, 1024, tileSheetImage.getFormat());

auto tile = tileSheetImage.lock().getRect(r);
spNativeTexture texture = IVideoDriver::instance->createTexture();
operations::blit(tile, myMap.lock(0,0).getRect(r));
texture->init(myMap.lock());

AnimationFrame frame(texture);
sprite.setAnimFrame(frame);
sprite.setPosition(0, 0);
sprite.render(rs);

```

---
Tags: c++
---


# Question
Title: How can I manually advance a timeline in GameMaker?
I have a timeline from 0 to 300 frames divided into maybe 20 different steps.

When I certain condition is met, I want to jump to the next step of that timeline. How can I do that?

# Answer
If you don't need fully automatical processing, then you can put all the moments to array and then check `timeline_position` with these values.

A small example. You have timeline with moments 0, 100, 500, and 1000. In `Create` event define the array:

```
// store timeline moments to the array
moments[0] = 0;
moments[1] = 100;
moments[2] = 500;
moments[3] = 1000;

// start timeline
timeline_index = timeline0;
timeline_position = 0;
timeline_running = true;

```

And how you can jump:

```
for (var i=0; i<array_length_1d(moments); i++)
{
    var pos = moments[i];
    if timeline_position > pos continue;

    show_message("current position: " + string(timeline_position) + "#next position: " + string(pos));
    timeline_position = pos;
    break;
}

```

In case when you need to do it fully automatically, then you need to do same way, but you need create the timeline yourself using `timeline_moment_add_script` function.
> 1 votes

---
Tags: game-maker
---


# Question
Title: Actor in Stage Does Not Update the MoveTo XY Location
I am creating a game wherein an apple is being shot with an arrow. The apple's location is the XY location of the user input and the arrow actor has to move to that location using the code actor.moveto. The problem is the arrow only moves only once to the user input's direction. I know that the moveTo action of the actor is updated many times per second when I called stageArrow.act in the update method so I am wondering why the arrow only moves once. Here's my code:

appleclass.java

```
public class AppleClass implements Screen {

Arrow arrow;
private final MainApp app;
public Image ShotImage;

public AppleClass(final MainApp app){
        this.app = app;
        this.stageApple = new Stage(new StretchViewport(app.screenWidth,app.screenHeight , app.camera));
        this.stageArrow =new Stage(new StretchViewport(app.screenWidth,app.screenHeight , app.camera));

        arrow = new ArrowClass(app);

    }

@Override
    public void show() {

        InputMultiplexer inputMultiplexer = new InputMultiplexer();
        inputMultiplexer.addProcessor(stageApple);
        inputMultiplexer.addProcessor(stageArrow);
        Gdx.input.setInputProcessor(inputMultiplexer);

        arrow();

    }

    public void arrow(){
        arrow.isTouchable();
        stageArrow.addActor(arrow);
        arrow.addAction((moveTo(Gdx.input.getX(),Gdx.input.getY(),0.3f)));   //===> only executes once.
        arrow.addListener(new InputListener(){
            public void enter(InputEvent event, float x, float y, int pointer, Actor fromActor){

            if (Gdx.input.isTouched()){
                        ShotImage.setVisible(true);

                          }
                        }
                    });}

}

@Override
    public void render(float delta) {

        Gdx.gl.glClearColor(0, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        update(delta);
}

public void update(float deltaTime){

        stageApple.draw();
        stageArrow.draw();

        stageApple.act(deltaTime);
        stageArrow.act(deltaTime);

    }

```

ArrowClass.java

```
public class ArrowClass extends Actor {
    MainApp app;
    AppleClass appleClass;
    public Texture arrowTexture;

    public ArrowClass(final MainApp app){
        this.app = app;
        arrowTexture = new Texture("medievalarrow.png");
        this.setSize(arrowWidth, arrowHeight);
        this.setTouchable(Touchable.enabled);
        this.setBounds(app.screenWidth*0.45f,0,arrowWidth,arrowHeight);
        this.setOrigin(0,0);

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

        final float delta = Gdx.graphics.getDeltaTime();
        this.act(delta);

        app.batch.begin();
        app.batch.draw(arrowTexture, getX(),getY(),getWidth(),getHeight());
        app.batch.end();

    }
}

```

Any help will be highly appreciated. Thanks.

# Answer
> 1 votes
I have found the answer to my own question, I have separated both class to a different stage and this solution works. I know that there is a better way of doing this and I am open for any edits or future answers. This is the code for using more than one stage :

```
        InputMultiplexer inputMultiplexer = new InputMultiplexer();
        inputMultiplexer.addProcessor(stage);
        inputMultiplexer.addProcessor(stage2);
        Gdx.input.setInputProcessor(inputMultiplexer);

```

# Answer
> 1 votes
I think the problem is because you are calling `this.act(delta)` in your `ArrowClass`' draw method. When you call `Stage#act()`, it will call the act method on all of its actors for you. Since you're calling it once when you draw and again when you update the stage, it's moving at twice the normal speed and that could be causing it to reach its destination prematurely.

A few other comments about your code, if I may:

First, you probably don't want two separate stages- unless you're using Scene2D.UI, you would normally have a single stage with Arrow and Apple added to it as actors.

Second, when you override `Actor#draw()`, you should use the batch it passes you to do the rendering instead of using the one from app. You also don't want to call `begin()` and `end()` inside your draw method- these are 'expensive' and you only want to call them once per frame. However, if you just use the batch that is passed to draw(), the Stage class will handle beginning and ending for you and you won't need to call them explicitly.

Third, you actually don't need to call `super.draw(batch, parentAlpha)` because it's an empty method in the Actor class.

Thus, your class could be simplified to the following:

```
public class ArrowClass extends Actor {
    AppleClass appleClass; // You never set this; you may not need it
    Texture arrowTexture;

    public ArrowClass(MainApp app, arrowWidth, arrowHeight) {
        arrowTexture = new Texture("medievalarrow.png");
        this.setSize(arrowWidth, arrowHeight);
        this.setTouchable(Touchable.enabled);
        this.setBounds(app.screenWidth*0.45f,0,arrowWidth,arrowHeight);
        this.setOrigin(0,0);

}
@Override
    public void draw(Batch batch, float parentAlpha) {
        batch.draw(arrowTexture, getX(),getY(),getWidth(),getHeight());
    }
}

```

# Answer
> 0 votes
I have not used stage actions that much, but I think that with

```
arrow.addAction((moveTo(Gdx.input.getX(),Gdx.input.getY(),0.3f)));

```

you are telling the arrow to move to its destination in 0.3 seconds.

Try changing the 0.3f to something bigger and see what happens.

---
Tags: libgdx, scene2d, android-studio
---


# Question
Title: Can you please help me transform this script to adequate to mobile touch in unity?
My code here works with a keyboard:

```
if (Input.GetKeyDown (KeyCode.UpArrow)) {
  if (transform.position.y < 1.662f) {
    transform.Translate (0, 0.26F, 0);
  }
}

if (Input.GetKeyDown (KeyCode.DownArrow)) {
  if (transform.position.y > 1.142f) {
    transform.Translate (0, -0.26F, 0);
  }
}

if (Input.GetKeyDown (KeyCode.RightArrow)) {
  if (transform.position.x < 3.681f) {
    transform.Translate (0.46f, 0, 0);
  }
}

if (Input.GetKeyDown (KeyCode.LeftArrow)) {
  if (transform.position.x > 3.221f) {
    transform.Translate (-0.46f, 0, 0);
  }
}

```

How could I transform it so that it works as touch input?

# Answer
> -1 votes
Lets say you have a virtual joystick with 4 buttons arranged like 'wasd' keys with names 'up','down','left','right'. Now, do this:

```
if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
{
 Ray ray = Camera.ScreenPointToRay(Input.GetTouch(0).position);
 RayCastHit hit;
 if(Physics.Raycast(ray, out hit)
 {
  if (hit.gameObject.name == "up" && transform.position.y < 1.662f)
  {
   transform.Translate (0, 0.26F, 0);
  }
  else if (hit.gameObject.name == "down" && transform.position.y > 1.142f)
  {
   transform.Translate (0, -0.26F, 0);
  }
  else if (hit.gameObject.name == "left" && transform.position.x > 3.221f)
  {
    transform.Translate (-0.46f, 0, 0);
  }
  else if (hit.gameObject.name == "right" && transform.position.x < 3.681f)
  {
    transform.Translate (0.46f, 0, 0);
  }
}}

```

Hope this helps :)

---
Tags: unity, input, touch
---


# Question
Title: How to draw Tiled map with MonoGame.Extended v0.6.266 beta?
I just recently installed MonoGame.Extended v0.6.266 beta because I needed some functionality that wasn't in v0.5 official. However, I noticed that the `draw()` method for `TiledMap.cs` has been removed. This is also the case for `TiledLayer.cs`. So my question is how do I draw the map and its layers? And I know that this is not an issue with the the way I installed the beta, because I scanned through the source files on the GitHub repo and saw that `draw()` was indeed removed.

# Answer
> 3 votes
I'm the creator of MonoGame.Extended ;)

Quite a lot has changed since the 0.5 release. We've been working heavily on the Tiled renderer to solve some memory and performance issues and make it possible to customize the rendering process so that it's more useful in actual games.

Some of this work is still in progress, so be aware that the following code is likely to change again in the near future. We do try to keep the demo updated with the latest changes.

As it stands today, the current way to render Tiled maps is to use the `FullMapRenderer`. The idea is to separate the rendering from the map itself, so that maps can be swapped in and out, and the renderer can be customized.

First you create a renderer in the `Initialize` method.

```
_mapRenderer = new FullMapRenderer(GraphicsDevice);

```

Then you can load and assign the map to the renderer in `LoadContent`.

```
_tiledMap = Content.Load<TiledMap>("my-map");
_mapRenderer.SwapMap(_tiledMap);

```

Finally, you can update the renderer (for tile animations) in the `Update` method.

```
_mapRenderer.Update(gameTime);

```

And of course, draw the map in the `Draw` method.

```
_mapRenderer.Draw(_camera.GetViewMatrix());

```

I hope that helps. As I said, things will change but hopefully you can appreciate the improvements we're trying to make.

---
Tags: monogame, monogame-extended
---


# Question
Title: Unity: Can we not change Animator State inside Update?
```
void Update () {

        if (goright == true) {
            rig.velocity = new Vector2 (m.movespeed, rig.velocity.y);
            m.anim.SetInteger ("State", 1);
        }

        if (goleft == true) {
            rig.velocity = new Vector2 (-m.movespeed, rig.velocity.y);
            m.anim.SetInteger ("State", 1);
        }
    }

    public void ondownMoveLeft(){

        goleft = true;
    }

    public void ondownMoveRight(){

        goright = true;
    }

    public void onupMoveLeft(){

        m.anim.SetInteger ("State", 0);
        goleft = false;
    }

    public void onupMoveRight(){

        m.anim.SetInteger ("State", 0);
        goright = false;
    }

```

i am using this code to move my character using UI buttons with the help of Event Triggers. i set it to change the animation from idle to running or from State 0 to 1 when the player moves and it does works that way but the problem is once it goes into State 1 it never comes back to State 0 but it should since i am setting the State back to 0 when the `OnPointerUp` trigger gets activated. am i missing something?

`OnPointerDown` is calling its respective ondown method and `OnPointerUp` is calling its respective onup method. for eg, when you press the left button it calls `OnPointerDown` which is set to call the method ondownMoveLeft.

i also checked with `Debug.Log` and everything is being executed but still the animation State is not changing.

# Answer
Since you use Mecanim you need to have two transitions, one from state 0 to state 1 and another from state 1 to state 0.
> 1 votes

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


# Question
Title: How can I place prefabs into a world and what's the best way to get them?
Hi all :) I'm making a 2D roguelike platformer and I want to make a load of hand crafted rooms and like spelunky place them around. When the player enters a room a script will go off. The script will know what exits the current room has and what entrance was used (Don't need to place anything where the player came from). I then have 2 options for choosing what rooms will work:

I can either have all the prefabs contain a script with a list of all the exits they have, then check that list for if the right one is there. I.E; Entered room from the left. Room has left, right and top exits. I can ignore the left as that's where I came from, I can ignore the bottom as there isn't an exit there but I need to check the arrays on the prefabs to see if they have right and top in them. After that I'd place the top one x units above and the bottom one x units below (I'd also check something wasn't there before placing over it).

The other option is to have 4 lists of prefabs. A list for top exits, bottom exits, left exits and right exits. Then look through those for what I need. Then I would place the blocks where they needed to be from there.

So, as the title says, what of those options would you use for picking and how can I then get the prefab I need and place it into the world. I'll use a "Centre" item for it and then place the centre of the prefab a certain amount to the side of the current rooms centre.

Thanks in advance for any help you can give :)

# Answer
> 1 votes
Having four lists of rooms and searching in the right list will be slightly faster than having one list and determining which rooms are eligible again and again.

But the four lists will have duplicates among each other, so they will take up slightly more memory (By the way: I hope you don't want to place actual copies of the rooms in these lists. References would do).

But both of these will be really, really minor points, unless your number or rooms is somewhere in the thousands. You are very likely optimizing prematurely here. Just do what's easier and fits better into your overall architecture.

Personally I would go for the first solution, simply because I might want to plan ahead for adding more exclusion criteria than just having the right exists. For example not having any exits leading to somewhere where I already have something else, fitting more than one already placed room, avoiding repetitions, avoiding placing rooms which depend on content which is still locked, etc. etc.

---
Tags: unity, roguelikes
---


# Question
Title: Unity3D: Facebook login into the game + Verification on Server Side
I don't need to know the specific code required for that, but I want to understand at high level how can I implement that and what SDKs I have to use to achieve that.

* **Facebook PHP SDKs:** Ok If I want to perform login with Facebook into my web page.
* **Unity3D's Facebook SDK:** Ok If I want to perform login inside my App without a server (apart Facebook's servers of course).

**What I want to achieve is:**

* User login into facebook from the App (just once, and eventually the option to log out on request of user, or to relog if login data expires)
* Login is verified by my Server (actually a user should really have a facebook account)
* Do not embed stuff like Facebook App ID in my App source code.

My server will store some data for each user and to identify users I need to be able to use some unique data provided by Facebook like session token etc. Of course the session token may change so I need anyway to be able to identify the user (to avoid losing memorized data).

# Answer
> 5 votes
**Token and App side**

So to do this you will need to get the the relevant Access Token from facebook:

* User Access Token if you want to post things on their behalf and access information about them.
* App Access Token if you want to change app settings

You can read about it here but from what you have said you will probably want the User Access token.

After you get the access token you send it to your server using a unique ID for the user, this could be the device Serial Number or better the Google/Apple ID so that someone who sells their phone doesn't accidentally sell their account on your app as well.

When the app wants to do something with facebook it sends the request to your servers which then fulfil the request server side and possibly return something to the phone once they are done, the app could keep going doing more stuff and wait for a response in the background then inform the user.

Eventually the Token will expire, depending on exactly how you use the token your servers will have to check every account periodically, when they want to use it or when the user returns to the app. Once this happens you could try sending a push notification to the users phone or simply wait for them to return to the app where they will have to re authenticate with facebook in order to get a new token which is sent back to your server to replace the old one.

To summarise:

1. User first logs into facebook to generate the Token for your app.
2. Token is sent to your server along with identifying information
3. Token is used to fulfil app requests (or whatever you want to use it for)
4. Token expires and the user must re authenticate with Facebook and the new token is stored on the server.

**SDK and server side**

When you actually want to implement this you might not necessarily need the Unity SDK as that requires an appID to work. If you really want to use it you might have to find out where the AppID is stored and set it dynamically at startup before initializing the SDK. Otherwise you'll have make your own interface and pass all the login data through your server, if you do this **use SSL to encrypt it** when someone finds out that you're sending their login data without security you will not have a good week... Then once you have the data you do the query from your servers and give the app back the result (essentially a man in the middle between the app and facebook).

The servers would use the relevant SDK for whatever language they get coded in or just the web API since some languages (e.g. C#) have web handlers built in. You would need to build a REST API which can handle all the requests that you need the app to make. Keep security in mind here again because you don't want someone with a computer making random requests on the app's behalf, look into authentication techniques between your server and your app otherwise (again) you won't have a good week when (**not if**) somebody figures out your vulnerable.

---
Tags: unity, c#, php, facebook
---


# Question
Title: How to make members of an Array into an actor and add them to stage?
I have an animation (enemies) that I would like to add multiple times on the screen. From what I know, I can save memory and framerate-per-second by using one animating image and make an arraylist of it wherein each member is turned to an actor and added multiple times to the stage. I have searched similar problems like this but the answers were really not that helpful. Any help will be appreciated. Here's my code:

EnemyAnimation class:

```
    public class EnemyAnimation extends Actor{

    Ninja app;
    LevelOneScreen levelOneScreen;

    private Animation animation;
    private static final int  FRAME_COLS_WALK = 10;
    private static final int  FRAME_ROWS_WALK= 1;
    public TextureRegion   currentFrame;
    private float stateTime = 0f;

    public float Xpos;
    public float Ypos;
    public static final int fallSpeed = 250;
    public boolean remove = false;
    final float delta = Gdx.graphics.getDeltaTime();

    public animation(final Ninja app){
        this.app = app;
        Texture ninSprite = new Texture(Gdx.files.internal("ninSprite.jpg"), true);
        ninSprite.setFilter(Texture.TextureFilter.MipMapLinearNearest,Texture.TextureFilter.MipMapLinearNearest);

        TextureRegion[][] tmp = TextureRegion.split(ninSprite, (int) ninSprite.getWidth() / FRAME_COLS_WALK, (int) ninSprite.getHeight() / FRAME_ROWS_WALK);
        TextureRegion[] ninTexRegion = new TextureRegion[FRAME_COLS_WALK * FRAME_ROWS_WALK];
        int index = 0 ;
        for (int i = 0; i < FRAME_ROWS_WALK; i++) {
            for (int j = 0; j < FRAME_COLS_WALK; j++) {
                ninTexRegion[index++] = tmp[i][j];
            }
        }

        animation = new Animation(0.044f,ninTexRegion);
        currentFrame = animation.getKeyFrame(stateTime, true);

    }

    public void draw(Batch batch, float parentAlpha) {

        super.draw(batch, parentAlpha);

        final float delta = Gdx.graphics.getDeltaTime();

        stateTime += delta;

        TextureRegion currentFrame = animation.getKeyFrame(stateTime, true);

        batch.draw(currentFrame,Xpos,Ypos,getWidth(),getHeight());

    }
}

```

LevelOneScreen class:

```
public class LevelOneScreen implements Screen {

    public Ninja app;
    private Stage stage;
    private Stage stageNinja;
    public EnemyAnimation enemyAnimation;
    private Image ninImage;
    private Image levelOneImage;
    private float deltaTime = Gdx.graphics.getDeltaTime();

    public ArrayList<EnemyAnimation> enemyAnimate;

    public LevelOneScreen(final Ninja app){
        this.app = app;
        this.stage = new Stage(new StretchViewport(app.screenWidth, app.screenHeight, app.camera));
        this.stageNinja = new Stage(new StretchViewport(app.screenWidth, app.screenHeight, app.camera));
        enemyAnimate = new ArrayList<EnemyAnimation>();
        enemyAnimation = new EnemyAnimation(app);
    }

    @Override
    public void show() {

        InputMultiplexer inputMultiplexer = new InputMultiplexer();
        inputMultiplexer.addProcessor(stage);
        inputMultiplexer.addProcessor(stageNinja);
        Gdx.input.setInputProcessor(inputMultiplexer);

        levelOneBackground();
        enemy();
    }

    public void enemy(){

        stageNinja.addActor(enemyAnimate);

       /*

         From here I cannot add the Arraylist enemyAnimate to the
         stage and I received some errors. I would like to add elements to
         enemyAnimate and make each added elements into actors with
         different positions to be added to the stage.

        */

    }

    @Override
    public void render(float delta) {

        Gdx.gl.glClearColor(0, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        update(delta);

    }

    public void update(float deltaTime){

        stage.draw();
        stageNinja.draw();

        stage.act(deltaTime);
        stageNinja.act(deltaTime);

    }

```

Update to my code:

I now use Array of libgdx but it still won't show the enemies on stage without an indexOutOfBounds error. Here's the code:

```
public class LevelOneScreen implements Screen {

    public Ninja app;
    private Stage stage;
    private Stage stageNinja;
    public EnemyAnimation enemyAnimation;
    private Image ninImage;
    private Image levelOneImage;
    private float deltaTime = Gdx.graphics.getDeltaTime();

    public Array<EnemyAnimation> enemyAnimate;

    public LevelOneScreen(final Ninja app){
        this.app = app;
        this.stage = new Stage(new StretchViewport(app.screenWidth, app.screenHeight, app.camera));
        this.stageNinja = new Stage(new StretchViewport(app.screenWidth, app.screenHeight, app.camera));
        enemyAnimate = new Array<EnemyAnimation>();
        enemyAnimate.add(new EnemyAnimation(app));
        enemyAnimation = new EnemyAnimation(app);
    }

    @Override
    public void show() {

        InputMultiplexer inputMultiplexer = new InputMultiplexer();
        inputMultiplexer.addProcessor(stage);
        inputMultiplexer.addProcessor(stageNinja);
        Gdx.input.setInputProcessor(inputMultiplexer);

        levelOneBackground();
        enemyAct1();
        //  ......
        enemyAct4();
    }

        public void enemyAct1(){

      for(int i = 0; i < 6; i++){enemyAnimate.add(new EnemyAnimation(app));}

    enemyAnimate.get(1).setPosition(app.screenWidth*0.1f,app.screenHeight);
    stageEnemy.addActor(enemyAnimate.get(1));
    float enemyTimeDrop1 = (app.screenHeight/app.screenHeight)*4.85f ;
    enemyAnimate.get(1).addAction(moveTo(app.screenWidth*0.1f,enemyDestination,enemyTimeDrop1));

    enemyAnimate.get(2).setPosition(app.screenWidth*0.1f+enemyAnimation.enemyWidth,app.screenHeight+enemyAnimation.enemyHeight);
       stageEnemy.addActor(enemyAnimate.get(2));
    float enemyHeight2 = app.screenHeight+enemyAnimation.enemyHeight;
    float enemyTimeDrop2 = (enemyHeight2/app.screenHeight)*4.85f ;
    enemyAnimate.get(2).addAction(moveTo(app.screenWidth*0.1f+enemyAnimation.enemyWidth,enemyDestination,enemyTimeDrop2));

    enemyAnimate.get(3).setPosition(app.screenWidth*0.1f+enemyAnimation.enemyWidth*2f,app.screenHeight+enemyAnimation.enemyHeight*2f);
        stageEnemy.addActor(enemyAnimate.get(3));
    float enemyHeight3 = app.screenHeight+enemyAnimation.enemyHeight*2f;
    float enemyTimeDrop3 = (enemyHeight3/app.screenHeight)*4.85f ;
    enemyAnimate.get(3).addAction(moveTo(app.screenWidth*0.1f+enemyAnimation.enemyWidth*2f,enemyDestination,enemyTimeDrop3));

    enemyAnimate.get(4).setPosition(app.screenWidth*0.1f+enemyAnimation.enemyWidth*3f,app.screenHeight+enemyAnimation.enemyHeight*3f);
        stageEnemy.addActor(enemyAnimate.get(4));
    float enemyHeight4 = app.screenHeight+enemyAnimation.enemyHeight*3f;
    float enemyTimeDrop4 = (enemyHeight4/app.screenHeight)*4.85f ;
    enemyAnimate.get(4).addAction(moveTo(app.screenWidth*0.1f+enemyAnimation.enemyWidth*3f,enemyDestination,enemyTimeDrop4));

    enemyAnimate.get(5).setPosition(app.screenWidth*0.1f+enemyAnimation.enemyWidth*4f,app.screenHeight+enemyAnimation.enemyHeight*4f);
        stageEnemy.addActor(enemyAnimate.get(5));
    float enemyHeight5 = app.screenHeight+(enemyAnimation.enemyHeight*4f);
    float enemyTimeDrop5 = (enemyHeight5/app.screenHeight)*4.85f ;
    enemyAnimate.get(5).addAction(moveTo(app.screenWidth*0.1f+enemyAnimation.enemyWidth*4f,enemyDestination,enemyTimeDrop5));

}

```

enemyAct1() is drawn but enemyAct4() is not and returns an indexOutOfBoundsError : index can't be \>= size: 21 \>= 17. Here's enemyAct4():

```
public void enemyAct4(){
    for(int i = 20; i < 30; i++){
        enemyAnimate.add(new EnemyAnimation(app));
    }

    enemyAnimate.get(21).setPosition(app.screenWidth/2-enemyAnimation.enemyWidth/2,app.screenHeight);
        stageEnemy.addActor(enemyAnimate.get(21));
    float enemyTimeDrop1 = 4.85f ;
    enemyAnimate.get(21).addAction(moveTo(app.screenWidth/2-enemyAnimation.enemyWidth/2,enemyDestination,enemyTimeDrop1));

    enemyAnimate.get(22).setPosition((app.screenWidth/2-enemyAnimation.enemyWidth/2)+enemyAnimation.enemyWidth,(app.screenHeight+enemyAnimation.enemyHeight));
    stageEnemy.addActor(enemyAnimate.get(22));
    float enemyHeight22 = (app.screenHeight+enemyAnimation.enemyHeight);
    float enemyTimeDrop22 = (enemyHeight22/app.screenHeight)*4.85f ;
    enemyAnimate.get(22).addAction(moveTo((app.screenWidth/2-enemyAnimation.enemyWidth/2)+enemyAnimation.enemyWidth,enemyDestination,enemyTimeDrop22));

    enemyAnimate.get(23).setPosition((app.screenWidth/2-enemyAnimation.enemyWidth/2)-enemyAnimation.enemyWidth,app.screenHeight+(enemyAnimation.enemyHeight));
    stageEnemy.addActor(enemyAnimate.get(23));
    float enemyHeight23 = app.screenHeight+(enemyAnimation.enemyHeight);
    float enemyTimeDrop23 = (enemyHeight23 /app.screenHeight)*4.85f ;
    enemyAnimate.get(23).addAction(moveTo((app.screenWidth/2-enemyAnimation.enemyWidth/2)-enemyAnimation.enemyWidth,enemyDestination,enemyTimeDrop23));

    enemyAnimate.get(24).setPosition((app.screenWidth/2-enemyAnimation.enemyWidth/2)+(enemyAnimation.enemyWidth*2f),app.screenHeight+(enemyAnimation.enemyHeight*2f));
       stageEnemy.addActor(enemyAnimate.get(24));
    float enemyHeight24 = app.screenHeight+(enemyAnimation.enemyHeight*2f);
    float enemyTimeDrop24 = (enemyHeight24/app.screenHeight)*4.85f ;
    enemyAnimate.get(24).addAction(moveTo((app.screenWidth/2-enemyAnimation.enemyWidth/2)+(enemyAnimation.enemyWidth*2f),enemyDestination,enemyTimeDrop24));

    enemyAnimate.get(25).setPosition((app.screenWidth/2-enemyAnimation.enemyWidth/2)-(enemyAnimation.enemyWidth*2f),app.screenHeight+(enemyAnimation.enemyHeight*2f));
        stageEnemy.addActor(enemyAnimate.get(25));
    float enemyHeight25 = app.screenHeight+(enemyAnimation.enemyHeight*2f);
    float enemyTimeDrop25 = (enemyHeight25/app.screenHeight)*4.85f ;
    enemyAnimate.get(25).addAction(moveTo((app.screenWidth/2-enemyAnimation.enemyWidth/2)-(enemyAnimation.enemyWidth*2f),enemyDestination,enemyTimeDrop25));

}

    @Override
    public void render(float delta) {

        Gdx.gl.glClearColor(0, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        update(delta);

    }

    public void update(float deltaTime){

        stage.draw();
        stageNinja.draw();

        stage.act(deltaTime);
        stageNinja.act(deltaTime);

    }

```

# Answer
You load a new `Texture` in each `EnemyAnimation` which loads alot of memory.

For example if it's a **500x500** image, it has **250,000 pixels**. One pixel has **3 bytes** so it's **750000 bytes** -\> **0.71 MB**. One enemy takes **1MB of `RAM`**. Remember that I've mentioned 500x500 image, your is probably bigger.

It's unacceptable, you should reuse the image on all enemies.

Use `AssetLoader`/`AssetManager` as written here: https://github.com/libgdx/libgdx/wiki/Managing-your-assets

You should load your `ninSprite.jpg` with `AssetManager` and then in your `NinjaAnimate` class call

```
Texture tex = manager.get("data/mytexture.png", Texture.class);

```

Remember to use only one instance of your AssetManager and load them only once.
> 1 votes

# Answer
An `EnemyAnimation` is an actor in itself, you do not need to *create an actor from the list of EnemyAnimation* as the title of your post suggests.

`EnemyAnimate` is NOT an actor, it is a `List` of actors, so the line

```
stageNinja.addActor(enemyAnimate);

```

should be replaced by

```
stageNinja.addActor(enemyAnimate.get(i)); // where i is an iterator you need to set to get the actor you want to get.

```

In the `LevelOneScreen` constructor you initialize an `EnemyAnimation` object but you never add it to the List.

You can change the line

```
enemyAnimation = new EnemyAnimation(app);

```

to

```
enemyAnimate.add(new EnemyAnimation(app));

```

and you can get rid of the enemyAnimation variable as it will not be used anymore.
> 1 votes

---
Tags: libgdx, animation, scene2d, android-studio
---


# Question
Title: OpenGL: Better Approach to Repeating Sprites (e.g. terrain)?
**Preface**: Linux (Ubuntu 16.04 Gnome), C++11, SDL2, GLEW 2.0, OpenGL 4.5

Hello ladies/gents,

My conundrum is this: *How do I handle draw a repeated texture (sprite) as a single object, at various dimensions and rotations, without manually draw each tile?*

I posted a similar question earlier about rotating a row of textures, to which the user Lasse provided insight on utilizing matrices. After two days of reading up on (and playing with) glm::translate and glm::rotate, I have not been able to rotate a row of sprites in place (as they always scale off of the 0,0 origin in center of screen, regardless of translations, producing increasingly less desirable motions). Additionally, rotating one seems to be rotating all sprites, but I am suspect that this is related to how I am drawing the sprites in batches. My understanding of uniforms is still, admittedly, embarrassing. I can provide snippets of the process involving the uniforms and the actual drawing, if it would help.

Is it possible to utilize uniforms and glm::translate/glm::rotate to rotate specific objects (such as level terrain pieces on a platformer)? I have found multiple examples through tutorials online, but almost all utilize a single object, with normalized device coordinates, and never with any type of moving/scaling projection matrix (read: camera).

I had a thought about potentially "drawing" the object and creating a 2D texture from the "drawn" object, so it could simply be titled as a single object with some shenanigans against the vertices. This is another, potential approach but I am unsure how useful (or treacherous) it is to implement.

If it's not abundantly clear by this point, my OpenGL understanding is woefully unequal to what I am attempting, but learning occurs best for me when I'm buried, lost, and overwhelmed in a new topic. I greatly appreciate any and all incoming feedback, advice, and information! :)

---

**EDIT**: Thanks to MalphasWats for pointing out something, I'm using glm::translate and glm::rotate, not glTranslate and glRotate. From reading so many dated tutorials, I had a mental 'slip', so to speak.

From MalphasWats' other comment regarding uniforms applying to the entire buffer waiting to be drawn, that does help explain some "oddities". It gives me some ideas on how to approach it as simply changing the rotation for each terrain object (across dozens of terrain objects) is simply not feasible as it would result in many extra draw calls for one or a few objects at at time.

The current 'workflow' (at least the relevant bits) for my level editor looks something like this:

* Camera is created and initialized on screen creation (at 1440x900 with 32x scale for no particular reason)
* update() function is called (GUI updates to position, size, etc; FPS calculation; updates to objects movement)
* draw() function is called. Here is where my repeating texture drawing (and issue) occurs. During the draw function, one of three sprite drawing actions happens (normal sprite, rotated single-sprite, repeating-sprite).
* draw() function is wrapped up, with all spritebatches drawn.

Camera step:

```
void Camera2D::init(int scrWidth, int scrHeight)
{
    m_screenWidth = scrWidth;
    m_screenHeight = scrHeight;
    m_orthoMatrix = glm::ortho(0.0f, static_cast<float>(m_screenWidth), 0.0f, static_cast<float>(m_screenHeight)); // building orthographic matrix
}

void Camera2D::update()
{
    if(m_hasChanged)
    {
        // camera translation
        glm::vec3 translate(-m_position.x + m_screenWidth/2, -m_position.y + m_screenHeight/2, 0.0f);
        m_cameraMatrix = glm::translate(m_orthoMatrix, translate);
        m_unscaledCameraMatrix = m_cameraMatrix;
        // camera scale
        glm::vec3 scale(m_scale, m_scale, 0.0f);
        m_cameraMatrix = glm::scale(glm::mat4(1.0f), scale) * m_cameraMatrix;
        m_hasChanged = false;
    }
}

```

Omitting update() function as it's not relevant.

draw() function:

```
void LevelEditScreen::draw()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glClearColor(0.45f, 0.5f, 0.55f, 1.0f);

    m_textureProgram.use();

    GLint textureUniform = m_textureProgram.getUniformLocation("mySampler");
    glUniform1i(textureUniform, 0);
    glActiveTexture(GL_TEXTURE0);

    // camera matrix
    glm::mat4 projectMatrix = m_camera.getCameraMatrix(); // mat4 ortho matrix (0, 1440, 0, 900), scaled by 32
    GLint pUniform = m_textureProgram.getUniformLocation("translation");
    glUniformMatrix4fv(pUniform, 1, GL_FALSE, &projectMatrix[0][0]);

    // handle sprites
    m_spriteBatch->begin();
    m_spriteBatch->draw(glm::vec4(0.0f, 0.0f, 1.0f, 1.0f), m_cursor.uvRect, m_cursor.textureID, 0.0f, GameEngine101::COLOR_RED); // debug box, 1 "tile", red, at center
    glm::vec4 sizeBounds = glm::vec4(0.0f);
    if(!rbNoRepeat->isTicked())
    {
        // this step repeats the texture, by drawing numerous sprites together, in an instant burst
        // NOTE: The associated drawing function is somewhat WIP, so it's messy, inefficient, and barely functional
        sizeBounds = glm::vec4( m_cursor.destRect.x, m_cursor.destRect.y, m_cursor.repeatSize[0], m_cursor.repeatSize[1] );
        m_spriteBatch->drawRepeat(m_cursor.destRect, m_cursor.uvRect, sizeBounds, m_cursor.textureID, 0.0f, m_cursor.color, m_cursor.rotation, projectMatrix, m_camera.getScale());
    }
    else
    {
        // draw a normal sprite that can be batch drawn
        sizeBounds = glm::vec4( m_cursor.destRect.x, m_cursor.destRect.y, m_cursor.destRect.z, m_cursor.destRect.w );
        m_spriteBatch->draw(m_cursor.destRect, m_cursor.uvRect, m_cursor.textureID, 0.0f, m_cursor.color, m_cursor.rotation);
    }

    // tidy up sprite batches, generate batches
    m_spriteBatch->end();

    // actually draw batches
    m_spriteBatch->renderBatch();

    m_textureProgram.unuse();

    // debug rendering
    m_debugRenderer->drawBox(sizeBounds, m_cursor.color, m_cursor.rotation);
    m_debugRenderer->end();
    m_debugRenderer->render(projectMatrix, 2.0f);

    m_gui->draw();
}

```

Finally, the basic Glyph constructor and the drawRepeat() function:

```
Glyph::Glyph(const glm::vec4& destRect, const glm::vec4& uvRect, GLuint Texture, float Depth, const ColorRGBA8& color) : texture(Texture), depth(Depth)
{
    // top left
    topLeft.setPosition(destRect.x, destRect.y + destRect.w);
    topLeft.setUV(uvRect.x, uvRect.y + uvRect.w);
    topLeft.color = color;
    // bottom left
    bottomLeft.setPosition(destRect.x, destRect.y);
    bottomLeft.setUV(uvRect.x, uvRect.y);
    bottomLeft.color = color;
    // top right
    topRight.setPosition(destRect.x + destRect.z, destRect.y + destRect.w);
    topRight.setUV(uvRect.x + uvRect.z, uvRect.y + uvRect.w);
    topRight.color = color;
    // bottom right
    bottomRight.setPosition(destRect.x + destRect.z, destRect.y);
    bottomRight.setUV(uvRect.x + uvRect.z, uvRect.y);
    bottomRight.color = color;
}

void SpriteBatch::drawRepeat(const glm::vec4& glyphSize, const glm::vec4& uvRect, const glm::vec4& sizeBounds, GLuint texture, float depth, const ColorRGBA8& color, float angle, glm::mat4& translation, float scale) // angle in radians
{
    // fail without info provided
    //if(!m_screenHeight || !m_screenWidth || !m_scale) { GameEngine101::fatalError("No screen width/height or scale specified for drawRepeat!"); }

    int x_iterations = static_cast<int>(sizeBounds.z / glyphSize.z);
    int y_iterations = static_cast<int>(sizeBounds.w / glyphSize.w);

    std::vector<Glyph> glyphs;
    glyphs.resize(x_iterations * y_iterations);
    std::vector<Vertex> vertices;
    std::vector<RenderBatch> renderBatches;
    int cv = 0; // current vertex
    int glyphOffset = 0;

    // tmp variable
    glm::vec4 tmpDestRect = glyphSize;

    // rotate by angle, converted from radians to degrees, on the z-axis
    //glm::mat4 groupRotation = translation;
    //glm::mat4 groupRotation = glm::mat4(1.0f);
    glm::mat4 groupRotation;
    groupRotation = glm::translate(groupRotation, glm::vec3(sizeBounds.x, sizeBounds.y, 0.0f));
    //groupRotation = glm::translate(groupRotation, glm::vec3(0.5f * sizeBounds.z, 0.5f * sizeBounds.w, 0.0f));
    groupRotation = glm::rotate(groupRotation, angle, glm::vec3(0.0f, 0.0f, 1.0f));
    //groupRotation = glm::translate(groupRotation, glm::vec3(-0.5f * sizeBounds.z, -0.5f * sizeBounds.w, 0.0f));
    //groupRotation = glm::scale(groupRotation, glm::vec3(scale, scale, 0.0f));
    groupRotation = glm::translate(groupRotation, glm::vec3(-sizeBounds.x, -sizeBounds.y, 0.0f));
    GLint pUniformM = m_glsl->getUniformLocation("rotation");
    glUniformMatrix4fv(pUniformM, 1, GL_FALSE, &groupRotation[0][0]);

    // create glyphs
    for(uint ix = 0; ix < x_iterations; ix++)
    {
        tmpDestRect.x = glyphSize.x + ( glyphSize.z * ix ); // set X position

        for(uint iy = 0; iy < y_iterations; iy++)
        {
            tmpDestRect.y = glyphSize.y + ( glyphSize.w * iy ); // set Y position
            glyphs.emplace_back(tmpDestRect, uvRect, texture, depth, color);
        }
    }

    // resize verticies vector
    vertices.resize(glyphs.size() * 6);

    // emplace_back uses the constructor for whatever is being stored
    //      in this case, it's RenderBatch
    renderBatches.emplace_back(glyphOffset, 6, texture);

    vertices[cv++] = glyphs[0].topLeft; // execute, THEN add 1 to cv
    vertices[cv++] = glyphs[0].bottomLeft; // execute, THEN add 1 to cv
    vertices[cv++] = glyphs[0].bottomRight; // execute, THEN add 1 to cv
    vertices[cv++] = glyphs[0].bottomRight; // execute, THEN add 1 to cv
    vertices[cv++] = glyphs[0].topRight; // execute, THEN add 1 to cv
    vertices[cv++] = glyphs[0].topLeft; // execute, THEN add 1 to cv
    glyphOffset += 6;

    for(uint cg = 1; cg < glyphs.size(); cg++)
    {
        if(glyphs[cg].texture != glyphs[cg - 1].texture) { renderBatches.emplace_back(glyphOffset, 6, glyphs[cg].texture); }
        else { renderBatches.back().numVertices += 6; }

        vertices[cv++] = glyphs[cg].topLeft; // execute, THEN add 1 to cv
        vertices[cv++] = glyphs[cg].bottomLeft; // execute, THEN add 1 to cv
        vertices[cv++] = glyphs[cg].bottomRight; // execute, THEN add 1 to cv
        vertices[cv++] = glyphs[cg].bottomRight; // execute, THEN add 1 to cv
        vertices[cv++] = glyphs[cg].topRight; // execute, THEN add 1 to cv
        vertices[cv++] = glyphs[cg].topLeft; // execute, THEN add 1 to cv
        glyphOffset += 6;
    }

    glBindBuffer(GL_ARRAY_BUFFER, m_vbo);
    glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(Vertex), nullptr, GL_DYNAMIC_DRAW); // orphan the buffer
    glBufferSubData(GL_ARRAY_BUFFER, 0, vertices.size() * sizeof(Vertex), vertices.data());

    // unbind buffer on completion
    glBindBuffer(GL_ARRAY_BUFFER, 0);

    // actually render
    glBindVertexArray(m_vao);
    for(uint i = 0; i < renderBatches.size(); i++)
    {
        glBindTexture(GL_TEXTURE_2D, renderBatches[i].texture);
        glDrawArrays(GL_TRIANGLES, renderBatches[i].offset, renderBatches[i].numVertices);
    }
    glBindVertexArray(0);
}

```

I understand debugging code based on snippets is hilariously difficult, but I am under the impression that I'm doing something obviously wrong. Hopefully this helps clear some of it up. If there is anything else that I can provide, please let me know!

Oh and shaders:

```
const char* GLVERT_SRC = R"(
#version 130
// vert shader

// input data from the VBO. Each vertex is 2 floats
in vec2 vertexPosition;
in vec4 vertexColor;
in vec2 vertexUV;

out vec2 fragmentPosition;
out vec4 fragmentColor;
out vec2 fragmentUV;

// projection matrix
uniform mat4 translation;
// model matrix (rotation)
uniform mat4 rotation;
// scale matrix
//uniform mat4 scaling;

void main()
{
    // Set the x,y position on the screen
    //gl_Position = translation * rotation * scaling * vec4(vertexPosition.xy, 0.0, 1.0);
    // gl_Position.xy = (projection * vec4(vertexPosition, 0.0, 1.0)).xy;
    gl_Position = translation * rotation * vec4(vertexPosition.xy, 0.0, 1.0);

    // the z position is zero since we are in 2D
    gl_Position.z = 0.0;

    //Indicate that the coordinates are normalized
    gl_Position.w = 1.0;

    fragmentPosition = vertexPosition;

    fragmentColor = vertexColor;

    fragmentUV = vec2(vertexUV.x, 1.0 - vertexUV.y);
})";

const char* GLFRAG_SRC = R"(
#version 130
// frag shader

in vec2 fragmentPosition;
in vec4 fragmentColor;
in vec2 fragmentUV;

// This is the 3 component float vector that gets outputted to the screen
// for each pixel.
out vec4 color;

uniform sampler2D mySampler;

void main()
{
    // cos(x) returns a number between -1 and 1. To convert it into the range 0 to 1
    // you simply do (cos(x) + 1.0) * 0.5
    vec4 textureColor = texture(mySampler, fragmentUV);

    // Make crazy colors using time and position
    color = fragmentColor * textureColor;
})";

```

# Answer
I'm about 2 questions ahead of you in my own OpenGL journey, but I'm starting to get a handle on things now. My project started in Python and then I ported to Javascript, and I'm not using SDL so it's a little different to you but the GL principles should be the same.

firstly, using matrices makes things simpler in the longer term, so if you can get your head around them, keep at it. Try this tutorial that came in handy for me. In a nutshell though, any matrix transforms you apply will apply to *everything* currently in a buffer being drawn, so your rotations will apply to everything currently being drawn, which is probably not what you want.

Depending on how many things are being rotated and how often, you will likely want to rework your pipeline a little so that the things being rotated are drawn individually, but this gets 'expensive' the more things you draw this way.

Your origin issue can be solved elegantly with a matrix. You mention `glTranslate()` and `glRotate()` which suggests you're using the older style 'fixed pipeline' openGL stuff, and I'm less familiar with that.

I'm building a 2D gl framework, and I use the following matrix to convert 'pixel coordinates' that I pass as vertices (30, 30), (120, 192) etc, into gl coordinates between (-1.0 and 1.0). It also flips the y-axis so top is -1 and *then* it translates it all up and left so top-left becomes (0,0):

```
projection_matrix = [
        2 / viewport_width, 0, 0, 0,
        0, -2 / viewport_height, 0, 0,
        0, 0, 2 / viewport_height, 0,
        -1, 1, 0, 1,
    ];

```

That's all very complicated, so let's break it down into a few steps:

```
identity_matrix = [
    1, 0, 0, 0,
    0, 1, 0, 0,
    0, 0, 1, 0,
    0, 0, 0, 1,
]

```

This is a special matrix that basically does *nothing*, whatever you pass in comes out the same the other end.

We can then *translate* things along the `x, y, z` axes with the bottom row:

```
translation_matrix = [
    1, 0, 0, 0,
    0, 1, 0, 0,
    0, 0, 1, 0,
    -1, -1, 0, 1,
]

```

This would translate everything *up and left*, so you would effectively be working with gl coordinates (0.0 - 2.0), so (0,0) *should* be at the top-left (where I prefer it).

I will point out that I finally learnt all of this about 2 days ago tearing my hair out trying to work out how to make a pixel-ndc coordinate 'projection' matrix (say that 5 times fast!).

In my top matrix, where I do this conversion, we can think of it like this:

I have a screen that is 500 pixels wide and 2.0 gl-thingies (sorry, I have no idea what they are called).

```
2.0 / 500 = 0.004 gl-thingies.

```

meaning each of the 500 pixels I want to draw is `0.004` gl-thingies. So if I want to draw something at `x=50`, I can work out the gl-coordinates by multiplying that by `0.004`, so:

```
50 * 0.004 = 0.2

```

I can build that into the matrix, which moves all the maths onto the GPU, which is probably where you want it (but I'm not the boss of you so...):

```
projection_matrix = [
    0.004, 0, 0, 0,
    0, 1, 0, 0,
    0, 0, 1, 0,
    -1, -1, 0, 1,
]

```

then obviously you can do the same for the other axes, say the screen is 400pixels high:

```
2.0 / 400 = 0.005

projection_matrix = [
    0.004, 0,     0, 0,
    0,     0.005, 0, 0,
    0,     0,     1, 0,
    -1,   -1,     0, 1,
]

```

and so on for z (I'm glossing over because my work has been 2d based so I just make up useful depths for layering things and just make it the same as the height).

So you can also build in the rotation and any scaling you want to do, but it will apply to *everything* you multiply by this matrix.

What you would want to do is something like:

1. create a buffer for all the 'main stuff'
2. load that buffer up with the data
3. set the matrix
4. draw the buffer
5. create a buffer for things rotated x degrees
6. load this stuff in
7. set the new matrix including rotation
8. draw the buffer

For performance purposes, you should only do 1 and 5 *once per program*.

2 and 6 should *only* be done when something in those buffers has changed, similarly, 3 and 7 should only be done when something about the view has changed - in my project, I write an entire level worth of tiles into my tile buffer at the start, then use a *second* matrix to translate things around as the player moves (I don't know how to apply 2 'translation' type matrices using fixed function OpenGL, so I guess that would have to be done in your code?).

4 and 8 should be done *every* frame - stuff stays in the buffers until you change it, uniforms keep their values until you write new ones in. (this is something I learnt **way** too late!!!).

So your question:

> Is it possible to utilize uniforms and glTranslate/glRotate to rotate specific objects

no, I don't think it is, at least, not with fixed-function, you could potentially do something mindbendingly clever with your own custom shaders, however, that's waaaaay out of my expertise! I'm wondering if you could create *another* buffer for rotation matrices and pass a matrix in for each vertex, but I don't know if that's sensible/possible... certainly worth trying, probably a bit expensive though? People use this word "expensive" a lot - it's basically about how long it takes the CPU to shove stuff into the GPU/GraphicsRAM, can it do it faster than the magic 16.66milliseconds you need to achieve 60 frames per second!

I'd certainly like to know how to do something like you want to do without having to draw individual sprites 1-at-a-time!

I will likely do it by applying the rotation transformation to the vertex co-ordinates before I send them off to the buffers (my sprites move a lot so I write to the buffer every frame), but I'm definitely wondering about the matrix buffer thing now too...

Finally, some self promotion - you can see what I've achieved with all this voodoo on my WIP game framework page. Which may or may not be actually working properly at any given moment as I tinker with it!! It's almost certainly not the "best way" to do what I want, but I'm slowly starting to realise that the people who know the best way are earning the big bucks making AAA+ games, not writing online tutorials and answering stack overflow questions sadly :(
> 2 votes

---
Tags: opengl, sdl2, linux, c++, glew
---


# Question
Title: Limit rotation to certain angles for transform.rotate
I'm working on a small project to learn Blender and Unity, and one issue I recently came across is that while I can have the turret of my tank rotate on the z-axis based on mouse movements, I can't for the life of me figure out how to lock it to certain angles.

My current approach was to use Mathf.Clamp to limit the range of values that I could pass to the rotate function, but that doesn't seem to have done anything at all, even though when outputting the value Clamp produces, I can tell it doesn't go over my specification.

The code I have:

```
enum RotationAxes {MouseX, MouseY, MouseXandY};
var axes : RotationAxes;
private var MouseX = RotationAxes.MouseX;
var sensitivityX : float = 15F;
var minimumZ : float= -35;
var maximumZ : float = 35;
function Update ()
{

    if (axes == MouseX)
    {
        //yRotation += Input.GetAxis("Mouse X");
        //transform.eulerAngles = Vector3(0, 0, yRotation);
        transform.Rotate(0, 0, Mathf.Clamp (Input.GetAxis("Mouse X")*sensitivityX, -30, 30));

    }

}

function Start ()
{

}

```

# Answer
Here's one way to approach it.

```
// Inspector parameters to control how we rotate.
var axisName     : String  = "Mouse X";
var sensitivity  : float   = 15f;
var minAngle     : float   = -30f;
var maxAngle     : float   = 30f;
var rotationAxis : Vector3 = new Vector3(0, 0, 1);

// Remember the original orientation of the object so we can rotate relative to that.
private var _initialRotation : Quaternion;

// Track the desired rotation angle over time.
// Note that this only works well for one axis.
// If combining multiple axes of rotation we'll usually want to store a Quaternion instead.
private var _currentAngle : float = 0f;

function Start() {
    // Cache the orientation of the object once it's spawned.
    // This lets us rotate relative to its placed orientation in a scene.
    _initialRotation = transform.localRotation;
}

function Update() {
    // Calculate the desired rotation angle by adding this frame's delta:
    _currentAngle += Input.GetAxis(axisName) * sensitivity * Time.deltaTime;

    // Clamp the rotation angle within the allowed range.
    _currentAngle = Mathf.Clamp(_currentAngle, minAngle, maxAngle);

    // Create a rotation about the desired axis using the clamped angle.
    // You could use Quaternion.Euler; I chose this route to support diagonal axes too.
    var rotation : Quaternion = Quaternion.AngleAxis(_currentAngle, rotationAxis);

    // Apply the rotation to our object.
    // Using localRotation means we don't override rotation from the parent hierarchy.
    // Putting `rotation` last means we rotate around the object's local axes.
    transform.localRotation = _initialRotation * rotation;
}

```
> 2 votes

# Answer
You could have an if statement in update that is like this: if (EulerAngles.x \>= maximumx) { EulerAngles.x == maximumx; } then, vise versa for the minimum rotation, but have it at a less than.
> 0 votes

# Answer
You basically have it, but you need to set the rotation instead of adding to it. Try this.

```
transform.rotation = Quaternion.Euler(0, 0, Mathf.Clamp (transform.eulerAngles.z + Input.GetAxis("Mouse X")*sensitivityX, -30, 30));

```

Edit: Also, don't forget to multiply the input value by Time.deltaTime to make the rate of rotation framerate independent.
> 0 votes

---
Tags: javascript, rotate
---


# Question
Title: How can I accurately simulate orbits in Unity?
I would like to create a space simulation with realistic gravity.

This means planets in 3d space which act as central gravity sources and multiple objects which are attracted by those planets gravity so that they orbit them in physically correct orbits (like in Kerbal Space Program, for example).

How can I implement such gravity sources with C# script?

# Answer
> 3 votes
Here is a C# script for a `GravitySource` component.

It requires a `Collider` attached to the same game object with the "Is Trigger" checkbox set. This collider represents the zone of influence of the bodies gravity. Any `Rigidbody`s inside of that collider will be affected.

The public property `gravity` needs to be set in the inspector. It represents the strength of the gravity source. The ideal value depends on the time-scale and space-scale of your simulation.

```
using UnityEngine;
using System.Collections;

public class GravitySource : MonoBehaviour {

    public float gravity;

    void OnTriggerStay(Collider other) {
        Rigidbody otherRigidbody = other.gameObject.GetComponent<Rigidbody>()
        if (otherRigidbody) {
            Vector3 difference = this.gameObject.transform.position - other.gameObject.transform.position;

            float dist = difference.magnitude;
            Vector3 gravityDirection = difference.normalized;
            Vector3 gravityVector = (gravityDirection * gravity) / (dist * dist) ;

            otherRigidbody.AddForce(gravityVector, ForceMode.Acceleration);

        }
    }
}

```

# Answer
> 3 votes
You can learn about the gravity formula, `Fg = G((Mass1 * Mass2)/distance^2)`, the distance is

```
d = sqrt( (x1 -x2)^2 + (y1 -y2)^2 + (z1 -z2)^2 )

```

now you can calculate the distance and use it in the Gravity formula.

after that you need to calculate the acceleration for each axi,

```
float aX = (x / hip) * tmp; // tmp is the gravity force and x is the object
                            // to go less the origin object
float aY = (y / hip) * tmp; //the same
float aZ = (z / hip) * tmp; //the same

```

so now add this to a variable x, y and z that represent the speed and upload all of this every frame * Time.deltaTime

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


# Question
Title: Turning the camera when the player turns
I have a 3rd person view of the player character, and I wish my camera to follow the player both when he moves and when he rotates.

So far I have the movement correct:

```
    public class CameraController : MonoBehaviour {

    public GameObject player;
    private Vector3 offset;
    // Use this for initialization
    void Start()
    {
        offset = transform.position - player.transform.position;
    }

    // Update is called once per frame
    void LateUpdate()
    {
        transform.position = player.transform.position + offset;
    }
}

```

However the rotation of the camera does not change when the player looks in either direction. How can this be done?

# Answer
> 3 votes
Unity had it's own smooth follow script in previous versions. It looks something like this-

```
using UnityEngine;
using System.Collections;

public class SmoothFollow : MonoBehaviour {

    // The target we are following
    public Transform target;
    // The distance in the x-z plane to the target
        //So this would be your offset
    public float distance = 10.0f;
    // the height we want the camera to be above the target
    public float height = 5.0f;
    // How much we
    public float heightDamping = 2.0f;
    public float rotationDamping = 3.0f;

    // Place the script in the Camera-Control group in the component menu
    [AddComponentMenu("Camera-Control/Smooth Follow")]

    void LateUpdate () {
        // Early out if we don't have a target
        if (!target) return;

        // Calculate the current rotation angles
        float wantedRotationAngle = target.eulerAngles.y;
        float wantedHeight = target.position.y + height;

        float currentRotationAngle = transform.eulerAngles.y;
        float currentHeight = transform.position.y;

        // Damp the rotation around the y-axis
        currentRotationAngle = Mathf.LerpAngle(currentRotationAngle, wantedRotationAngle, rotationDamping * Time.deltaTime);

        // Damp the height
        currentHeight = Mathf.Lerp(currentHeight, wantedHeight, heightDamping * Time.deltaTime);

        // Convert the angle into a rotation
        var currentRotation = Quaternion.Euler(0, currentRotationAngle, 0);

        // Set the position of the camera on the x-z plane to:
        // distance meters behind the target
        transform.position = target.position;
        transform.position -= currentRotation * Vector3.forward * distance;

        // Set the height of the camera
        transform.position = new Vector3(transform.position.x,currentHeight,transform.position.z);

        // Always look at the target
        transform.LookAt(target);
    }
}

```

# Answer
> 1 votes
Shraa1's answer will work, but if you want something simple to add to your code, you can just use LookAt.

```
transform.LookAt(player.transform);

```

This keeps the camera pointed at the player.

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


# Question
Title: How deep does the GameObject.GetComponentsInChildren() , Go?
So I have a `GameObject` which my scene will be it's children.
I wanted to get the `BoxCollider` of all the objects and their sub-objects and their sub-objects's sub-objects and ... .
So can I do that with just the `GetComponentsInChildren()`, or should I navigate through them all and find them one by one?

# Answer
> 3 votes
The documentation you link covers the answer to this, quite clearly. `GetComponentsInChildren` will return components from *all* sub children.

---

This is the API reference you link, emphasis mine:

> **Description**
> Returns all components of `Type type` in the `GameObject` or ***any of its children***.
> The search for components is carried out ***recursively*** on child objects, ***so it includes children of children, and so on***.
> <sub> \- Unity API: GameObject. GetComponentsInChildren</sub>

---
Tags: unity, gameobject, game-component
---


title: Unity: add InputTracking to my script

text:
# Question
Title: Unity: add InputTracking to my script
I'm new to unity and 3D world developement so I'm following Unity's tutorial for beginners right here. And I'm in the section with title "Camera Nodes" where they gave me a c# script to attach it to the camera object.
I did attach it to the camera but the problem with the script when I debug it I get an error of undefined class:

```
The name 'InputTracking' does not exist in this context

```

And this is the script:

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

public class UpdateEyeAnchors : MonoBehaviour {

    GameObject[] eyes = new GameObject[2];
    string[] eyeAnchorNames = { "LeftEyeAnchor", "RightEyeAnchor" };

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {
        for (int i = 0; i < 2; ++i)
        {
            // If the eye anchor is no longer a child of us, don't use it
            if (eyes[i] != null && eyes[i].transform.parent != transform)
            {
                eyes[i] = null;
            }

            // If we don't have an eye anchor, try to find one or create one
            if (eyes[i] == null)
            {
                Transform t = transform.Find(eyeAnchorNames[i]);
                if (t)
                    eyes[i] = t.gameObject;

                if (eyes[i] == null)
                {
                    eyes[i] = new GameObject(eyeAnchorNames[i]);
                    eyes[i].transform.parent = gameObject.transform;
                }
            }

            // Update the eye transform
            eyes[i].transform.localPosition = InputTracking.GetLocalPosition((VRNode)i);//--the error is this line
            eyes[i].transform.localRotation = InputTracking.GetLocalRotation((VRNode)i);//--and this one
        }
    }
}

```

This is the link of the class `InputTracking` in Unity's API, but I don't know how to add it to my script :)
Thanks in advance.

# Answer
You need to add `using UnityEngine.VR;` to the top of your file. `InputTracking` is located in that namespace, which is indicated by the docs.
> 1 votes

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


# Question
Title: Am I allowed to push my Unity based game's source code to github?
I got the Personal version of Unity 5.5 to play around with it1. Let's say I own the rights on all the assets I use in my project, or they are licensed in a way that allows me to use, modify and republish them. That includes all the scripts, models, images, sounds and whatnot. But what about the fact that it's built with a commercial game engine?

Do the Unity terms allow me to host my project's source folder (including the assets) on github? Do I need to include a certain license for that?

Note that I don't care about releasing the game, I'm just talking about sources of stuff I am making to learn the technology.

---

1) no pun intended

# Answer
Absolutely.

When you create a game with Unity you don't transfer any rights to any of *your* copyrighted material (or others' material that you are licensed to use) to Unity, nor do you give up any of those rights. So you are still free to do whatever you want with all of that.

As long as you don't store anything of Unity's (or anyone else's) that you are not licensed to use and redistribute, you'll be fine. For example if you were to have somehow obtained a valid source license to Unity's internals, that license would likely prohibit you from redistributing that source to the public.

But anything that's yours or that you have a license for, you're fine.

This is documented, as noted by @UnholySheep in the comments, in both the overview page and the TOS.
> 9 votes

---
Tags: unity, licensing
---


# Question
Title: How do I better organise rendering in an entity component system?
I'm developing an isometric RPG, with 3D characters in 2D level. I was using a standard object orientated programming paradigm, but was faced with a lot of issues. Recently, I learned about entity component systems, and am currently rewriting my engine using this paradigm.

I use OpenGL, and have two rendering systems - one for drawing in 2D, and one for drawing in 3D. Each system consists of one VBO id, with the appropriate geometry, shader program id, id of texture unit binded to the texture atlas (which accommodates all tilesets or all model textures) and other information like that. The alternate systems provide different logic for drawing in 2D and 3D.

When it comes to the components for these systems, I am stuck.

Say I have component, defined by the buffer offset from the beginning of VBO buffer and the primitive count that needs to be rendered. Let's pretend that I have two instances of these components. The first instance belongs to the level floor entity, and describes the bunch of quad tiles. The second instance is a character mesh that belongs to the player entity. The first component instance should use the 2D rendering system, and second instance should use the 3D rendering system, but the data structure of these instances are identical. It must be said that I use EntityX and the components gets in the systems, automatically depending on their type.

Both systems require position and craphics components, so both systems will take both component instances, and one of these component will be processed improperly, what with a 2D graphics component in a 3D rendering system, and vice versa. I'm thinking about creating the "hollow" components, like sprite and model, which will indicate what graphics components in the entity mean. Since these component will not contain any properties, and would be used only as flags, this solution seems clumsy.

How do I better organise rendering in an entity component system?

# Answer
From what I understand from your question, you have:

* Two separate systems, 2D and 3D rendering
* Each entity has a component describing the data needed for each system to operate
* The systems require the same data structure, but operate independently of one another
* You're looking for a clean way to differentiate the two components

While 1:1 mapping of Components to Systems isn't always ideal, in this situation, it makes sense to have two components (2DRenderComponent, 3DRenderComponent). You can have them use the same base code (e.g, RenderComponent is extended by both 2DRenderComponent and 3DRenderComponent), and just process the specific component with the relevant system. This prevents you from needing to use empty components to tag them, and makes it immediately obvious which is which (also allows you to have both 2D and 3D components for one entity, if you were to want that \[e.g, a 3D model with a 2D representation for the mini-map\]).

I agree that you shouldn't try to shoehorn your rendering into an ECS model, and that, ideally, the Components just hold pointers to actual primitives in the relevant render system itself - this allows your system to control and optimize rendering, without knowing/caring that it's inside of an ECS.
> 3 votes

# Answer
Most ECS systems are flawed by design (by flawed I mean it is just a mine opinion).

Usual way of doing things:

```
Entity.AddComponent<X>();
Entity.AddComponent<Y>();

```

This is flawed, because makes you need to add "hollow components".

Components should be added automatically by systems when entities register for them.

**Alternative design:**

```
SystemXK.Register(Entity);
SystemYZ.Register(Entity);

```

**Advantages:**

* You do not query system from components, but you add components on systems, meaning that you can have 2 different entities, with the same component but working on 2 total different Systems.

The main reason why people use ECS is to allow easy serialization of entities in a DB, which is not possible in my alternative design (using it for personal projects only).

This is much better for code design because you actually decouple Components assemblation from systems. If you want an Entity in a system you just register the entity, then it is the system to provide the components.

I truly believe you should understand very well OOP before moving on ECS, and then you should really understand ECS too. Most ECS frameworks around are just "copy-cat" because "copying is cool", and all have their same design flaws. There are really few ECS frameworks authors that made some decent project. Or authors that try to understant, use, iterate and make something new.

Trying to implement your own ECS is good to start.

You do not need to make your rendering system necessarily a ECS, but you can make it usable through a ECS. If you have a plain OOP render system it is easy to wrap it in a Entity system, the opposite is very hard, so beware before ECS-ing your middleware.
> 1 votes

---
Tags: opengl, c++, architecture, entity-system
---


# Question
Title: Offsetting ground texture doesn't work in WebGL
so I've created a 2D sidescroller game, the technique I used is to keep the player on the same place, and move the obstacles towards him. I also offset the ground and backdrop constantly to create the illusion of player moving.

The ground texture is on a quad, and the texture wrap mode is set to repeat. In the editor everything is running fine as I wanted, however when I build it (WebGL), in the browser the ground doesn't seem as if it is set to Repeat but rather Clamp. Here's how it looks:

You can see from the left part of the image the ground doesn't repeat, the strange thing is that, after the game runs for a few more seconds it fixes, and then in a few seconds becomes like that again.

heres the code attached to the ground to keep it offsetting constantly:

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

public class Offset : MonoBehaviour {

public float scrollSpeed;
public Material mat;

private float offset;

// Use this for initialization
void Start () {
    mat = GetComponent<Renderer>().material;
}

// Update is called once per frame
void Update () {
    offset = Mathf.Repeat(Time.time * scrollSpeed, 1);
    mat.mainTextureOffset = new Vector2(offset, mat.mainTextureOffset.y);
}
}

```

What may I be doing wrong, and how can I fix it?

Thanks in advance!

# Answer
for texture scrolling you should use "Repeat" in import settings instead of "clamp"
> 1 votes

---
Tags: unity, c#, textures, webgl, side-scroller
---


# Question
Title: What is an example of a binary 3d file format?
I'm new to GD so if this is too broad I apologize. I'm looking for some quick information.

What binary file format supports the basic game rendering information?

* raw position vertices
* Texture/UV
* (or) Color
* Normals
* Animation keyframes

I'm aware that .obj and .dae have all of the above, however these files are in ascii. What file type supports these and is in binary?

And is it common to make custom 3d model format for one's game engine?

# Answer
As mentioned in the comments:

Nearly every common data format used by 3D tools can be stored as either ASCII or binary, the difference is only in how the contained data is stored on disk - the actual format does not change. One example for this is the **FBX** format.

For the second question: It is common practice to use custom formats for 3D models and animations in game engines. The ones used by 3D content creation tools contain a lot of information that is unnecessary for games. Also the data is usually rearranged so that it can be simply read into the corresponding buffers (e.g.: for rendering) at runtime and does not need to be prepared. The conversion from common 3D formats to engine-specific ones is part of the so-called "Asset Conditioning Pipeline" (and is commonly performed either via Plugins, e.g.: for Autodesk Maya, or special standalone tools that are part of the engine)
> 1 votes

---
Tags: file-format, 3d-modeling
---


title: How to use SDL_TTF's outlines

text:
# Question
Title: How to use SDL_TTF's outlines
This might be a basic question but googling isn't turning out anything useful:

How are we supposed to use TTF\_SetFontOutline ? I know we're able to create an outline (and it looks alright) but since it's the same colour as the main font I don't see any practical usage for it.

I can't find any way to set the colour separately and rendering two font instances makes it very hard to line up.

So what is a typical usage case for it?

# Answer
> 10 votes
You can acheive what you want by drawing the text with an outline in one color, and then drawing it without outline on top of that, in another color.

---

Here's an example of white text with a black outline from the libsdl forum:

```
#define OUTLINE_SIZE 2

/* load font and its outline */
font = TTF_OpenFont(font_path, font_size);
font_outline = TTF_OpenFont(font_path, font_size);
TTF_SetFontOutline(font_outline, OUTLINE_SIZE);

/* render text and text outline */
SDL_Color white = {0xFF, 0xFF, 0xFF};
SDL_Color black = {0x00, 0x00, 0x00};
SDL_Surface *bg_surface = TTF_RenderText_Blended(font_outline, text, black);
SDL_Surface *fg_surface = TTF_RenderText_Blended(font, text, white);
SDL_Rect rect = {OUTLINE_SIZE, OUTLINE_SIZE, fg_surface->w, fg_surface->h};

/* blit text onto its outline */
SDL_SetSurfaceBlendMode(fg_surface, SDL_BLENDMODE_BLEND);
SDL_BlitSurface(fg_surface, NULL, bg_surface, &rect);
SDL_FreeSurface(fg_surface);

/* we now have RGBA white text with black outline in bg_surface */

```

# Answer
> 1 votes
The colour is set to be the same as the font, so it can't be used as you'd like it to be.

I'd suggest having a look at bitmap fonts, there's a tutorial here.

Alternatively, if you'd like to continue using SDL\_TTF, you could look into generating a glyph atlas. I personally don't have much experience with this but it is explained in another question here.

---
Tags: sdl, ttf
---


# Question
Title: How to handle multiplayer in JavaScript?
I'm just doing a bit of research into tech to use for a mobile multi-player game.

It's more an experiment at present so for the moment, the only thing that Players need to be aware of is the other Players.

If this was a typical web application and not a game It'd just have HTTP requests firing all the time -- but since this is a game, performance and accuracy is going to be a problem.

Due to the game being targeted at multiple phone platforms, lets say that the client will be written in JavaScript or a framework based on JavaScript. The server technology is totally open.

Each player will need to make the equivalent of a HTTP post and get only using a faster protocol. The reason for multiplayer being web based is because multiplayer across Bluetooth or other local networking would be too diverse across the platforms and could cause problems.

So the question boils down to whats a good protocol/technology to use for JavaScript multiplayer? Any advice on the server side stuff or does it matter? Any reason I should drop this two-tier architecture and go with direct phone-to-phone connection?

# Answer
> 15 votes
You want a better communication protocol then HTTP. You probably want UDP or TCP. Browsers have no way of doing UDP communication so your only choice is TCP.

For TCP you would want to use a WebSocket, however browser support is unstable on websockets.

This means you would need to use a COMET technique to emulate TCP, one popular emulation would be a websocket embedded in a flash application.

Socket.IO is a library (for node.js) that supports websockets and emulates them with an appropiate fallback on non compliant web browsers (it uses flash and other COMET techniques).

For multiplayer JavaScript games I would recommend the usage of socket.io and node.js

# Answer
> 4 votes
Both the question and the accepted answer were published in 2011, and the times have quite changed since :)

Websockets is quite prevalent, but an even better technology is WebRTC which allows for unreliable UDP streams. These are much, much better for games.

Other than communication, there are many other obstacles to overcome when writing multiplayer games such as game state reconciliation, client-side prediction, serialization and many others.

`<shameless self promotion>`

I'm one of the original developers of lance.gg, a multiplayer game server/library based on node.js where we've solved many of the problems mentioned (and many others!). Our goal is to make multiplayer game development easier for JavasScript game developers. I warmly invite you to use it as a starting point for making your game.

`</shameless self promotion>`

# Answer
> 1 votes
Check this:

---
Tags: multiplayer, javascript, performance, mobile
---


# Question
Title: Creating an Array of 1s and 0s (with all 1s touching)
I am a novice programmer trying to add an unnecessary and complicated element to a text adventure! ...and I've run into a question I am not sure how to research further (I suspect due to lack knowledge of the proper terminology).

I am working on a small text adventure that uses an 11x11 array. Player is capable of moving into spaces with a 1 and incapable of moving to a 0. I need to a) retain the outer boundary 0s, b) randomize the content inside the border, and c) ensure that there is a linked path of 1s that will eventually connect to a 2 (the exit):

```
0 0 0 0 0 0 0 0 0 0 0
0 1 1 0 0 0 0 1 0 0 0
0 0 1 1 1 1 1 1 1 1 0
0 0 1 0 0 0 0 0 0 1 0
0 0 1 1 1 1 1 1 1 1 0
0 1 1 0 1 0 1 0 0 0 0
0 1 0 0 1 0 1 0 0 0 0
0 1 1 1 1 0 1 1 1 2 0
0 0 0 1 0 0 1 0 0 0 0
0 0 0 0 0 0 1 1 0 0 0
0 0 0 0 0 0 0 0 0 0 0

```

I'd appreciate any pointers here - not sure what direction I should be looking in. Thinking of scrapping this feature so if it's not viable I don't mind hearing that :) Thanks for reading.

# Answer
> 2 votes
You are essentially trying to generate a **spanning tree**.

But what in the hell is a spanning tree? The non-tech humans usually call it a **maze**!

I will not give you javascript code, but I'll tell you where you can learn how to develop the algorithm yourself. This Presentation from Jamis Buck is the Maze algorithms 101. You MUST read it! It is very simple reading, and has lots of interactive demos.

If you want to dive deep into the theory, try reading the Wikipedia page on Spanning Trees. You'll learn the nomenclatures and find about cycles.

Good luck!

---
Tags: javascript, algorithm, maze
---