# Question
Title: How to FIX Phaser Idle Clicker Game Images?
I'm new in game development Phaser.. I'm trying out a code tutorial for a clicker game I browsed from Zenva and did a few adjustments with the images (along with the codes) but I can't help to notice that the monsters' images are all showing up and compiled to each other at the center of the canvas, while in the tutorial I saw, it should be one monster and each time you kill it by clicking, a different monster shows up.

```
var game = new Phaser.Game(800, 600, Phaser.AUTO, '');

game.state.add('play', {
preload: function() {
    this.game.load.image("preloadBackground","assets/misc/BackgroundPreload.png");

    this.game.load.image("amphisbaena", "assets/monsters/Amphisbaena.png");
    this.game.load.image("baba_yaga", "assets/monsters/Baba Yaga.png");
    this.game.load.image("banshee", "assets/monsters/Banshee.png");
    this.game.load.image("centaur", "assets/monsters/Centaur.png");
    this.game.load.image("cerberus", "assets/monsters/Cerberus.png");
    this.game.load.image("chimera", "assets/monsters/Chimera.png");
    this.game.load.image("chinese_dragon", "assets/monsters/Chinese Dragon.png");
    this.game.load.image("chupacabra", "assets/monsters/Chupacabra.png");
    this.game.load.image("european_dragon", "assets/monsters/European Dragon.png");
    this.game.load.image("frost_giant", "assets/monsters/Frost Giant.png");
    this.game.load.image("gargoyle", "assets/monsters/Gargoyle.png");
    this.game.load.image("griffin", "assets/monsters/Griffin.png");
    this.game.load.image("harpy", "assets/monsters/Harpy.png");
    this.game.load.image("hydra", "assets/monsters/Hydra.png");
    this.game.load.image("ifrit", "assets/monsters/Ifrit.png");
    this.game.load.image("krakken", "assets/monsters/Krakken.png");
    this.game.load.image("medusa", "assets/monsters/Medusa.png");
    this.game.load.image("mermaid", "assets/monsters/Mermaid.png");
    this.game.load.image("minotaur", "assets/monsters/Minotaur.png");
    this.game.load.image("santelmo", "assets/monsters/Santelmo.png");
    this.game.load.image("slime", "assets/monsters/Slime.png");
    this.game.load.image("sphinx", "assets/monsters/Sphinx.png");
    this.game.load.image("twrch_tryth", "assets/monsters/Twrch Tryth.png");
    this.game.load.image("wyvern", "assets/monsters/Wyvern.png");

    this.game.load.image('gold_coin', 'assets/misc/coin.png');
    this.game.load.image('health_img', 'assets/misc/Monster Health.png');

    this.game.load.image('dagger', 'assets/496_RPG_icons/W_Dagger002.png');
    this.game.load.image('swordIcon1', 'assets/496_RPG_icons/S_Sword15.png');

},
create: function() {
    var state = this;

    var background = this.game.add.image(game.world.X, game.world.Y, 'preloadBackground');
    var gcLogo = this.game.add.image(44, 28, 'gold_coin');
    var mon_healthLogo = this.game.add.image(28, 474, 'health_img');

    });

    var monsterData = [
        {name: 'Amphisbaena',       image: 'amphisbaena',       maxHealth: 5},
        {name: 'Baba Yaga',         image: 'baba_yaga',         maxHealth: 10},
        {name: 'Banshee',           image: 'banshee',           maxHealth: 10},
        {name: 'Centaur',           image: 'centaur',           maxHealth: 10},
        {name: 'Cerberus',          image: 'cerberus',          maxHealth: 10},
        {name: 'Chimera',           image: 'chimera',           maxHealth: 25},
        {name: 'Chinese Dragon',    image: 'chinese_dragon',    maxHealth: 40},
        {name: 'Chupacabra',        image: 'chupacabra',        maxHealth: 5},
        {name: 'European Dragon',   image: 'european_dragon',   maxHealth: 40},
        {name: 'Frost Giant',       image: 'frost_giant',       maxHealth: 30},
        {name: 'Gargoyle',          image: 'gargoyle',          maxHealth: 20},
        {name: 'Griffin',           image: 'griffin',           maxHealth: 20},
        {name: 'Harpy',             image: 'harpy',             maxHealth: 15},
        {name: 'Hydra',             image: 'hydra',             maxHealth: 20},
        {name: 'Ifrit',             image: 'ifrit',             maxHealth: 50},
        {name: 'Krakken',           image: 'krakken',           maxHealth: 40},
        {name: 'Medusa',            image: 'medusa',            maxHealth: 35},
        {name: 'Mermaid',           image: 'mermaid',           maxHealth: 15},
        {name: 'Minotaur',          image: 'minotaur',          maxHealth: 30},
        {name: 'Santelmo',          image: 'santelmo',          maxHealth: 5},
        {name: 'Slime',             image: 'slime',             maxHealth: 5},
        {name: 'Sphinx',            image: 'sphinx',            maxHealth: 15},
        {name: 'Twrch Tryth',       image: 'twrch_tryth',       maxHealth: 15},
        {name: 'Wyvern',            image: 'wyvern',            maxHealth: 20}
    ];
    this.monsters = this.game.add.group();

    var monster;
    monsterData.forEach(function(data) {
        // create a sprite for them off screen
        monster = state.monsters.create(state.game.world.centerX, state.game.world.centerY, data.image);
        // use the built in health component
        monster.health = monster.maxHealth = data.maxHealth;
        // center anchor
        monster.anchor.setTo(0.5);
        // reference to the database
        monster.details = data;

        //enable input so we can click it!
        monster.inputEnabled = true;
        monster.events.onInputDown.add(state.onClickMonster, state);

        // hook into health and lifecycle events
        monster.events.onKilled.add(state.onKilledMonster, state);
        monster.events.onRevived.add(state.onRevivedMonster, state);
    });

    // display the monster front and center
    this.currentMonster = this.monsters.getRandom();
    this.currentMonster.position.set(this.game.world.centerX, this.game.world.centerY);

    this.monsterInfoUI = this.game.add.group();
    this.monsterInfoUI.position.setTo(this.currentMonster.x - 240, this.currentMonster.y + 180);
    this.monsterNameText = this.monsterInfoUI.addChild(this.game.add.text(0, 0, this.currentMonster.details.name, {
        font: '38px Arial Black',
        fill: '#fff',
        strokeThickness: 4
    }));
    this.monsterHealthText = this.monsterInfoUI.addChild(this.game.add.text(0, 50, this.currentMonster.health + ' HP', {
        font: '32px Arial Black',
        fill: '#ff0000',
        strokeThickness: 4
    }));

onDPS: function() {
    if (this.player.dps > 0) {
        if (this.currentMonster && this.currentMonster.alive) {
            var dmg = this.player.dps / 10;
            this.currentMonster.damage(dmg);
            // update the health text
            this.monsterHealthText.text = this.currentMonster.alive ? Math.round(this.currentMonster.health) + ' HP' : 'DEAD';
        }
    }
},
onKilledMonster: function(monster) {
    // move the monster off screen again
    monster.position.set(this.game.world.centerX, this.game.world.centerY);

    var coin;
    // spawn a coin on the ground
    coin = this.coins.getFirstExists(false);
    coin.reset(this.game.world.centerX + this.game.rnd.integerInRange(-100, 100), this.game.world.centerY + 75);
    coin.goldValue = Math.round(this.level * 1.33);
    this.game.time.events.add(Phaser.Timer.SECOND * 3, this.onClickCoin, this, coin);

    this.levelKills++;

    if (this.levelKills >= this.levelKillsRequired) {
        this.level++;
        this.levelKills = 0;
    }

    this.levelText.text = 'Level: ' + this.level;
    this.levelKillsText.text = 'Kills: ' + this.levelKills + '/' + this.levelKillsRequired;

    // pick a new monster
    this.currentMonster = this.monsters.getRandom();
    // upgrade the monster based on level
    this.currentMonster.maxHealth = Math.ceil(this.currentMonster.details.maxHealth + ((this.level - 1) * 10.6));
    // make sure they are fully healed
    this.currentMonster.revive(this.currentMonster.maxHealth);
},
onRevivedMonster: function(monster) {
    monster.position.set(this.game.world.centerX, this.game.world.centerY);
    // update the text display
    this.monsterNameText.text = monster.details.name;
    this.monsterHealthText.text = monster.health + 'HP';
},
onClickMonster: function(monster, pointer) {
    // apply click damage to monster
    this.currentMonster.damage(this.player.clickDmg);

    // grab a damage text from the pool to display what happened
    var dmgText = this.dmgTextPool.getFirstExists(false);
    if (dmgText) {
        dmgText.text = this.player.clickDmg;
        dmgText.reset(pointer.positionDown.x, pointer.positionDown.y);
        dmgText.alpha = 1;
        dmgText.tween.start();
    }

    // update the health text
    this.monsterHealthText.text = this.currentMonster.alive ? this.currentMonster.health + ' HP' : 'DEAD';
}
});

game.state.start('play');
```

I removed a few codes to save space and to make it less confusing, the codes preload, create and update functions to run the game are shown at the bottom, here's the original code where I got it from:

