text:
Add a Countdown Timer that increments in JavaScript and resets per level(Resovled)
I am currently developing a Simon says type game using jquery and javascript.
I have linked a fully copy of the game on github
Github download and unzip to see the game fully https://github.com/Jamiex304/Simon_Says_Game_Demo(Disabled because resolved)
And I have reached a problem I want to add a timer that the player can see ?
currently the level will just go on til the user clicks the wrong button in the sequence.
Some Basic info on the game the user will see a random sequence each level a new sequence is added with one more extra move Each time the user enters the right sequence they go to the next level all info can be found in the attached JavaScript with comments
WHAT I WANT HELP ADDING
I just want to add a timer that starts at 10 seconds when the user clicks the start button Each time the enter the right sequence the timer starts again when they reach 5 right sequences the timer adds 5 extra seconds and so
I already have a div made for it called Timer so the user can see it in the middle of the screen
I have attached the html code and the JavaScript that the game events and the github link offers the full game
Javascript
var game={ //game object
    level: 1, //current level
    turn: 0, //current turn
    difficulty: 1, // user difficulty
    score: 0, //current score
    active: false, //whether a turn is active or not
    handler: false, // whether the click and sound handlers are active
    shape: '.shape', // cached string for the pad class
    genSequence: [], //array containing the generated/randomized pads
    plaSequence: [], //array containing the users pad selections

    init: function(){                   //initialises the game
        if(this.handler === false){     //checks to see if handlers are already active
            this.initPadHandler();      //if not activate them
        }
        this.newGame();             //reset the game defaults

    },

    initPadHandler: function(){

        that=this;

        $('.pad').on('mouseup',function(){

            if(that.active===true){

                var pad=parseInt($(this).data('pad'),10);

                that.flash($(this),1,300, pad);

                that.logPlayerSequence(pad);

            }
        });

        this.handler=true;

    },

    newGame: function(){            //resets the game and generates a starts a new level

        this.level=1;
        this.score=0;
        this.newLevel();
        this.displayLevel();
        this.displayScore();

    },

    newLevel: function(){

        this.genSequence.length=0;
        this.plaSequence.length=0;
        this.pos=0;
        this.turn=0;
        this.active=true;

        this.randomizePad(this.level); //randomize pad with the correct amount of numbers for this level
        this.displaySequence(); //show the user the sequence

    },

    flash: function(element, times, speed, pad){ //function to make the pads appear to flash

        var that = this;                        //cache this

        if(times > 0){                          //make sure we are supposed to flash
            that.playSound(pad);                //play the corresponding pad sound
            element.stop().animate({opacity: '1'}, {        //animate the element to appear to flash
                duration: 50,
                complete: function(){
                element.stop().animate({opacity: '0.6'}, 200);
                }
            });                                             //end animation

        }

        if (times > 0) {                                    //call the flash function again until done the correct amount of times
            setTimeout(function () {
                that.flash(element, times, speed, pad);
            }, speed);
            times -= 1;                     //times - 1 for each time it's called
        }
    },

    playSound: function(clip){              //plays the sound that corresponds to the pad chosen

        var sound= $('.sound'+clip)[0];
        console.log(sound);
        console.log($('.sound'+clip));
        sound.currentTime=0;                //resets audio position to the start of the clip
        sound.play();                       //play the sound

    },

    randomizePad: function(passes){         //generate random numbers and push them to the generated number array iterations determined by current level

        for(i=0;i<passes;i++){

            this.genSequence.push(Math.floor(Math.random() * 4) + 1);
        }
    },

    logPlayerSequence: function(pad){       //log the player selected pad to user array and call the checker function

        this.plaSequence.push(pad);
        this.checkSequence(pad);

    },

    checkSequence: function(pad){           //checker function to test if the pad the user pressed was next in the sequence

        that=this;

        if(pad !== this.genSequence[this.turn]){    //if not correct

                this.incorrectSequence();

            }else{                                  //if correct
                this.keepScore();                   //update the score
                this.turn++;                        //incrememnt the turn

            }

        if(this.turn === this.genSequence.length){  //if completed the whole sequence

            this.level++;                           //increment level, display it, disable the pads wait 1 second and then reset the game
            this.displayLevel();
            this.active=false;
            setTimeout(function(){
                that.newLevel();
            },1000);
        }
    },

    displaySequence: function(){                    //display the generated sequence to the user

        var that=this;

        $.each(this.genSequence, function(index, val) {     //iterate over each value in the generated array

            setTimeout(function(){

                that.flash($(that.shape+val),1,300,val);

            },500*index*that.difficulty);               // multiply timeout by how many items in the array so that they play sequentially and multiply by the difficulty modifier
        });
    },

    displayLevel: function(){                           //just display the current level on screen

        $('.level h2').text('Level: '+this.level);

    },

    displayScore: function(){                           //display current score on screen
        $('.score h2').text('Score: '+this.score);
    },

    keepScore: function(){                              //keep the score

        var multiplier=0;

        switch(this.difficulty)                         //choose points modifier based on difficulty
        {
            case '2':
                multiplier=1;
                break;

            case '1':
                multiplier=2;
                break;

            case '0.5':
                multiplier = 3;
                break;

            case '0.25':
                multiplier = 4;
                break;
        }

        this.score += (1 * multiplier);                 //work out the score

        this.displayScore();                            //display score on screen
    },

    incorrectSequence: function(){                      //if user makes a mistake

        var corPad = this.genSequence[this.turn],       //cache the pad number that should have been pressed

            that = this;
            this.active=false;
            this.displayLevel();
            this.displayScore();

        setTimeout(function(){                          //flash the pad 4 times that should have been pressed
            that.flash($(that.shape+corPad),4,300,corPad);
        },500);

        $('.start').show();                             //enable the start button again and allow difficulty selection again
        $('.difficulty').show();

    }

};
$(document).ready(function(){                           //document ready

    $('.start').on('mouseup', function(){               //initialise a game when the start button is clicked
        $(this).hide();
        game.difficulty = $('input[name=difficulty]:checked').val();
        $('.difficulty').hide();
        game.init();

    });

});

http://stackoverflow.com/questions/2064186/how-can-i-make-a-jquery-countdown

Please mark an answer as accepted when your problem is resolved. If you don't think any of the answers deserve to be marked as accepted write your own answer and mark that.

Got it working full javascript below
var game = { //game object
    level: 1, //current level
    turn: 0, //current turn
    difficulty: 1, // user difficulty
    score: 0, //current score
    active: false, //whether a turn is active or not
    handler: false, // whether the click and sound handlers are active
    shape: '.shape', // cached string for the pad class
    genSequence: [], //array containing the generated/randomized pads
    plaSequence: [], //array containing the users pad selections

    init: function () { //initialises the game
        if (this.handler === false) { //checks to see if handlers are already active
            this.initPadHandler(); //if not activate them
        }
        this.newGame(); //reset the game defaults

    },

    initPadHandler: function () {

        that = this;

        $('.pad').on('mouseup', function () {

            if (that.active === true) {

                var pad = parseInt($(this).data('pad'), 10);

                that.flash($(this), 1, 300, pad);

                that.logPlayerSequence(pad);

            }
        });

        this.handler = true;

    },

    newGame: function () { //resets the game and generates a starts a new level

        this.level = 1;
        this.score = 0;
        this.newLevel();
        this.displayLevel();
        this.displayScore();

        //initialize timer to 10 seconds (10.0)
        this.timer = 10;

    },

    newLevel: function () {

        this.genSequence.length = 0;
        this.plaSequence.length = 0;
        this.pos = 0;
        this.turn = 0;
        this.active = true;

        this.randomizePad(this.level); //randomize pad with the correct amount of numbers for this level
        this.displaySequence(); //show the user the sequence
    },

    flash: function (element, times, speed, pad) { //function to make the pads appear to flash

        var that = this; //cache this

        if (times > 0) { //make sure we are supposed to flash
            that.playSound(pad); //play the corresponding pad sound
            element.stop().animate({
                opacity: '1'
            }, { //animate the element to appear to flash
                duration: 50,
                complete: function () {
                    element.stop().animate({
                        opacity: '0.6'
                    }, 200);
                }
            }); //end animation

        }

        if (times > 0) { //call the flash function again until done the correct amount of times
            setTimeout(function () {
                that.flash(element, times, speed, pad);
            }, speed);
            times -= 1; //times - 1 for each time it's called
        }
    },

    playSound: function (clip) { //plays the sound that corresponds to the pad chosen

        var sound = $('.sound' + clip)[0];
        console.log(sound);
        console.log($('.sound' + clip));
        sound.currentTime = 0; //resets audio position to the start of the clip
        sound.play(); //play the sound

    },

    randomizePad: function (passes) { //generate random numbers and push them to the generated number array iterations determined by current level

        for (i = 0; i < passes; i++) {

            this.genSequence.push(Math.floor(Math.random() * 4) + 1);
        }
    },

    logPlayerSequence: function (pad) { //log the player selected pad to user array and call the checker function

        this.plaSequence.push(pad);
        this.checkSequence(pad);

    },

    checkSequence: function (pad) { //checker function to test if the pad the user pressed was next in the sequence

        that = this;

        if (pad !== this.genSequence[this.turn]) { //if not correct

            this.incorrectSequence();

        } else { //if correct
            this.keepScore(); //update the score
            this.turn++; //incrememnt the turn

        }

        if (this.turn === this.genSequence.length) { //if completed the whole sequence

            this.level++; //increment level, display it, disable the pads wait 1 second and then reset the game
            this.displayLevel();
            this.active = false;

            // Stop counting when sequence is correct to avoid time running out before starting next level
            clearInterval(this.timerInterval);

            //Add 5.0 seconds each 5th level
            this.timer = 10 + 5 * Math.floor(this.level / 5);

            //Update timerdisplay to show fulltime while displaying next level sequence
            $(".Timer p").html(this.timer);

            setTimeout(function () {
                that.newLevel();
            }, 1000);
        }
    },

    // Countdown and update timer, call incorrectsequence when time's up
    countDown: function () {
        this.timer -= 0.1;
        $(".Timer p").html(this.timer.toFixed(1)); // Display 9.0 instad of 9
        if (this.timer < 0.1) {
            this.incorrectSequence();
        }
    },

    displaySequence: function () { //display the generated sequence to the user

        var that = this;

        var timerCount = 0;

        $.each(this.genSequence, function (index, val) { //iterate over each value in the generated array
            timerCount = index;
            setTimeout(function () {

                that.flash($(that.shape + val), 1, 300, val);

            }, 500 * index * that.difficulty); // multiply timeout by how many items in the array so that they play sequentially and multiply by the difficulty modifier
        });

        // Wait to start timer until full sequence is displayed
        setTimeout(function () {
            that.timerInterval = setInterval(function () {
                that.countDown()
            }, 100)
        }, 500 * timerCount * that.difficulty);
    },

    displayLevel: function () { //just display the current level on screen

        $('.level h2').text('Level: ' + this.level);

    },

    displayScore: function () { //display current score on screen
        $('.score h2').text('Score: ' + this.score);
    },

    keepScore: function () { //keep the score

        var multiplier = 0;

        switch (this.difficulty) //choose points modifier based on difficulty
        {
            case '2':
                multiplier = 1;
                break;

            case '1':
                multiplier = 2;
                break;

            case '0.5':
                multiplier = 3;
                break;

            case '0.25':
                multiplier = 4;
                break;
        }

        this.score += (1 * multiplier); //work out the score

        this.displayScore(); //display score on screen
    },

    incorrectSequence: function () { //if user makes a mistake

        //Stop counting down timer and display start message
        clearInterval(this.timerInterval);
        $(".Timer p").html("Get Ready your time starts when you click start");

        var corPad = this.genSequence[this.turn], //cache the pad number that should have been pressed

            that = this;
        this.active = false;
        this.displayLevel();
        this.displayScore();

        setTimeout(function () { //flash the pad 4 times that should have been pressed
            that.flash($(that.shape + corPad), 4, 300, corPad);
        }, 500);

        $('.start').show(); //enable the start button again and allow difficulty selection again
        $('.difficulty').show();

    }

};
$(document).ready(function () { //document ready

    $('.start').on('mouseup', function () { //initialise a game when the start button is clicked
        $(this).hide();
        game.difficulty = $('input[name=difficulty]:checked').val();
        $('.difficulty').hide();
        game.init();

    });

});

