# Question
Title: Can Harlowe for Twine 2 handle variable references inside a Datamap?
I'm starting to learn Twine and I'm putting together a little framework for making a game.

I'm trying to make a DataMap named 'Door' that has a key/value pair of "openCondition",$doorUnlocked. What currently happens is that "openCondition" is set to what $doorUnlocked is when 'Door' is created (false). This is fine, but when $doorUnlocked becomes 'true', "openCondition" stays the same, because it's already been set.

Is is possible to set a DataMap value to a reference of a variable? Are reference variables even built into Harlowe? If not, are they available in any other Twine format?

# Answer
**Not really.** Harlowe offers a very simplified interface to JavaScript and does some stuff to shield inexperienced developers from potential "gotchas" like accidentally constructing a reference. Looking at the Harlowe source, DataMaps are implemented using JavaScript Maps, and whenever a value is set on them, it seems to `clone()` the value before assigning it.

Depending on your level of comfort with JS, you may find more success with the Snowman 2 format, which is basically Underscore templating. You'd be able to use one of the JS techniques to simulate reference values: probably either passing around objects or using closures.

A workaround is to always store the door-is-unlocked value in one place: either in `$Door's opencondition` or in `$doorUnlocked` but not in both.
> 1 votes

---
Tags: twine, harlowe
---


# Question
Title: With LibGDX how is it okay to use Fonts statically?
I am working on a engine/framework/game in LibGDX as a baseline for future Java games (really lightweight and stuff, just gamestates, entity framwork, physics, font, etc), but I am unsure of how I should handle font.

Should I create a Font Factory to generate fonts, manage them, and allow static access to fonts? Or should I just create fonts when I need them, like in my HUD/GUI/Player/Level/etc.

# Answer
To answer your question; it should be absolutely fine to have static fonts. As long as you remember to dispose of them when you exit the game.

What I would recommend though is using the `AssetManager` (like spectacularbob mentioned in his comment). In reality you should probably use the `AssetManager` for all of your assets (music, textures, atlases, fonts etc.), because it simplifies the process of disposing of assets by only having to dispose of the `AssetManager` instead of every single asset, and it makes it easy to load assets on-demand from `AssetDescriptor`s (look at this official tutorial).

To show how `AssetDescriptors` could be implemented in a static way, take a look at this snippet from one of my projects:

```
public static class Assets {
    ////////// Skins //////////
    public static final AssetDescriptor<Skin> SKIN = new AssetDescriptor<Skin>("skins/default.json", Skin.class);

    ////////// Textures //////////
    public static final AssetDescriptor<Texture> LOGO = new AssetDescriptor<>("graphics/meta/logo.png",
            Texture.class);
    public static final AssetDescriptor<Texture> TEST_TEXTURE_BLOCK = new AssetDescriptor<>(
            "graphics/block/sample.png", Texture.class);

    ////////// Fonts //////////
    // In this project I was using FreeTypeFont, but using normal BitmapFonts is fine as well!
    public static FreeTypeFontGenerator FREETYPE_GENERATOR = new FreeTypeFontGenerator(
            Gdx.files.internal("fonts/bricks.ttf"));

    ////////// Music //////////
    public static final AssetDescriptor<Music> INTRO_MUSIC = new AssetDescriptor<Music>("audio/music/intro.mp3",
            Music.class);

    ////////// SHADERS //////////
    public static final ShaderProgram DEFAULT_SHADER = SpriteBatch.createDefaultShader();
}

```

Then you can load them using `AssetManager#get(AssetDescriptor<T> assetDescriptor)`:

```
assetManager.get(Assets.LOGO); //Or whatever asset you want.

```
> 1 votes

# Answer
Just do one thing you can change the method which your following now. you can use the "hiero" tool for the font creation . Just download "hiero" jar file from the following link

https://libgdx.badlogicgames.com/tools.html

by using hiero you will be able to access almost all the fonts . after creating the fonts save it on your android project files "asset" folder and add the folowing code.

```
 private BitmapFont font;
 font = new BitmapFont(Gdx.files.internal("myNewFontCreatedByHiero.fnt"));

```

this is the simple method to create the fonts . which you can dispose after the usage although it doesn't required any additional codes too . "hiero" is a simple jar file which helpfull to create the different fonts for the libgdx. Later you can dispose the font

```
     font.dispose();

```

in your dispose method
> 0 votes

# Answer
No, native resources like fonts should not be static, especially on Android this can cause lots of problems. I would suggest using the singleton pattern to create a class that manages such resources and also properly dispose of them.

You can read more about this subject on the Lib GDX wiki: https://github.com/libgdx/libgdx/wiki/Memory-management
> 0 votes

---
Tags: libgdx
---


# Question
Title: How can I control a game 2d car mechanic from acceleration & speed to just 1 value?
So I have a car in a 2d game that runs on acceleration and speed, two values that have a max. The acceleration is small, under the value of 1 and it rises by an incrementation. The speed is large number like 100 and it rises by incrementing the current acceleration. They are both incremented relative to the fps but that's not important.

What I am trying is to have a formula with having only one value (with a max) instead of two as I am trying to simplify the UI for the player.

Alternatively, I was thining of having a value (lets call it speed) that gets incremented by something, without a max, but is limited by, lets say road friction (like multipling it with 0.99). Such a thing would be felt lower when the car is slow but eventually the friction would act as a max/limit, the car oscilating to near max values.

I know too little of physics and car stuff to figure this out on my own so I am reaching out for help. Thanks!

# Answer
I think your idea of simulating friction is on the right track. A stronger limiter of speed in real life is air resistance, which increases with the square of speed.

Air resistance is a type of drag, and to use it you would do something like

```
DRAG_COEFFICIENT = .0001
drag_acceleration = speed * speed * DRAG_COEFFICIENT
speed = speed - drag_acceleration * timestep

```

At lower speeds, this drag will have a relatively small effect due to the very small `DRAG_COEFFICIENT`. As the car moves faster, it will cause the car to accelerate less and less. At some value of `speed`, the drag will overtake what's being added by your acceleration and cause the car to top out.
> 4 votes

# Answer
I would suggest a Logarithmic function. A logarithmic curve starts to climb quickly, but slows as it tends towards the limit.

You'd have to tinker with the equation to get it just right for what you want, but that's the basic concept. Your increment is the X-axis here, and your speed the Y-axis. As X gets higher, Y tends towards a maximum limit.
> 0 votes

---
Tags: physics, mathematics, vehicle
---


# Question
Title: How to model an Attack( ) action? How to model combat? In general, how objects communicate?
I never understood how would you elegantly describe two people talking in OO. I think this question extends to how similar objects communicate in general. I am designing a game now and Units have to attack each other.

My first idea was something along the lines:

```
public class Unit {
   public void attack(Unit targetUnit) {
      //calculates damage base on this unit stats
      targetUnit.takeDamage(damage);
  }

  public void takeDamage(int damage) {
    this.health = health - damage;
  }

}

```

And then later:

```
Unit whiteKnight = new Unit();
Unit blackKnight = new Unit();

//a possible combat interaction
whiteKnight.attack(blackKnight);
blackKnight.attack(whiteKnight);

```

Is this acceptable? Is this the standard?

# Answer
I highly suggest to stick to the entity/component system. To give you an example with your mentioned design.

You would create 2 components

1. AttackComponent
2. HealthComponent

The AttackComponent would have a method to attack an entity.

The HealthComponent would have a method to modify the health property.

Then you attach those 2 components to every entity that you want to be able to fight or only the health component if you want the entity to be able to take damage.

Then in the AttackComponent method attack, you would take the entity as target and just take theirs healthcomponent and call the modify method.

It is maybe a bit more work to have a working entity/component design, and it is maybe sometimes a bite overkill to generate an own component for such an easy task like health, but believe me, your game will be way more easier to create/manage/handle and of course you will always have the possibility to convert such a system, easy into an editor.
> 1 votes

# Answer
Mediator design pattern is what you want to do eventually. Links to resources at bottom of post, and link to an amazing book from 1994 that I highly suggest to anyone who does programming.

There is no one way to program this design pattern properly. You can make the mediator do all of the work, and just update the objects, or have the mediator not care about any passed messages, and have the game objects handle the messages themselves.

I apologize if my java code is incorrect. I haven't played with Java for a while. Here is a quick example that fits your code:

*CUnit.java*

```
import IMediator;
public class CUnit {
    private IMedator m_Mediator;
    // You will want this to be overrided by the WhiteKnight/BlackKnight classes.
    public void ReceiveMessageFromMediator(NameValuePair message)
    {
        if ( message[0] == "attack" )
        {
            takeDamage(message[1]);
        }
    }
}

```

*CUniManager.java*

```
import IMediator;
import CUnit;
public class CUnitManager implements IMediator
{
    public void SendMessageToMediator(NameValuePair message)
    {
        if ( message[0] == "attack" )
        {
            CUnit curUnit = findUnitByName(message[1]);
            if ( curUnit != null )
            {
                curUnit .ReceiveMessageFromMediator(new NameValuePair(message[0], message[2]);
            }
        }
    }
}

```

After mediator design patterns there are other types out there. Such as Subscribe/Publish.

Links:

https://sourcemaking.com/design\_patterns/mediator

http://www.amazon.ca/Design-Patterns-Elements-Reusable-Object-Oriented/dp/0201633612/ref=sr\_1\_1?ie=UTF8&qid=1448477793&sr=8-1&keywords=design+patterns

Publish/Subscribe https://en.wikipedia.org/wiki/Publish%E2%80%93subscribe\_pattern

Related question https://stackoverflow.com/questions/3162291/mediator-pattern-vs-publish-subscribe
> 0 votes

# Answer
The other two answers by LukGus and Yosh Synergi address one half of the problem: the entity design where the `Attack()` and `TakeDamage()` methods are defined, but I thought I'd address the other half, that is, this part:

```
Unit whiteKnight = new Unit();
Unit blackKnight = new Unit();

//a possible combat interaction
whiteKnight.attack(blackKnight);
blackKnight.attack(whiteKnight);

```

Generally speaking you won't actually do this. Mainly because this only allows for a finite number of units in your game and with a finite number of interactions. What if you wanted a third unit on say...Team Red? You can't just add another `Unit RedKnight` and have it attack/be attacked like the white and black ones here, afterall who's attacking whom and when? Is there a color-advantage? (i.e. white always attacks first, allowing white teams to slay black and red units before those units can deal damage to white).