```
var game = new Phaser.Game(800, 600, Phaser.AUTO, '');

game.state.add('play', {
    preload: function() {
        this.game.load.image('forest-back', 'assets/parallax_forest_pack/layers/parallax-forest-back-trees.png');
        this.game.load.image('forest-lights', 'assets/parallax_forest_pack/layers/parallax-forest-lights.png');
        this.game.load.image('forest-middle', 'assets/parallax_forest_pack/layers/parallax-forest-middle-trees.png');
        this.game.load.image('forest-front', 'assets/parallax_forest_pack/layers/parallax-forest-front-trees.png');

        this.game.load.image('aerocephal', 'assets/allacrost_enemy_sprites/aerocephal.png');
        this.game.load.image('arcana_drake', 'assets/allacrost_enemy_sprites/arcana_drake.png');
        this.game.load.image('aurum-drakueli', 'assets/allacrost_enemy_sprites/aurum-drakueli.png');
        this.game.load.image('bat', 'assets/allacrost_enemy_sprites/bat.png');
        this.game.load.image('daemarbora', 'assets/allacrost_enemy_sprites/daemarbora.png');
        this.game.load.image('deceleon', 'assets/allacrost_enemy_sprites/deceleon.png');
        this.game.load.image('demonic_essence', 'assets/allacrost_enemy_sprites/demonic_essence.png');
        this.game.load.image('dune_crawler', 'assets/allacrost_enemy_sprites/dune_crawler.png');
        this.game.load.image('green_slime', 'assets/allacrost_enemy_sprites/green_slime.png');
        this.game.load.image('nagaruda', 'assets/allacrost_enemy_sprites/nagaruda.png');
        this.game.load.image('rat', 'assets/allacrost_enemy_sprites/rat.png');
        this.game.load.image('scorpion', 'assets/allacrost_enemy_sprites/scorpion.png');
        this.game.load.image('skeleton', 'assets/allacrost_enemy_sprites/skeleton.png');
        this.game.load.image('snake', 'assets/allacrost_enemy_sprites/snake.png');
        this.game.load.image('spider', 'assets/allacrost_enemy_sprites/spider.png');
        this.game.load.image('stygian_lizard', 'assets/allacrost_enemy_sprites/stygian_lizard.png');

        this.game.load.image('gold_coin', 'assets/496_RPG_icons/I_GoldCoin.png');

        this.game.load.image('dagger', 'assets/496_RPG_icons/W_Dagger002.png');
        this.game.load.image('swordIcon1', 'assets/496_RPG_icons/S_Sword15.png');

        // build panel for upgrades
        var bmd = this.game.add.bitmapData(250, 500);
        bmd.ctx.fillStyle = '#9a783d';
        bmd.ctx.strokeStyle = '#35371c';
        bmd.ctx.lineWidth = 12;
        bmd.ctx.fillRect(0, 0, 250, 500);
        bmd.ctx.strokeRect(0, 0, 250, 500);
        this.game.cache.addBitmapData('upgradePanel', bmd);

        var buttonImage = this.game.add.bitmapData(476, 48);
        buttonImage.ctx.fillStyle = '#e6dec7';
        buttonImage.ctx.strokeStyle = '#35371c';
        buttonImage.ctx.lineWidth = 4;
        buttonImage.ctx.fillRect(0, 0, 225, 48);
        buttonImage.ctx.strokeRect(0, 0, 225, 48);
        this.game.cache.addBitmapData('button', buttonImage);

        // the main player
        this.player = {
            clickDmg: 1,
            gold: 50,
            dps: 0
        };

        // world progression
        this.level = 1;
        // how many monsters have we killed during this level
        this.levelKills = 0;
        // how many monsters are required to advance a level
        this.levelKillsRequired = 10;
    },
    create: function() {
        var state = this;

        this.background = this.game.add.group();
        // setup each of our background layers to take the full screen
        ['forest-back', 'forest-lights', 'forest-middle', 'forest-front']
            .forEach(function(image) {
                var bg = state.game.add.tileSprite(0, 0, state.game.world.width,
                    state.game.world.height, image, '', state.background);
                bg.tileScale.setTo(4,4);
            });

        this.upgradePanel = this.game.add.image(10, 70, this.game.cache.getBitmapData('upgradePanel'));
        var upgradeButtons = this.upgradePanel.addChild(this.game.add.group());
        upgradeButtons.position.setTo(8, 8);

        var upgradeButtonsData = [
            {icon: 'dagger', name: 'Attack', level: 0, cost: 5, purchaseHandler: function(button, player) {
                player.clickDmg += 1;
            }},
            {icon: 'swordIcon1', name: 'Auto-Attack', level: 0, cost: 25, purchaseHandler: function(button, player) {
                player.dps += 5;
            }}
        ];

        var button;
        upgradeButtonsData.forEach(function(buttonData, index) {
            button = state.game.add.button(0, (50 * index), state.game.cache.getBitmapData('button'));
            button.icon = button.addChild(state.game.add.image(6, 6, buttonData.icon));
            button.text = button.addChild(state.game.add.text(42, 6, buttonData.name + ': ' + buttonData.level, {font: '16px Arial Black'}));
            button.details = buttonData;
            button.costText = button.addChild(state.game.add.text(42, 24, 'Cost: ' + buttonData.cost, {font: '16px Arial Black'}));
            button.events.onInputDown.add(state.onUpgradeButtonClick, state);

            upgradeButtons.addChild(button);
        });

        var monsterData = [
            {name: 'Aerocephal',        image: 'aerocephal',        maxHealth: 10},
            {name: 'Arcana Drake',      image: 'arcana_drake',      maxHealth: 20},
            {name: 'Aurum Drakueli',    image: 'aurum-drakueli',    maxHealth: 30},
            {name: 'Bat',               image: 'bat',               maxHealth: 5},
            {name: 'Daemarbora',        image: 'daemarbora',        maxHealth: 10},
            {name: 'Deceleon',          image: 'deceleon',          maxHealth: 10},
            {name: 'Demonic Essence',   image: 'demonic_essence',   maxHealth: 15},
            {name: 'Dune Crawler',      image: 'dune_crawler',      maxHealth: 8},
            {name: 'Green Slime',       image: 'green_slime',       maxHealth: 3},
            {name: 'Nagaruda',          image: 'nagaruda',          maxHealth: 13},
            {name: 'Rat',               image: 'rat',               maxHealth: 2},
            {name: 'Scorpion',          image: 'scorpion',          maxHealth: 2},
            {name: 'Skeleton',          image: 'skeleton',          maxHealth: 6},
            {name: 'Snake',             image: 'snake',             maxHealth: 4},
            {name: 'Spider',            image: 'spider',            maxHealth: 4},
            {name: 'Stygian Lizard',    image: 'stygian_lizard',    maxHealth: 20}
        ];
        this.monsters = this.game.add.group();

        var monster;
        monsterData.forEach(function(data) {
            // create a sprite for them off screen
            monster = state.monsters.create(1000, state.game.world.centerY, data.image);
            // use the built in health component
            monster.health = monster.maxHealth = data.maxHealth;
            // center anchor
            monster.anchor.setTo(0.5, 1);
            // reference to the database
            monster.details = data;

            //enable input so we can click it!
            monster.inputEnabled = true;
            monster.events.onInputDown.add(state.onClickMonster, state);

            // hook into health and lifecycle events
            monster.events.onKilled.add(state.onKilledMonster, state);
            monster.events.onRevived.add(state.onRevivedMonster, state);
        });

        // display the monster front and center
        this.currentMonster = this.monsters.getRandom();
        this.currentMonster.position.set(this.game.world.centerX + 100, this.game.world.centerY + 50);

        this.monsterInfoUI = this.game.add.group();
        this.monsterInfoUI.position.setTo(this.currentMonster.x - 220, this.currentMonster.y + 120);
        this.monsterNameText = this.monsterInfoUI.addChild(this.game.add.text(0, 0, this.currentMonster.details.name, {
            font: '48px Arial Black',
            fill: '#fff',
            strokeThickness: 4
        }));
        this.monsterHealthText = this.monsterInfoUI.addChild(this.game.add.text(0, 80, this.currentMonster.health + ' HP', {
            font: '32px Arial Black',
            fill: '#ff0000',
            strokeThickness: 4
        }));

        this.dmgTextPool = this.add.group();
        var dmgText;
        for (var d=0; d<50; d++) {
            dmgText = this.add.text(0, 0, '1', {
                font: '64px Arial Black',
                fill: '#fff',
                strokeThickness: 4
            });
            // start out not existing, so we don't draw it yet
            dmgText.exists = false;
            dmgText.tween = game.add.tween(dmgText)
                .to({
                    alpha: 0,
                    y: 100,
                    x: this.game.rnd.integerInRange(100, 700)
                }, 1000, Phaser.Easing.Cubic.Out);

            dmgText.tween.onComplete.add(function(text, tween) {
                text.kill();
            });
            this.dmgTextPool.add(dmgText);
        }

        // create a pool of gold coins
        this.coins = this.add.group();
        this.coins.createMultiple(50, 'gold_coin', '', false);
        this.coins.setAll('inputEnabled', true);
        this.coins.setAll('goldValue', 1);
        this.coins.callAll('events.onInputDown.add', 'events.onInputDown', this.onClickCoin, this);

        this.playerGoldText = this.add.text(30, 30, 'Gold: ' + this.player.gold, {
            font: '24px Arial Black',
            fill: '#fff',
            strokeThickness: 4
        });

        // 100ms 10x a second
        this.dpsTimer = this.game.time.events.loop(100, this.onDPS, this);

        // setup the world progression display
        this.levelUI = this.game.add.group();
        this.levelUI.position.setTo(this.game.world.centerX, 30);
        this.levelText = this.levelUI.addChild(this.game.add.text(0, 0, 'Level: ' + this.level, {
            font: '24px Arial Black',
            fill: '#fff',
            strokeThickness: 4
        }));
        this.levelKillsText = this.levelUI.addChild(this.game.add.text(0, 30, 'Kills: ' + this.levelKills + '/' + this.levelKillsRequired, {
            font: '24px Arial Black',
            fill: '#fff',
            strokeThickness: 4
        }));
    },
    onDPS: function() {
        if (this.player.dps > 0) {
            if (this.currentMonster && this.currentMonster.alive) {
                var dmg = this.player.dps / 10;
                this.currentMonster.damage(dmg);
                // update the health text
                this.monsterHealthText.text = this.currentMonster.alive ? Math.round(this.currentMonster.health) + ' HP' : 'DEAD';
            }
        }
    },
    onUpgradeButtonClick: function(button, pointer) {
        // make this a function so that it updates after we buy
        function getAdjustedCost() {
            return Math.ceil(button.details.cost + (button.details.level * 1.46));
        }

        if (this.player.gold - getAdjustedCost() >= 0) {
            this.player.gold -= getAdjustedCost();
            this.playerGoldText.text = 'Gold: ' + this.player.gold;
            button.details.level++;
            button.text.text = button.details.name + ': ' + button.details.level;
            button.costText.text = 'Cost: ' + getAdjustedCost();
            button.details.purchaseHandler.call(this, button, this.player);
        }
    },
    onClickCoin: function(coin) {
        if (!coin.alive) {
            return;
        }
        // give the player gold
        this.player.gold += coin.goldValue;
        // update UI
        this.playerGoldText.text = 'Gold: ' + this.player.gold;
        // remove the coin
        coin.kill();
    },
    onKilledMonster: function(monster) {
        // move the monster off screen again
        monster.position.set(1000, this.game.world.centerY);

        var coin;
        // spawn a coin on the ground
        coin = this.coins.getFirstExists(false);
        coin.reset(this.game.world.centerX + this.game.rnd.integerInRange(-100, 100), this.game.world.centerY);
        coin.goldValue = Math.round(this.level * 1.33);
        this.game.time.events.add(Phaser.Timer.SECOND * 3, this.onClickCoin, this, coin);

        this.levelKills++;

        if (this.levelKills >= this.levelKillsRequired) {
            this.level++;
            this.levelKills = 0;
        }

        this.levelText.text = 'Level: ' + this.level;
        this.levelKillsText.text = 'Kills: ' + this.levelKills + '/' + this.levelKillsRequired;

        // pick a new monster
        this.currentMonster = this.monsters.getRandom();
        // upgrade the monster based on level
        this.currentMonster.maxHealth = Math.ceil(this.currentMonster.details.maxHealth + ((this.level - 1) * 10.6));
        // make sure they are fully healed
        this.currentMonster.revive(this.currentMonster.maxHealth);
    },
    onRevivedMonster: function(monster) {
        monster.position.set(this.game.world.centerX + 100, this.game.world.centerY + 50);
        // update the text display
        this.monsterNameText.text = monster.details.name;
        this.monsterHealthText.text = monster.health + 'HP';
    },
    onClickMonster: function(monster, pointer) {
        // apply click damage to monster
        this.currentMonster.damage(this.player.clickDmg);

        // grab a damage text from the pool to display what happened
        var dmgText = this.dmgTextPool.getFirstExists(false);
        if (dmgText) {
            dmgText.text = this.player.clickDmg;
            dmgText.reset(pointer.positionDown.x, pointer.positionDown.y);
            dmgText.alpha = 1;
            dmgText.tween.start();
        }

        // update the health text
        this.monsterHealthText.text = this.currentMonster.alive ? this.currentMonster.health + ' HP' : 'DEAD';
    }
});

game.state.start('play');
```