Javascript has the setInterval(function(), milliseconds) function which could help here.
If you need to get rid of the interval once you're done with it you can store your interval like so, and then clear it:
var timer = setInterval(tick, 1000);
clearInterval(timer);

You probably meant to write var timer = setInterval(tick, 1000); without a set of parentheses following the function identifier, as to pass the function reference rather than call the function and pass the result.

Indeed, fixed. My JS is a little rusty, the version I used as a reference has setInterval(function(){tick()},1000)

but the problem i am having is implementing it with my code and my javascript, i have found dozens of examples but i cant get any of them to work with my code if u take a look at the game u can see what i want and what i mean

@Jamiex304 your github link doesn't work for me.

I guess you want something like this:
var givenTime=10000
var timeLimit
var clockInterval
resetClock()
function updateClock(){
    var now=new Date().getTime()
    if(now<timeLimit){
        //Set the displayed clock to timeLimit-now
    }
    else{
        //Time has run out
        clearInterval(clockInterval)
    }
}
function resetClock(){
    timeLimit=new Date().getTime()+givenTime
    clearInterval(clockInterval)
    clockInterval=setInterval(updateClock,10)
}

You have timeLimit set to the point in time where the timer runs out, and then a function in an interval recalculate the time left approximately once every 10 ms. Beware that you can't count on setInterval to fire exactly as often as you ask for, see setTimeout or setInterval?

this is great, but the problem i am having is implementing it with my code and my javascript, i have found dozens of examples but i cant get any of them to work with my code if u take a look at the game u can see what i want and what i mean

Try, and if you fail, post your broken code.


text:
Avoiding memory allocation in Android game development
For obvious reasons, allocating memory on the fly in Android game development is not recommended.  For example:
http://developer.android.com/training/articles/perf-tips.html:

There are two basic rules for writing efficient code:

Don't do work that you don't need to do.
Don't allocate memory if you can avoid it.

I'm following this advice and am avoiding any memory allocation whilst the game is in progress; however, it's limiting my approach to certain tasks.  Whilst I could change my code to see what happens, there's a fair amount of it, and it's not going to tell me about the resulting performance on anything other than the limited range of hardware I have available to test it on.
I was wondering if there are any general rules of thumb which can provide an insight into this problem, such as how much allocation/deallocation you can get away with; whether it's the individual size of the allocation or the overall amount that's most important; things you can do to mitigate against the problem (I'm assuming the problem is chiefly having the garbage collector kick in and damage performance, and/or insufficient memory being available if it doesn't fire frequently enough); does it affect some versions of Android more than others, etc.

Which language?

@Ben Just updated tags; Java, and OpenGL.  Toyed with writing the whole thing in C++ but having seen the performance so far that doesn't seem to be necessary.

Well, C++ is a lot more open to managing your own memory. Not only does Java often force you into dynamic allocation, but it's hard to have a guarantee about when it's freed. If you need to manage memory very carefully, C++ or even maybe C is the way to go. HOWEVER, I'd say don't worry about it. You just said that the performance isn't a problem. The only tip I could really give you with java is to try to allocate in bigger chucks( allocate 100 integers in 1 'new' rather than 100 'new's ). But I assume you probably already do that.

@Ben Currently I allocate exactly nothing on the fly.  I've pre-allocated an array of objects, and so when I need a new one in game I just iterate through that array for the first "dead" one, set it to "alive" and use it.  I do this with particles too. I mean, for particles it would be insane to allocate/free tens/hundreds of 10 or 20 byte objects per frame, but less stupid to allocate a handful of 100 or 200 bytes objects.