So the general idea (and exact implementation will differ) is to store an *array* of units, possibly separated by team/faction/side/alliance or by type (e.g. for a Bullet Hell sort of game, you store Bullets in one array, Entities in another, and visual flair that doesn't interact with the previous two, in a third, etc.) and then you just loop through the arrays looking for overlaps (or other qualifiers of "do I attack now?").

e.g.

```
List<Unit> whiteTeam = new List<Unit>();
List<Unit> blackTeam = new List<Unit>();
...
foreach(Unit white in whiteTeam) {
    white.update(); //movement, etc
}
foreach(Unit black in blackTeam) {
    black.update();
}
foreach(Unit white in whiteTeam) {
    foreach(Unit black in blackTeam) {
        if(white.canAttack(black)) { //are they in range, etc?
            white.doAttackAndDamage(black); //deal damage
        }
        if(black.canAttack(white)) { //am I in range (etc) of them?
            black.doAttackAndDamage(white);
        }
    }
}

```

Notice that white units are never checked against other white units. Also note that both white and black attacks are processed at the same time. This may not always be possible. I did it here, because every attack is an `A<->B` comparison, it doesn't matter if we break it out into two nested loops (checking `A->B`, then again for `B->A`) or do it as a single nested loop (checking both at the same time) except that doing it this way is computationally faster.

The same would be true for games where bullets are in play: it is going to be very rare for bullets to need to check collisions against other bullets, so by separating out bullets and units by team means that each bullet makes fewer checks: it only needs to check against the enemy units. If a bullet *does* need to intercept (collide) with other bullets, it can be handled separately.

You have to watch out for handling ostensibly simultaneous events in a sequential manner. You don't want to give an edge to the white team by processing all white team attacks and removing black units from the array *before* processing the black team's attacks (unless the game is turn based and you *do* want that, but it you don't handle that in a white-then-black manner, but usually attacker-then-defender). But you *might* want to know that an enemy has been slain (or a bullet intercepted or whatever) while still processing the same side. E.g. if White Dude #17 killed Black Dude #12, White Dude #18 should look at Black Dude #12 and go "I don't need to attack him, he's already dead, but Black Dude #13...he's still alive and in range."

So your `canAttack()` method will probably end up being rather complicated (are they alive, are they in range, am I on cooldown, have I been stunned? etc). As well as your entity update loops. I know the one I have for a scrolling 2D shooter is: it has to process enemy bullets, player bullets, enemies, allies, particles, and bullet/bullet collisions (only across teams) and only *after* all of that is done, do things get removed for being dead/intercepted/old/off-screen. And things dying might spawn *more bullets* (e.g. an enemy that explodes on-death).

And that way everything happens in a way that looks fair to the player: if two bullets that both cause interception hit each other, then *both* should be intercepted (it shouldn't matter which one runs first).

But say I want to have a bullet that acts like an energy shield that intercepts, say **10** bullets? What happens if *it* intercepts another bullet that itself can intercept multiple bullets (say, 5)? What happens then? Well, in my case I said "ok, both of you subtract your intercept counts from each other, anyone at or below 0 remaining intercepts dies."

One of the problems I ended up having was dealing with bullets that move very very fast. It was easy for them to "skip over" a smaller, slower moving, interceptor on the other team. So I had to break down the movement into "move no farther than my own size, check collisions, repeat." So all of the collision code is actually inside the movement loop, so things got insanely convoluted quickly. For large battle zones with lots of units (or bullets), it would be completely infeasible to check against *everything* in the scene, at which point you have to break things down into quadtrees or similar.

By breaking things into quad trees, you break up your arrays, yeah these:

```
List<Unit> whiteTeam = new List<Unit>();
List<Unit> blackTeam = new List<Unit>();

```

So that they themselves are abstracted away. The TL;DR is that you break space into chunks and each entity/bullet only has to query what chunk its in (and the neighbors) and check against only the entities contained within that volume. Anything that's way over on the other side of the map isn't even considered. We've already pre-computed the distance check ("am I in range?") for a large majority of the battlefield. It still needs to be called, but it will only be queried for objects that *might* be in range. That is, if it's 1000 pixels away and no attack reaches farther than 50 pixels, we can break the battlefield down into 10 unit-wide volumes. No matter where inside that 50 by 50 pixel sized area a unit is, we know for a fact that it can only attack things in its volume or the 8 neighboring volumes. Anything farther away than that is Definitely Too Far Away and we don't even bother asking.

So instead of 10,000 bullets having to check collisions against 10,000 bullets, they instead check against only the few dozen in close proximity, saving even more CPU.
> 0 votes

---
Tags: game-design, software-engineering, game-mechanics
---


# Question
Title: Unity3D: Lightmap bleeding in standalone build
I'm running into an issue about some lightmap glitches made of black seams lines occuring only in the standalone build of our game, and it does only affect certain scenes. below is attached a screenshot of both editor and .exe build of the same scene.

I'm also attaching below the current Lighting settings for that current scene, but before, our second UV Channel is not generated inside Unity3D but authored in 3DSMAX :

Now, even if the generated lightmaps are 4096, their texture inspector shows a max size of 2048 and no compression (tried a build with a max size of 4k with no change), i also discovered that Mip Maps are enabled by default (might be the problem ?).

Above all, my build settings are Windows standalone x86, although the game is VR Only wouldn't be better to make it x86\_64 only and would it solve this issue ?

**Current Unity Version and infos:** \- Unity 5.6.0f3 \- Oculus Utilities 1.14 \- Build settings for windows: Auto graphics API - Static/Dynamic Batching - GPU Skinning - VR supported (Oculus + OpenVR) - MultiPass Stereo Rendering - Optimize Mesh Data enabled.

**Mesh import infos:**

Mesh compression off - Read/Write enabled - Optimize Mesh Enabled - Normals: Import

i would also state that we had a previous gearVR build (with 2048 resolution lightmaps) and this issue was never encountered

Thank you.

# Answer
> 0 votes
Solved, The issue here was in Build Settings \> Vertex Compression that was turned to "everything", unchecking the UV1 channel (the second channel used for lightmap UVs) solved this issue.

---
Tags: unity, lighting, virtual-reality, oculus
---


# Question
Title: How do you actually build once you encounter the 'Too many method references' error?
I'm making a very simple mobile F2P arcade game in Unity After adding SDKs for facebook, gamesparks, firebase, and appodeal I coud not build, getting the "Too many method references: 76221; max is 65536" error.

The solution from Too many field references: 70613; max is 65536 is apparently to export an ADT project, import it into Android studio and go from there.

I built following these instructions, and after building my Android studio project had errors relating to the facebook SDK similar to here: Unity exporting android project with Facebook SDK issue

The solution proposed there is to copy all the `.aar` from your Unity project to files to the Android studio project and add lines to the build.gradle file referencing them, which I did.

After doing all that the 4 facebook related errors are gone but one new one appears:

> Error: more than one library with package name 'android.support.v7.appcompat

A proposed solution for that is to search for the offending file and delete it in windows explorer but there is nothing with that name in my Android studio project folder. I tried removing some `.aar` files with appcompat in the name but I ended up reverting to the previous 5 facebook errors

This whole thing has been a bit of a nightmare and I have no idea what I am doing. I would love to hear from someone who encountered this error and got past it and was able to build their game again. Surely this must be a common issue for anyone making a commercial mobile game in Unity?

# Answer
> 1 votes
I have not solved this. But I *have* bypassed it.

1. Appodeal have another SDK package with less methods
2. I removed parts of this appodeal SDK. They have libraries for each ad provider they use. I will un-register from the ad providers whose libraries I removed.

This way I was able to get the methods to under 65536, so I can build normally from Unity

---
Tags: unity, android
---


# Question
Title: SpriteKit SKTileMapNode with Tileset Integration
SpriteKit supports tile maps as of iOS 10 and has a pretty powerful engine. Only, I am having trouble discovering if it is possible, and how to natively create, tile sets directly from a tileset image.

For example, it seems that many other tile map programs (such as Tiled) support uploading a single tileset image with a few inputs (16x16 tiles at 64px for each tile, for example) to create an array of tile textures. The only way that I've found to integrate this with Xcode's new SKTileSet feature is to manually crop each tile into it's own image, upload that image into a separate texture, and access them via name.

Is there a better way to upload a tile map image and access its tiles using Apple's SKTileMapNode engine?

# Answer
I'm working on the same thing, and the best options I've found are to either use imagemagick to split the images then import them to Xcode, or to import the master image and split it in code ...and optionally create a texture atlas, depending on how you prefer to keep track of which tile is which.
> 1 votes

---
Tags: tilemap, spritekit, xcode
---


# Question
Title: Autoscroll a TextArea to youngest/freshest row/line
I want to use a **TextArea** UI widget as a UI integrated Logger. Therefore the TextArea should always show the youngest message.

I browsed the whole API to find the proper method but could not find any. **TextArea$setCursorPosition** while passing **TextArea$getLines** as its parameter did not worked as intended.

I read about **TextArea$setPrefRows** and used it with getLines but also no luck.

How can I use TextArea to get autoscroll behaviour down to the most recent line?

# Answer
I had a similar situation in a game I was working on, and what I ended up doing was putting the TextArea in a ScrollPane and then adding an action with each line to scroll it to the bottom (there appears to be a bit of a bug in setting the position).

```
spMessages.addAction(Actions.sequence(Actions.delay(0.0f), new Action() {
  @Override
  public boolean act(float delta) {
    spMessages.setScrollPercentY(1.0f);
    return true;
  }
}));

```

A bit of a hack, but I chalked it up as "a cool UI effect" :)
> 1 votes

---
Tags: java, libgdx
---


title: Blender layer weight material to Unity

text:
# Question
Title: Blender layer weight material to Unity
How to set in Unity this Blender material with layer weight node?

# Answer
Cycles render engine work totally different than Unity (this is valid for almost every combination of 3D software), so there is **only one way how to ship pixel informations from Blender to Unity: using textures/maps.** Another problem with Unity is, there are no material editor, so you need to **bake everything in Blende**r and import final maps to Unity. This can be really painful in case Blender-Unity, because is impossible adjust anything in Unity. Also this is topic for a book. For simple materials, just **bake colors/albedo and normal**, for PBS prepare for long way until you find out, it does not make sense and you look for Substance Live

EDIT: Short version: What do you want is impossible.
> 1 votes

---
Tags: unity, blender, materials
---


title: Problems with arrays

text:
# Question
Title: Problems with arrays
I'm having a problem with the arrays that is in my code, I found the problem,but I don't know where or what lines to fix it. First, I'm setting variables and I dragged the gameobjects and buttons inside below arrays in the inspector

```
public GameObject[] expansion;
public Button[] panelButton;
public int isExpanded = 0;

```

Then I call the gameobjects inside the arrays using these function by button that I've created in the scene.

```
public void Expand()
{
    Debug.Log(isExpanded);
    while(isExpanded>0)
    {
        if(expansion[isExpanded] != null && panelButton[isExpanded] != null)
        {
            expansion[isExpanded].gameObject.SetActive(true);
            panelButton[isExpanded].gameObject.SetActive(true);
            Debug.Log(panelButton[isExpanded]);
            isExpanded++;
            return;
        }
    }
}

```

I also created this function to enable and disable the gameobjects inside the array using panelButton that is visible in the scene

```
public void SelectBase(GameObject selectBase)
{
    if(expansion[isExpanded] != null && panelButton[isExpanded] != null)
    {
        if(selectBase == expansion[isExpanded])
        {
            return;
        }
        if(expansion[isExpanded] != null)
        {
            expansion[isExpanded].gameObject.GetComponent<BoxCollider>().enabled = false;
            expansion[isExpanded].gameObject.tag = "Base";
        }
        if(selectBase !=null)
        {
            selectBase.gameObject.GetComponent<BoxCollider>().enabled = true;
            selectBase.gameObject.tag = "NewBase";
        }
        expansion[isExpanded] = selectBase;
    }
    return;
}

```

The problem is, when I click on the SelectBase function, it will affecting the isExpanded value thus messing up with the gameobject arrays. Can anyone possibly give me some insights? Thank you

# Answer
> 0 votes
Ok so I managed to fixed the arrays. I messed up with the `isExpanded` count by the way, and that's why the functions weren't working properly in the first place. I also removed the `while` loop.

```
void Expand()
{
    if(isExpanded<=2)
    {
        Debug.Log(isExpanded);
        isExpanded=isExpanded+1;
        expansion[isExpanded].gameObject.SetActive(true);
        panelButton[isExpanded].gameObject.SetActive(true);
        Debug.Log(panelButton[isExpanded]);
        Debug.Log(expansion[isExpanded]);
        Debug.Log(isExpanded);
    }
    else if(isExpanded>2)
    return;
    Debug.Log("all spawned");
}

void Remove()
{
    Debug.Log(isExpanded);
    if(isExpanded>0)
    {
        expansion[isExpanded].gameObject.SetActive(false);
        panelButton[isExpanded].gameObject.SetActive(false);
        isExpanded=isExpanded-1;
        Debug.Log(isExpanded);
    }
    else if(isExpanded==0)
    return;
    Debug.Log("done");
}

```

But I still have to deal with the `'IndexOutOfRangeException: Array index is out of range.'` everytime I click the button that runs `Expand()`, and all the objects inside the array is visible though, while the new `Remove()` function that I've made is working properly.

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


# Question
Title: Why I have to press the button twice to deactivate the GameObject for the first time?
*game engine:unity3d*

*scripting language: unityscript*

code:

```
   var setmenu:GameObject;

  var settings_menu:boolean;

   function Start()        {

   settings_menu=false;

  }
   function settingButtonClick(){

  if(settings_menu==false)
  {
  setmenu.SetActive(true);
    settings_menu=true;

  }
         else
  {
  setmenu.SetActive(false);
   settings_menu=false;
   }
 }

```

The problem is I have to click the UI button twice to SetActive to become false for the 1st time. But after that when I again activate and then press to deactivate it works fine with single click.

# Answer
At the `Start()` you're setting the variable `settings_menu` to false, then you're checking whether that variable is false or not. Since it is false at first, it will set the menu active on your first press of the button.

The problem you have is *not* the function, but rather the fact that you're setting a preset value instead of checking whether the menu is active or not at start. What you should be doing is this:

```
Start()
{
 settings_menu = setmenu.activeSelf; //set the state of the menu to the variable instead.
}

```
> 2 votes

# Answer
Insted of trying in if statement you can try this

setmenu.SetActive(!settings\_menu);
settings\_menu=!settings\_menu;

with out if statement and i think this should work fine
> 1 votes

---
Tags: unity, unityscript
---


# Question
Title: Help understanding the parkour tutorial in Cocos2d
I was practicing the parkour tutorial for chapter 7, but I failed to understand why we should move the same delta movement of `this.gameLayer`, which contains the background layer and the animation layer in opposite direction. Why do we do this?

# Answer
**This is to keep the player centered on the screen (while maintaining the illusion of motion).**

The player is moving (right) relative to `this.gamelayer`. If `this.gamelayer` is shifted to the left the same amount, the two movements will 'cancel' each other out.

---

The paragraphs right before these instructions explained in slightly different words:

> Since the physic body will move right infinitely and the sprite will synchronize it's position with the physic body.
>
> A few seconds later, the player will go outside of the screen, just as it is in the last tutorial.
>
> So we need to move the game layer's x position each frame to make it in a visible range.
> 1 votes

---
Tags: cocos2d, cocos2d-x-js
---


# Question
Title: how to initialize a 3d array of Vectors3 in Unity
I scoured the web for how to create a 3d array of Vectors to store chunks location info for a Voxel terrain generation based on Craig Perko's Terrain generation on YouTube. I was also using lists and dictionaries in the past but I want to try with arrays now. I already declare a 3d byte array for the blocks Inside chunks. But I got no clue on how to create a Vector3 3d array or byte 3d array to hold the chunks positions in space. So any help on how to create a 3d array of vectors3 from a loop of Positions is greatly appreciated. I am quite new and noOb so sorry if this doesnt make any sense.

```
for (int x = 0; x < 2; x++)
{
    for (int y = 0; y < 2; y++)
    {
        for (int z = 0; z < 2; z++)
        {
            Vector3[,,] = new Vector3[,,]
            {
                {
                    {
                        new Vector3[x,y,z]
                    }
                }
            };
        }
    }
}

```

# Answer
> 2 votes
I'm not sure what you are going to achieve with this, probably because I never did anything with voxels.

But you can create and initialize your 3d array like this:

```
var xSize = 2;
var ySize = 2;
var zSize = 2;

Vector3[,,] myVectors = new Vector3[xSize,ySize,zSize];
for (int z = 0; z < zSize; z++)
{
    for (int y = 0; y < ySize; y++)
    {
        for (int x = 0; x < xSize; x++)
        {
            myVectors[x,y,z] = new Vector3();
        }
    }
}

```

---
Tags: unity, voxels
---


title: How do Aimbots get detected?

text:
# Question
Title: How do Aimbots get detected?
I was wondering on the programming methods which are used to detect when a player is using an Aimbot/AutoAim cheat.

# Answer
Most games allow you to manually spawn an invisible bot, and a lot of aimbots don't filter these out.

By spawning 3 different bots and checking if the user aims at them, you can check whether they have aimbot or not.
> 4 votes

---
Tags: first-person-shooter, anti-cheat, aiming
---


# Question
Title: Fundamental physics component(s) in component-based game engine
What are the "smallest" physics components in your component-based game engine?

Would it make sense to create something like Positionable, Rotatable, Movable, Collidable and combine them the way you want or is it better to use one unified component like PhysicsInteractable?

# Answer
> 1 votes
Well, it depends of the overall look of your engine. I have always aimed for static and dynamic objects; the static ones just sit there with their collision data and the dynamic ones get updated and checked against static and other dynamic objects.

# Answer
> 1 votes
Well first of all it depends on what you really need. In 2D Platformer, you don't really need a real rotation value, only for your character to look in the right direction.

Position is the most basic and should be implemented most of the time (maybe not in some really exotic and transcendent gameplay).

Best thing might be to implement a component for every physical aspect you want to check for:

* is an object collideable, get a collideablecomponent
* is it movable? Movecomponent
* does it emit like a force on other objects (like wind from a fan), create a component for that

These should be your atoms, especially in your game engine. Just imagine you want to create something like this:

* you have components for moving and collision combined, cause everything that moves can collide.
* now you want something like a ghost (can move, can't collide) and jelly (can't collide, can't move)

Only if you are 100% certain you don't need it, you can go for those hybrids.

What I'm working on is a Node-based system. These are hybrid structures but are gatherings of those atomic Components. An Object may have the moveCollideNode, which is the positionComponent, the moveComponent and the collideComponent.

**Edit:** What I forget to mention was, that other parts of your engine might need those simple components. Like position and direction for your graphics engine or the object state for controls (just collided and is dizzy, so can't shoot). Someone could manipulate your physic properties in those parts if he has access to that kind of component.

---
Tags: physics, component-based
---


# Question
Title: How do I pause and resume a game in ActionScript 2?
I'm making a game where the player must avoid random falling objects. I dont know how to implement pausing. I've been stuck on this for 2 days!

I tried using `gotoAndPlay` and such, but the objects continue to run in the background. When I resume the game, they're still falling and it seems like the frame resets and loads new random falling objects.

(Simple English would be appreciated; English isn't my mother tongue.)

# Answer
I hope this example will helpful for you here i have two frames MainIntro and Gameplay if i cick the button of play then it moves to the next frame of GamePlay and then invoke the functions. Here i used gotoAndStop()..

```
package
{

import flash.display.MovieClip;
import flash.events.MouseEvent;
import com.greensock.*;
import com.greensock.easing.*;

import Globe;

public class MainIntro
{

    public function MainIntro(Mc:MovieClip)
    {
        Globe.self.realstage = Mc;

        Mc.intro_mc.play_mc.addEventListener(MouseEvent.CLICK, GameStart);
        Mc.intro_mc.play_mc.buttonMode = true;
        Mc.intro_mc.ins_btn.buttonMode = true;

    }

    public function GameStart(e:MouseEvent):void
    {

Globe.self.realstage.intro_mc.play_mc.removeEventListener(MouseEvent.CLICK,
GameStart);
        Globe.self.realstage.gotoAndStop(2);
        var gameply:GamePlay = new GamePlay();
    }

}

  }

```
> -2 votes

---
Tags: flash, actionscript, pausing
---


# Question
Title: I'm very new to Unity, is it all scene/script based?
I've been watching tutorials for a good amount of time now, basically just how to create a simple FPS game to get an understanding of the design process in Unity.

The tutorial I watched is very heavily based around the designer, and outside of some simple scripts to handle stuff like raycasting it doesn't involve much coding. My previous experience with game development has been only 2D stuff with XNA, and that was more what I'm used to when it comes to programming, where I'm doing pretty much everything.

I'm having trouble making sense of Unity though...it seems like it's all script/scene based from the programmers side? Like say I wanted to jump from one level to the next, do I just unload one scene and load the next and let the scripts I have for that scene + Unity do its thing?

Sorry if this questions been asked, it's not exactly an easy thing to search for.

# Answer
Yes, the whole game will run in the objects inside the Scene. Set a new Scene as active, and the last Scene will stop doing its work.

The only exception would be GameObjects that executed this method: `DontDestroyOnLoad`, those are persistent between Scenes (which is one way to share data between Scenes, like the player's score through the levels).
> 4 votes

---
Tags: unity
---


title: Multiplication and Division Bug

text:
# Question
Title: Multiplication and Division Bug
Hi guys first time poster with a quick question. I'm just getting started with coding and as an easy exercise I wanted to make a block move and sprint. I got it to do that but when I press the shift key too fast the getKeyUp part divides the speed variable too many times. How do I fix this?

```
public class Movement : MonoBehaviour
{
    public float speed = 5f;
    public float speedmutiplier = 2f;

    private void FixedUpdate()
    {
        if (Input.GetKey("w"))
        {
            transform.Translate(0, 0, speed * Time.deltaTime);
        }

        if (Input.GetKey("s"))
        {
            transform.Translate(0, 0, -speed * Time.deltaTime);
        }

        if (Input.GetKey("a"))
        {
            transform.Translate(-speed * Time.deltaTime, 0, 0);
        }

        if (Input.GetKey("d"))
        {
            transform.Translate(speed * Time.deltaTime, 0, 0);
        }

        if (Input.GetKeyDown("left shift"))
        {
            speed = speed * speedmutiplier;
        }

        if (Input.GetKeyUp("left shift"))
        {
            speed = speed / speedmutiplier;
        }
    }
}

```

# Answer
It seems to me that you're trying to implement a simple running state. The problem is that you're using `GetKeyDown` and `GetKeyUp`. Those functions will return true in their respective frames, but if you press the button in really quick succession, you might be able to press the button down, then up and then down again in the same frame, but the next up action will be in the next frame, therefore calling the `GetKeyUp` function twice but not the `GetKeyDown` function.

What you should be doing instead is, checking whether the shift key is pressed at the start of the `FixedUpdate` and then applying the multiplier there, using a base speed and a variable speed.

```
public class Movement : MonoBehaviour
{
    public float baseSpeed = 5f;
    public float speedmutiplier = 2f;

    private void FixedUpdate()
    {
        float speed = baseSpeed;
        if (Input.GetKey("left shift"))
        {
            speed = baseSpeed * speedmutiplier;
        }

        if (Input.GetKey("w"))
        {
            transform.Translate(0, 0, speed * Time.deltaTime);
        }

        if (Input.GetKey("s"))
        {
            transform.Translate(0, 0, -speed * Time.deltaTime);
        }

        if (Input.GetKey("a"))
        {
            transform.Translate(-speed * Time.deltaTime, 0, 0);
        }

        if (Input.GetKey("d"))
        {
            transform.Translate(speed * Time.deltaTime, 0, 0);
        }
    }
}

```
> 3 votes

# Answer
Assuming that you'd like to have a maximum and a minimum speed, you can Clamp the `speed` between a maximum and a minimum.

Like this:

```
public class Movement : MonoBehaviour
{
    public float speed = 5f;
    public float speedmutiplier = 2f;
    public float minimumSpeed = 1.25f;
    public float maximumSpeed = 640f;

    private void FixedUpdate()
    {
        // ...
        if (Input.GetKeyDown("left shift"))
        {
            speed = speed * speedmutiplier;
        }

        if (Input.GetKeyUp("left shift"))
        {
            speed = speed / speedmutiplier;
        }

        speed = Mathf.Clamp(speed, minimumSpeed, maximumSpeed)
    }
}

```
> 0 votes

# Answer
The main problem is the use of FixedUpdate() together with GetKeyUp/GetKeyDown. Unity resets them **once per Update** loop. When they are used in FixedUpdate() Unity can "miss" some of them.

As a rule use FixedUpdate mainly for physics related stuff, the rest goes to Update (or rarely LateUpdate).

So you should replace FixedUpdate with Update. Additionally I would still replace GetKeyDown/GetKeyUp with GetKey (look @John Hamilton answer on how you can do that).

Here is some additional info from Unity docs that may help you understand how Update and FixedUpdate work and why FixedUpdates is intended for physics related things:

> Unlike the main frame update, Unity’s physics system does work to a fixed timestep, which is important for the accuracy and consistency of the simulation. At the start of the physics update, Unity sets an “alarm” by adding the fixed timestep value onto the time when the last physics update ended. The physics system will then perform calculations until the alarm goes off.

Translation for the other mere mortals like me:

When the time between each Update is small (i.e. high frame rate) then Unity runs one(or even zero) FixedUpdate then one Update and repeat the whole process. But when the time between Updates becomes too long (i.e low frame rate) then Unity begins to "insert" more FixedUpdates in-between Updates because it tries to maintain fixed time between FixedUpdates.
> 0 votes

# Answer
Make sure that `deltaTime` is properly used in the speed computation. Unless you are comfortable with approximations, a correct, framerate-independent implementation should probably use `Pow()`:

```
    if (Input.GetKeyDown("left shift"))
    {
        speed = speed * Math.Pow(speedmutiplier, Time.deltaTime);
    }

    if (Input.GetKeyUp("left shift"))
    {
        speed = speed / Math.Pow(speedmutiplier, Time.deltaTime);
    }

```
> 0 votes

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


title: Point inside a large polygon

text:
# Question
Title: Point inside a large polygon
I am just starting to get into using pyBox2D as I already knew python well and I was wondering if I have 500 points of a large polygon, how would I be able to check if a point lies inside of this polygon. I tried to just make a polygon with 500 vertices but this isn't allowed in pyBox2D as the maximum vertices is 16.

I thought about splitting the polygon into many smaller polygons but I don't full know how to check if the point is inside all of these polygons. Do I need to create a body and add the polygon fixture or can I just use b2PolygonShape and then query the point from the shape?

I have been writing all my code using the github wiki for pyBox2D and they have a section on point querying a shape but I don't know how to implement this in my project.

# Answer
> 1 votes
Box2D shapes aren't a great fit for this, specifically because of that vertex count limit. They use a small, fixed-size, internal array for the points (in most implementations).

Fortunately, if you don't need the other features of Box2D for this particular polygon, there are other methods that are quite approachable.

Here's one way to do it:

```
def is_point_inside_polygon(poly, point):
    previous = poly[-1]
    hitcount = 0

    for current in poly:
        if (previous.y != current.y &&
            min(previous.y, current.y) <= point.y < max(previous.y, current.y)):

            lerp = (point.y - previous.y) / (current.y - previous.y)
            xIntersect = previous.x + lerp * (current.x - previous.x)

            if (point.x < xIntersect):
                ++hitcount

        previous = current

    hitcount = hitcount % 2

    return hitcount != 0

```

Note: I don't really know Python, so there could be syntax problems in there, or things that just don't exist. Let me know if it's not clear how to correct any mistakes I made in there.

This method is based on the fact that an infinite ray in any direction from your test point will intersect the polygon either an odd number of times or an even number of times, and that parity tells you whether the point is on the inside or outside of the polygon. Look here for details about this method.

---
Tags: box2d, python, pygame
---


# Question
Title: Should the level design be in Unity scenes (GameObjects) or in 3D programs (mesh)
I am wondering what is the most common and best way to design a game in Unity from the point of view of best practice and performance and the most easily maintainable?

Is it really performant to design the level in Unity editor using a GameObject for each part of the level? or should the whole world of the level be designed in any 3D software and then exported to Unity as a on GameObject?

# Answer
This is very project dependent. Every studio, group, and developer has a preferred method.

Generally, you use meshes when it's easier to construct something in your 3D editor rather than the scene editor (objects with geometry that needs to be changed on the fly. Terrain, caves, some buildings, etc). And then use the scene editor to place prefabs, movable objects, instanced scenery, and game logic items.

The performance aspects you mention come into effect with things like occlusion culling, instancing, and draw batching. If the whole scene is one mesh, then EVERYTHING gets rendered every frame which can be costly. This can be somewhat mitigated by splitting up your world geometry into multiple fragments.

So in general, do what you're comfortable with. There are tons of tools and plenty of documentation to make either approach work for you.
> 3 votes

# Answer
Unity has a quite useful terrain editor which can be used for creating outdoor scenarios. But unfortunately Unity lacks a proper general-purpose editor for indoor levels. So if you want to create an indoor level, then importing it as a 3d model is pretty much the only feasible way to get the level geometry into your scene. I am mostly talking about walls, floors and ceilings here. Any interactable or independently moving objects should be separate game-objects which you place with the editor after importing your level geometry from your 3d modeling program.

However, for some projects it can make sense to build your own level editor into Unity by creating some editor scripts (or downloading one from the asset store). Such an editor could work in form of "building blocks" which can be combined in different ways or in form of creating procedural meshes. The best strategy is highly dependent on the game you want to create.

Also keep in mind that Unity can only do optimizations like frustum culling and LOD-groups on complete 3d meshes, not on parts of one 3d mesh. So when you have very large levels, you might want to break them down into multiple independent game-objects. You might also have to implement some own logic to load and unload (Instantiate and Destroy) parts of the level at runtime to make sure you only have the level geometry in your scene which is currently visible or otherwise relevant for the game.
> 1 votes

---
Tags: unity, 3d, 3d-meshes, level-design
---


title: Unity applying weight to objects

text:
# Question
Title: Unity applying weight to objects
Say i have two objects:

This is a rather big ball.

For scale here is my character next to the ball:

In the real world no single man would be able to push this nor would he be able to survive being crushed by it rolling down hill.

However My character is able to do both.

I am rather new to Unity and was wondering if there is something you can do about it? My initial thought was to add weight to objects but im not quite sure how?

Could anyone please explain how you go around these type of issues?

# Answer
> 4 votes
Increase the Rigidbody's `mass` property.

---
Tags: unity, physics
---


# Question
Title: Strange behavior b/w Nav Mesh Agent and Trigger Collider
I'm running into an issue where my click to move character has problems navigating when in an enemy's detection trigger collider. Specifically, whenever my character is inside the trigger collider, there seems to be "inertia" or refusal to navigate properly. Movement is ordinarily very responsive because of how I have the Nav Mesh Agent component set up. When I'm in the trigger, something seems to be wrong with the pathfinding, but I can still force myself to get out.

I have a very basic click to move player movement script.

```
    public class PlayerMovement : MonoBehaviour
    {
        private NavMeshAgent navMeshAgent;

        void Start()
        {
            navMeshAgent = GetComponent<NavMeshAgent>();
        }

        void FixedUpdate()
        {
            if (Input.GetMouseButton(0))
            {
                Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
                RaycastHit hit;

                if (Physics.Raycast(ray, out hit))
                {
                    navMeshAgent.destination = hit.point;
                }
            }
        }
    }

```

I also have a very standard enemy detection script attached to an empty game object which is a child of the enemy. I've done it this way so my enemy object itself doesn't have a bunch of colliders.

```
public class EnemyDetection : MonoBehaviour
{
    private GameObject player;

    public bool playerDetected;

    void Start()
    {
        player = GameObject.FindGameObjectWithTag("Player");
    }

    void OnTriggerEnter(Collider other)
    {
        if (other.gameObject == player)
        {
            playerDetected = true;
        }
    }

    void OnTriggerExit(Collider other)
    {
        if (other.gameObject == player)
        {
            playerDetected = false;
        }
    }
}

```

Finally, I have an enemy movement script attached to the enemy object which handles the actual nav mesh destination setting.

```
public class EnemyMovement : MonoBehaviour
{
    private GameObject detectionTrigger;
    private EnemyDetection enemyDetection;

    private NavMeshAgent navMeshAgent;
    private GameObject player;

    void Start()
    {
        detectionTrigger = transform.Find("Detection Trigger").gameObject;
        enemyDetection = detectionTrigger.GetComponent<EnemyDetection>();

        navMeshAgent = GetComponent<NavMeshAgent>();
        player = GameObject.FindGameObjectWithTag("Player");
    }

    void Update()
    {
        if (enemyDetection.playerDetected)
        {
            navMeshAgent.SetDestination(player.transform.position);
        }
    }
}

```

# Answer
> 2 votes
I figured it out. The solution was to change the layer of the detection trigger object to "Ignore Raycast".

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


title: Texture appearing blurry

text:
# Question
Title: Texture appearing blurry
I've just created another scene in Tiled and imported it into Unity using Tiled2Unity and I'm having a strange issue, while the image looks crisp and as it should in Tiled, when imported into Unity it's appearing blurry (all of the graphics in the prefab Tiled2Unity creates).

My tiles are 64x64 and the scale is PPU is set to 1.

Tiled (how I want it to look) -

Unity (how it imports)

Any help is appreciated, thank you.

# Answer
> 2 votes
Select the texture you have imported in the `Project` tab, and then in the `Inspector`, set `Filter Mode` to `Point`.

# Answer
> 0 votes
I needed the change the filter mode, and compression mode against the texture that Tiled2Unity imported, this was found under "Assets/Tiled2Unity/Textures", altering the settings in the inspector against the texture made the blur go away.

---
Tags: unity, tiles, tiled
---


# Question
Title: Why can't I see how many installs my game has on its Google Play page?
I made an Android game, and I uploaded and published it to Google Play. Then, I installed it on my phone.

Why can't I see the install count, on its Google Play page?

# Answer
> 7 votes
Since you just uploaded it today, you won't see the number of installs yet. See the documentation where it says the statistics are updated on a daily basis. The statistics are not "live". You'll only be able to see how many people downloaded on a given day *after* the day is over. This is similar to Google Analytics. So be patient and check back later. Congrats on publishing a game.

# Answer
> -1 votes
Google doesn’t release the official downloads/revenue numbers publicly, so it’s impossible to know the exact download numbers for any app—— unless you’re Google, the actual app publisher/developer, or have access to their credentials.

Sensor Tower allows you to see pinpoint download (& revenue) estimates from the previous month for nearly any app in their free platform. You can access daily and more granular data/figures with their Store Intelligence product, which is used by mobile leaders like Zynga, Uber and Supercell.

---
Tags: google-play
---


title: How to freeze particle system?

text:
# Question
Title: How to freeze particle system?
I have set particle system of duration 5 seconds.

But, I wouldn't like particle system to repete but to be frozen in fourth second forever.

How to do that?

# Answer
You can do it with `Pause()` function of `ParticleSystem` class. Here is an example;

```
using UnityEngine;
using System.Collections;

public class ParticleController : MonoBehaviour {

    public ParticleSystem particles;

    // Update is called once per frame
    void Update () {
        //After 4 seconds, pause particles
        if(Time.timeSinceLevelLoad > 4f) {
            particles.Pause();
        }
    }
}

```

Check here for further information
> 2 votes

---
Tags: unity, particles
---


# Question
Title: Unity 2D - Tile based puzzle. Game Over logic doesn't work
I'm trying to create a clone of the popular mobile game 1010! However I am struggling to determine when the player can no longer make any moves and therefore it is game over. **Can you see any flaws in my logic?**

This is my Game Board - It's a 9x9 Grid which is stored as a 2dArray of transforms. The three shapes at the bottom are held in a 'ToolBox':

The shapes are just a Game Object which contain 1-5 child Game Objects which have a SpriteRenderer

My current Game Over logic loops through the Tool Box and for each shape it loops through the grid and sets the position to the grid\[x, y\] and then calls my IsValidPosition(Shape shape) method.

The IsValidPosition(Shape shape) gets each child transform of the shape and checks whether it is within the Game Board or if the position in the grid is currently occupied by another shape.

This is where the Game Over check starts:

```
void PlaceShape(Shape shape) {
    if (m_gameBoard.IsValidPosition (m_activeShape)) {
        m_gameBoard.StoreShapeInGrid (m_activeShape);
        m_activeShape.m_placed = true;
        m_toolBox.RemoveShape (m_activeShape);

        //When placed, set sorting layer to board so that sprites dont render over unplaced shapes, also set color back to solid.
        foreach (SpriteRenderer sprite in m_activeShape.GetComponentsInChildren <SpriteRenderer> ()) {
            sprite.sortingLayerName = "Board";
            sprite.color = m_activeShape.m_color;
        }

        //If we completed any lines then score them.
        if (m_gameBoard.m_completedLines > 0) {
            m_scoreManager.ScoreLines (m_gameBoard.m_completedLines);
        }

        if (IsGameOver ()) {
            Debug.Log ("GAME OVER");
            if (m_gameOverPanel) {
                m_gameOverPanel.SetActive (true);
            }
        }

        //Destroy game objects with no children.
        Cleanup ();
    } else {
        m_toolBox.PutShapeBack (shape);
    }
}

```

This is the method that loops through the shapes that are currently in the tool box:

```
bool IsGameOver() {
    foreach(Shape shape in m_toolBox.m_toolBox) {
        Debug.Log (shape.name);
        shape.m_fitsOnBoard = m_gameBoard.WillItFit (shape); //Tell shape if it fits on the board.
        shape.Reset ();
    }

    foreach (Shape shape in m_toolBox.m_toolBox) { //If at least 1 shape can fit on the board then it's not game over yet.
        if (shape.m_fitsOnBoard) {
            return false;
        }
    }
    return true;
}

```

The Game Board's WillItFit(Shape shape) method is then called for each shape in the tool box:

```
public bool WillItFit(Shape shape) {
    for (int y = 0; y < m_height; y++) {
        for (int x = 0; x < m_width; x++) {
            shape.transform.position = new Vector2 (x, y);
            if(IsValidPosition (shape)) {
                Debug.Log(shape.name + " fits at x: " + x + ", y: " + y);
                return true;
            }
        }
    }
    return false;
}

```

Then the IsValidPosition(Shape) method is called which subsequently calls the IsWithinBoard and IsOccupied methods:

```
bool IsWithinBoard(int x, int y) {
    return (x >= 0 && x < m_width && y >= 0 && y < m_height);
}

bool IsOccupied(int x, int y, Shape shape) {
    return (m_grid [x, y] != null && m_grid [x, y].parent != shape.transform);
}

public bool IsValidPosition(Shape shape) {

    foreach (Transform child in shape.transform) {
        Vector2 pos = Vectorf.Round (child.position);

        if (!IsWithinBoard ((int) pos.x, (int) pos.y)) {
            Debug.Log (shape.name + " position: " + pos + " IS NOT WITHIN THE BOARD");
            return false;
        }

        if(IsOccupied ((int) pos.x, (int) pos.y, shape)) {
            Debug.Log (" position: " + pos + " IS ALREADY OCCUPIED");
            return false;
        }
    }

    return true;
}

```

# Answer
Finally got to the bottom of this. The shapes that are stored in the toolbox are scaled down to 50% of the actual size. So when I was iterating through the tool box and moving all the shapes to every given position the child transforms of the shape game object weren't where they were supposed to be.

I figured this out by making the WillItFit(Shape shape) method a coroutine and making it wait 0.5s in between each loop so that I could see what was happening.

The fix was to set

```
shape.transform.localScale = Vector3.One;

```

in the first line of the WillItFit(Shape shape) method
> 0 votes

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


# Question
Title: How to make a vehicle sense and obey traffic lights in Unity?
I am creating a traffic simulator and I have my vehicle and traffic light system working. My vehicle stops when the traffic light turns red, but it stops wherever it currently is instead of in front of the light, even when specifying a `range`.

I am building this project in unity3d with C#. Below is a part of my code.

* `material1` is the red traffic light.
* `range` is the minimum specified distance between vehicle current position and traffic light location.

```
if(!(m.CM.color.Equals(material1.color)) && (Vector3.Distance(transform.position, TrafficLightPosition <= range) ))
{
    ApplySteer ();
    Drive (1);
    CheckWaypointDistance ();
    LerpToSteerAngle ();
}

```

I heard about this unity feature called OnTriggerEnter/Exit/Stay, can someone please tell me if this will work in the traffic lights context?

# Answer
You didn't specify a language/ engine, so I'll give a platform agnostic answer...

You could create a zone in front of the traffic light that says "stop here if the traffic light is red" to your vehicle when it is inside the zone, further vehicles approaching the traffic light will stop when they see that there is another car stopped directly in front of them.
> -1 votes

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


# Question
Title: Why do I get odd color effects in smooth transitions with OpenGL?
I am making a planet generator, and when I go too close to the planet, the smoothly colored surface has striations. Very visible striations, as seen in the attached image. The color transition is supposed to be completely smooth, set with a double precision floating point (which, AFAIK, is actually overkill), but no matter how I generate it, the striations appear. I understand that there are only so many nuances of grey or other colors to go around, but if I place a grey shade of 140 (in a 0-255 range) next to one with 141 in any graphics program (e.g. GIMP), they are indistinguishable, meaning there should be no striation, as they would 'melt together'. I checked polygon topology, that's not it (if I set the color nuances to rotate, the striations do not follow polygons at all). I've tried upping the color depth to 32 bit, with no change. I even tried manually casting the resulting values as 'float' for the glColor3f assignment! Nothing works, the striations remain! Is there a limit on the nuances OpenGL can give to colors? Can I remove that? Or is there another explanation?

# Answer
These are called Mach bands, they’re an optical illusion, commonly referred to as *banding*.

A simple technique to avoid banding is to use dithering (spatial or temporal, or both).

You can try with simple white noise dithering first: in your fragment shader, before outputting the final colour, add a small random number such as `(rand() - 0.5) / 255` to each of its components. If you do not have a random function available, you may try this one (just pass `gl_FragCoord.xy` as its argument).
> 2 votes

# Answer
Your image goes from RGB 0|0|0 to RGB 97|97|97, with the specific region you have highlighted going from RGB 19|19|19 to RGB 22|22|22 in increments of 1.

In other words, what you are seeing as banding is actually consecutive greyscale colours in increments of 1, but at the darker end of the range.

Measuring 140 next to 141 in an image program is not representative of the colour range you are using; you need to measure darker colours, in the 10s, 20s or 30s, to be able to do an equal comparison.

What you're seeing is just colour banding, caused by the fact that (and irrespective of how much precision you use internally) the final destination framebuffer is an 8|8|8|8 RGBX or RGBA format.

This is nothing to do with OpenGL and everything to do with your hardware.
> 1 votes

---
Tags: opengl, color
---


# Question
Title: Why Change from one coordinate system to another?
When dealing with affine transformations, why do we need to change from one frame to another? What are some reasons. What are the pros and cons of doing this and the limitations if this was not possible.(Change of Coordinate Transformations)

# Answer
> 1 votes
Here are 2 important ones. Let's assume we model a galaxy.

* We have a moon that rotates around its own axis and orbits a planet, which orbits a sun, which orbits the center of the galaxy. Here we use a coordinate system that has the moon as the origin, one that has the planet as the origin, one that has the sun as the origin, and one that has the galaxy as the origin.
* In the same example as above, consider floating point precision limits. Once we reach the outer edges of the galaxy, the resolution of a single precision floating point value will map all the 5000 vertices of the moon to a few dozen points, due to rounding errors on single precision floating point values, giving it a rather unfortunate shape.

# Answer
> 1 votes
The reason we change coordinate systems, is to simplify relationships between objects in a simulation or game.

For example: In computer graphics, we are only interested in where objects are, relative to the camera, or eye. Therefore, we need a coordinate system which describes the space according to the eye. We call this, a *view* transform.

This is all fine and well in Cartesian space, but sometimes we need to work in non Cartesian space, such as texture space (used for normal mapping), and being able to simplify moving from object space to texture space, or from world space to texture space, makes it a lot easier.

---
Tags: physics, linear-algebra
---


title: What is inertia in a physics engine?

text:
# Question
Title: What is inertia in a physics engine?
Inertia seems to be useful in a physics engine, so useful that even in Box2DLite, a demo of Box2D it hasn't been omitted.

See this Body class from Box2DLite:

```
struct Body
{
    Body();
    void Set(const Vec2& w, float m);

    void AddForce(const Vec2& f)
    {
        force += f;
    }

    Vec2 position;
    float rotation;

    Vec2 velocity;
    float angularVelocity;

    Vec2 force;
    float torque;

    Vec2 width;

    float friction;
    float mass, invMass;
    float I, invI; //inertia and reverse inertia
};

```

In the implementation of the class, inertia is set as the mass multipled by something:

```
I = mass * (width.x * width.x + width.y * width.y) / 12.0f;
invI = 1.0f / I;

```

What does this formula means ? I understood from wikipedia that Inertia is how much something doesn't want to move but there's not much formulas in this article. Why is it useful in a physics engine ? How is it used in the context of a collision ? Is it compared to other bodies ?

# Answer
> 4 votes
I believe what we're looking at here more specifically refers to **rotational** inertia and inverse **rotational** inertia; not to linear inertia (nor inverse linear inertia).

Wikipedia explains that **rotational inertia** is *also known as* the **moment of inertia**. From here you can take a look at Wikipedia's List of Moment of Inertia where the constant integer 12, shows up in a few of the formulas like for the rotational inertia of rectangular plate about its center.

**Rotational inertia** is useful in the context of simulating a collision in providing a measure to which the object should resist rotation in collisions that have a tangential component. In other words, it provides a measure of how much rotational velocity should be changed due to collisions that can be thought of as bumping up and rubbing against another body.

# Answer
> 0 votes
Inertia is a body's resistance to changes in angular velocity(rotational speed).

Inertia, in game engines is usually fudged a little, but is represented as a 3x3 matrix transform.

that transform is used to change an angular impulse (final angular deltaV = inertia * deltaV). In the case I just outlined, this is actually the inverse inertia transform, or inertia^-1

When you do this it is the same as dividing a linear impulse by the mass of the body.

In your case, using the contact point, you compute the torque (force to induce change in velocity around an axis), and transform it with the inverse inertia, which produces the final change in angular velocity.

---
Tags: box2d, physics-engine
---


title: Game search engine in a p2p format

text:
# Question
Title: Game search engine in a p2p format
I am currently using Java to develop a multiplayer game engine. However, I am stuck on one thing. Many games (Overwatch, DotA) have automatic game search engines - you click a button and the computer automatically finds you a game. My first thought to replicate this was to have a server that every computer running the game would connect to, then would find groups of, say, in a 3v3 team game, 6, start a new room with those 6, and run the game. However, there is one major problem here: I am only 14 and am nowhere NEAR being able to afford a server farm that would be necessary. Since I cannot afford this, a single server running the game would be out of the question, so I've been looking into the p2p (peer-to-peer) format. The problem is, I cannot think of a way to have an automatic game search engine in a p2p format without a host server. Is there any way that I can replicate this with a p2p format?

# Answer
First of all, there is no way to do this 100% peer to peer, as cozmic pointed out. You need some kind of third party that establishes the connection between the clients. Bittorrent uses tracker servers for this for example.

There are however a couple of free solutions that you could use, in order for your clients to discover other clients.

First of all, there is Heroku on which you can host small programs (like your own java connection server). I don't think it would be enough to host the entire game server on it, but as long as it just establishes the connection between the clients, and one of your clients is the host (p2p) it should work fine. Heroku provides 550 hours per month for free, which amounts to about 18 hours per day, so your game wouldn't work 24/7. Fortunately you can increase this to be basically 100% of the time, by adding a credit card. It **won't** charge you anything, it just needs this so it can verify that you don't abuse the service.

The second option would be to use something like Firebase-Database, and have the clients enter their connection details (IP address) into the database.

Finally, you can check your router settings, if you can open ports, you can host this server on your computer. You would just have to use some dyndns service, that resolves a domain, to your IP address since most residential providers change your IP address every now and then.

To actually establish the connection, you might want to use a protocol like STUN and if that fails TURN. There are a lot of free stun servers out there, like these.
> 0 votes

# Answer
Peer to peer matchmaking is always done via a third party server:

When a game is created, a message is sent to the matchmaking server informing it that a game with \< max players is available.

when a player is added to the game, the matchmaking server is updated. if the max players is reached, another notification is sent, which removes the game from the list of available games.

If a player drops out, the server is again notified, allowing the game to be re-advertised.

When the game is destroyed (finished or cancelled), the server will again remove it from the list of available games.

Clients can, in turn, connect to the matchmaking server to find IP addresses of available games, when the player selects a game, the server sends that IP address on a first come, first served basis, and the client then connects directly, and the game begins.
> 0 votes

# Answer
I haven't yet programmed anything network-related myself, but when reading this question I had the following idea:

First off, I can't think of any way to achieve this without any kind of server. Think about it, how should one client of your game know about any other client in the world if there is no server connecting them or if the user doesn't give it any address to connect to. I can't imagine that there would be a way this could work.

The idea that I head however consists of a small server, that is responsible for connecting clients only and then let the clients establish a connection between each other themselves. This way as much work as possible is done by the client and all the server effectively does, is to send a client an address to connect to.

The server would be really inexpensive then.

One thing to consider with this is, that you would need to take great care about the protection of user data when sending it to clients to connect to.
> -1 votes

---
Tags: java, multiplayer, peer-to-peer
---


# Question
Title: Why are examples of game textures often represented on a sphere model?
I have recently started working with Unity and was looking for textures for the background (castle walls and such pieces) on a game that I am thinking about eventually building. I noticed that the textures are often represented as ball shaped, such as for example in this sample image here:

For example, why are the texture patterns not shown as simply flat squares? I guess there is a reason behind this that has to do with mapping to 3d surfaces but I was not sure so I wanted to check here.

Why are textures often represented in spherical shapes in examples and previews?

# Answer
> 81 votes
Because these are not textures. Textures should really be displayed as simple images, exactly as you suggest.

These are called materials, which are the texture, a shader, and a whole mess of other inputs such as a normal map.

These materials react differently based on the direction and intensity of light, so you need different angles and a directional light to get an impression of what the material looks like. Spheres do this better than other trivial shapes.

An example where this is useful (notice the massive difference in the specular highlight):

A possible reason to display simple textures as materials is if you want to show what the textures look like, without actually providing the textures. This is useful if you want people to pay for the textures.

# Answer
> 12 votes
Spheres are a reasonable combination of various factors.

They're simple enough to generate and draw that they aren't going to cause a significant performance impact when rendering many of them, but they not *so* simple as to eliminate all complexity from the model. This lets them suggest how the visual elements being previewed (textures, as you asked about, but also shaders) interact with non-planar surfaces and in a variety of orientations relative to the view and to light sources. In particular this can be useful for previewing anything with a reflective component; a sphere will have normals in effectively every direction.

Often one can switch the model being used as a preview: cubes and tori are also common, depending on the tool. But spheres have become the de facto standard since they work *pretty well* in *most* cases.

# Answer
> 1 votes
Spheres provide the ability to view a material, normal and parallax mapped, from many different angles at a glance, which is good for a consumer to see the quality, and viability of the material.

Cubes are far less viable for this, as they only show a limited number of possible viewing angles, and are always flat surfaces. Spheres on the other hand, are curved surfaces, which, in a "real" game, are something you probably want to see(think changing exterior terrain, instead of an interior corridor).

---
Tags: textures
---


# Question
Title: unity, socketio, nodejs. amount of messages sent is multiplied by amount of NPcs that have ever spawned
I am building a 2d top down multiplayer mmo. very lightweight.

***a note on architecture***

I am using Unity as an engine, I have a backend Nodejs/socket.io websockets server. and a main Master client that defines what target monsters have, where people and NPCs are positioned in the world and who gets hit by projectiles etc so everyone is in agreement. Thing seem to be working pretty well. But I have thing weird problem where if I have 1 monster it works perfectly. However as I add more monsters to the game messages like for example (Enemy is moving) Get transmitted in the command promt as many times as there are monsters. Whats worse, if I delete those monsters through code (see below) the server still sends messages based on the amount of monsters that ever existed. until I restart the master client and normal client and start over. at which point itll reset everything.

I have been going over my code a great deal and cannot find the problem really. and could use a little help.

**server code**

```
    // Section for Enemy logic from Master Client

   socket.on('enemyRegister', function(data){

        // builds a monster on the client

   socket.broadcast.emit('enemyRegister', data);

    socket.on('enemyMove', function(data){

        // moves the monster that matches the given ID

        console.log('enemy is moving', data);

    socket.broadcast.emit('enemyMove', data);

    });

    socket.on('enemyStopMove', function(data){

        // stops the monster that matches the given ID

        console.log('enemy stopped moving', data);

    socket.broadcast.emit('enemyStopMove', data);

    });

    socket.on('enemyTarget', function(data){

    // feeds a 'target' data string to the monster that matches the given ID

    console.log('setting target', data);

    socket.broadcast.emit('enemyTarget', data);

});

    socket.on('enemyLoseTarget', function(data){

    // remove a 'target' data string to the monster that matches the given ID

    console.log('removing target', data);

    socket.broadcast.emit('enemyLoseTarget', data);

});

    socket.on('enemyShoot', function(data){

     // Plays 'shoot' animation on the monster that matches the given ID

    console.log('shooting on', data);

    socket.broadcast.emit('enemyShoot', data);

});

    socket.on('enemyMelee', function(data){

     // Plays 'hit' animation on the monster that matches the given ID

    console.log('melee hit on', data);

    socket.broadcast.emit('enemyMelee', data);

});

    socket.on('hitPlayer', function(data){

     // Send damage information
        var something = players[data.playerId];

        console.log('sending info to ', something.socketID);

    socket.broadcast.to(something.socketID).emit('hitPlayer', data);
});

    socket.on('deleteAllEnemies', function(data){

     // Deletes All enemies

    console.log('deleting all enemies');

    socket.broadcast.emit('deleteAllEnemies');

});

    });

```

**Master client enemy creation**

```
    void Update () {

        if (Input.GetKeyDown("i"))
        {
            CreateMonster();
        }

    if (Input.GetKeyDown("o"))
    {
        foreach(KeyValuePair<string, Vector3> enemy in spawnedEnemies)
        {
            var thisEnemy = GameObject.Find(enemy.Key);
            Destroy(thisEnemy);

        }
        spawnedEnemies.Clear();
        mobNumber = 0;
        socket.Emit("deleteAllEnemies");

    }
}

void CreateMonster()
{
    var selectedSpawnPoint = spawnPoints[Random.Range(0, spawnPoints.Length)];  // create a variable,

    selectedSpawnPoint.transform.position = new Vector3(Random.Range(0, 10), Random.Range(0,10), 0);

    var spawnedEnemy = Instantiate(Enemy[Random.Range(0, Enemy.Length)], selectedSpawnPoint.transform.position, selectedSpawnPoint.transform.rotation);

    spawnedEnemy.name = "enemy " + mobNumber;
    mobNumber++;

    spawnedEnemies.Add(spawnedEnemy.name, spawnedEnemy.transform.position);

    numberOfMonsters = spawnedEnemies.Count;

    socket.Emit("enemyRegister", Network.MobIdAndLocationToJson(spawnedEnemy.name, spawnedEnemy.transform.position));
}

```

}

**normal client enemy spawning code**

```
    public void SpawnEnemy(SocketIOEvent e)
{
        var id = e.data["id"].str;
        var spawnPosition = new Vector3(e.data["x"].n, e.data["y"].n, 0);
        var enemy = Instantiate(orcShaman, spawnPosition, Quaternion.identity) as GameObject;

        enemy.name = id;
        enemies.Add(id, enemy);
}

```

**code for deleting all enemies on client**

```
    public void DeleteAll() // TODO Delete Before Launch
{
    foreach (KeyValuePair<string, GameObject> enemy in enemies)
    {
        var thisEnemy = GameObject.Find(enemy.Key);
        Destroy(thisEnemy);
    }
    enemies.Clear();
}

```

Any guidance or a push in the right direction would be greatly appreciated im at a loss as to what the issue could be. The server does not store an array of the monsters, only the master client does and the normal client do that. so I dont understand how the server is trying to send information for each monster that has been created. specially when the actions acctually come out correct in game.

thank you for reading.

# Answer
Figured out the problem:

it was a remnant from a previous build in which I was trying to store all enemy data in variables and was not closing the registration of enemies properly:

**changed**

```
       socket.on('enemyRegister', function(data){

        // builds a monster on the client

   socket.broadcast.emit('enemyRegister', data);

```

**to**

```
       socket.on('enemyRegister', function(data){

        // builds a monster on the client

   socket.broadcast.emit('enemyRegister', data);

});

```

and its fixed. Silly mistake but maybe it could help someone some day.
> 2 votes

---
Tags: unity, node.js, socket
---


# Question
Title: Copy location/rotation information in Unity
I place a cube in my level (scaled along one axis) and start doing something else.

Then I place another cube, but want to copy and paste the location and rotation data from the first cube onto this new one.

So far I'm doing that by copying & pasting 6 numbers one by one. Is there a faster way to clone the location/rotation of an object (eg. with a single key press)?

# Answer
> 3 votes
In editor: Select your first game object by clicking on it. Then right click the transform of the first object and click "Copy Component". Then select the other game object, right click its transform and click "Paste Component Values".

Edit: I made you a gif!

---
Tags: unity, transformation
---


# Question
Title: unity: how to make instantiated gameobject to have rectTransform of the canvas? (c#)
```
public GameObject canvas;  // the canvas

GameObject changerSign = Instantiate(changerPopup,
    new Vector3(235, 350, 0),
    this.transform.rotation);
changerSign.transform.SetParent(canvas.transform);

```

this will make a UI at the screen. while it does make the object as wanted, the rect transform won't get fixed(?) to the newly set parent(the Canvas), but instead to where it was first made. how could I get it under canvas's rect transform? could be some too basic question, but couldn't find any answer anywhere so far :(

# Answer
for childing there are two Parameter in `Setparent`:

> **parent :** The parent Transform to use.
>
> **worldPositionStays:** If true, the parent-relative position, scale and rotation are modified such that the object keeps the same world space position, rotation and scale as before.https://docs.unity3d.com/ScriptReference/Transform.SetParent.html

```
using UnityEngine;
using System.Collections;

public class NewBehaviourScript : MonoBehaviour {
    public GameObject canvas;  // the canvas
    public GameObject changerPopup; // the UI prefab

    void Start () {
        GameObject changerSign = Instantiate(changerPopup,Vector2.zero,Quaternion.identity);//it's better that you change transform.rotatoin to Quaternion.identity

        //here you need to childing your Instantiated prefab to canvas
        //there are two way of doing it:

        //1.child it without adapting with canvas(worldPositionStays = true , this is mean keep Previous position, rotation, scale)
        //If true, the parent-relative position, scale and rotation are modified such that the object keeps the same world space position, rotation and scale as before.
        changerSign.transform.SetParent(canvas.transform, true);
        //equivalent:
        changerSign.transform.parent = canvas.transform;

        //2.child it with adapting with canvas(worldPositionStays = false , this is mean set Previous position)

        changerSign.transform.SetParent(canvas.transform,false);
        //equivalent1:
        changerSign.transform.SetParent(canvas.transform,canvas.transform.parent);
        //equivalent2:
        //first child it by using first way , next adapt it with canvas
        changerSign.transform.parent = canvas.transform;
        RectTransform rt = changerSign.GetComponent<RectTransform>();
        rt.anchoredPosition = rt.transform.position;// or use this rt.localPosition = rt.transform.position;

        //next you can set position by localPosition :
        rt.localPosition = new Vector2(50,50);
        }
    }

```

for more information there is useful discuss here

---

you should use `localPosition` instead of `position` in canvas...what is difference?

```
position        The position of the transform in world space.
localPosition   Position of the transform relative to the parent transform.

```

http://unity3d.com/support/documentation/ScriptReference/Transform.html

---

Note:If you want set position for your prefab in canvas ,I prefer instead of calculating suitable position by `new Vector(x,y)`, it's better to use built-in RectTransform's AnchorPositions

but how to access RectTransform's left, right, top, bottom positions via code?

```
using UnityEngine;
using System.Collections;

public class RectAnchors : MonoBehaviour {
    public GameObject canvas;  // the canvas
    public GameObject changerPopup; // the UI prefab

    public enum SetRect{Center,Left,Right,Top,Bottom,LB,RB,LT,RT}
    public SetRect setrect;

    void Start () {
        GameObject changerSign = Instantiate(changerPopup,
            Vector2.zero,
            Quaternion.identity);

        changerSign.transform.parent = canvas.transform;
        RectTransform rt = changerSign.GetComponent<RectTransform>();
        float left   =  rt.offsetMin.x + 100;
        float right  = -rt.offsetMax.x;
        float top    = -rt.offsetMax.y;
        float bottom =  rt.offsetMin.y + 100;

        switch(setrect){
        case SetRect.Center: rt.anchoredPosition = new Vector3 (0, 0);
            break;
        case SetRect.Bottom: rt.anchoredPosition = new Vector3 (0, bottom);
            break;
        case SetRect.Left: rt.anchoredPosition = new Vector3 (left, 0);
            break;
        case SetRect.Right: rt.anchoredPosition = new Vector3 (right, 0);
            break;
        case SetRect.Top:
            rt.anchoredPosition = new Vector3 (0, top);
            break;
        case SetRect.LB: rt.anchoredPosition = new Vector3 (left, bottom);
            break;
        case SetRect.RB: rt.anchoredPosition = new Vector3 (right, bottom);
            break;
        case SetRect.LT: rt.anchoredPosition = new Vector3 (left, top);
            break;
        case SetRect.RT:
            rt.anchoredPosition = new Vector3 (right, top);
            break;
        }
    }
}

```
> 1 votes

# Answer
well i feel silly after knowing this :P

have to specify the parent for the rect transform too.

```
changerSign.GetComponent<RectTransform>().parent = canvas.GetComponent<RectTransform>();

```

adding this works.

edit: problem wasn't these, but instead was the fact I was supposed to use transform.localPosition. I don't understand why despite the fact it's a child of a canvas, but it's solved. Thanks to everyone answered trying to help me.
> 0 votes

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


# Question
Title: How can I enhance this keyboard handler class (remove global variables)
I would like to enhance my keyboard class to be more tight and encapsulated. The first issue I've addressed is **Singleton** design pattern. I've done this as follows:

```
/*** inside keyboard.h ***/
class Keyboard
{
public:
    static Keyboard* Instance(){
        if(s_pInstance == NULL)
            s_pInstance = new Keyboard;
        return s_pInstance;
    }
    ...
private:
    static Keyboard* s_pInstance;
    Keyboard() {}
    ...
};

/*** inside keyboard.cpp ***/
#include "keyboard.h"

Keyboard* Keyboard::s_pInstance = NULL;
...

```

The design pattern works just fine. Now in `while(true)` I can do

```
while(Window is Open){
...
    if ( Keyboard::Instance()->isKeyDown() ){
        if ( Keyboard::Instance()->m_key == GLFW_KEY_E )
            std::cout << "E is pressed ..." << std::endl;
    }
...
}

```

In GLFW, I have to declare `key_callback` as static member function. To store keyboard actions, I've introduced global variables and every time I call any Keyboard function, I need to update those global variables as follows:

```
bool Keyboard::isKeyDown()
{
    // assign global variables to data members
    update(g_key, g_scancode, g_action, g_mode);

    if( m_action == GLFW_PRESS ){
        std::cout << "Key down..." << std::endl;
        ...
        // reset global variables
        m_action = -1;
        g_action = -1;
        return true;
    }

    return false;
}

void Keyboard::update(int k, int s, int a, int m)
{
    m_key      = k;
    m_scancode = s;
    m_action   = a;
    m_mode     = m;
}

```

The code works but I don't believe this is the right way to encapsulate my class. Any suggestion how to remove these global variables which is a consequence due to using static function?

This is the full code

```
#ifndef _KEYBOARD_H
#define _KEYBOARD_H

#include <GLFW/glfw3.h>

class Keyboard
{
public:

    static Keyboard* Instance(){
        if(s_pInstance == NULL)
            s_pInstance = new Keyboard;
        return s_pInstance;
    }
    void init(GLFWwindow* window);
    void update();
    bool isKeyDown();
    bool isKeyUp();

    int m_key, m_scancode, m_action, m_mode;
private:
    static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode);

    GLFWwindow* m_pWindow;
    Keyboard() {}
    static Keyboard* s_pInstance;
    bool keys[1024];

    void update(int, int, int, int);

};

#endif

```

`keyboard.cpp` is

```
#include "keyboard.h"
#include <iostream>

Keyboard* Keyboard::s_pInstance = NULL;

int g_key, g_scancode, g_action, g_mode;

void Keyboard::init(GLFWwindow* window)
{
    m_pWindow = window;
    glfwSetKeyCallback(window, key_callback);
}

void Keyboard::key_callback(GLFWwindow* window, int key, int scancode, int action, int mode)
{
    g_key      = key;
    g_scancode = scancode;
    g_action   = action;
    g_mode     = mode;
}

bool Keyboard::isKeyDown()
{
    update(g_key, g_scancode, g_action, g_mode);

    if( m_action == GLFW_PRESS ){
        std::cout << "Key down..." << std::endl;
        keys[m_key] = true;

        m_action = -1;
        g_action = -1;
        return true;
    }

    return false;
}

bool Keyboard::isKeyUp()
{
    update(g_key, g_scancode, g_action, g_mode);

    if( m_action == GLFW_RELEASE ){
        std::cout << "Key up..." << std::endl;
        keys[m_key] = false;

        m_action = -1;
        g_action = -1;
        return true;
    }

    return false;
}

void Keyboard::update(int k, int s, int a, int m)
{
    m_key      = k;
    m_scancode = s;
    m_action   = a;
    m_mode     = m;
}

```

# Answer
In your `key_callback()` function, you can get the `Keyboard` singleton and directly set its `m_key`, `m_scancode`, `m_action` and `m_mode` member variables. Something like this:

```
void Keyboard::key_callback(GLFWwindow* window, int key, int scancode, int action, int mode)
{
    Keyboard::instance->update(key, scan code, action, mode);
}

```
> 1 votes

---
Tags: c++, keyboard, glfw
---


# Question
Title: Way to deserialized or load last save state scene with GameObject and other classes instead of storing normal fields via binary format?
I humbly ask for help in order to solve this problem. I successfully take a quick guide to learn more about save and load state of the game. Basically first, I know how to use `PlayerPrefs`to store basic string, int, and float.

Now, looking for a more effective way to store saved files via serialization. At first, after my first few researches online, I watch some video tutorial and only provides storing basic fields (int, string, bool, float, etc.) and saved in a created file. I attempt to try it on classes but didn't worked unless I marked as `[Serializable]`.

Next, trying to save Gameobject created, prefabs or not, didn't work and it requires to serialize that class itself that is "GameObject". I took first attempt using this guide from *StackOverflow* with the accepted answer, I do understand and saving a GameObject or other custom classes require to store it and converted into .xml file.

Here's my two main problem need to resolve. the first one is that the runtime returned `NullPointerException` after I ensured all of the necessary objects are created as new. The error stopped at this line (ask for more code source if you need):

```
            DataContractSerializer ds = new DataContractSerializer (data2.GetType ()); // --> Serialize to .xml file.
            MemoryStream stream = new MemoryStream();

            ds.WriteObject (stream, data2); // --> The error stops here.
            stream.Seek (0, SeekOrigin.Begin);
            file.Write (stream.GetBuffer (), 0, stream.GetBuffer ().Length);
            file.Close();

```

As you can see, this is the part of the code where you can save and stored in a file created on a persistent file directory for the stored classes such as GameObject, List, and/or other custom classes.

The second problem will be tackled after the first problem is resolved. The second problem involves loading last state saved. For the normal fields such as integer or string, using `BinaryFormatter` and `FileStream` works well to load stored values form a file created last time. I tried that on stored custom classes such as `GameObject` but it required a different method like this one but it is a bit hard to understand how to translate it in Unity and still observe some ways to work it out, the best way to load stored classes from a file.

**UPDATE 1 (as of 5/22/2017)** As requested by @DMGregory, here is the class I'm trying to deserialize a class that contains the following fields inside.

```
[DataContract]
public class TreeData2 {

    // - - - Spouse - - -
    [DataMember] private List<GameObject> _masters;

    public List<GameObject> masters {

        get { return _masters; }
        set { _masters = value; }

    }

    [DataMember] private List<GameObject> _targets;

    public List<GameObject> targets {

        get { return _targets; }
        set { _targets = value; }

    }

    [DataMember] private List<FamilyDatabase> _familyGroup;

    public List<FamilyDatabase> familyGroup {

        get { return _familyGroup; }
        set { _familyGroup = value; }

    }

    [DataMember] private GameObject _node;

    public GameObject node {

        get { return _node; }
        set { _node = value; }

    }

    [DataMember] private List<string> _mothers;

    public List<string> mothers {

        get { return _mothers; }
        set { _mothers = value; }

    }

    [DataMember] private List<string> _fathers;

    public List<string> fathers {

        get { return _fathers; }
        set { _fathers = value; }

    }

    [DataMember] private List<GenerationDatabase> _genDb;

    public List<GenerationDatabase> genDb {

        get { return _genDb; }
        set { _genDb = value; }

    }

    // - - - Root Action - - -
    [DataMember] private List<GameObject> _child;

    public List<GameObject> child {

        get { return _child; }
        set { _child = value; }

    }

    // Gen Database (Main)
    [DataMember] private List<string> _mothersDB;

    public List<string> mothersDB {

        get { return _mothersDB; }
        set { _mothersDB = value; }

    }

    [DataMember] private List<string> _fathersDB;

    public List<string> fathersDB {

        get { return _fathersDB; }
        set { _fathersDB = value; }

    }

    [DataMember] private List<GameObject> _mastersDB;

    public List<GameObject> mastersDB {

        get { return _mastersDB; }
        set { _mastersDB = value; }

    }

    [DataMember] private List<GameObject> _targetsDB;

    public List<GameObject> targetsDB {

        get { return _targetsDB; }
        set { _targetsDB = value; }

    }

    [DataMember] private List<string> _mothersT;

    public List<string> mothersT {

        get { return _mothersT; }
        set { _mothersT = value; }

    }

    [DataMember] private List<string> _fathersT;

    public List<string> fathersT {

        get { return _fathersT; }
        set { _fathersT = value; }

    }

    [DataMember] private List<GameObject> _mastersT;

    public List<GameObject> mastersT {

        get { return _mastersT; }
        set { _mastersT = value; }

    }

    [DataMember] private List<GameObject> _targetsT;

    public List<GameObject> targetsT {

        get { return _targetsT; }
        set { _targetsT = value; }

    }

}

```

`data2` is the variable name of the `TreeData2` class and yes I'm making a family tree like structure via *Unity* for the game that shows progress of unlocking and storing lists of the branches. Here's the recap with the mentioned variable name.

```
            FileStream file = File.Create (Application.persistentDataPath + "/check/treeData2.dat");
            TreeData2 data2 = new TreeData2();

            . . .

            DataContractSerializer ds = new DataContractSerializer (data2.GetType ()); // --> Error stops here. Returns NullPointerException due to failed in parsing in .xml file in storing GameObject classes and List<T>.
            MemoryStream stream = new MemoryStream();

            ds.WriteObject (stream, data2);
            stream.Seek (0, SeekOrigin.Begin);
            file.Write (stream.GetBuffer (), 0, stream.GetBuffer ().Length);
            file.Close();

            string result = XElement.Parse(Encoding.ASCII.GetString(stream.GetBuffer()).Replace("\0", "")).ToString();

            print ("SAVE TREE COMPLETE");
            print ("Result: " + result);

```

# Answer
Unfortunately, after several experiments to find the easy way to store `GameObjects` effectively without hassle, there is no shortcut in preserving files + game objects during save and load state. I decided to give up for banging my head too hard to go crazy in making expectations on saving scene in one go. There are many steps to understand it.

Right now, storing info on each game object's specified sections/components require complex serializable classes, a meticulous way for sharing and retrieving each part of data. Explanation on this link and for more effective way in preserving data (but still not on game object) via formatting into JSON file.

It is a wise choice to make a better roadmap for tracking last state from scratch if you want to make your own save/load state for both common variables, serializable classes, and game object.

**UPDATE:**

However, there is another way to save and load `GameObject` using this solution found on this Unity Q&A section. It discusses about "**SerializerHelper**" that lets you serialize not only serialized classes but also game objects, scenes and other non-serializable classes. Check this forum as well in order to understand how it works. You can try this Unity package to try out saving/loading GO here to download. (Requires to register Dropbox account if needed.)
> 1 votes

---
Tags: unity, savegame, file-format, xml, serialization
---