Anyone have an idea why it goes like that? Please feel free to share your thoughts, and thank you for stopping by! :D

# Answer
Nevermind, guys. I fixed the problem.. the reason why all the images are showing at the center of the screen is because of the "this.monsters = this.game.add.group();" and the " monster = state.monsters.create(state.game.world.centerX, state.game.world.centerY, data.image);" code. Now, the "x" serves as the horizontal position of the images and it should be more than the value of the canvas to have the stacked images off the screen and look more like this instead.

Now the remainder is the monster that is clickable and respawns as a new monster from the group which is what I was going for, let me put it in this way.. It's like dealing a deck of cards, the table is the screen, the deck are the stacked images and the one card at the center of table is randomly picked from the rest is our card.. the deck of cards shouldn't be on the table or it would result as the problem that I had, what youd should do is to put the deck of cards away from the table so it wouldn't appear on the screen as stacked images leaving one card at the center of the table. now that I have learned my lesson.. I hope this would help others as well.. :D
> 1 votes

---
Tags: javascript, html5
---


# Question
Title: How to map control key to a specific angle or orientation?
At the moment, I basically have built out a large hash table of various angles and what direction they map to, if the user would press right, up, down, left. This is needed, in my case, as I have a collection of geometries that when the user presses right, they all go right, and when left, they all go left ...

However, when the scene containing these is rotated anything other than its original state, these controls need to be updated/reversed/etc. That is, if you're looking at the scene from behind, pressing left now has the objects all going right, etc.

I was trying to see if there is a simpler way of applying matrix transformations instead of hard coding a large hash table mapping various scene angles to keys.

# Answer
> 1 votes
I haven't thought about this for too long. But it seems fairly simple. I assume you know what the modelViewMatrix is. This 4x4 matrix transforms coordinates (points) from world space to camera space. There is a similar matrix called the normalMatrix that transforms vectors (usually normalvectors). It does the same as the modelViewMatrix, but skips all translating operations. This normalMatrix is a 3x3 matrix. Just invert that matrix and multiply it with a camera-space vector that represents the direction of the key being pressed. Once you get the vector back into world space, you might want to project it down onto the floor plane (dropping the y-component could possibly do).

---
Tags: opengl, 3d, mathematics, opengl-es, webgl
---


# Question
Title: Unity : Objects become black when size is changed to smaller
While working with Unity 5.4, my models become black when I resize them to a smaller scale. When I make the models bigger they are fine. I am using a directional light . On the image below as you can see on the left the model is fine. But the others are black.

HOPE YOU CAN HELP.

# Answer
Always try to scale your fbx kind of item outside unity. You may also encounter light mapping issue if you do that inside unity.For your current problem we need more info.
> 1 votes

# Answer
Thanks you for every thing. So what I did is resize the models until light was showing and used the model import setting tab to reduce the size scale from 1 to something low like 0.6 resizing model but keeping it lit.
> 1 votes

---
Tags: unity, vuforia
---


title: Jagged shadows with default settings

text:
# Question
Title: Jagged shadows with default settings
This is what it looks like no matter the settings I use when I try to use shadows in Unity. Changing the Bias or the Normal Bias does effect the shadows, but I cannot get the shadows to be smooth with any settings. Making the model bigger does fix this, but I would optimally not scale the model up, as it is already at 10.

# Answer
Use **hard shadow** with **very high** shadow resolution. This will effect on editor as well as build. Change quality settings levels for your intended platform. In shadow section **hard shadow only** and **very high** shadow resolution. May also increase **anti aliasing** in rendering section. These will effect on build quality.
> 1 votes

# Answer
So it seems like while changing the quality settings did increase the quality of the shadows it did not remove the artifacts, but when I was int he QualitySettings menu, I saw some settings that I had seen in other forums. Changing the shadow distance to a lower value increased the quality of the shadows and removed the artifacts. This also allows the use of soft shadows, but the bias then needs to be increased slightly to .005.
> 4 votes

---
Tags: unity, shadows
---


# Question
Title: Transforming position in y-axis (going in the middle) in Unity
I am making a 2d game where an object goes up, down or in the middle with given Input.

But when the object goes to the middle with GoMiddle() it starts glitching and it can't go back up or down

```
Vector2 Pos;
public bool DownKeyPressed = false;
public bool UpKeyPressed = false;
public bool MiddleKeyPressed = false;

// Use this for initialization
void Start()
{

}

// Update is called once per frame
void Update()
{
    Pos = transform.position;

    UMDCOntroller();

    transform.position = Pos;
    print(Pos.y);
}

void GoDown()
{
    if (Pos.y >= 1.2f)
    {
        Pos = Vector2.Lerp(Pos, new Vector2(Pos.x, Pos.y - 1.2f), 0.1f);
    }
    else
    {
        DownKeyPressed = false;
    }

}

void GoUp()
{
    if (Pos.y <= 2.8f)
    {
        Pos = Vector2.Lerp(Pos, new Vector2(Pos.x, Pos.y + 1.2f), 0.1f);
    }
    else
    {
        UpKeyPressed = false;
    }

}

void GoMiddle()
{

if(Pos.y < 2)
    {
        Pos = Vector2.Lerp(Pos, new Vector2(Pos.x, Pos.y + 1.2f), 0.1f);

    }

else if(Pos.y >= 2) {

        Pos = Vector2.Lerp(Pos, new Vector2(Pos.x, Pos.y - 1.2f), 0.1f);

    }
    else
    {

        MiddleKeyPressed = false;
    }

}

void UMDCOntroller()
{

    if (Input.GetKeyDown(KeyCode.S))
    {
        DownKeyPressed = true;

    }

    if (DownKeyPressed)
    {
        GoDown();
        UpKeyPressed = false;

    }

    if (Input.GetKeyDown(KeyCode.D))
    {

        MiddleKeyPressed = true;
    }

    if(MiddleKeyPressed)
    {

        GoMiddle();

    }

    if (Input.GetKeyDown(KeyCode.W))
    {

        UpKeyPressed = true;

    }

    if (UpKeyPressed)
    {

        GoUp();

    }

}

```

I am asking this question again because I didn't receive an answer

Thanks

# Answer
> 0 votes
The problem is that you are moving the object too much up and down every time you check if it is already on the right spot. Therefore it jumps up and down because

```
if(Pos.y < 2)
    Pos = Vector2.Lerp(Pos, new Vector2(Pos.x, Pos.y + 1.2f), 0.1f);

```

moves it up so far that

```
else if(Pos.y >= 2)
    Pos = Vector2.Lerp(Pos, new Vector2(Pos.x, Pos.y - 1.2f), 0.1f);

```

kicks in and moves it down again. This never stops, so the object jumps between two positions.

What you have to do is check whether or not the object is in a region near the target and then you stop the movement. This could look like that:

```
void GoMiddle()
{
    float epsilon = 0.1f;
    if ((Pos.y >= 2 - epsilon && Pos.y <= 2) || (Pos.y <= 2 + epsilon && Pos.y >= 2))
    {
        Pos.y = 2;
        MiddleKeyPressed = false;
    }
    else if (Pos.y >= 2)
        Pos = Vector2.Lerp(Pos, new Vector2(Pos.x, Pos.y - 1.2f), epsilon);
    else if (Pos.y < 2)
        Pos = Vector2.Lerp(Pos, new Vector2(Pos.x, Pos.y + 1.2f), epsilon);
}

```

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


title: Random black pixels GLSL shader bug

text:
# Question
Title: Random black pixels GLSL shader bug
I've recently been following a tutorial for writing a game engine in Java using LWJGL 2. I followed the tutorial for writing a fragment shader that utilizes spotlights in GLSL.

The example game currently running in the engine is a spotlight that follows the camera and a plane mesh with a tile texture. When I run the game, when viewing the mesh at certain distances and angles, namely close distances and sharp angles, I run into this interesting bug when certain pixels just go black. This has only occurred when I modified the fragment shader to include spotlights. This can only mean that there is a bug in the fragment shader itself.

The fragment shader code is below. What I believe to be the problematic code is marked with a comment below in the function `calcSpotLight`.

**Update:** I have found that the problem was indeed in my graphics card's driver. I just updated the driver and reran the program and indeed received no black pixels.

**Edit:** It appears that the problem is indeed in the `calcSpotLight` function, but within the `calcSpotLight` function, the problem is the `calcPointLight` function. I still don't know what the exact problem is, but that should narrow down the possible errors.

```
#version 330

const int MAX_POINT_LIGHTS = 4;
const int MAX_SPOT_LIGHTS = 4;

in vec2 texCoord0;
in vec3 normal0;
in vec3 worldPos0;

out vec4 fragColor;

struct BaseLight
{
    vec3 color;
    float intensity;
};

struct DirectionalLight
{
    BaseLight base;
    vec3 direction;
};

struct Attenuation
{
    float constant;
    float linear;
    float exponent;
};

struct PointLight
{
    BaseLight base;
    Attenuation atten;
    vec3 position;
    float range;
};

struct SpotLight
{
    PointLight pointLight;
    vec3 direction;
    float cutoff;
};

uniform vec3 baseColor;
uniform vec3 eyePos;
uniform vec3 ambientLight;
uniform sampler2D sampler;

uniform float specularIntensity;
uniform float specularPower;

uniform DirectionalLight directionalLight;
uniform PointLight pointLights[MAX_POINT_LIGHTS];
uniform SpotLight spotLights[MAX_SPOT_LIGHTS];

vec4 calcLight(BaseLight base, vec3 direction, vec3 normal)
{
    float diffuseFactor = dot(normal, -direction);

    vec4 diffuseColor = vec4(0,0,0,0);
    vec4 specularColor = vec4(0,0,0,0);

    if(diffuseFactor > 0)
    {
        diffuseColor = vec4(base.color, 1.0) * base.intensity * diffuseFactor;

        vec3 directionToEye = normalize(eyePos - worldPos0);
        vec3 reflectDirection = normalize(reflect(direction, normal));

        float specularFactor = dot(directionToEye, reflectDirection);
        specularFactor = pow(specularFactor, specularPower);

        if(specularFactor > 0)
        {
            specularColor = vec4(base.color, 1.0) * specularIntensity * specularFactor;
        }
    }

    return diffuseColor + specularColor;
}

vec4 calcDirectionalLight(DirectionalLight directionalLight, vec3 normal)
{
    return calcLight(directionalLight.base, -directionalLight.direction, normal);
}

vec4 calcPointLight(PointLight pointLight, vec3 normal)
{
    vec3 lightDirection = worldPos0 - pointLight.position;
    float distanceToPoint = length(lightDirection);

    if(distanceToPoint > pointLight.range)
        return vec4(0,0,0,0);

    lightDirection = normalize(lightDirection);

    vec4 color = calcLight(pointLight.base, lightDirection, normal);

    float attenuation = pointLight.atten.constant +
                        pointLight.atten.linear * distanceToPoint +
                        pointLight.atten.exponent * distanceToPoint * distanceToPoint +
                        0.0001;

    return color / attenuation;
}

vec4 calcSpotLight(SpotLight spotLight, vec3 normal)
{
    vec3 lightDirection = normalize(worldPos0 - spotLight.pointLight.position);
    float spotFactor = dot(lightDirection, spotLight.direction);

    vec4 color = vec4(0,0,0,0);

    //This is likely the problematic code, but I'm not 100 percent sure

    if(spotFactor > spotLight.cutoff)
    {
        color = calcPointLight(spotLight.pointLight, normal) *
                (1.0 - (1.0 - spotFactor)/(1.0-spotLight.cutoff));
    }

    return color;
}
void main()
{
    vec4 totalLight = vec4(ambientLight,1);
    vec4 color = vec4(baseColor, 1);
    vec4 textureColor = texture(sampler, texCoord0.xy);

    if(textureColor != vec4(0,0,0,0))
        color *= textureColor;

    vec3 normal = normalize(normal0);

    totalLight += calcDirectionalLight(directionalLight, normal);

    for(int i = 0; i < MAX_POINT_LIGHTS; i++)
    {
        if(pointLights[i].base.intensity > 0)
            totalLight += calcPointLight(pointLights[i],normal);
    }

    for(int i = 0; i < MAX_SPOT_LIGHTS; i++)
    {
        if(spotLights[i].pointLight.base.intensity > 0)
            totalLight += calcSpotLight(spotLights[i],normal);
    }

    fragColor = color * totalLight;
}

```