@Ben So I'm trading the more or less constant time iterating through a number of arrays to create/process the objects they contain against the presumably much more uneven iteration through a list of dynamically allocated objects.  I've never allocated memory in C/C++ and subsequently used it from Java (other than with OpenGL FloatBuffers and the like) although I am competent in C++; is it possible (ie to subsequently use the memory as if you'd done it via a call to new?)

I don't think it's bad to allocate memory for new game objects. It may sound like a bad idea, but when you think about it how often is a new game object going to be spawned? Not once per frame, not even once every second most the time. The thing you most have to avoid to keep up performance is allocating every frame. Even if you allocated a new game object every frame, it still probably wouldn't be much of a problem. Particles are different, though. You allocate a lot of those, so the active/inactive thing is probably a good idea for those.

Generally allocation is okay. Just don't do stuff like build up a 100,000 vertex mesh every frame and you should be okay. Keep dynamic allocation to a minimum, but do it if it makes sense.

most of the iteration for dead objects can be avoided by maintaining a pool of dead objects that just take one from and can set to alive

@ratchetfreak A List containing the offsets into the fixed array of objects which are currently dead?  I guess a list of ints is pretty cheap.

@Ben The bullets in my game are objects, not particles, and they can be created/destroyed tens of times per second.  I think I'm going to have to bite the bullet, so to speak, and try it.  Pre-allocating things is preventing me from using proper OO techniques.

In my experience with android, it is the garbage collection the kills the performance, not the allocation, although these two are tied hand and hand.  As mentioned on the comments, pre-allocation is a way to deal with this issue. This is known as a memory pools.  Another similar solution is object pool pattern. An object pool allocates as needed, but does not immediately destroy an object. If an object is needed and an old object is still alive, the old object is issued. this saves on the allocation and destroying of a frequently used, short lived objects.
In both cases, the objects are checked in and out of the pool, so you are never creating or destroying the objects yourself.
This object pool example is a generic pool, which you can use to create a pool for any object type.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
OpenGL not rendering full scene, it is a mystery
I am trying to draw a scene in the sort of style of mock vector graphics. I've helped on a 2D game before with GLSL, but I tried to keep a simple approach to this project since I'm working by myself, and I want to get the mechanics down before I have to fiddle too seriously with the graphics.
My problem is, for some befuddling (but probably simple) reason, not all of my scene is being rendered. Let me try to explain with my code ...
public class Game
{
    public static GameWindow gamewindow;

    ...

    public delegate void drawhandler(object sender, FrameEventArgs e);
    public static event drawhandler draw;

    public Game()
    {
        gamewindow = new GameWindow();
        gamewindow.Load += load;
        gamewindow.Resize += resize;
        gamewindow.UpdateFrame += update;
        gamewindow.RenderFrame += render;
        gamewindow.Run(60.0);
    }

    GameState.Ship ship;
    GameState.Space space;
    Camera camera;

    void load(object sender, EventArgs e)
    {
        gamewindow.VSync = VSyncMode.On;
        gamewindow.Width = 8*190;
        gamewindow.Height = 8*120;

        camera = new Camera(new PointF(0,0), new SizeF(gamewindow.Width, gamewindow.Height));
        space = GameState.Space.fromrandom(...);
        foreach (Physical p in space.bodies)
            if (p.GetType() == typeof(GameState.Ship))
                ship = (GameState.Ship)p;

        camera.lookat = ship.position;
    }

    void resize(object sender, EventArgs e)
    {
        camera.viewsize = new SizeF(gamewindow.Width, gamewindow.Height);
        GL.Viewport(0, 0, (int)camera.viewsize.Width, (int)camera.viewsize.Height);
    }

    void update(object sender, FrameEventArgs e)
    {
        ...
    }

    void render(object sender, FrameEventArgs e)
    {
        GL.Viewport(0, 0, (int)camera.viewsize.Width, (int)camera.viewsize.Height);
        GL.ClearColor(Color.Black);
        GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
        GL.MatrixMode(MatrixMode.Projection);
        GL.LoadIdentity();

        //GL.Ortho(0, vw, 0, vh, 0.0, 4.0);
        camera.setortho();

        GL.MatrixMode(MatrixMode.Modelview);
        GL.LoadIdentity();

        if (draw != null)
            draw(this, e);

        gamewindow.SwapBuffers();
    }
}

So what happens is that the scene "space" is randomly created when loading. In order to draw the objects in "space", I do this:
public class Space
{
    public List<Physical> bodies = new List<Physical>();
    ...

    public Space(List<Physical> bodies)
    {
        this.bodies = bodies;
        init();
    }

    void init()
    {
        ...
        Game.draw += draw;
        ...
    }

    ...

    void draw(object sender, FrameEventArgs e)
    {
        foreach(Physical body in bodies)
            body.draw(sender, e);
    }

    ...
}

And finally, to draw the hero's ship in that list:
public class Ship : Physical
{

    ...

    public override void draw(object sender, FrameEventArgs e)
    {
        GL.PushMatrix();
            GL.Color3(color);
            GL.Translate(position.X, position.Y, 0);
            // HACK debug thrust vector
            GL.Begin(PrimitiveType.Lines);
                GL.Vertex2(0f,0f);
                GL.Vertex2(velocity.X*100, velocity.Y*100);
            GL.End();
            //
            GL.Rotate(rotation, 0, 0, -1);
            GL.Scale(SCALE, SCALE, SCALE);
            GL.Begin(PrimitiveType.LineLoop);
                GL.Vertex2(-1.0f, -1.0f);
                GL.Vertex2(-0f, 1.0f);
                GL.Vertex2(1.0f, -1.0f);
                GL.Vertex2(-0.0f, -0.5f);
            GL.End();
        GL.PopMatrix();
    }

    ...

}

Simple enough, this works as expected. The only other things I am drawing are "planets", which are simply circle line loops. Now let's draw a quad right in the middle for the hell of it ...
GL.PushMatrix();
    GL.Color3(Color.Orange);
    //GL.Translate(0, 0, 0);
    GL.Begin(PrimitiveType.Quads);
        GL.Vertex2(-50.0f, 50.0f);
        GL.Vertex2(-50.0f, -50.0f);
        GL.Vertex2(50.0f, -50.0f);
        GL.Vertex2(50.0f, 50.0f);
    GL.End();
GL.PopMatrix();

I'll put this after I invoke the "draw" event and before I swap buffers in the render method. Upon running, nothing changes!
I am almost certain that I am making a trivial mistake, but stepping through the code line by line I can find no error. I appreciate any advice in advance.

Depth buffer? Try turning off the depth buffer :) glDisable(GL_DEPTH_TEST); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); <-- Do that once

Gave it a try, no go. But there's no real reason I should be worried about the depth buffer (I believe) since everything is being drawn to the same depth. It's a habit from a previous episode of "why is nothing working right".

Depth buffer bit me more than twice.. it is enabled by default i a mode where even drawing in the same depth hides future draws. My next try would be to isolate only that last rectangle (comment out drawing everything before thst)

Excellent idea! I've got a green quad now, and nothing else. Hopefully I can just keep moving this quad back further in the code and see where it gets tangled up.

Glad i could help:)

Thanks to Lennart Rolland, I found out that the third-party font library I was using (QFont) had a bug in the way it manages its matricies. By moving my quad around in the drawing code, I was able to see where it got mangled. Thanks again for the help!

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
How to increase player Lifes count
I am new in Unity Game Development. I am designing infinite game using C# scripting.
There are many cubes in my game scene. if single cube is hit by player, He gets 100 points.
if same color, two cubes are hit then gets 250 points.
if same color three cubes are hit, gets 500 points....
This kind functionality is used in my game. It increases my score. I want to increase player life after every 2000 points or above. for Example. first life increase 2000 or above, second 4000 or above, third 6000 or above...so on. I don't want to use if condition for every 2000 points because game is infinite.
I don't know how to solve this logic. any help would be appreciated.
Thanks

You can do something like this:
// This is somewhere outside the update function
var lastPoints = 0;

// This is inside the update function
if(currentPoints - lastPoints > 2000) {
    increaseHealth();
    lastpoints = points;
}

This way you can infinitely increase the player hitpoints, until the points counter overflows.


text:
How can I implement a camera like the one in RotMG?
RotMG, an MMO top-down shooter, takes on a unique 2d-3d style, and has an intriguing camera;

The game is obviously 3d, not simply isometric, and if you play the game and turn on camera rotation you will notice the effect the game produces, like so.
RotMG is made using flash, and I am currently experimenting with libgdx (which uses lwjgl/opengl). How should I go about implementing a RotMG-like camera?

Can't speak to the exact implementation details (and if I could it would be off-topic), but here's some obvious ingredients to put together:

The camera is using an orthographic projection. You can tell this because a vertical wall is exactly vertical on-screen no matter where it is — if the camera were perspective then they would be "leaning outward" from the center.
Once you have the camera set up, you just apply the rotation in 'modelview' space — it's exactly the same as if you had a first-person moving camera. The complete sequence of transformations you'd use are:

orthographic projection
rotate around X axis to look down at world
translate forward and down to establish camera's distance from player character
rotate around Y axis (the player-controlled rotation)
translate horizontally to follow player's position in world

Note: Since orthographic projection doesn't give any visual cue about how far the camera is from the scene, it can be easier to make mistakes than with perspective projection, and if you get things really wrong you can have the scene disappear due to near/far limits. This isn't a reason not to use orthographic projection — it's just something to know can go wrong.
The walls, floors, water pool, etc. are ordinary 3D geometry with low-resolution textures. To have the pixelated effect, make sure to specify NEAREST rather than LINEAR texture magnification filtering.
The characters and the water spray are 2D sprites. To learn about how to draw them and keep them upright even as the camera turns, read about billboarding. (The thin black outline and shadows are a completely separate problem to implement.)


text:
How should a Unity object control it's state?
I've been using Unity's component based design, and the biggest problem I've faced is how to control an object's( not component's ) state.
The problem is, some components must act differently based on the object's state. However, checking an object's state within a non-specific component( imagine we have a "DamageEnemyComponent" ) won't work at all because it makes assumptions about the object it's attached to.
The alternative is to make each component perform one, and only one function. The components are then disabled/enabled or added/removed depending on the object's state( probably managed by a more specific component. )
Imagine we have a "Boomerang" object. Assume it has only two states; idle( being held by the player ) and firing. In the idle state, the boomerang would have very few components, because we don't want it to interact with the world while it's simply being held. It may have components to listen for a "throw", though. Once it is thrown, some state manager on the object needs to update the object to have components for moving, damaging enemies, maybe picking up items etc. When the boomerang is back in the hands of the player, it's component list would need to be restored. This would work, but it would basically be building a new game object for each state, which is incredibly tedious and messy without Unity's editor. Not to mention the inheritance and interfaces can't be used well here( since the state specific components will be built into the state manager script. )
I can't see a way to control state using Unity's components. How is this usually done? It feels as if Unity should provide a way to build different states in the editor, much like building an object.

I find that, basically, having components with zero assumptions about the object is wishful thinking. It just never happens in reality. So I don't fret when a component needs to assume existence of some other component(s) on the same object and access them.

@Nevermind Is it right that the "DamageEnemy" component should know about a boomerang? At that point, the DamageEnemy component is better off being built into the state manager.

No, but you can do it the other way round: Boomerang component holds state, and knows to enable/disable DamageEnemy depending on it. That's how I'd do that anyway.

@Nevermind Add properties to the script to force adding a component to the object.( A dependency )

For states, I usually use Enums, and then do a switch statement within the Update method. Enabling/disabling components is probably easier than adding/removing them.
If you need to listen for or be ready to execute a method that should only happen within a specific state, check the state at the start of the method.
If the file gets too long and confusing, you can certainly break certain parts down into their own components and link/reference the various classes between each component as required, then enable/disable each component as required when changing states.
Here's a rough version of how I might code the start of a Boomerang:
// Various states the boomerang can be in
enum BoomerangState {
    Idle = 1,
    Firing = 2
}

BoomerangState state;

// Decide if we should launch the boomerang
bool WeShouldLaunch() {
    return state == BoomerangState.Idle ? true : false;
}

// Launch the boomerang and enable its collider
void Launch() {
    GetComponent<BoxCollider>().enabled = true;
    state = BoomerangState.Firing;
}

// Return boomerang to idle state and disable its collider
void MakeIdle () {
    state = BoomerangState.Idle;
    GetComponent<BoxCollider>().enabled = false;
}

void Update () {
    // Do things based on current state
    switch (state) {
        case BoomerangState.Idle:
            // Hold boomerang and be ready to launch it
            if (WeShouldLaunch()) {
                Launch();
            }
            break;
        case BoomerangState.Firing:
            // Make boomerang fly where needed
            // ...
            // Then when done:
            MakeIdle();
            break;
    }
}

// Only deal damage if boomerang is out and about (eg not idle)
void OnCollisionEnter(Collider col) {
    if (state == BoomerangState.Firing) {
        // Damage the collider we hit
    }
}


text:
When are Unity scripts actually disabled?
When I disable an active script in unity, will it be disabled then and there, or will it only be disabled at the end of the frame?
For example, if I disable a certain script from within a "OnCollisionEnter" event method, will the "disabled" script still perform it's Update method for this frame?

I just tested this using the following code:
void OnCollisionEnter( Collision collision )
{
    this.enabled = false;
    Debug.Log( "Collided with " + collision.gameObject.tag );
}

void Update()
{
    if( this.enabled )
    {
        Debug.Log( "Enabled" );
        return;
    }
    Debug.Log( "Disabled" );
}

"Enabled" was displayed until the object came in contact with something, it outputted "Collided with tag". "Disabled" was never shown, proving that disabling/enabling an object takes immediate effect. It's probably just a flag that is checked when calling event methods.
This is assuming that Update methods are called after OnCollisionEnter, which they, according to the Unity documentation, are.

I think this document from the Unity help should be useful. Look to the diagram at the bottom of the page.
Physics and collisions are processed before the game logic so if you disable an object during collision it will become disabled after its next update.

That doesn't really confirm it. Destroyed objects aren't actually destroyed until the end of the frame, so it could be the same for disabled ones.

Disabled objects are actually disabled until the end of the frame, but there's no opportunity for collision detection to occur. However on the flips side the update will still occur so the answer to your question is yes, the update will carry out.

Edited my response to better answer your question.

Why would collision detection not be triggered, but the update would?

Sorry I misunderstood what you're asking, I thought you also wanted to know if collision would continue to occur. (It's early in the morning where I am...). Basically if you disable the object during collision, update will then happen and only after that will the object be disabled.

Okay, I just tested this by disabling a script upon collision. It's next update was NOT called.

In which case you have your answer and the documentation needs to be updated :)

Well the documentation never said anything about this. It only told us the order in which the events are triggered.


text:
Specular light flickering with high specular power
I'm having some issues with specular lights, to be more specific, the specular color seems to be flickering when I set high power, like 512 (I set the specular color to green, so you can see better):
https://i.stack.imgur.com/SNAmA.gif
And when a power like 32 is used, everything seems ok:

Pixel shader hlsl:
pin.NormalW = normalize(pin.NormalW);

float3 toEyeW = normalize(gEyePosW - pin.PosW);

// Start with a sum of zero.
float4 ambient = float4(0.0f, 0.0f, 0.0f, 0.0f);
float4 diffuse = float4(0.0f, 0.0f, 0.0f, 0.0f);
float4 spec    = float4(0.0f, 0.0f, 0.0f, 0.0f);

// Sum the light contribution from each light source
float4 A, D, S;

ComputeDirectionalLight(gMaterial, gDirLight, pin.NormalW, toEyeW, A, D, S);

ambient += A;
diffuse += D;
spec    += S;

float4 litColor = ambient + diffuse + spec;

litColor.a = gMaterial.Diffuse.a;

return litColor;

ComputeDirectionalLight function:
void ComputeDirectionalLight(Material mat, DirectionalLight L,
  float3 normal, float3 toEye,
out float4 ambient,
out float4 diffuse,
out float4 spec)
{
      // Initialize outputs.
      ambient = float4(0.0f, 0.0f, 0.0f, 0.0f);
      diffuse = float4(0.0f, 0.0f, 0.0f, 0.0f);
      spec = float4(0.0f, 0.0f, 0.0f, 0.0f);

      // The light vector aims opposite the direction the light rays travel.
      float3 lightVec = -L.Direction;

      // Add ambient term.
      ambient = mat.Ambient * L.Ambient;

      // Add diffuse and specular term, provided the surface is in
      // the line of site of the light.

      float diffuseFactor = dot(lightVec, normal);

      // Flatten to avoid dynamic branching.
      [flatten]
      if (diffuseFactor > 0.0f)
      {
          float3 v = reflect(-lightVec, normal);
          float specFactor = pow(max(dot(v, toEye), 0.0f), mat.Specular.w);

          diffuse = diffuseFactor * mat.Diffuse * L.Diffuse;
          spec = specFactor * mat.Specular * L.Specular;
      }
  }

I'm using DirectX 11.

This does not look like traditional specular highlight.. Are you sure you are making one?

What do you mean? Maybe It's because directional light source is almost in front of the sphere?

Distance to light source is not used in the specular equation.

The problem is that L.Direction vector is not normalized, so the dot product "max(dot(v, toEye)" is calculating |v|*cos Θ instead of cos Θ, which is not what we want. So normalizing it on CPU side solves the problem. Thank you @snake5 for helping me on chat with it.


text:
How can I support the clamping of quaternion-based rotations?
Currently I have an orbiting camera that fixates on a single point. In the node-based structure, _cameraNode is a child of _cameraTargetNode. I am able to orbit around the target node via the following code snippet:
Urho3D::Quaternion rotY = Urho3D::Quaternion(1.f, Urho3D::Vector3(dy, 0.f, 0.f));
Urho3D::Quaternion rotX = Urho3D::Quaternion(1.f, Urho3D::Vector3(0.f, dx, 0.f));

Urho3D::Vector3 curPos = _cameraNode->GetTransform().Inverse().Translation();

_cameraNode->RotateAround(curPos, rotY, Urho3D::TS_LOCAL);
_cameraNode->RotateAround(Urho3D::Vector3::ZERO, rotX, Urho3D::TS_PARENT);

cameraNode->LookAt(Urho3D::Vector3::ZERO, Urho3D::Vector3::UP, Urho3D::TS_PARENT);

Now what I want to do is clamp this movement. I want to be able to orbit within a set area between the two following values:
const Urho3D::Vector3 rotClampMin = Urho3D::Vector3(0.f, -45.f, 0.f);
const Urho3D::Vector3 rotClampMax = Urho3D::Vector3(90.f, 45.f, 0.f);

RotateAround sets both the angle and position of _cameraNode, so I must pre-compute the values with the clamping in mind. I would like to avoid working with Euler angles as much as possible. How can I clamp my rotation prior to calling _cameraNode->RotateAround?