I checked to see if there was maybe some division by zero problem or something of the like, but I can't for the life of me figure out what the problem actually is. And since debugging in GLSL is nearly impossible, I've decided that my last possible option is to post my question here.

Here are some example images of the bug in game:

Here, the black pixels can be seen at the bottom of the spotlight

Here, the black pixels are mostly at the edge of the spotlight

Any help would be appreciated.

# Answer
Unexpectedly black pixels sometimes indicate that you've got an infinity or NaN in the shader somewhere. For example normalize(vec3(0,0,0)) will generate a NaN. To me, the most obvious candidate in the above shader is the reflectDirection variable, but I could be wrong. GLSL has isinf() and isnan() functions that you can use to detect those cases.

If that doesn't help, I'd suggest using a graphics debugging tool like the one at http://renderdoc.org/ to debug the problem.
> 8 votes

# Answer
There is at least one serious problem in the code. In `calcLight()`, the test below is invalid. Calling `pow` with a negative first argument is undefined behaviour, so you need to test `specularFactor` sooner.

```
    float specularFactor = dot(directionToEye, reflectDirection);
    specularFactor = pow(specularFactor, specularPower);

    if(specularFactor > 0)

```

Just change it to:

```
    float specularFactor = dot(directionToEye, reflectDirection);
    if(specularFactor > 0)
    {
        specularFactor = pow(specularFactor, specularPower);

```

Some random remarks:

* you have an `exponent` uniform that is actually for *quadratic* attenuation; you should name it `quadratic` for readability.
* adding 0.0001 to `attenuation` probably avoids division by zero but if that case ever happens your light will be 10000 times too powerful; I suggest removing it and doing `return color / max(attenuation, 1.0)` instead).
> 2 votes

# Answer
A guess (too long to put in a comment):

If spotFactor becomes 0.6 at a specific pixel, from this

```
float spotFactor = dot(lightDirection, spotLight.direction);

```

then color goes negative here (as you said spotLight.cutoff is 0.71):

```
color = calcPointLight(spotLight.pointLight, normal) *
            (1.0 - (1.0 - spotFactor)/(1.0-spotLight.cutoff));

```

will be:

```
1 - (1 - 0.6) / (1 - 0.71) -> -0.379310345

```

and the breakpoint is ofc where the dot product and spotLight.cutoff are **equal or close to equal**.

After this i cannot guess what happens. Maybe you simply produce black where the dot product is 0.71 - may happen at only a few pixels, where the spotlight values are much on negative. Or maybe the GPU driver goes nuts there :-).

Other notes:

* You calculate lightDirection twice for the spot light, once in calcSpotlight and once in calcPointlight. I may rather write the different parts separately...
* The 0.0001 is highly dubious. Potentially you add a big value with a small value in float32 space - this may be impossible, as you only have 7 significants to use. Cannot add 1000 + 0.0001 and expect to get 1000.0001, since 32-bit space isn't sufficient for that precision (or is at the limit). I didn't try to follow all of the code, but high exponents and division by almost-zero are potential sources for weirdness. As is \[huge specular value\] / 0.0001, if that occurs.
> 2 votes

---
Tags: opengl, java, glsl, lighting, lwjgl
---


title: 2D diagonal movement using Rigidbody2D

text:
# Question
Title: 2D diagonal movement using Rigidbody2D
I have a problem with 2d player movement, as I am unable to move on the Y-axis. Yet, the movement on the X-axis is working as intended.

Below, you can see my code:

```
public Sprite directionUp;
public Sprite directionDown;
public Sprite directionLeft;
public Sprite directionRight;

public float speed = 0.1f;
public byte direction = 0; //0 - up, 1 - right, 2 - down, 3 - left

private SpriteRenderer spriteRenderer;
private Rigidbody2D rb2D;
private Sprite[] directionArray;

// Use this for initialization
void Start () {
    rb2D = GetComponent<Rigidbody2D>();
    spriteRenderer = GetComponent<SpriteRenderer>();

    directionArray = new Sprite[]{ directionUp, directionDown, directionLeft, directionRight };
    if(directionArray[0] != null) spriteRenderer.sprite = directionArray[0];
}

// Update is called once per frame
void Update ()
{
    if (Input.GetKeyDown(KeyCode.Keypad7))
    {
        rb2D.MovePosition(rb2D.position + new Vector2(-1f, 1f));

        if (directionArray[0] != null) spriteRenderer.sprite = directionArray[2];
    }
    else if (Input.GetKeyDown(KeyCode.Keypad9))
    {
        rb2D.MovePosition(rb2D.position + new Vector2(1f, 1f));

        if (directionArray[0] != null) spriteRenderer.sprite = directionArray[3];
    }
    else if (Input.GetKeyDown(KeyCode.Keypad1))
    {
        rb2D.MovePosition(rb2D.position + new Vector2(-1f, -1f));

        if (directionArray[0] != null) spriteRenderer.sprite = directionArray[2];
    }
    else if (Input.GetKeyDown(KeyCode.Keypad3))
    {
        rb2D.MovePosition(rb2D.position + new Vector2(1f, -1f));

        if (directionArray[0] != null) spriteRenderer.sprite = directionArray[3];
    }
    else if (Input.GetKeyDown(KeyCode.W) || Input.GetKeyDown(KeyCode.Keypad8))
    {
        rb2D.MovePosition(rb2D.position + new Vector2(0f, 1f));

        if (directionArray[0] != null) spriteRenderer.sprite = directionArray[0];
    }
    else if (Input.GetKeyDown(KeyCode.S) || Input.GetKeyDown(KeyCode.Keypad2))
    {
        rb2D.MovePosition(rb2D.position + new Vector2(0f, -1f));

        if (directionArray[0] != null) spriteRenderer.sprite = directionArray[1];
    }
    else if (Input.GetKeyDown(KeyCode.A) || Input.GetKeyDown(KeyCode.Keypad4))
    {
        rb2D.MovePosition(rb2D.position + new Vector2(-1f, 0f));

        if (directionArray[0] != null) spriteRenderer.sprite = directionArray[2];
    }
    else if (Input.GetKeyDown(KeyCode.D) || Input.GetKeyDown(KeyCode.Keypad6))
    {
        rb2D.MovePosition(rb2D.position + new Vector2(1f, 0f));

        if (directionArray[0] != null) spriteRenderer.sprite = directionArray[3];
    }
}

```

By the way, please keep in mind I am quite new to Unity.

EDIT 1///////////////////////

I have attached the entire script, some of the variables are unused right now(was testing other methods of movement).

I tried to both Keypad - 1, 3, 6, 9, as well as the combinations which I didn't get to work yet (but this is off-topic and I will look into it once I will get the Y-axis to move).

Thanks, Zryw

# Answer
I found the solution; it turned out to be a beginner's mistake. I locked the Y-axis in the Rigidbody2D component (to prevent the gravity effect pulling my character downwards all the time). I unchecked that and set the Gravity Scale to 0 and it is working!
> 0 votes

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


title: What is wrong with my Chest script?

text:
# Question
Title: What is wrong with my Chest script?
I'm making an RPG in Unity3D and I am trying to make a script for a chest to open. So I built this script! But it doesn't work. I just want some help fixing this script.

```
#pragma strict
var Text : GameObject;
var OpenedChest : GameObject;
var CurrentChest : GameObject;

function OnTriggerEnter()
{
    Text.SetActive(true);
    if (Input.GetKeyDown("e"))
    {
        CurrentChest.SetActive(false);
        OpenedChest.SetActive(true);
    }
}

function OnTriggerExit()
{
    Text.SetActive(false);
}

```

I get no compiler errors. When I go into the collider that triggers the text, that works, but what doesn't is when I press E to open the chest. It doesn't activate the other chest. What is wrong with my script?

# Answer
The issue in your code is that you only check for the key press in the `OnTriggerEnter` function, which only gets called when the collider enters the trigger. What you probably want to do instead is check for the keypress inside the `OnTriggerStay` function, which gets called while the collider lies inside the trigger.
> 6 votes

# Answer
Is the script attached to the game object of one of the two chests `CurrentChest` and `OpenChest`? Then keep in mind that deactivating a game object also deactivates all scripts attached to it. That means any events on them won't fire anymore. You likely only want to disable specific components of the chests.
> 2 votes

---
Tags: unity, javascript, unityscript
---


title: What is the benefit of YCbCr?

text:
# Question
Title: What is the benefit of YCbCr?
Why would someone want to store images as YCbCr instead of RGB in RAM or in GPU memory?

# Answer
> 4 votes
Chroma subsampling is usually used with YCbCr, that makes pics smaller. Say, 512x512 pic in rgb takes 768 kb. While same pic in YCbCr with 4:2:0 subsampling will take 384 kb. Sure, that's good only for photos, or video-like images.
Other reasons might include image processing/analysis, when luma/chroma components needs to be separate.
Or when you play video, and compression scheme involves luma/chroma separation (and optionally subsampling). It's much faster then to compose RGB image in pixel shader, rather than decode pic fully on cpu.

# Answer
> 1 votes
Vlad covered the common cases above. There's one other neat way I know of to take advantage of a chroma/luma split for compression, when using GPU-friendly compressed formats like S3TC, so I figured I'd add it on here:

---

**DXT1** compression breaks an image into 4x4-texel blocks, and stores two endpoint colours per block, representing each texel inside as a blend somewhere between these two endpoints.

This can cause errors if, say, the block contains both red and green, each in light and dark varieties. The compressed format can only handle variation along one line in colour space, so about the best the compressor can do is blend between bright green and dark red, getting the wrong colour in places that want dark green or bright red.