Well, since you want to clamp on Euler angles (or else I didn't get what was ratClampMin), converting your quaternion to Euler angles remains a valid solution.  Else you need to do the conversion the other way round, converting the obvious inequalities with Euler angles into inequalities of quaternions, with an adequate change of variables (https://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles).  That may lead up to more than four inequalities due to the use of sine and cosine function.  Also I didn't get what "values" you want to pre-compute.

What I meant by pre-compute is that I would prefer to clamp, then rotate. I will see what comes from using Euler angles a bit more, however half the reason I started using Quaternions (outside of the obvious fact that Urho3D uses them internally) is because I've ran into the known issues of Euler angles and wish to avoid them.

I was able to do this by applying the correction after the initial transformation, though I would prefer an answer that applies the correction prior to the initial transformation so as to avoid transforming the camera twice.
After the:
_cameraNode->RotateAround(curPos, rotY, Urho3D::TS_LOCAL);
_cameraNode->RotateAround(Urho3D::Vector3::ZERO, rotX, Urho3D::TS_PARENT);

I added the following logic:
Urho3D::Vector3 curRotation = _cameraNode->GetRotation().EulerAngles();
Urho3D::Vector3 correction = Urho3D::Vector3::ZERO;

if (curRotation.x_ < rotClampMin.x_)
    correction.x_ = rotClampMin.x_ - curRotation.x_;
else if (curRotation.x_ > rotClampMax.x_)
    correction.x_ = rotClampMax.x_ - curRotation.x_;

if (curRotation.y_ < rotClampMin.y_)
    correction.y_ = rotClampMin.y_ - curRotation.y_;
else if (curRotation.y_ > rotClampMax.y_)
    correction.y_ = rotClampMax.y_ - curRotation.y_;

curPos = _cameraNode->GetTransform().Inverse().Translation();

rotX = Urho3D::Quaternion(correction.x_, Urho3D::Vector3(1.f, 0.f, 0.f));
rotY = Urho3D::Quaternion(correction.y_, Urho3D::Vector3(0.f, 1.f, 0.f));

_cameraNode->RotateAround(curPos, rotX, Urho3D::TS_LOCAL);
_cameraNode->RotateAround(Urho3D::Vector3::ZERO, rotY, Urho3D::TS_PARENT);

This works perfectly.

You should mark this as the accepted answer; it should have been long enough that the timer is expired.


text:
Where should I put code if I want it to run automatically?
I'm new to programming and I found an animation script that has code that is called in the OnMouseDown event, when the user clicks the object. I'd like the code to run automatically, instead of responding to an event. Where can I put code to be called automatically

I'm not sure entirely what you mean by "code start automatically" or but I assume you want to make it so that the animations play immediately once the scene loads. If that is the case, all you need to do is call the "Play()" function inside the "Start()" function.
You should consider reading Unity's Documentation on the Monobehaviour Class. What you have right now works because it is, essentially, overloading a function in the base Monobehaviour class which recieves an event on click. If you wish to define different conditions which make the animations play or stop, you need to add a function overload or implement your own logic depending on the results you desire.
Lastly, since you've added that you are new to programming, I would suggest you read up more on object oriented design and coding fundamentals before continuing with Unity. You can get by with looking at pre-made code samples, but understanding the way programming works on a fundamental level will help you when it comes to reading API documentation and understanding the flow of programming.
I hope this helps, let me know if you were looking for something more specific.

That did help me! I just didn't know where to put the "Play()" function exactly. Adding it inside the "Start()" function brought me just the result I wanted. Thanks!


text:
When two RPC methods have the same name, which is called?
I have a situation where I would want two of the same components( in a hierarchy ), to be on a GameObject. If this component has an RPC method, it obviously cannot change name per instance of the component.
Which RPC method will be called? Unity says this:
"if two RPC functions in different scripts have the same name only one of them is called when RPC is invoked"
This says nothing about which will actually be called. Does Unity define a behavior for when this happens? Is there any alternatives that will avoid this?

This probably depends on internal compiler details. Usually the reason for not saying things like this is so they can change the behaviour if they want. If you state what will happen then future versions will have to honour that, even if it gets in the way of optimizing.

Other than to specify that "only one" is called, Unity does not guarantee any behavior in this case. The most likely scenario, which you can determine through experimentation, is that either the first RPC that becomes registered/known to the system is called, or the last one is. However, this is an implementation detail.
Unity explicitly does not want you to care about which function is called in the scenario you're describing; there are several potential reasons, including:

This could be because their implementation of the RPC mechanism trades efficiency of dispatch for the inability to deterministically resolve overloaded RPC names.
Alternatively, this allows them the flexibility to change their implementation in the future without worrying about violating an API constraint.
It's kind of a bad habit to have two RPC methods with exactly the same name in the scene, as it complicates things and makes it harder to reason about execution flow. By not providing a guarantee they are discouraging you from this behavior.

Unfortunately, if there's two components on a single game object that have a common base class with a single RPC, this problem is going to be encountered. I created an alternative that searches for the correct component and uses reflection to call the method. I feel this is a HUGE problem with Unity's networking. Anyway, your answer answered the question. Thanks.

Is it not possible to use the FQN of the RPC name (I've never actually used the mechanism)? That's unfortunate.

Perhaps, haven't tried it. I'll try it out though. It might be a much better solution than what I've got right now. Presumably RPC just uses System.Reflection, so it should work.


text:
Change unity physics engine speed
Is there a simple way to change the speed* of unity's physics engine like in the game SuperHot?
Any script language is ok but javascript is preferred.
*I am not sure if speed is the correct term.

You can use Time.TimeScale for slow motion effect.


text:
If fixed timesteps are unreliable across web platforms, what can I use in my game loop?
As I have found out in my previous question, window.setInterval is not the best choice for a cross-platform game loop. What is my alternative for a game loop in Javascript that will (attempt to) run at the same speed on all devices?

Also, you'll want to look into using requestAnimationFrame over something like setInterval()

You shouldn't assume your timesteps are fixed for a local game either. Always measure your time step and make sure only the appearance of the game is affected by a non standard interval

You shouldn't use equal intervals for game loop. Instead of this use time_delta (current_time - last_update_time). Send time_delta to  game object's update method and update position and other parameters depending on time_delta. For example, simple object moving with const velocity will be:
function update(time_delta) {
    position = position + velocity * time_delta;
}

In this case, you don't need to set fixed frame per second and allow game to update state as fast as possible.

Good but rather incomplete answer. I'll just leave this here: http://gafferongames.com/game-physics/fix-your-timestep/
In sum, use fixed step delta times, it gives better accuracy for physics integration and is more predictable.

you could simplify this to position += velocity * time_delta


text:
How can I separate component functionality from networking logic?
Is it possible to make network independent components that allow networking details to be specified externally?
For example, if I have a "Follow" script that follows a game object, it would need to do certain actions on the server and certain actions on the client. However, these things can change based on the network architecture. Single player games would not even need to consider what runs where. That makes perfect sense, except why should a component as general as "Follow" need to be different across different types of game?
I've tried creating a base component class that figures out how to call each method based on options set in the editor, but that failed due to RPC names needing to be different across all components attached to one game object. Not to mention it was messy. I've tried abstracting method calls to figure out how they should be called, but that doesn't solve the problem of WHICH methods should be network invoked.
I really don't want to build this into the components themselves, even though it might be the easiest / most obvious solution. That would destroy their portability across projects.

So you want to create a generic network handler that will parse generic commands to be handled by generic classes across multiple platforms?...

Need a little more clarification on what you mean by networking details specified externally.  Are you talking about externally specified configuration parameters or externally specified code?  The parameters is relatively easy where you probably want an interface that queries a configuration server for the parameters to be used during runtime.  External specified code is going to be a lot more difficult.

@RightHandedMonkey I actually had the editor in mind. So, for each method, I oculd tick boxes or whatever saying which method is called where.

I wouldn't recommend that, although it's technically possible.  You might use the editor to choose a method to handle a particular event, such as a button click. But for non-trivial behavior you should separate the components.  One big component which does different things depending on editor settings is a bad idea for the reasons in my answer.  Your configuration should be used for minor or non-functional changes in behavior. i.e. You might have a button on your lawnmower to change the speed of the blade, but you shouldn't have a button that turns it into a toaster.

It sounds like your intuition is correct and the components should be separate.  However, I would look for better abstractions.  For example, you say:
"a base component class that figures out how to call each method"
Putting Unity aside, this is something of a design anti-pattern (in OOP).  You'll wind up with messy classes that don't have a clear purpose and do too broad a variety of things (violate Single Responsibility).  You will also have a base class that has knowledge of the more specific derived classes (the inverse of what you want).  Instead, try to break the functionality into logical parts and use those as class boundaries.  Here's an arbitrary example of classes you might create:

FollowBehavior - keeps one object at a given proximity to another object
FollowNavigator - determines which coordinates an object should move to when following (consumed by FollowBehavior)
NavigationClient - Sends requests to a server to move an object from one set of coordinates to another (optional)
NavigationPredictor - used to smooth the rendering on the client by anticipating acknowledgements from the server.  Helps avoid server lag.

You can see that each class is responsible for a very specific task.  They are also modular.  e.g. You might keep the general follow behavior, but "plug in" a new FollowNavigator for a new experience.  Hope that helps.

I'll mark this as the answer before the expiry date. I'm just going to let others have a chance at an even better answer. Thanks for the answers and comments.


text:
How can I make Network.RPC call a method with params object[]?
Why do I need to do this? The game I'm working on fully conforms to a component style design. Every component that a game object uses is placed on the object and is disabled/enabled based on it's state machine's current state. This means if I have two components that share a base class that has an RPC method, they won't work due to this:
"RPC function names should be unique accross the scene, if two RPC functions in different scripts have the same name only one of them is called when RPC is invoked"
http://docs.unity3d.com/ScriptReference/NetworkView.RPC.html
This means an arbitrary component will be the "this" of the RPC method that actually gets called. So, to fix this I've added a unique name to every component and have to do some relatively slow searching and reflection in order to have a safe RPC call. So, now every RPC call should go through my RPC method. This method simply serialises the parameters into a string and sends them to unity's RPC method.
This works great, except one tiny thing. Serialising the entire array results in Unity doing no serialisation in NetworkView.RPC. That's fine, except as far as I can tell, Unity's NetworkView.RPC method is the only thing in the universe that knows how to serialise a NetworkViewID properly.
So, serialising the whole array of objects isn't an option. So, I now I serialise them IF they're not a NetworkViewID, then send the entire object array to Unity, which it does interpret correctly:
protected void ComponentRPC( string methodName, RPCMode mode, params object[] args )
{
    object[]                serialisedObjects       = new object[args.Length + 2];

    serialisedObjects[0] = uniqueName;
    serialisedObjects[1] = methodName;
    for( int i = 2; i < serialisedObjects.Length; ++i )
    {
        if( args[i - 2].GetType() == typeof( NetworkViewID ) )
        {
            serialisedObjects[i] = args[i - 2];
            continue;
        }
        serialisedObjects[i] = base.Serializer.Serialize<object>( args[i - 2] );
    }

    // Serialise arguments and call our RPC method through Unity.
    networkView.RPC( "ComponentRPCNetwork", mode, serialisedObjects );
}

I also put the unique component name and method name in the array. The only problem now is, Unity won't put the objects it serialises into my params object[] parameter. The RPC method:
[RPC] private void ComponentRPCNetwork( params object[] args )
{
    // First we have to deserialise the method arguments.
    string              uniqueID                    = ( string )args[0];
    string              methodName                  = ( string )args[1];
    object[]            deserialisedArgs            = new object[args.Length - 2];
    for( int i = 0; i < deserialisedArgs.Length; ++i )
    {
        if( args[i + 2].GetType() == typeof( byte[] ) )
        {
            deserialisedArgs[i] = args[i + 2];
            continue;
        }
        deserialisedArgs[i] = base.Serializer.Deserialize<object>( ( string )args[i + 2] );
    }... // More stuff.

So, my question is, can I get Unity's NetworkView.RPC method to put it's serialised objects into this "args" parameter? If not, can anyone see anyway around this?
By the way I'm using Vexe's framework, so you might see unusual things like "base.Serializer" etc.

Can you not just have [RPC] private void ComponentRPCNetwork(object[] args ), basically, drop the params on your [RPC] method? If you need to use it locally too you can just write a local wrapper that takes a params and passes an array to the [RPC] method.

Dropping the params still doesn't help. Unity's RPC method is looking for a method that takes every argument passed into it. So, if I pass it ( Vector3, Vector3, string ), it'll look for a method with those exact parameters and not accept anything else even though syntactically it would compile.

Ah, I understand the issue now, you'd have to cast everything in the array to an object. Well, it's undocumented, but the RPC method does allow a byte array. You can serialize your object array into a byte array. Pull out the NetworkViewID, resulting in something like: ComponentRPCNetwork(NetworkViewID viewID, byte[] objects )?

Yeah, then nothing passes through unity's serialiser, which I've found is the only way to get the serialising of a NetworkViewID to work properly. If I let Unity serialise a NetworkViewID, it works fine. If I use JSON, the allocated id won't be found by the receiver. If I use BinaryFormatter, it won't allow me to serialise it because it's missing the System.Serializable attribute.

I regularly use RPC like the following:
{
    //Send all the ship components to other clients
    NetworkViewID viewID = ship.GetComponent<NetworkView>().viewID;
    foreach(ModuleDefinition module in ship.GetAllModuleDefinitions()) {
        networkView.RPC ("AddShipModule",
                         RPCMode.Others, viewID, netOwner,
                         ModuleDefinition.WriteByteStream(module));
    }
}

[RPC]
public void AddShipModule(NetworkViewID newPlayerView,
                          NetworkPlayer netPlayer,
                          byte[] moduleInitializer) {
    if (netPlayer != Network.player) {//don't update ourselves
       //deserialize moduleInitializer into module and add it to local instance
    }
}

This is when using my own serializer to create the moduleInitializer out of an object and its components. That byte[] array could just as easily be full of JSON or any other binary data.
If your allocated ID is not being found on the other end, it could be because the object you're trying to communicate was created incorrectly, giving it a different NetworkView.viewID. You can always use Network.Instantiate or you can send a message to clients that an object needs to be instantiated and send the NetworkView.viewID along with it.

Yeah, I started to suspect that it's probably just my creation code. But if that's the case, how come this works perfectly using RPCs directly?

It's a good question that I don't have an answer to. Perhaps there are other factors at play when you're switching between the two methods of RPC. If you're not sure about the creation code, you can post a new question for that so we don't get too off topic here.


text:
Is it worth it to encrypt data?
I am using Java to write a moderately simple video game and I need to transfer some large files (edit: Live game data and possibly assets.) between the client and the server. I need to decide whether I want to encrypt the data even though no sensitive information is being transferred. If I were to encrypt the data what method would be the best? Also, does encrypting data make cheating harder?

are the large files assets (like textures and models)?

No they are not assets.

Encrypting the data each player receives makes cheating and ripping of assets a bit harder, but not impossible. The data needs to be decrypted by your game client anyway, so the encryption algorithm and key must exist on the users machine. That means the users have everything they need to decode the network traffic. So you only add a layer of security through obscurity, which isn't any real security.
It could get interesting, however, when you have cheaters who are eavesdropping or even manipulating the connection of other players to get an advantage. Attacks of that level of sophistication are quite uncommon in gaming, but certainly not inconceivable, especially when cheater and target are on the same network. When you encrypt the data for each player separately with a key only known to the receiver, you can prevent that.
But make sure you use a cryptographically secure algorithm. There are libraries available for most common algorithms in most programming languages. In Java, you even have hard encryption in the standard library.

Yeah, that was my first idea.

I see the following reasons to encrypt data:

Protect your users' actual sensitive data by adding to the amount of encrypted traffic. If hackers have to wade through not sensitive game assets, they're much less likely to find a user's actual sensitive data.
Protect your servers. Using asymmetric key encryption (like TLS, what people still commonly refer to as "SSL") usually ensures that the user is not tricked into giving their password to a man-in-the-middle, who can then use it to get a level deeper into your server. (assuming you verify who you're talking to)
Protect users' in-game purchases, e.g. in so-called "free to play" games. If your game has micro-transactions, attackers like to hack a user and transfer in-game items to another account under the attackers' control, where it can then be sold. Proper encryption makes it harder to spot the password in the traffic.
Protect yourself from stupid ISPs. Some ISPs (Hotel Wifi) look at clear-text traffic and modify it. E.g. replacing banner ads with their own. Also, certain mobile carriers will re-compress image files to save bandwidth. If your game assumes all assets are true-color PNGs and they convert them to 4-bit to save space, your game will crash. Using TLS encrypted connection ensures that the files your server sends are what your client gets, because ISPs can't introspect them. This is even more important if your downloaded assets contain scripts that an attacker could replace to run malicious code on your user's machine (esp. if you have automatic patches to your game engine that gets run as root via an installer, or so).

Whatever reason sways you, do not roll your own encryption. It's too easy to subtly get something wrong and do a lot of work but leave the barn wide open. Go with the established standard (i.e. use a TLS connection) to protect the data in transit, and verify the server certificate against its public certificate to be sure you're talking to the right machine (that's a thing commonly forgotten).
Regarding cheating: Your client has to be able to decrypt the data it gets and make requests. The client runs on the user's machine. If the client app can do that, it can do anything else. Reverse-engineering that is trivial. Is it harder to have any encryption compared to plain text? Sure. But it'll barely deter anyone. If your game has a network component, make all the game-relevant calculations happen on the server, and only transfer data to the user that they should have at this point in the game.
For speed, you can have the client pre-calculate the likely result of an action and display that while it asks the server to verify that and actually write it into the server's storage. If someone is trying to cheat, the server will thus catch it and the client's display will immediately reset to the "un-cheated" state.
Encryption is not an anti-cheat measure.

But, no sensitive data is transferred.

@Benjamin Re item 1? Not by your app. But by other apps on the user's computer. If you send unencrypted, hackers know they can just ignore your app's data and home in on HTTPS connections to hack your user's home banking. If you mean Re item 2, where do you keep game state, and why do you need to download anything at all if your game is all offline and doesn't have a way to associate the user with their data?

It is a multiplayer game but no sensitive data is transferred.

Do you care if people can get your assets? Do you transfer gameplay data? If any of the questions is true, then encrypt.
I would use XOR cipher. It's super simple, super efficient, not super secure but you apparently don't care (it WILL make cheating harder of course, if you send gameplay data though). It works with streaming data, and the encryption is the same as the decryption -- just apply it twice to get the original.
XOR cipher C++ code example:
char * key = "whatever";
int keylen = strlen(key);
int i, string_length = strlen(string);
for(i=0; i<string_length; i++)
    string[i]=string[i]^key[i%keylen];

where "key" is your cipher key. What it does is for each character of your string, you select a character from your key and you XOR it. when you XOR it again you get the original. Replace "whatever" with .. whatever :)

The answer to your first question is not true as it is semi-open source, the answer to your second question is true. Is it possible to implement in Java or would I have to use some sort of bridge?

Ok, then encrypt the gameplay data at least, or more, to confuscate what's gameplay data and what's not :) It is possible to do it in Java. I'm not a Java coder but it's straightforward : a xor operator and basic string handling. I provide a C++ example.

-1 A simple XOR cypher is so easy to crack that even an amateur hacker won't be stopped by it for long. When you use encryption, at least use a cryptographically secure algorithm. And no, it's not harder to implement. You just have to use a library.

Thanks. @Phillip Would it still make cheating harder?

@Benjamin Depends on how skilled the hacker who programs the cheat. It would take them between a few minutes and a few hours longer to reverse-engineer your network protocol. So you can expect that a simple XOR encoding will give your community at most one day more before the first cheats are offered for download.

@Benjamin every step of obfuscation makes the hurdle bigger but it's never impossible to overcome.

@Philipp Would periodically changing the key in new updates help?

@Benjamin Not really. When they figured out you use XOR encoding and they figured out how your protocol looks unencoded, figuring out the new key is trivial. In fact, a cheat could be written to figure out the new key on its own. All they need is a segment of your netcode which is always the same in plaintext. XOR the plaintext with its encrypted version and you get the key (this is known as a "known plaintext attack").

@Benjamin for a XOR cipher? it's the work of a few minutes to match up expected plaintext data to the cipher text, however using a true crypto algorithm then they'll have to dive into the code/assets to find the key. Better would be a random key per connection

Omg I just offered a simple solution for a simple video game, what's up with all those downvotes? I get it, you want to promote your own solution, but no need to stomp on mine. Ok Benjamin, if you are writing WoW or a real-money-auction house and expect thousands of rabid players ready to cheat, do NOT use XOR, sure, go wild with security, you can never have enough anyway. If you want something simple, do something simple, I really doubt on the first day of your game release your players will release cracks and cheats.

@ratchetfreak Thanks for the help! I will most likely be using a built in Java encryption method. Would changing that key help? Also, how would be the best way to generate random keys?

@Benjamin you can use KeyAgreement to let client and server agree to a private key between them. It's designed to let 2 parties generate one privately so a eavesdropper can't derive it.

@Babis Main problem with your answer is "it WILL make cheating harder of course". It's not true, because modify client much easier for cheaters than faking requests to server. So if client have no defence from modification encrypting data just eats CPU time without any reason.

@ratchetfreak Okay, I will try that.

@Kostya I said hardER, not "hard", "very hard" or something else. It is true - XOR makes it harder than plain bytes.


text:
Does compressing data before transfer make a game run faster?
I want to make my game as fast as possible as it is real time and fast paced. I have already decided to encrypt my data here and I was wondering whether compressing it would be faster for the client and the server? Also I was wondering if it is better to encrypt data before or after compression.

It depends where the bottle neck is.
If you IO bound (the game is always waiting on network IO) then yes compressing will help.
If your game is CPU or memory bound then it will just run slower.
You should compress before encrypting because cipher text is less compressible as a result of trying to remove patterns that could be used to reverse engineer the cipher.
A better solution would be to make the protocol as compact as possible to begin with, for example by using a binary transfer method; binary data is easier to parse than text data and can be more compact (a double fits into 8 bytes while most doubles printed out take more than that).

Okay! What would the best method for encryption be?

AES with code block chaining is good enough

Just to add to your question : When sending binary data over sockets you have to watch out for different endianness ( talking about C/C++ and System APIs, Not sure about java )

@EdoardoTygerDominici DataOutputStream does high byte first. And the ByteBuffers default to BIG_ENDIAN.

@ratchetfreak Sorry, misspoke. Meant to ask, "What would be the best method for compression?"

@Benjamin Use what is available, java.util.zip.Deflater uses the standard ZLIB compression


text:
Stroring components in arrays (entity component system)
I'm looking for ways to improve my ECS and I've seen many people suggest storing components in arrays. This seems great, considering fast access for a component using entity id and more importantly, fast iteration over elements of array (because systems do this all the time) and fewer cache misses than if I store components in Entity or use:
std::map<int,std::shared_ptr<Component>> components // where int is a component id

But I have some questions about this approach.
1) Do I have to create array for each component? Something like:
PositionComponent positionComponents[MAX_OBJECTS];
HealthComponent healthComponents[MAX_OBJECTS];
...

Or is there a better way to store different components contiguously in memory?
2) How can I get components using entity id if I do this?
I'd like to implement some function like this:
template <class T>
T* getComponent(int entityId) const {
    ... // ??
}

so I can then use it like this:
PositionComponent* pc = getComponent<PositionComponent>(entityId);

This seems great, considering fast access for a component using entity id and more importantly, fast iteration over elements of array (because systems do this all the time) and fewer cache misses than if I store components in Entity or use:

Have you actually measured cache misses? Are they in any way being a problem for you? Would eliminating them for your component accesses be likely to have a measurable impact? Is it valuable for you to spend your optimization time worrying about them instead of focusing on parallelism or better GPU usage? Do you at least have measurements of your code before any such change so you can compare them to measurements from after the change?
Simply putting things in an array doesn't guarantee fewer cache misses, either. It's the first step of several to improving cache usage for components. It may be a false step for improving your overall performance, too.

1) Do I have to create array for each component? Something like:

PositionComponent positionComponents[MAX_OBJECTS];
HealthComponent healthComponents[MAX_OBJECTS];

A std::vector or the like would work just as well. Note that as the vector could reallocate its backing storage and invalidate existing existing iterators/pointers you'll have to use component indices rather than pointers.
You can also easily write a chunked storage means (like a std::deque, but not optimized for queues) that allows the structure to grow, keep fast iteration, and have stable pointers.

2) How can I get components using entity id if I do this?

template <class T>
T* getComponent(int entityId) const {
    ... // ??
}

You can store an additional boost::flat_map or std::unordered_map or a custom high-performance hash table that maps entity IDs to component indices for that component type.
You'll probably just want to map to an index or a temporary pointer (one you promise never to retain) as that allows the component holder to defragment its component collection. That both can potentially allow the holder to release blocks of memory and more importantly (for data-oriented needs) is essential to actually making iteration over components faster. It's likely going to be much faster to use your existing approach than it is to iterate over a huge and sparsely-populated array. Remember that with a sparse array (even if 99% occupied) you have to add an additional if (isInUse) check inside your loop over the components which is an additional read+branch instruction that can have a noticeably negative impact on your overall iteration speed.
See BitSquid's four articles on the topic. Those guys tend to focus on C-like code and eschew modern C++ approaches with identical performance but easier usage, but the underlying approaches they use are applicable in C, C++, C#, Rust, or similar languages.