Example of DXT1 cmpression - note colour bleeding & floating reddish texels around the edges of the face and life jacket.

---

The more heavyweight **DXT5** compression stores colour information as DXT1 blocks, but also has an independent alpha channel.

We can use a colour model that splits out luma and chroma components to take advantage of this, storing only chroma information in the DXT1 colour block, and luma information in the alpha block. Now a single 4x4 block of the image can represent colours varying on two axes - the DXT1 block representing shifts in hue/saturation, and the alpha block representing shifts in lightness - better representing areas of the block with separate transitions in both chroma and luma. We also get higher precision devoted to the luma channel, which helps because our vision is more sensitive to luma differences.

Example of using this luma-chroma splitting technique to improve S3TC compression. The result is almost indistinguishable from the uncompressed source image, identical in resolution but one quarter the file size, and can be decoded fully on the GPU (the hardware handling the DXT5 decode, and a simple fragment shader converting back to RGB).

---

The images above are from this paper from NVIDIA detailing a technique for realtime compression into YCoCg-DTX5. YCoCg isn't exactly the same as YCbCr, but shares the core concept of expressing colours along luma and chroma axes rather than RGB.

---
Tags: color
---


title: Calculate length of isometric line

text:
# Question
Title: Calculate length of isometric line
In my isometric game the user can draw a line of arbitrary length, and I need to calculate the "unprojected length" of the same line. Users can only draw lines in 6 directions (4 isometric directions and vertically)

How do I calculate the given BLUE line provided I have the given RED line?

Ray/plane intersection seems to be overkill for such a simple calculation. My isometric angles are 30 degrees, exactly as shown in the image below.

**Edit:** Assuming a 3D object is projected with isometric projection, it becomes a bit smaller in screen coordinates, no? So what would be the original 3D length before "isometric projection"? Since the user is drawing lines on an already "projected" isometric view, the length cannot be the simple length.

# Answer
> Assuming a 3D object is projected with isometric projection, it becomes a bit smaller in screen coordinates, no?

Maybe not quite the way you think, if you're using a true isometric projection.

"Isometric" comes from Greek terms for "**equal measure**," referring to the fact that **the six axes you describe are all equally foreshortened**.

Eg. If I took six identical rods, pointing up, down, north, south, east, west, and rendered them with an isometric projection (say, looking from the south-east corner), each rod's projection on my screen would be the same size as all the others, no matter where I placed them in my scene.

So, if you're using isometric projection, all you need to do is measure the line in screenspace (using Pythagorean theorem for diagonals), then divide it by your screen-pixels-per-world-unit scaling value (ie. your zoom factor).

The wrinkle comes in the fact that we're really sloppy about how we use the term "isometric" in games. It's frequently used to describe the dimetric projection in games with 2:1 diamond-shaped tiles, or even more generally for any view angle that's "vaguely corner-on"...

If you're using one of these almost-isometric projections, then it gets a bit more complicated. You'll need to edit your question to give us more details about how you're constructing your projection so we can identify the appropriate scaling to apply.
> 2 votes

# Answer
I believe you can analyze the distance the user drew on screen, and the distance between the camera and the platform, as well as the FOV of the camera. Using this info, you could use some geometry to figure out the length relative to the platform the user drew on. I made this graphic below- is this what you're asking?
> 1 votes

---
Tags: mathematics, geometry, isometric
---