To be honest, I have more problems with the design and lots of virtual casts I have to do at the moment(I store Components in Entity as std::vector<Component*>) than cache misses. I just want to make "pure" ECS where entity is just an id.
And how would that unordered map work? I don't quite get it. Can you provide a more specific example, please?
And thanks for that link, will definitely check it out.

@EliasDaler: the articles linked explain the use of a hash table like unordered_map, only they use their own. The concepts are the same.

Unfotrunately, their articles doesn't answer my question. Their component design is very different from mine. But still, thanks, I'll mark this answer as your explanation makes sense to me now.

@EliasDaler: perhaps I don't understand the question, then. The article goes over how you use a hash table to map entity IDs to component indices. That bit should work the same even if your components are different. If I'm understanding you properly.

@SeanMiddleditch Just a clarification for Q 2 if you can respond. So suppose we store a std::vector<componentType> positions; in a system (say the MovementSystem) that is the one responsible to iterate over all such components for processing. So you're saying that besides that vector (which stores the data for an entity) we should also contain a hash_table/unordered_map<ComponentType> which will give us the index of our target entityId into that std::vector<ComponentType> positions vector?

@Nikos: that's the low-tech way, sure. And totally sufficient for many users. There's more sophisticated implementations of that general idea which are possible (based on "slot maps" or what the bitsquid articles called "packed arrays" or what EnTT calls "sparse sets") but don't over-engineer if you don't have to. :) You might want to check out some other open source C++ hash tables (like those in Abseil) besides unordered_map which has... issues (it's designed for a set of invariants that don't apply here but which impose serious perf overhead for this case).

1) Do I have to create array for each component?

Yes, but a vector would be more convenient, and equally performant.

2) How can I get components using entity id if I do this?

You should store the Entity ID on the components themselves. Keep your vector sorted by that ID, and then use vector::lower_bound to retrieve the components. In my own testing, this lookup is actually faster than a map up to a certain point.


text:
LibGDX , Scale button with animation when it is pressed
I am developing game using LibGDX . I want to create beautiful menu and to scale buttons when they are pressed but not in this way , when it is pressed scale it 1.5f , I want to scale it with animation . I am using imagebuttons .

Since you are using Actors you can simply give the actor an Action. For scaling you could use this method:
myActor.addAction(Actions.scaleTo(scaleX, scaleY, duration);

Then when the user stops pressing the button you can cancel the current action and give the actor a new one that scales back down to the original size.

You could change the scale by a factor n each time in the render loop when the button is pressed.
Initialisation of your ImageButton:
button = new ImageButton(Assets.button_style);
    button.addListener(new InputListener(){
        public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
                // enable scaling when button is pressed
                scale = true;
        return true;
        }

        public void touchUp (InputEvent event, float x, float y, int pointer, int button) {
                button.setChecked(false);

                // disable scaling when button is released
                scale = false;
        }

        public void exit(InputEvent event, float x, float y, int pointer, Actor toActor) {
             // disable scaling when button is exited with mouse
             scale = false;
        }
    });

Render Loop:
if(scale) {
    // set width and height (add n to current size)
    button.setWidth(button.getWidth() + n);
    button.setHeight(button.getHeight() + n);

    // re-adjust position
    button.setPosition(button.getX() - n/2, button.getY() - n/2);
}

Hope that helps. Limitations are that your animation has to be linear, if you want another kind of Interpolation you should read something about Interpolation.


text:
how can I put an array of objects into a script?
I want to create an animation from an object sequence. I already achieved exactly what I needed with the "MeshAnimaton script" from bummzack:
using UnityEngine;
using System.Collections;

/**
 * Animate a mesh by cycling through different meshes.
 * @author bummzack
 */
public class MeshAnimation : MonoBehaviour {

    public Mesh[] Meshes;
    public bool Loop;
    public float FrameDuration;

    private int _index;
    private bool _playing;
    private float _accumulator;
    private MeshFilter _meshFilter;

    public void Start()
    {
        _meshFilter = GetComponent<MeshFilter>();
        _index = 0;
    }

    public void Update()
    {
        if(!_playing){
            return;
        }

        _accumulator += Time.deltaTime;

        if(_accumulator >= FrameDuration){
            _accumulator -= FrameDuration;
            _index = (_index + 1) % Meshes.Length;

            if(_index == 0 && !Loop){
                Stop();
                return;
            }

            _meshFilter.mesh = Meshes[_index];
        }
    }

    // play the animation
    public void Play()
    {
        _playing = true;
    }

    // stop the animation
    public void Stop()
    {
        _playing = false;
    }

    // restore the first frame
    public void Reset()
    {
        _index = 0;
        _accumulator = 0.0f;
        _meshFilter.mesh = Meshes[_index];
    }

    // Mouse down to toggle Stop/Play, just for testing
    public void OnMouseDown()
    {
        if(_playing){
            Stop();
            Reset();
        } else {
            Play();
        }
    }
}

That worked fine with an object sequence which consisted of 20 meshes. But now I have to do the same with sequences that consist of big amounts of objects. Is there a way to put an array of certain object names into the script instead of dragging each mesh file separately onto the script component? I would appreciate any kind of help.

In the Unity Editor can select multiple files in the project view and drag them on the array in the inspector. Make sure the inspector is locked on the game object, so that it does not lose focus.

Thanks JeanLuc, that makes it definitely much easier! You really helped me to save a lot of time. And also thanks jhocking, that's a helpful information to write some code that would work without any dragging. I'm relatively new to programming but I'm gonna try to build in the Resources commands. Anyway thanks again guys!

Yes, but be aware when using @jhocking approach with Resources.Load, if you don’t need the resource (i.e. your mesh) anymore, you should unload it by calling Resources.UnloadAsset, otherwise you might run into OutOfMemory issues, where on Mobile Platforms you app will crash and on PCs it will behave badly.

If you use Unity Serialization with public variables or the attribute SerializeField in the Unity Editor Inspector, then the Unity Engine will handle the resource loading and unloading, when you load another scene.

Similar to what he said about UnloadAsset, when you link meshes directly then they are all loaded. I forget if not unloading resources will cause a memory leak or if it will reference the already loaded asset (you'd need to test it) but if the latter then the worse case is it uses up as much memory as loading all the meshes.

As for scene switching, there's no mention of this in the script reference so I may be mis-remembering, but I think Resources.UnloadUnusedAssets is called automatically (and if not, you could easily call that yourself) http://docs.unity3d.com/ScriptReference/Resources.UnloadUnusedAssets.html

You need to use Resources.Load() in order to load objects by name. Basically, put your model in a folder called "Resources" and then they can be loaded using the Resources commands. If the models aren't in a "Resources" folder then the only way Unity would know about those assets is to link directly as an array of meshes (ie. what you're already doing and want to change).


text:
Do resolution settings have any impact or give any advantage in online FPS games?
There is this crazy theory that has always bothered me. I am not after a technically but more theoretically (although technical knowledge is required to) answer;
Two friends are playing the same video game over the internet (say ... CS:GO). The only difference is that Bob is playing on a 640x480 but Mike on 1900x1600.
Does the different resolution give any of them any advantage?

Do you mean resolution difference alone, with everything else being the same, or dependant on it? (FramesPerSecond, screen size, etc)

Well, if higher resolutions lower the FPS of a second player, I think advantage of the first player (friend) is obvious

@KromStern obviously the resolution has an impact on the FPS but I am more curious to know whether that has any impact on the game engine. Game engine has to somehow figure out where your single shot went exactly, wouldn't the scale of x/y/z coordinates be much greater on a higher resolution? Wouldn't the game engine have to do extra work to calculate the coordinates which would obviously have a minimal but still some impact on the speed of networking (interpolation etc). I hope that makes sense.

No. All of those calculations are performed in 3D space independent of the screen resolution. What can impact gameplay is a different FOV (field of view) as it allows one person to see more of the screen than the other

@Steven: Don't forget, that player input is done in resolution pixels before being transformed into 3D world of the game, so having 1920px gives a better precision than 800px.

@krom stern good point.

Assuming they are using something like SDL, it is likely evaluated by pixels as explained but I somehow doubt that makes a mention worthy difference in gameplay winnings.

It may be useful to look into hit boxes to understand how determining hit or miss is divorced from rendering and details of the character's model.

The resolution should not affect computation of simulation logic such as "where your bullet hit." Any reasonable game will divorce such simulation data from the final render resolution of the screen. That means the main thing you're talking about with respect to resolution is what the player sees.

If all other things are equal, then a lower resolution might give a player a disadvantage.
A higher resolution render will be able to transmit more fine detail for objects further away. What may be reduced to 4x4 pixel smudge in the distance on a 640x480 display may be 9x9 pixels on a higher-resolution one, which may be enough additional information to convey a better sense of the color of the object which in turn may be enough to convey to the player whether the object is a friend, foe, or irrelevant.
Depending on the nature of the game, however, this may not matter; the loss of fidelity in distance rendering may only impact objects so far away that they are beyond a reasonable player's concern anyway (their weapons cannot reach them, and/or the object in question could close to a relevant range in a reasonable period of time, et cetera).
This advantage is not likely to introduce any sort of statistical significance in the win/loss rate of players, although the number of real-world factors that complicate actually testing this hypothesis are many, and consequential I doubt any real evidence exists.

In practice, lots of factors will be altered by a change in resolution (so all things are not equal). For example, it takes more processing power to render more pixels, and this can result in a decreased responsiveness to user input, conveying an advantage to the player with a lower resolution (and thus a higher responsiveness). The factors so impacted will vary depending on the specifics of the implementation of the game in question, and are far too broad to enumerate completely here.
Beyond anything else, though, I suspect players who opt to run at lower resolutions or with lower graphical settings to convey an advantage to themselves do it either because it does give them a clear boost to their FPS or because they feel like it does. It's important not to overlook the placebo effect, the fact that if a player thinks they have an advantage they may play better regardless of whether or not they actually have one (the opposite is also true).
Perhaps to reinforce this point, most players don't seem to really understand what "FPS" is measuring (and specifically, how it's a non-linear measurement) and will bend over backwards to push 5 FPS on to a game running at 500, not realizing how small of fraction of time that is. They nonetheless may assert that they perform much better at 505 FPS than 500, which is almost certainly attributed to the placebo effect.

It might be worth noting that the resolutions @vba4all mentioned are of different aspect ratios, which could result in different information displayed to either player, unless there were some type of letterboxing.

That's a good point, I guess I'd assume letterboxing is used for the "all things equal" case (since otherwise, as you note, you see more; this can matter more in top-down or sidescroller games than FPSs but is still worth equalizing for the same reasons)

Just to add as a note: there are some games (Quake-based games like CoD) which send a packet each frame. This means that the higher FPS you have, the more packets you're sending.

@AcidShout that's also a valid point. I think that the interpolation accounts for the equality in networking. From the article it seems that graphics ( or rather the FPS rate each player gets ) does matter.

Yes, indeed it does. Also, it's important to know that some games have the so hated antilag. It basically takes your packet time and rolls back the server till your exact moment, executes your packet, then continues. If you manage to disable all kinds of prediction (meaning that all you see is exact player positions for that time), you may see bad animations, but all your hits will actually hit (supposing you're aiming at a hitbox). Prediction sometimes doesn't help as much as described. (and what I said is valid specifically for CoD MW3. I don't know if it's valid for other games.)

Pros

Higher resolution should give the player more visual information about the game world. Everything will be clearer and more sharply defined. This should confer an advantage in overall situational awareness, which in an FPS is important.
There should be no effect on game state as the game engine does not compute the position of objects and actors based on screen resolution but on resolution independent internal map co-ordinates or something along those lines.

Cons

The higher the resolution, the lower the frame rate as the hardware has to do more work to render each frame and it has a finite processing capacity. Frame rates lower than around 20 frames per second are too slow for games where there is a lot of action and the camera (point of view) is changing a lot as movement of objects in the field of view will become less noticable.

This one requires a little more explanation. The human visual system is quite good at identifying and tracking moving objects (whether they be prey, predator or environmental hazard), and less good at identifying static objects (or in our case, objects whose movement is rendered with low fidelity due to reduced framerate).
In an FPS, much of the game play revolves around rapidly identifying and assessing potential targets and threats and forumlating a suitable response (i.e. "twitch" gaming). Strategies tend to be more of a secondary layer, but the twitch is more important.
For slower paces games such an RPGs a framerate a low as 15 FPS may be acceptable, but anything below 10 FPS is very noticeable and rapidly becomes a slideshow.
TL;DR
You must strike a balance between high detail (higher resolution) and smooth action (higher framerate).

20 FPS is definitely unacceptable for networked games. You should add the frameTime to latency. Also, greater resolutions also mean more complex assets wich may have additional latency during streaming even with powerfull PCs. but I fear there are other settings in game that may favour a player.


text:
Getting name fragments for a name generator
Back again to ask more about name generation -- this time about the dictionary of syllables which I apparently need to reliably generate a name. For reference, my last question.
I've written a little bit of code which, given a file, uses the first line to determine how long the name can be (with multiple options for variability), then builds one from the syllables given in the rest of it. It works decently enough, given example syllables in an example file. For those wanting to try out a set of syllables of their own, I've made a version on Ideone.com. stdin contains the list of lengths and syllables.
That's where I'm having an issue, though. What should I use for the syllables? I've looked around, but I've been unable to find a good list of names to draw from. Maybe it's just that I'm bad at this or something, but I can't really get a good list of syllables that make  names. To add to that, I have to do it by hand, and I'd much rather make a program to split a list of names into syllables, but I can't get that to work. I'll post the source for my attempt once I'm home.
In short, how can I get a good list of syllables for use in a name generator? Is there pre-existing code I can use or modify and pass it a list of names to chop into syllables, then save those to a file? If not, how would I go about writing my own?

What you're looking for are N-grams. Basically you would first get a list of names (say, from the US census). Then, you pass that through an N-gram processor to find 2 or 3 grams. Then you can generate unique names by combining the grams with a markov chain.

@mklingen Would that be the entire list giving me two or three grams, or each name? I'd assume each name, but I just want to confirm. Also, could you post an answer of that (i.e. With pseudocode) so I can accept it?

You'd want to find N-grams in names individually, then count the resulting N-grams to find the most common ones. This is kind of speculation on my part (haven't implemented this in practice), so I'll wait for someone who is more knowledgable than me to provide a real answer.

I suggest you base yourself on some syllable-based languages then add the missing syllables, such as "K_" single consonants and so on.
For example:

Add arbitrary rules for names of creature races / game region. (eg: sand area names all end in ?i and start with m? and never have any p? or ?e, at most one single-consonant in a name) to give some ""consistency"" / familiarity to the player.
Then add a function to turn those syllables into the user's writing system (eg: English letter spellings).
This is the part that will have to be localized for different languages.
Also, you might need to add a localized black-list to invalidate obscene words that will randomly come up and their close-enoughs syllables, and in multiple cultures across the world. although it could be hilarious without you could end up with your game pulled off the shelves if its not 18+. Make sure to check within names for matching obscene words even when surrounded by extra syllables.
You're opening a big can of cultural problems with random name generation. For example in your previous question one name was "Gozidi" with can sound awfully close to 'big member down there' in French with a tiny bit of stretch. That's an innocent enough example that will only cause some giggling but you can imagine some more offensive things accidentally coming out and people getting quite upset.
Drama you can do without when all you want to do is create a fun game. It's something to keep in mind.

Ooh, I didn't think about it from this perspective. I'll see if I can do that. The problem is that I'll still have to manually put in the syllables -- really, this answer would have been better suited to my first question than this. Still, it's a good answer. I'll see if I can start making it. Also, in response to your concerns about a cultural can of worms, this game is being made for myself and a few friends. I might eventually publish it, but that's a big if, so I'm not too concerned about it. Same goes for localization -- for now, it'll be hardcoded to English.