# Question
Title: Preparing a 2D character to export from Blender to Unity?
I'm an animator for a game currently, and I don't have Unity (can't download due to too much gigs coupled with slow internet,) but the game designer told me I can use Blender to export animations into Unity.

I asked if I needed to prepare multiple files to export, and they told me that I could just have one file with all the animations in it. The game, as stated in the title, is 2D.

My problem now is, how do I turn a rig into an actual character with different animations under it? (Right now I only have an 'idle' animation, but need to make running, jumping, walking, etc.) I mean how do I save this 'idle' animation and work on another animation without overwriting the previously finished animation(s)?

Thank you much

# Answer
> 1 votes
For a 2d game , you should use other instruments to animate the character like Spriter pro , however you can put all the "steps" of the animation in one file and then export it in PNG , then in Unity you can use the "Sprite Editor" to cut the image and make various pieces . This is the documentation of the Sprite Editor : https://docs.unity3d.com/Manual/SpriteEditor.html .

# Answer
> 0 votes
Note, I haven't done much work with animations in Unity from Blender.

I believe (in Blender), you create a new animation by going to the Dope Sheet, and then to the Action Editor. This should allow you to create new actions. You can then create more animations (make sure to press the F button so that Blender saves the animation even if nothing is currently using it!). Here's what Blender looks like when selection the action editor:

When the game designer told you that Unity can have the one file, they mean it. Unity will take the .blend file (you can send that to them), automatically run it through a fbx exporter (even if you make a change, and then save), and allow you to drop it onto the scene.

Unity will also find the animations that you set up in Blender, and allow the designer to set up the animations to their liking using the animation panel (this is where my knowledge lacks).

---
Tags: unity, python, blender
---


# Question
Title: What properties should be private, public, and protected?
I'm currently trying to write a base player class, and I'm not exactly sure what I should make private, and what I should make public. I know that as a programmer, I need to keep as many variables as private as possible, but I don't know which setters I need to keep private, or just leave public. Is it bad to leave those setters public?

Here's the code for reference:

```
using UnityEngine;
using System.Collections;

/// <summary>
/// Base Class for the Player
/// </summary>
public class Player {

public PlayerSpecies species;

private float currentHealth;
private float currentXP;
private int currentMana;

private int playerLevel;

// variables that depend on player level
private float requiredXP;
private float maxHealth;
private int maxMana;
private float strengthFactor;
private float speedFactor;

// currency variables
private int chipCount;
private int solusCount;
private int orbCount;
private int xpCoinCount;

public Player()
{
    maxMana = 20;
}

/// <summary>
/// The player's species.
/// </summary>
public PlayerSpecies Species
{
    get { return species; }
    set { species = value; }
}

/// <summary>
/// The player's name.
/// </summary>
public string PlayerName { get; private set; }

/// <summary>
/// The player's current health.
/// </summary>
public float CurrentHealth
{
    get { return currentHealth; }
    set { currentHealth = value; }
}

/// <summary>
/// The player's current experience count.
/// </summary>
public float CurrentXP
{
    get { return currentXP; }
    set { currentXP = value; }
}

/// <summary>
/// The player's current mana count.
/// </summary>
public int CurrentMana
{
    get { return currentMana; }
    set { currentMana = value; }
}

/// <summary>
/// The player's current level.
/// </summary>
public int PlayerLevel
{
    get { return playerLevel; }
    set { playerLevel = value; }
}

/// <summary>
/// Required XP for next level. The value is dependent on player's level.
/// </summary>
public virtual float RequiredXP
{
    get { return requiredXP; }
    set { requiredXP = value; }
}

/// <summary>
/// The maximum health the player can have. The value is dependent on player's level.
/// </summary>
public virtual float MaxHealth{
    get { return maxHealth; }
    set { maxHealth = value; }
}

/// <summary>
/// The maximum mana the player can have. The value is dependent on player's level.
/// </summary>
public int MaxMana
{
    // Calculates the maximum mana the player can have.
    get
    {
        maxMana = playerLevel * 20;
        return maxMana;
    }
    private set { maxMana = value; }
}

/// <summary>
/// The strength factor added to the player. The value is dependent on the player's level.
/// </summary>
public virtual float StrengthFactor
{
    get { return strengthFactor; }
    set { strengthFactor = value; }
}

/// <summary>
/// The speed factor added to the player. The value is dependent on the player's level.
/// </summary>
public virtual float SpeedFactor
{
    get { return speedFactor; }
    set { speedFactor = value; }
}
}

```

Thanks in advance!

# Answer
> -1 votes
By definition, all variables SHOULD be private. Every function or variable is private by default in Unity, but there's no problem writing the 'private' reserved word. If you want to get or set one of them from another class, you have to create a getter/setter function, but these functions must be public, otherwise they will be useless.

There is no problem having public setters.

I hope I helped you!

---
Tags: unity, c#, software-engineering, rpg
---


# Question
Title: Turning x and y difference between two points into a projectile moving between them at a fixed speed
In a libgdx project of mine, I have two units on a 2d field who want to fire at each other. They both know the x and y distance to each other by subtracting their enemies position from their own:

```
Vector2 path = pos.cpy().sub(target.getPos());

```

What's the simplest way of turning this Vector2 into a vector that'll allow the units to fire at each other, with the projectile being sent off with `Projectile.maxSpeed`?

I was thinking of normalizing `path` and multiplying both `x` and `y` with the desired bullet speed, but I fear I may be overthinking this and that applying trigonometry would be simpler.

# Answer
Your intuition is correct, the easiest way to do it would be to normalize your vector, and then rescale it using the Projectile.maxSpeed. If you need the angle for some reason, you can get the direction to the target by using the atan2, which can be used to convert an x and y difference into a rotation. Here's some C pseudo-code to show you:

```
float x_diff = target.x - me.x;
float y_diff = target.y - me.y;
float direction_to_target = atan2(y_diff, x_diff);
float direction_to_target_degrees = direction_to_target * 180 / PI;

```
> 2 votes

---
Tags: java, libgdx, vector, trigonometry
---


# Question
Title: How to minimize the repetitive creation of component in libgdx ashley?
The below example is creation of character `Entity`. My problem is do I always need to call these `engine.createComponent(...class)` to create a component? Or should I wrap these to another class that handles the creation of entities?

```
PooledEngine engine = new PooledEngine();

...

CharacterComponent character = engine.createComponent(CharacterComponent.class);
TextureComponent texture = engine.createComponent(TextureComponent.class);
SizeComponent size = engine.createComponent(SizeComponent.class);
TransformComponent transform = engine.createComponent(TransformComponent.class);
PhysicsComponent physics = engine.createComponent(PhysicsComponent.class);

Entity entity = engine.createEntity();
entity.flag = Constants.CHARACTER;

entity.add(character);
entity.add(texture);
entity.add(size);
entity.add(transform);
entity.add(physics);

engine.addEntity(entity);

```

# Answer
If you want the simplest method you could just use something along the lines of a Factory:

```
public class CharacterFactory
{
    public static Entity spawnCharacter(PooledEngine engine)
    {
        CharacterComponent character = engine.createComponent(CharacterComponent.class);
        TextureComponent texture = engine.createComponent(TextureComponent.class);
        SizeComponent size = engine.createComponent(SizeComponent.class);
        TransformComponent transform = engine.createComponent(TransformComponent.class);
        PhysicsComponent physics = engine.createComponent(PhysicsComponent.class);

        Entity entity = engine.createEntity();
        entity.flag = Constants.CHARACTER;

        entity.add(character);
        entity.add(texture);
        entity.add(size);
        entity.add(transform);
        entity.add(physics);

        engine.addEntity(entity);

        return entity;
    }
}

```

Then when you use it:

```
PooledEngine engine = new PooledEngine();

Entity bob = CharacterFactory.spawnCharacter(engine);
Entity alice = CharacterFactory.spawnCharacter(engine);

```

You might have to clean up one or two syntactic or semantic issues in the Java I wrote (I'm a C++ programmer, haven't used Java in a couple years) but this would be my first step until I needed a more complex management solution for Character creation, this works best when your Characters are all very similar and you can throw in extra parameters to get exactly the behavioral differences you are looking for.
> 4 votes

---
Tags: java, libgdx, oop
---


title: OpenGL fix objects to camera

text:
# Question
Title: OpenGL fix objects to camera
I'm developing some game in order to learn OpenGL.

I can make an object follow me around when I move forward, backward, left, right, up or down, by setting it's position right infront of the camera.

Problem starts when the camera rotates / tilts (looking up, down, left, right...).

The object is indeed sticks infront of the camera position (because I calculate a vector going out from the camera position and place it there), however I can't make the angle of the object to rotate/tilt along with the camera, so it is just fixed.

I think I might have to set the object coordinate system to correlate with the camera's coordinate system, but I can't figure out how. Maybe I'm wrong and there's another way to do that.

## My game implementation

I have 4 vectors for the camera and 4 vectors for each object: origin, x, y and z (to represent the objects coordinate system).

To move the camera, I substract z axis from origin.

Same for other directions.

In order to tilt the camera, for example to the right, I just calculate rotation around Z axis and apply to X,Y axes.

**Note: Movement in the world works good, in all directions and angles.**

Here's the (the relevant) code I use to position objects in the world. Before drawing them I first put them in their origin (recall: I save an origin and x,y,z axes to all my objects), then do some scale to fit my desired size:

```
// translate to position
gl.glTranslatef((float)origin.x, (float)origin.y, (float)origin.z);
// scale to size
gl.glScalef((float)size.x, (float)size.y, (float)size.z);

```

Any ideas?

# Answer
> 1 votes
Your code should be placing the object in one fixed spot with no rotation. It sounds like you want it to be moving so that it's always viewed from the same angle by the camera whenever the camera moves. I guess these are basically like powerups then? If so I guess this makes sense to do.

The good news is that it is simple to rotate the object in the same way as the camera.

```
model = glm::translate(model, glm::vec3(position.x, position.y, position.z));
model = glm::scale(model, glm::vec3(scale));
model = glm::rotate(model, rotationAngle, glm::vec3(rotationAxis.x, rotationAxis.y, rotationAxis.z));

```

To find your rotation angle can be a little difficult though.

So You may find it easier to call the LookAt method for a perpendicular point.

You can find this with the cross product of the origin and the camera's up vector. The result is a vector that shoots off at a right angle from the view. Then you just have the object 'look at' this point.

---
Tags: opengl
---


title: Performance Issues Using Lua in C++

text:
# Question
Title: Performance Issues Using Lua in C++
I'm making an engine in C++ with Lua for its scripting language (using LuaBridge as the binding). I have a lot of entities and those entities have components. One of the components on those entities is a script component. Every time I want to call a different function from a Lua script, I always have to call `luaL_dofile`. If I call this with more than 20 scripts, my game takes too much time per frame reducing it to 5 FPS on my machine. Every script has an `Init`, `FixedUpdate`, `Update`, and `Shutdown` function. For every script, I call all of these functions in order. Is there a way to reduce the latency introduced in each frame from using Lua?

Some pseudo code of my usage of LuaBridge:

```
    // In Update function:
    for (int i = 0; i < scripts.size(); i++)
    {
        luabridge::LuaRef func = luabridge::getGlobal(L, "Update");
        if(func.isFunction())
          func(dt);
    }

```

# Answer
> 3 votes
I think part of the problem (which also caused me to misinterpret the question at first) is the `lual_dofile()` calls.

This sounds like all scripts are always loaded in the same global state, overwriting each other, so loading/parsing causes a significant overhead.

Instead, I'd suggest you use `lua_newthread()` to create a separated context once per script file loaded.

This allows you to load all your script files once and then simply switch between them before calling `update()` or any other Lua function, without having to reload/recompile anything.

# Answer
> 0 votes
**Reduce and Simplify Lua Usage**

Think long and hard about every instance where you use Lua over C++, understand why the flexibility of an interpreted script is more valuable than writing C++, why waste a precious context switch from C++ to Lua if you don't actually gain anything for it?

* Is it easier to tweak it in a Lua script than in C++, is your recompilation time for your engine/game really a bottleneck in iteration?
* Does the code actually change frequently, or is it something that you may only write once and revise sparingly?
* Is this a critical component that will get called many times per entity in your game loop, and in turn, have a performance hit? If so, it's probably better suited for C++ just to avoid running in a VM and having to eat the context switching costs.
* Is this something that you want users/modders to be able to tweak themselves? If so, Lua may be a fitting candidate, if the performance hit is worth it.
* Are you implementing scripting too early in your project? What if you are wasting your time developing the scripting system or scripts themselves? Scripting things makes them more flexible to be loaded and configured without program recompilation, but it comes with a heavy price. You must spend time working on your script integration, you must spend time debugging your scripts without your native debugger, you must spend extra time working on optimizations trying to make up for the cost of using a scripting language.

I think you might be happier replacing your entire Lua system and stockpile of scripts with C++ until you actually think you fit the criterion of using a scripting language over native C++. Using 4 functions in 20 some scripts per entity in your game loop does not seem remotely necessary unless you really need every component to have the flexibility of Lua at every step (I personally think that is never necessary).

However, if you still consider Lua necessary, I do have the following tips:

* Reduce Context Switches between Lua and C++: Don't call a Lua function from C++ that loops through a list of object and calls C++ functions that call Lua functions. That back and forth between C++ and Lua is difficult for the CPU to handle.
* Precompile Lua scripts, Cache references to functions and Lua files so Lua doesn't waste time finding Functions and reinterpreting files.

---
Tags: c++, scripting, lua
---


# Question
Title: OpenGL ES Frame Skipping causing visible artifacts
I'm using OpenGL ES 3.0 on Android 5.1, and am noticing the following issues. I tried to implement the game loop which does exactly 60 updates and do as many frames as it can. Everything is smooth, but the object is being rendered twice, I think due to interpolation by hardware.

If you zoom the image (click to view in separate tab) you'll see that the green square is being rendered twice. And now if I remove the catch-up code, it works correctly.

As you can see it now renders fine. Now I'll show you my game loop. I'm using `GLSurfaceView` class, and doing my render in `onDrawFrame` of the renderer.

```
double now = TimeUtils.currentTime();

if (previous == -1)
    previous = now;

double delta = now - previous;

if (delta >= SECOND)
    delta = frameTime;

lag += delta;

while (lag >= frameTime)  // This line plays catchup.
                          // If commented, it works otherwise the
                          // artifact occurs
{
    updates++;
    doUpdate(frameTime);

    lag -= frameTime;
}

frames++;
glClear(GL_COLOR_BUFFER_BIT);
doRender(frameTime);

if (now - lastStatsTime >= SECOND)
{
    updatesPerSecond = updates;
    framesPerSecond = frames;

    updates = frames = 0;
    lastStatsTime = now;
}

previous = now;

```

Is there anything that I'm doing wrong? I'm using a dynamic VBO for rendering, the lines are generated every frame and I use `glBufferData` to send them to GPU. This happens every frame (This is being done for educational purpose, to learn how VBOs are streamed).

Are there any issues that I'm forgetting?

# Answer
If you zoom the second image - you can see that green square rendered twice and on it to, so probably you have two draw calls for your green square...
> 1 votes

---
Tags: opengl, java, android, opengl-es, opengl-es3
---


# Question
Title: How to wrap ECS components to OOP in libgdx ashley?
Currently I am using builder-pattern to create my `Entities`

```
PooledEngine engine = new PooledEngine();

...

CharacterComponent character = engine.createComponent(CharacterComponent.class);
TextureComponent texture = engine.createComponent(TextureComponent.class);
SizeComponent size = engine.createComponent(SizeComponent.class);
TransformComponent transform = engine.createComponent(TransformComponent.class);
PhysicsComponent physics = engine.createComponent(PhysicsComponent.class);

Entity entity = engine.createEntity();
entity.flag = Constants.CHARACTER;

entity.add(character);
entity.add(texture);
entity.add(size);
entity.add(transform);
entity.add(physics);

engine.addEntity(entity);

```

Because `PooledEngine` class didnt support the creation of casting an Entity to another class that extends Entity. Example `engine.createEntity(Character.class);`, I am having hard thinking how do I wrap these components into single class.

**Objectives**

```
class interface ICharacter {
    void attack();
}

class interface IMoveable {
    void move();
}

class Character extends Entity implements ICharacter, IMoveable {

    private Body body;
    private Vector2 position;

    public Character() {
        PhysicsComponent physics = Mappers.physics.get(this);
        TransformComponent transform = Mappers.transform.get(this);

        body = physics.body;
        position = transform.position;
    }

    @Override
    public void attack() {

    }

    @Override
    public void move() {
        ...
        position.add(x, y);
    }

}

```

# Answer
You are totally defeating the purpose of using an Entity-Component-System by creating that Character class. The whole drive behind ECS architecture is the decoupling/separation of data(Components) and logic(Systems). What you need to do is create separate Systems to handle attack and movement logic.

Read these two articles, they'll help you get a better understanding of ECS architecture and how to use it:

**What is an entity system framework for game development?**

**Why use an entity system framework for game development?**
> 2 votes

---
Tags: java, libgdx
---


# Question
Title: Isometric Tile Selection with rectangular bounding boxes
I am having problems trying to determine which tile I have selected with the mouse.

Currently it selects two tiles, rather than one. Producing the following results:

My tiles height, is half their width, and all tiles have the same dimensions.

The tiles are rectangles and their Cartesian position has been translated to a relative isometric position.

Because I am checking the mouse position with the sprites bounds, it will select two tiles, as demonstrated in the image below:

I suppose my question is, how to I determine that my mouse x/y is within the 'diamond' of the rectangle?

# Answer
This is how the original Civ 1 does it:

It separates the world into rectangles as you do, each rectangle's width and height is the same as the maximum width and height of a tile.

When you click on the screen, it gets the relative position if the mouse from the current rectangle's top-left corner and gets the color from the following image with thise relative coordinates.

Based on the cootrdinate, it can determine the currently picked tile.

**How you should do it**

An isometric tile is a square rotated 45 degrees and scaled vertically to ½.

By reversing this you can transform the mouse's position to a grid. If you divide these coordinates with the height of the tile then you get the currently picked tile.
> 1 votes

# Answer
This is a shot in the blind, but I can see two potential solutions:

**Per-pixel collision detection:** This is probably too much for the job, but using per-pixel collision detection would solve the issue, as only one tile would have opaque pixel under the cursor at a time.

**Distance:** When multiple tiles could be selected, calculate the absolute distance ( sqrt((x2-x1)^2 + (y2-y1)^2) ) between the cursor and the centre of the tile. The tile under the cursor will be the one that's the closest.
> 0 votes

---
Tags: isometric, coordinates
---


title: Random Functions in Unity

text:
# Question
Title: Random Functions in Unity
Is their a way to execute or call a random function in unity. Something like:-

```
  void Update(){random(func1(),func2())}

  void func1(){print("func1")}

  void func2(){print("func2")}

```

# Answer
> 2 votes
The solution by Qbix works when the list of possible functions is static. But what if the list is only known at runtime?

First you need to wrap the function calls into delegates, so you can treat them as variables. A premade delegate from the .NET framework which takes no arguments and returns no arguments is `Action` (There are also template delegates for functions with parameters and with return values). You can then add all the functions to a list and pick a random element from that list:

```
List<Action> functions = new List<Action>();
functions.Add( func1 );
functions.Add( func2 );
functions.Add( func3 );

Action randomFunc = functions[new Random().Next(0, functions.Count)];
randomFunc();

```

# Answer
> 0 votes
Simplest way in the world:

```
Random random = new Random();
// it will roll from 0 (inclusive) to 2 (exclusive) so 0 and 1
int number = number.Next(0, 2);

if(number == 0) func1();
else if(number == 1) func2();

```

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


# Question
Title: Randomly instantiate avoiding overlapping in Unity 5
I'm starting a 2D game where I want all the letters A-Z displayed in a random position and, then, the player collects them all in the correct order. I need to randomly instantiate the letters without overlapping. I use C#.

# Answer
## Separated grid

Randomly pick a box that hasn't been chosen yet, then randomly place the item within that grid space. The space between the boxes is enough so that items placed on the edge of a box doesn't intersect with an item placed on the edge of an adjacent box. This can be implemented pretty simply with a list and a bit of math.

## Try, and try again

Randomly place the items, after each placement, check for overlap. If there's an overlap, remove the item and choose a new random location until you've found one that doesn't overlap.

## Try, and move

Randomly place the items, after each placement, check for overlap. If there's an overlap, move the new item away from the existing item until it fits or goes out of bounds. If it goes out of bounds, try placing it again.

## Use physics

Randomly generate the objects with physics and gravity. Allowing them to drop into a container, letting the physics system keep track of keeping them separated based on their colliders.

## Uniform and wiggle

Place all the items uniformly on a grid, in random order, then change their positions by a small random amount, ensuring that doing so doesn't cause them to overlap.
> 2 votes

# Answer
It's not the cleanest method, but an easy starting point would be to make a `char[]` array filled with all the letter, then randomize the order. Create an array of `Vector3` points that can contain the letters (obviously at least 26 points). Then instantiate an object containing the letter from the next `char[]` value randomly to one of the `Vector3` points. That might be an object that is given the next `char[]` value as a `char` which works with a script on the object to display that letter.
> 0 votes

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


# Question
Title: Programatically Build List of Custom Class Objects (prefabs)
This seems like it should be a simple thing, but I cannot seem to figure out a method.

Currently, I have a `public List<MapGraphItem> roomList` variable, and in the inspector, I add prefabs from Tiled2Unity for a given biome - currently a list of nine tiles for my test biome. Map generation works great via this method. `MapGraphItem` is a custom class that is applied to these prefabs via script.

I'd like to programmatically build the list so that I can build it appropriately based on the biome that's being called (dungeon, forest, desert, et cetera). I seem to be having trouble getting unity to put together a list of the items anyhow (they are in a specific assets folder and also have a specific prefix, in this case "dng\_").

I tried this and some variations on it:

```
List<GameObject> _obj = GameObject.FindObjectsOfType(typeof(GameObject)).Select(g => g as GameObject).Where(g => g.name.StartsWith("dng_")).ToList();

```

But it seems the objects need to be loaded first (plus, I'd need to convert it to a `List<MapGraphItem>` before using it).

I could add another field to the `MapGraphItem` class for biome type and basically load ALL of the assets, but that's a huge waste of resources. Manually adding these for each biome is really not ideal, and really not efficient.

Thanks!

# Answer
> 1 votes
UPDATE: It appears that using the `Resources` folder was the best way to handle this. In the end, I scrapped the methodology I was using entirely and have gone to something different, so I'm not currently using this solution, though I'm likely to again in the near future.

The basis for using `Resources` folders can be found here: https://docs.unity3d.com/Manual/LoadingResourcesatRuntime.html

The short answer is to create a folder called `Resources` anywhere in your project assets area. There can even be more than one of these folders in various locations for organization. You can then programmatically load these at runtime using `Resources.Load()` as outlined here.

This allows you to control where your resources exist logically in the layout of your project, and even call resources from multiple groups into the same script.

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


# Question
Title: Creating a list of buttons dynamically in code
I have a list of contacts. I need to create a scrollable list of buttons that are created dynamically so I can add each contact name as the button text. How would I do this all in code? My biggest concern is making sure the sizes stay consistent. I haven't had to do that in code before.

EDIT:

And here is the code to add the buttons to this:

```
for (int i = 0; i < count; i++)
{
    if (i > 0)
        crt.sizeDelta = new Vector2(crt.sizeDelta.x, crt.sizeDelta.y + initHeight);
    GameObject contactButton = Instantiate(Resources.Load("Contact Button")) as GameObject;
    contactButton.transform.parent = contactsList.transform;
    contactButton.GetComponentInChildren<Text>().text = names[i];
}

```

# Answer
> 2 votes
`ScrollRectHolder` holds `ScrollRect` component. The content of it is `ScrollContent`. Add `Vertical Layout Group` component on `ScrollContent`. It's also the parent of the buttons that will be instantiated each time you need. `Button` is the button prefab that will be instantiated. The variable `initialHeight` is the initial height of `ScrollContent`. Have to get it from `Rect Transform` of `ScrollContent`. Need to update `sizeDelta` with adding `initialHeight` whenever you add a new button.

```
public void AddNewButton()
{
 mRect.sizeDelta = new Vector2(mRect.sizeDelta.x, mRect.sizeDelta.y + initialHeight);
 GameObject gO = Instantiate(buttonPrefab);
 gO.transform.parent = transform;
}

```

unitypackage with scene, script and prefab. Unity 5.2.4f1.

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


title: Scene Transition in libgdx

text:
# Question
Title: Scene Transition in libgdx
How can I make transition between stages in libgdx ?

I have 2 screens MenuScreen and GameScreen each of which has a stage

I write the following to make a transition :

in MenuScreen

```
SequenceAction sequenceAction = new SequenceAction();
sequenceAction.addAction(Actions.moveTo(-Gdx.graphics.getWidth(), 0, 4.0f));
sequenceAction.addAction(Actions.run(new Runnable() {
     @Override
     public void run() {
        gameMain.setScreen(new GameScreen(gameMain));
             }
     }));
stage.getRoot().addAction(sequenceAction);

```

in GameScreen

```
stage.getRoot().setPosition(Gdx.graphics.getWidth(), 0);
stage.getRoot().addAction(Actions.moveTo(0, 0, 4.0f));

```

but the problem is GameScreen does not following MenuScreen directly i.e it wait until MenuScreen has completely gone from screen and I want them to move at the same time

# Answer
There are a lot of different kinds of transition. To concretely answer this question clarify which kind of transition you are looking for.

If you want to do a blended transition, you'll need to render a single frame of the old scene to a buffer, render a single frame of the new scene to a buffer, and then do the transition animation. Here's a pointer for the FrameBuffer.

A simpler strategy is probably to just fade to black on the old scene, then fade in from black on the new scene.
> 1 votes

---
Tags: java, android, libgdx, scene2d
---


title: Jenkins CI with Unity on local machine

text:
# Question
Title: Jenkins CI with Unity on local machine
I have seen some people using Jenkins CI with Unity, would it be wise to install Jenkins locally and use it with Unity? I've never used Jenkins, so I can't imagine why not. Is this ill-advised?

I would have set up Jenkins on my old laptop, but I don't have windows on it. Is there any harm in using it locally?

# Answer
> 1 votes
Jenkins CI does come with the disk I/O, memory, and CPU overhead inherent in running a Java + Apache Tomcat service continuously while your computer is running, otherwise there are no other realistic consequences.

The question is, if you've never used Jenkins CI, why do you want to integrate it with Unity? Unless you discover a good reason that outweighs the costs of adding a new technology to your project/toolchain, don't. So the question "would it be wise" and "is this ill-advised?" depends widely on your project's requirements and even then falls upon personal opinion.

# Answer
> 0 votes
There is no harm using Jenkins on your local machine. Since a CI system is intended to run builds automatically (e.g. nightly builds with tests to ensure code integrity) it would be better to have it running on another machine.

Jenkins can be used on different operating systems as can be seen in the download section on the Jenkins website (https://jenkins-ci.org/).

---
Tags: unity
---


# Question
Title: How to edit and persist serializable Assets in the Editor Window?
I have an asset saved in my project which represents a *serializable scriptable object*. Code of the object is very simple:

```
using UnityEngine;
using System.Collections;

public class TestScriptable : ScriptableObject {
    public float gravity = .3f;
    public float plinkingDelay = .1f;
    public float storedExecutionDelay = .3f;
}

```

There is no problem changing values for this object in the inspector, and the changes do persist and survive after exiting → entering *Unity*.

I am trying to mimic the inspector behavior in an `Editor Window`. But any changes I do in the `Editor Window`, though reflected in the `Inspector`, do not persist. Here is my two scripts which lay inside the `Editor` folder:

**the first one** (auxiliary) - this script replaces inspector fields (see image above) with button, which calls my custom `EditorWindow`.

```
using UnityEngine;
using UnityEditor;

[CustomEditor(typeof(TestScriptable))]
public class TestScriptableEditor : Editor {
  public override void OnInspectorGUI() {
    if (GUILayout.Button("Open TestScriptableEditor"))
      TestScriptableEditorWindow.Init();
  }
}
```

**the second** (with my problem) - script, where I'm trying to change my asset values:

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

public class TestScriptableEditorWindow : EditorWindow {
    public static TestScriptableEditorWindow testScriptableEditorWindow;
    private TestScriptable testScriptable;

    [MenuItem("Window/TestTaskIceCat/TestScriptableEditor")]
    public static void Init() {
        // initialize window, show it, set the properties
        testScriptableEditorWindow = GetWindow<TestScriptableEditorWindow>(false, "TestScriptableEditorWindow", true);
        testScriptableEditorWindow.Show();
        testScriptableEditorWindow.Populate();
    }

    // initialization of my troubled asset
    void Populate() {
        Object[] selection = Selection.GetFiltered(typeof(TestScriptable), SelectionMode.Assets);
        if (selection.Length > 0) {
            if (selection[0] == null)
                return;

            testScriptable = (TestScriptable)selection[0];
        }
    }

    public void OnGUI() {
        if (testScriptable == null) {
            /* certain actions if my asset is null */
            return;
        }

        // Here is my tries to change values
        testScriptable.gravity = EditorGUILayout.FloatField("Gravity:", testScriptable.gravity);
        testScriptable.plinkingDelay = EditorGUILayout.FloatField("Plinking Delay:", testScriptable.plinkingDelay);
        testScriptable.storedExecutionDelay = EditorGUILayout.FloatField("Stored Execution Delay:", testScriptable.storedExecutionDelay);
        // End of the region of change values
    }

    void OnSelectionChange() { Populate(); Repaint(); }
    void OnEnable() { Populate(); }
    void OnFocus() { Populate(); }

}

```

---

My questions is: what am I doing wrong? What could be the problem? How to fix it? Am I loading the asset wrongly in the Editor Window? Or what? Any help/ideas would be appreciated.

# Answer
> 5 votes
Well, everything is simple and complicated, and simple again at the same time.

Despite the visual changes in the inspector - it doesn't mean that the data were actually changed. It looks like everything works fine, but......In my opinion it is shortcoming of the *Unity*

For correctly work you should use few things:

* GUI.changed \- returns true if any controls changed the value of the input data. We would be using it for changes detection.
* Undo.RecordObject \- records any changes done on the object after the RecordObject function. The `Undo state` is recorded, allowing you to revert the change using the `Undo` system.
* EditorUtility.SetDirty (**!!!the most important thing!!!**) - shortly: marks target object as "dirty" and therefore requiring a save. For more information - click the link.

Now, all we need to do is to write some code at the bottom of the `OnGUI()` method;

```
if (GUI.changed) {
    // writing changes of the testScriptable into Undo
    Undo.RecordObject(testScriptable, "Test Scriptable Editor Modify");
    // mark the testScriptable object as "dirty" and save it
    EditorUtility.SetDirty(testScriptable);
}

```

i.e. your code will be like this:

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

public class TestScriptableEditorWindow : EditorWindow {
 public static TestScriptableEditorWindow testScriptableEditorWindow;
 private TestScriptable testScriptable;

 [MenuItem("Window/TestTaskIceCat/TestScriptableEditor")]
 public static void Init() {
  // initialize window, show it, set the properties
  testScriptableEditorWindow = GetWindow<TestScriptableEditorWindow>(false, "TestScriptableEditorWindow", true);
  testScriptableEditorWindow.Show();
  testScriptableEditorWindow.Populate();
 }

 // initialization of troubled asset
 void Populate() {
  Object[] selection = Selection.GetFiltered(typeof(TestScriptable), SelectionMode.Assets);
  if (selection.Length > 0) {
   if (selection[0] == null)
    return;

   testScriptable = (TestScriptable)selection[0];
  }
 }

 public void OnGUI() {
  if (testScriptable == null) {
   /* certain actions if my asset is null */
   return;
  }

  testScriptable.gravity = EditorGUILayout.FloatField("Gravity:", testScriptable.gravity);
  testScriptable.plinkingDelay = EditorGUILayout.FloatField("Plinking Delay:", testScriptable.plinkingDelay);
  testScriptable.storedExecutionDelay = EditorGUILayout.FloatField("Stored Execution Delay:", testScriptable.storedExecutionDelay);

  // Magic of the data saving
  if (GUI.changed) {
   // writing changes of the testScriptable into Undo
   Undo.RecordObject(testScriptable, "Test Scriptable Editor Modify");
   // mark the testScriptable object as "dirty" and save it
   EditorUtility.SetDirty(testScriptable);
  }
 }

 void OnSelectionChange() { Populate(); Repaint(); }
 void OnEnable() { Populate(); }
 void OnFocus() { Populate(); }
}
```

That's all. It was simple and easy.

---

Now the complicated-simple part of the story...

`SetDirty` \- is certainly good. But this function is due to be deprecated in versions of Unity \> 5.3. And also in some versions it will be removed. When? I dont't know. Instead of using `SetDirty` you could go another way:

All actions in the custom Editor or EditorWindow you should do between two calls:

```
serializedObject.Update()

// Here is some of your code

serializedObject.ApplyModifiedProperties()

```

This code contains:

The last four is like the `SetDirty`: they will mark the modified object (or/and scene) as "dirty" and create `Undo states` for you.

So, knowing that, we could get something like this:

```
using UnityEngine;
using UnityEditor;

public class TestScriptableEditorWindow : EditorWindow {
    public static TestScriptableEditorWindow testScriptableEditorWindow;
    private TestScriptable testScriptable;
    // declaring our serializable object, that we are working on
    private SerializedObject serializedObj;

    [MenuItem("Window/TestTaskIceCat/TestScriptableEditor")]
    public static void Init() {
        testScriptableEditorWindow = GetWindow<TestScriptableEditorWindow>(false, "TestScriptableEditorWindow", true);
        testScriptableEditorWindow.Show();
        testScriptableEditorWindow.Populate();
    }

    // initialization of troubled asset
    void Populate() {
        Object[] selection = Selection.GetFiltered(typeof(TestScriptable), SelectionMode.Assets);
        if (selection.Length > 0) {
            if (selection[0] == null)
                return;

            testScriptable = (TestScriptable)selection[0];
            // initialization of the serializedObj, that we are working on
            serializedObj = new SerializedObject(testScriptable);
        }
    }

    // our manipulation
    public void OnGUI() {
        if (testScriptable == null) {
            /* certain actions if my asset is null */
            return;
        }

        // Starting our manipulation
        // We're doing this before property rendering
        serializedObj.Update();
        // Gets the property of our asset and create a field with its value
        EditorGUILayout.PropertyField(serializedObj.FindProperty("gravity"), new GUIContent("Gravity"), true);
        EditorGUILayout.PropertyField(serializedObj.FindProperty("plinkingDelay"), new GUIContent("Plinking Delay"), true);
        EditorGUILayout.PropertyField(serializedObj.FindProperty("storedExecutionDelay"), new GUIContent("Stored Execution Delay"), true);
        // Apply changes
        serializedObj.ApplyModifiedProperties();
    }

    void OnSelectionChange() { Populate(); Repaint(); }
    void OnEnable() { Populate(); }
    void OnFocus() { Populate(); }
}

```

So, it is simple because you should use just

`Update` → actions → `ApplyModifiedProperties`.

But it is complicated because you should do a lot of work with bunch of property classes: `FindProperty`, `PropertyField` и `SerializedProperty`.

But when you understand how it works - it is becoming so easy...

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


# Question
Title: How can I implement a file format that allows for random access to varying-sized sub-files?
I need to store and update collections of serialized data (of varying sizes) into a single file that is compact and allows for efficient random access to the stored data.

Some real world examples:

1. Storing a series of JSON objects (of varying sizes) that can be pulled out individually for parsing given an index or hash key.
2. Other serialized structures that may contain persisted state or configuration settings given an index or hash key.

How can I implement such a file format?

I think at the very least there would need to be an index that points to blocks of the serialized data. Minecraft uses the Region file format which allocates space in the file by a fixed block size and then store data in the header of the file to determine the location and size of the data.

If the data I was storing was static, something like this format would probably be a fit, however, the data could change in length. Because the length may change, I think some mechanism would need to be in place to defragment the file.

# Answer
To do this efficiently the first chunk of data in your file will need to be some kind of index or table-of-contents. Each row of this index refers to a distinct chunk of serialized data within the archive, a "sub-file." At a minimum, each row need only contain the offset to the actual sub-file data within the archive.

For example, if you use filename hashes to refer to your files and your sub-file dataset is small enough and entirely known beforehand, you may be able to create a perfect hash from key to index element.

In practice, though, you'll probably actually want the key to the sub-file in each index row as well, and to organize the rows so you can quickly find the correct row for a given key (for example, by sorting them, you allow for a binary search to locate the index row for a key sub-file key).

You'll also probably want to put the size of each file in the index row as well. You can simply expect that the first N bytes at the file's offset are it's size, of course, but I prefer having the size in the index because it's occasionally useful to have (and it keeps the chunks of serialized data more contiguous).

That's enough for a basic implementation, so you weren't too far off in your initial supposition. There's a few other pitfalls though.

If you're going to generally process the archive by reading it into memory, and then later writing back a new version of it, things are basically done. Fragmentation isn't an issue, nor is adding/removing/altering the size of files. You know the full set before you write to disk and can handle everything fairly trivially.

If you're not able to read the whole thing into memory and rewrite it every time, things get more complicated. Writing into the middle of a file isn't generally possible, unless memory-map the file. In those cases you can, but often cannot extend the size of the file as a tradeoff. This causes issues with both the index chunk (updating sizes, adding/removing rows) and the actual content of the sub-files (which may need to grow).

There are several ways to handle this, some more appropriate for particular scenarios than others, and some which need to be mixed-and-matched to create a full solution:

* For the index, choose a fixed number of rows (say, 1024). That's how many sub-files you can have per archive. This solves issues with the index needing to be updated, but only defers the problem of adding new entries until you hit the threshold. It doesn't address the issue of the actual size of the sub-file data growing as items are added, though. You'd need to memory-map the file to update the index, most likely.
* For the index, store it externally in a sidecar file. It's much quicker to update because it's generally way smaller and thus most of the concerns about having the storage to load the whole thing into memory go away. It does mean you have two files instead of one, and if you lose or corrupt one or the other, you're basically screwed.
* For the sub-files, write all new or modified sub-files to the *end* of the file, leaving old versions of the files, or deleted files, in the archive consuming space until a defrag happens. You can write the file in append mode this way but you can't update the index chunk this way.
* For the sub-files, maintain record deletion status in the index chunk so you know if a file was deleted. Add a free-list chunk after the index that defers to free regions of space in the sub-file chunk formerly taken up by removed sub-files or sub-file that shrank (maybe, though there are tradeoffs here if that sub-file ever needs to grow again). Try to write new stuff or modified-such-that-size-changed stuff into some of these free chunks. You can do this via memory-mapping, until you hit the case where can't fit anywhere and must write via append.
* For something really complicated and probably overengineered, write an offset to the end of the file in your index chunk. Every time you need to add a new asset or update one, write a entirely new index chunk at the end of the file (purely appending), followed itself by an offset to the new end of the file, followed by the new data. This can be done entirely with an append write, but is probably the most complicated solution. It's also the most wasteful space-wise (nothing is ever re-used until a defrag), and least-optimal for random access as if you don't find the desired file in the initial index chunk you need to start hopping to the next chunk and trying there; as you get more and more index chunks, newer files take longer to search for.

For all cases where a defrag is required, simply loading everything and serializing it out fresh will suffice. It's expensive, memory-wise, but it's the simplest. Memory-mapping may let you do the defrag in-place but it's a lot more work.
> 5 votes

# Answer
Use zip format, and take advantage of vast infrastructure of existing tools.
> 0 votes

# Answer
Since your data is changing constantly it's not enough to store an index and keep 'subfiles' of data. This is easy to deal with in ram as separate loosely affiliated data structures but will require writing out the ENTIRE file every time you update some values.

The situation you describe is basically what a database is for. A database will store your data on disk in data structures that already have extra room allocated for additional entries, and indexes that allow you to access data items quickly and efficiently.

Doing all this on your own is actually much more work than it sounds like. SQLLite is an easy to use, free database that could be used for your needs.
> -1 votes

---
Tags: c++, file-format
---


# Question
Title: Why is there almost never online multiplayer in indie games?
There are alot of which are local but very few who have online.

# Answer
> 2 votes
I don't think "very few" is accurate, but aside from the semantics there it's likely that the highest reason is infrastructure. Outside of PC (Mac and Linux) gaming where peer to peer is fairly easy, most gaming (mobile and console) requires a server-client multiplayer option, and running servers and paying for bandwidth to allow that is not cheap. Indie developers typically have considerably smaller budgets and bottom lines.

---
Tags: game-design, game-mechanics, game-industry
---