text:
Multiplication and Division Bug
Hi guys first time poster with a quick question. I'm just getting started with coding and as an easy exercise I wanted to make a block move and sprint. I got it to do that but when I press the shift key too fast the getKeyUp part divides the speed variable too many times. How do I fix this?
public class Movement : MonoBehaviour
{
    public float speed = 5f;
    public float speedmutiplier = 2f;

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

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

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

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

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

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

What do you mean by too many times. Could you maybe record what happens and upload a video or gif showing it here?

It is, in fact, impossible to tell you what is going wrong when you do not tell us what it is doing to begin with.

I don't think you actually want that GetKeyUp section, if I understand correctly? There is no reason I can possibly see for you to be dividing the speed by the same value that you use to boost it on KeyDown. Now, friction... that there is another story altogether.

It seems to me that you're trying to implement a simple running state. The problem is that you're using GetKeyDown and GetKeyUp. Those functions will return true in their respective frames, but if you press the button in really quick succession, you might be able to press the button down, then up and then down again in the same frame, but the next up action will be in the next frame, therefore calling the GetKeyUp function twice but not the GetKeyDown function.
What you should be doing instead is, checking whether the shift key is pressed at the start of the FixedUpdate and then applying the multiplier there, using a base speed and a variable speed.
public class Movement : MonoBehaviour
{
    public float baseSpeed = 5f;
    public float speedmutiplier = 2f;

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

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

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

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

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

Assuming that you'd like to have a maximum and a minimum speed, you can Clamp the speed between a maximum and a minimum.
Like this:
public class Movement : MonoBehaviour
{
    public float speed = 5f;
    public float speedmutiplier = 2f;
    public float minimumSpeed = 1.25f;
    public float maximumSpeed = 640f;

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

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

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

The main problem is the use of FixedUpdate() together with GetKeyUp/GetKeyDown. Unity resets them once per Update loop. When they are used in FixedUpdate() Unity can "miss" some of them.
As a rule use FixedUpdate mainly for physics related stuff, the rest goes to Update (or rarely LateUpdate).
So you should replace FixedUpdate with Update. Additionally I would still replace GetKeyDown/GetKeyUp with GetKey (look @John Hamilton answer on how you can do that).
Here is some additional info from Unity docs that may help you understand how Update and FixedUpdate work and why FixedUpdates is intended for physics related things:

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

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

Make sure that deltaTime is properly used in the speed computation. Unless you are comfortable with approximations, a correct, framerate-independent implementation should probably use Pow():
    if (Input.GetKeyDown("left shift"))
    {
        speed = speed * Math.Pow(speedmutiplier, Time.deltaTime);
    }

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


text:
Is there a term for the sounds that play when text is printed out letter by letter?
Take a game like Undertale: whenever a character "talks", the text is printed out one by one, and a sound is played for each letter, as if the character is actually talking (even if it's just gibberish). These sounds are usually different for each character. What are those types of sounds called? If I wanted to get placeholder sounds for such a dialog system, how do I find them?

I am not sure that if it is exactly what you are asking but the answer might be 8-Bit Sound?

@TolgaŞen I don't think so.

The Animal Crossing series just names their default babbling "Animalese", so maybe other games just make up a name?

TV Tropes calls this Voice Grunting:

Voice acting is ubiquitous in video games today, but in the old days,
  when budgets were smaller, sound hardware was more basic, and
  disk/cartridge space was limited, developers had to resort to text. In
  games where story was emphasized, they figured some of the drama was
  lost when a potentially emotional scene was pantomimed like a silent
  movie. So some games incorporated "sort of" voice acting, in two
  forms.
One form is a sort of beeps at various pitches, generally speeding up
  or slowing down depending on how quickly the speaker is talking. ...

Or, when the sounds are nonsense syllables rather than beeps & typing, Speaking Simlish:

The language of NPCs and other AI constructs in simulation games and
  some RPGs, made up of nonsense sounds strung together like actual
  words. It's not a cypher, normal speech spoken backwards or anything
  like that, it is quite simply gibberish or "Simlish" as the Sims
  Manual says
This became especially popular in cartridge and floppy-based releases
  once fully voiced CD-ROM releases began showing up, as something of a
  compromise between the expression provided by voice acting and the
  enormous amount of storage required for it

Something like the voices in Banjo Kazooie could be considered either of the above, I'd say.

some of the drama was lost when a potentially emotional scene was pantomimed like a silent movie - yet in games like Final Fantasy VI the music contributes to the tone/feel/drama in a major way.

Yeah, I don't necessarily agree with the analysis in the quoted articles, I was just looking for some external reference to define the appropriate terms.

There's no specific word to describe this particular effect. On the other hand, we can think of printing words letter by letter and playing a sound for each letter written as a typewriter-like animation. This said, you may call those sounds just 'typewriter typing' or similar.
If you had some sound resources in a project, you could name them 'sndTextTyping1', 'sndTextTyping2'...
If you don't want to rely on those terms and want to know the exact word (in case it actually exists), you may want to ask this question on the English Language & Usage Stack Exchange site.

That would be a logical thing to do if not for the fact that the asker is looking in particular for the game development jargon term, which is more likely to be known here than on a site for learning English usage.

In addition to the other answers, this 'grunting' is used to simplify game localization. This way the developers don't have to hire voice actors in every supported language, and manage those different recordings per region.
To replicate this effect, you could record various random 'syllables' in each voice (10 samples might do). Manually store the number of syllables for each text word in your dialog. Then play a random 'grunt' sound for each syllable in each dialog word.  You could fudge it and just play random grunts regardless of the actual number of syllables.

This seems to answer the questions "why is this technique used" or "how do I implement this"  — not the questions that were asked "what is this called" and "where can I find placeholder sounds" (the latter resource request generally being considered off-topic for this site)

source: Stack Exchange

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

sort: votes


text:
How does ESRB content rating work for games with DLC?
Lets say you have a game rated "Teen" by the ESRB, but later down the line, you release a DLC that would push the game's rating to "Mature". Are the two ratings kept separate for the base game and the DLC or will the base game be "upgraded" to the higher DLC rating?

The two ratings are kept separate, and furthermore one only needs to resubmit the DLC if it would exceed the rating given to the base game, as noted in the ESRB's rating guidelines.

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


text:
OpenTK Camera Rotation issue
I'm currently developing a 3D game engine in C# using OpenTK.
I have basic game objects, and each game object has transform (translation, rotation and scaling). A game object can have components (much like Unity).
One game object (The camera game object) has three components, A camera, free move and a free look component. The free move component allows the user to move the camera around the scene, whilst the free look camera is SUPPOSED to rotate the camera. However, I get this odd effect:
https://youtu.be/rcdWZcaEqSY
(Note that, the plane isn't changing position, it seems the camera is ... turning upside down?)
On top of that, once I rotate the camera, moving the camera (using the arrow keys) gets really weird, up can become down, left can become right. It's all very odd.
Anywho, here is the update method for my Free Look component:
protected override void OnUpdate(object sender, UpdateEventArgs e)
{
    Rectangle bounds = Game.GetCurrentGame().Window.Bounds;

    Vector2 center = new Vector2(bounds.Left + (bounds.Width / 2), bounds.Top + (bounds.Height / 2));

    Vector2 mousePosition = new Vector2(System.Windows.Forms.Cursor.Position.X,
                                            System.Windows.Forms.Cursor.Position.Y);
    Vector2 deltaPosition = center - mousePosition;

    bool rotX = deltaPosition.X != 0;
    bool rotY = deltaPosition.Y != 0;

    if(rotY)
        Transform.Rotate(new Vector3(0, 1, 0), MathHelper.DegreesToRadians(-deltaPosition.X * sensitivity));
    if(rotX)
        Transform.Rotate(new Vector3(1, 0, 0), MathHelper.DegreesToRadians(-deltaPosition.Y * sensitivity));

    if (rotY || rotX)
        System.Windows.Forms.Cursor.Position = new Point((int)center.X, (int)center.Y);

    base.OnUpdate(sender, e);
}

here is the Rotate method in my transform class:
public void Rotate(Vector3 axis, float angle)
{
    rotation = (Quaternion.FromAxisAngle(axis, angle) * rotation).Normalized();
}

I hope someone can help me get to the bottom of this, I've been so frustrated!
If there's any other code you need to see, just let me know.

This is a common mistake when implementing camera rotation - see "I'm rotating an object on two axes, so why does it keep twisting around the third axis?" for a detailed write-up on why it happens (including animated examples) and strategies you can employ to fix it.

@DMGregory Thanks for the input, sadly I'm still struggling with this, since I'm not using unity it's a little difficult to translate.


text:
Unity not scrolling when mouse not over object
In Unity I am using a scroll view. It works semi-perfectly (had a lot of problems with it, don't like how the UI system works).
The content for my scroll view is a bunch of buttons aligned vertically with some spacing between them. The problem is that the scroll rect will only scroll if I'm hovering over one of the buttons. If the mouse is between two buttons, it won't scroll.
Here are some screenshots:

Also, you may see that I'm not using the standard Scroll Rect, mine is nothing special, just disabled the dragging that is stupid to be used on non-touch devices.

Add Image component to your ScrollView so it looks like a background and tick RaycastTarget. Set it's color opacity to 0f and tell me if that works.

Thanks, that worked perfectly! If you want you can reply with an actual answer and mark it as a solution.

ScrollView by default has an Image component with a RaycastTarget enabled like on the image below.

In order to detect touch and clicks, UI elements need to have at least one component with RaycastTarget enabled.
Your ScrollView doesn't have the default Image background so it doesn't respond to clicks. Add Image component to your ScrollView so it looks like a background and tick RaycastTarget. Set it's color opacity to 0f and voilà :)


text:
LineRenderer not working using Vuforia in Unity
So I'm trying to render a line that shows up when camera sees an image target and moves around with it. Very typical AR application. But my line renderer doesn't seem to show at all.
Here's the code:
using UnityEngine;
using System.Collections;

public class myLine : MonoBehaviour
{
    // Creates a line renderer that follows a Sin() function
    // and animates it.

    public Color c1 = Color.yellow;
    public Color c2 = Color.red;
    public int lengthOfLineRenderer = 20;

    void Start()
    {
        LineRenderer lineRenderer = gameObject.AddComponent<LineRenderer>();
        lineRenderer.material = new Material(Shader.Find("Particles/Additive"));
        lineRenderer.widthMultiplier = 0.2f;
        lineRenderer.positionCount = lengthOfLineRenderer;

        // A simple 2 color gradient with a fixed alpha of 1.0f.
        float alpha = 1.0f;
        Gradient gradient = new Gradient();
        gradient.SetKeys(
            new GradientColorKey[] { new GradientColorKey(c1, 0.0f), new GradientColorKey(c2, 1.0f) },
            new GradientAlphaKey[] { new GradientAlphaKey(alpha, 0.0f), new GradientAlphaKey(alpha, 1.0f) }
            );
        lineRenderer.colorGradient = gradient;
    }

    void Update()
    {
        LineRenderer lineRenderer = GetComponent<LineRenderer>();
        var t = Time.time;
        for (int i = 0; i < lengthOfLineRenderer; i++)
        {
            lineRenderer.SetPosition(i, new Vector3(i * 0.5f, Mathf.Sin(i + t), 0.0f));
        }
    }
}

and here's my set up:

I also tried attaching the script directly to the ImageTarget and nothing happened.

I think the problem here is that the camera is moving around in the scene to match orientation with your image target. But what you want is for the camera to be fixed and have the 3D model move around to match the image target. Am I correct? If so, you need to select the camera and change the "World Center Mode" to....Camera, I believe.

@Draco18s No i'm moving the camera around and have my target fixed. I want the line to show up on top of my image target, but it doesn't.

Check that your line is being draw in local coordinates, not world, especially if your image target isn't placed at the origin. You may also wish to scale the coordinates you're setting so that it's larger.

@Draco18s It seems to renders on PC but not on my device. only shows a pink square instead of what it's supposed to show.


text:
How can I prevent cheating in a distributed multiplayer game?
A problem I've been thinking about recently is how it might be possible to create a multiplayer game without a centralised game server.
Is it possible to distribute "server" responsibilities across players? I feel like it would be too easy for modified/hacked clients to change the multiplayer experience, are there any ways around this?

For some games it is possible. Take chess, for example. Can you cheat at online chess without the opponent noticing? Cheating at chess is hard, because the game:

has no hidden information
is deterministic (no randomness involved)
is only about making the right decisions. Reflexes or precision don't matter.

When your opponent says they just moved their king from a3 to f1, your game client can recognize that this is an illegal move and reject it. The only possible cheat left is AI assistance (which actually is a serious issue for competitive chess, by the way). But there is really no workaround for that unless you force players into a controlled environment. A while ago I asked a question about how to design a game as AI-unfriendly as possible, but didn't get really good answers. So I am not going to cover this issue.
While there is no good way to get around the third requirement, you can get around the first and second by using some applied cryptography.
Take battleship, for example. How can you verify that your opponent didn't cheat by lying about their fleet layout? Have each player calculate a cryptographic hash of their layout at the start of the game and send it to the opponent. At the end of the game when the complete layout of the enemy is revealed, you can verify if the hash matches the layout. You might want to add some bytes of random data to the data from which the hashes are calculated (also to be revealed at the end of the game) to prevent the opponent from brute-forcing your fleet layout when you've reached the endgame and the number of possible positions is low enough to allow that.
The same method can also be used if you want some randomness in your game, because randomness is essentially hiding of information from all players.
Before you start the game, have both players create a long list of random bits (more than you will need for the complete game). Use a cryptographically secure RNG seeded from an unpredictable entropy source. Again, have the player hash their lists and exchange the hashes for post-game verification. During the game, use these two lists as one-time pads for each other. When you need a random bit, have each player reveal the next bit from their list, XOR the bits with each other, and use the result. This gets you a random number which both players contributed to but none could predict. Again, at the end of the game, send your complete list to the opponent so they can verify the hash and confirm you didn't lie during the game.

But how do you deal with players you catch cheating?
In a game with more than two players which follows above guidelines, everyone knows when a player cheated. So they can simply all disconnect from that player and continue the game without them. There is no practical difference between someone ragequitting because they can't stand losing or being kicked for cheating.
But what about a two-player game where the clients can't agree on who cheated? This is actually not unlikely to happen if both clients aren't aware that they are playing different versions of the game. This is essentially equivalent to a rule dispute in a tabletop game. If you can't come to an agreement, the only solution is to abort the game and call it inconclusive. Again, equivalent to a ragequit. Who is the quitter from your perspective depends on how guilty you feel.

Even if the opponent notices it doesn't really matter for the hacker

Also, hacked clients could be the ones rejecting the moves made by vanilla clients

I like your idea about the encryption though, that's something I hadn't really thought of. It wouldn't be possible to make it work in all circumstances though would it? The game would have to lend itself to that kind of "protection" (at least from my understanding)

@theonlygusti You can simply disconnect from any peers you caught cheating. And what's the difference between a forced disconnect due to cheating (true or not) or a ragequit because one can't stand to lose? There is none.

@theonlygusti regarding your third comment: As I wrote in the answer, not every game can be protected like that. The game must be about decision making, not fast-paced action.

@theonlygusti I added a paragraph about how to deal with cheaters when you can prove they are cheating.


text:
How can I use StringTokenizer instead of array?
I'm currently redeveloping an OBJ & MTL importer for my game engine. At the moment, I'm focusing on increasing how quickly I can parse large OBJ files.
For now, I can parse about 1.2M vertices, uvs and normals in around 4-6 seconds. Which is awesome, considering the file that I'm parsing, couldn't be parsed originally.
Anyways, on with my question; I want to be able to make the following method use a StringTokenizer instead of String array. The reason is because using String.split is slow and I want to parse the file relatively fast.
private OBJIndex parseIndex(String token)
{
    String[] tokens = token.split("/");

    OBJIndex result = new OBJIndex();
    result.setVertexIndex(Integer.parseInt(tokens[0]) - 1);

    if(tokens.length > 1)
    {
        if(!tokens[1].isEmpty())
        {
            hasUVs = true;
            result.setUvIndex(Integer.parseInt(tokens[1]) - 1);
        }

        if(tokens.length > 2)
        {
            hasNormals = true;
            result.setNormalIndex(Integer.parseInt(tokens[2]) - 1);
        }
    }

    return result;
}

How would I go about doing this?

What research have you done and where have you gotten stuck?

If you want fast loading times in your game, what engines do is: not using text based data-files (obj, xml ..) on big data like meshes in the first place.
Instead, prepare the data in an offline process, specifically for your engines needs and optimize this instead. In your engines data-exporter tool, read in the obj files and write the optimized data binary. Then there is no parser needed anymore when the game actually starts and runs, it just reads in the binary data directly into its data structures.
Unreal calls this process cooking, other engines have other terms for the same thing. The point is: optimize your engines data formats for fast loading, this excludes text based data formats for big data.

The problem of parsing an obj file is still present here, it's just happening at import time in the editor rather than at runtime in the finished game. While our time requirements might be less exacting for offline baking processes, there are still good reasons to optimize this: it lets content creators iterate faster, and can save a lot of time whenever you need to do a big batch re-import because your binary format changed or somesuch.

Agreed @DMGregory, cooking/baking times is not unimportant. However when it comes to optimization of game loading times on an engine level (that's how I understood the question), its best to go binary. That was my point, sorry if that wasn't clear from my post.

Now that I read it again, I think you are right @DMGregory, it doesn't really answer the question as it was. Though it has the terms "for my game engine" in its question body, which changes the direction of the question a little and opens it for better optimization options. No harm done, Ill leave it here as an extended comment, maybe Mathew is interested in better optimizations, than the actual String.Split thing.

Yep, you raise a perfectly valid point about data baking that's worth repeating. Implementing this suggestion efficiently will still need an answer to the OP's question about parsing the text data in the first place.


text:
Loss in quality on downsized sprites in Game Maker
I'm having an issue with sprites quality in Game Maker.
I have some sprites used for UI with an original size of 2048*512. I need to resize them in game to 512*128. But when I do, I got a loss in quality.
This is the original picture, resized to 512*128 with a third-party software:

This is the sprite, as it appears in Game Maker room editor (and in game) once resized to 512*128:

Are there general guidelines for this kind of situation?
By the way, it's on Windows. Though I tried launching the game on an Android device and the result was the same.

Try activating Interpolate colors between pixels in Global Game Settings->Windows->Graphics

I got the same result, with or without the option. It was actually already checked and I tried unchecking it.

I encountered this very unpleasant problem, which is related only to the way you make GM:S draw things. The solution I found is very simple, instead of drawing directly to the screen, I first draw whatever I need onto a surface, then I draw the surface itself on the screen. The interpolation quality is way better than drawing onto the screen, both for sprites and fonts (since fonts are stored in texture groups as well as sprites).

I wonder if Game Maker enables mipmapping on Surfaces, but not on other textures/sprites (implicitly assuming that you'll only be displaying those at native size or larger, not smaller)

That's a tricky question, I don't guess so since you can preview texture pages, and there aren't smaller versions of bigger sprites. You may want to implement your own mipmapping algorithm if you need one.

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


text:
Good basemap generator
I am currently making a board game and cannot seem to find any vector world map creators where I can select a region of the world to capture and have it download that section. I just want a base map so no city names and preferably no borders.
The map doesn't have to be vector if it is of good enough quality.

I have downloaded high resolution JPG maps for some clients with the Mapbox Studio tool. Its a software you need to install on your computer but it gives access to Google-style maps with tons of customization options and everything you do can be exported as 300dpi JPG files. Not vector but in good (print) quality.
You can remove city names, borders and everything you want via a CSS-style language they are using and there are also some ready-made styles you can use.

Wikimedia Commons has various blank SVG maps of the world.
The useful thing about SVG is that you already have the polygon information about the borders in an easily parseable XML format. Most of these maps even have the country-paths named with the ISO country-codes. When you are developing a web application, you can even make that map interactive with some JavaScript.
If you want only a part of the map, you will need to cut them out with a vector graphics editor like Inkscape.
But if you want to use one of these maps, keep the license conditions in mind. Most of them are in the public domain, which means you can use them freely. Others are under share-alike licenses which can make it hard to monetize your game if you use them.


text:
TBS Shooter targeting AI
I have some experience in developing all sorts of (small) games using Unity3D, I have a few personal game projects and I also work for a small game studio. The only subject in game development that I've avoided at all costs was AI, up until now. My other projects required just basic NPC algorithms, so i can't call that AI.
On to my problem: I have 2 or more player opponents that have to shoot at each other, taking turns (think of a Worms game). They fire using a ballistic arc, adjusting firing power and gun elevation. The problem is making the CPU player to behave like a human player would, without using firing at random. I have, from other games, and algorithm that computes the angle and projectile velocity required to hit dead-on the target, but that would kill the opponent in the first few seconds. So i need a smarter, human like approach: fire a trial shot, smartly adjust to improve aim. Also account for wind direction and speed that affect the projectile.
After some AI research, I was thinking of using genetic algorithms, but i do not need a perfect solution to my problem (to hit the target in the first round) but rather a constant improving one. Also if the algorithm could be tuned for easy/medium/hard difficulty would be great. I do not necessarily need a complete solution, but a direction to dig to.

How about, determine a % of how often you want the computer to hit accurately, and adjust their aim randomly up to this %age.  Or get the computer to fire the first shot randomly, calculate how far out they were, and adjust for the next shot (with a bit of randomness) by this factor.

Hi, I've had in mind something like that, based on chances, but seems like cheating. Also the target is killed with just one shot, maybe two in the future


text:
OpenTK Terrain - Triangle strip issue
I'm currently trying to render terrain in an OpenGL application I'm making (using OpenTK in C#). Something really odd is happening and I'm not sure why.
Here is the code I use to load my terrain from a heightmap (Yes I know setting up indices the way I am at the moment is silly, but it's just so I can use the mesh renderer class I made). I render the terrain using Triangle Strips.
    public Terrain(string heightmapFile)
    {
        if (!File.Exists(heightmapFile)) throw new FileNotFoundException("File not found at path '" + heightmapFile + "'");

        using (var bitmap = new Bitmap(heightmapFile))
        {
            var vertices = new List<Vertex>();
            var indices = new List<int>();

            int index = 0;

            for (int y = 0; y < bitmap.Height - 1; y++)
            {
                for (int x = 0; x < bitmap.Width; x++)
                {
                    float z = bitmap.GetPixel(x, y).R / 127.5f - 1.0f;
                    float z1 = bitmap.GetPixel(x, y + 1).R / 127.5f - 1.0f;

                    vertices.Add(new Vertex(new Vector3(x, y, z)));
                    vertices.Add(new Vertex(new Vector3(x, y + 1, z1)));

                    indices.Add(index);

                    index++;
                }
            }

            AddVertices(vertices.ToArray(), indices.ToArray());
        }
    }

Here is the result:

What's going on here? What am I doing wrong?

You need to start a new triangle strip per y value.
If I remember right, a triangle strip draws one new triangle for each vertex you give it, reusing the previous two. It's trying to make one very long triangle strip by wrapping the end of row y==0 over to the beginning of row y==1. The vertex at y == 1, x == 0 is using the last two vertices from when y == 0, x == bitmap.Width - 1 and y == 0, x == bitmap.Width - 2.
You can either make a separate triangle strip object (probably easiest), or you can use primitive restart. Or maybe switch to non-strip triangles.


text:
How do I change from positive degrees to negative degrees?
Recently, in Unity, I tried to move a sphere along a figure-eight path. It first moves in a circle, and after completing the circle, it starts the  second circle in reverse, using negative rotation. However, my plan did not work as I expected. The reason is that Unity changes negative degrees into positive degrees, so -15 degrees becomes 345 degree. Therefore, the direction of the circular movement won't change, when you flip from a positive degree to a negative degree. In other words, if the first path is clock-wise the second path (after changing the sign of the degree) will be clock-wise, too.
Is there any practical way to overcome this problem, and change the direction of rotation by changing from positive degrees to negative degrees?
Here is one of the scripts I have tried:
public class PlayerMover : MonoBehaviour
{
    float x;
    public float speed=100.1f;
    private Transform playerTransform = null;

    void Start ()
    {
        playerTransform = GetComponent<Transform>();
    }

    void Update ()
    {
        x=speed*Time.deltaTime;
        playerTransform.Rotate(0, 5 *funct(x) * x, 0);
        playerTransform.position += playerTransform.forward ;
    }

    public float funct(float u)
    {
        u=Mathf.Sin(u);
        return u;
    }
}

As you can see. even the function I use to flip from positive degrees to negative degrees is a smooth and continuous function, mathematically speaking.

This looks a bit odd. x is recalculated each frame as the speed times the seconds elapsed since the last frame, so it's likely varying between roughly 100/60 and 100/30, depending on your framerate. Sin of x is positive on almost all of this interval, so if you're running at a consistent framerate even a little over 30 fps, funct(x) will always be positive. (And if you're running with vsync at exactly 30 then funct(x) will always be negative). That sounds at odds with what you described you intended it to do though, in terms of "flipping from positive degrees to negative degrees"

@DMGregory: I even tried a step function with constant values +c  and -c, but couldn't achive changing the direction of rotation.

It's not the function that's the problem, it's your input. Are you intending x to increase over time? You might want Time.time rather than Time.deltaTime. The delta is just the interval since your last frame, so when your framerate is stable it doesn't increase or decrease much.

Your diagnosis of the problem is incorrect. Unity handles negative angles just fine, as you can see here:

The problem is how you're calculating your rotation increment. As described above, Time.deltaTime is the time in seconds that have elapsed since the last frame (typically 1/60 - 1/30). As long as your framerate holds steady, this value is nearly constant. It's good for scaling change over time to keep a consistent rate, but it doesn't itself progress over time.
If you want something to change over time, then you'll want to either:

accumulate the frame increments you're getting from Time.deltaTime into a member variable that can remember how much it's built up from frame to frame, or
make the change a function of the time since startup, Time.time. (Just note that if your game runs for a whole day, this can start to lose precision)

Here's the code used above. You can see just like yours it rotates each frame by an increment that's scaled by a sine function. In this one though, the sine varies over Time.time, so the phase progresses from frame to frame
public class Figure8 : MonoBehaviour {

    public float secondsPerLoop = 3f;
    public float forwardSpeed = 1f;

    void Update () {
        // Sharp direction change.
        // float direction = Mathf.Sign(
        //  (Time.time / secondsPerLoop) % 1.0f - 0.5f);
        // float rotationDoubling = 2f;

        // Smooth direction change.
        float direction = Mathf.Sin(
            Time.time * 2f * Mathf.PI / secondsPerLoop);
        float rotationDoubling = 2.43f; // Eyeballed, not precise.

        float rotationIncrement =
            rotationDoubling * Time.deltaTime * 360f / secondsPerLoop;

        transform.Rotate(0f, direction * rotationIncrement, 0f);
        transform.Translate(0f, 0f, forwardSpeed * Time.deltaTime);
    }
}

Thanks for your enlightening answer. Now I have a better understanding how to apply time to simulate other motions too.

Have you tried animations instead? Not saying it should be done with animations, just an alternative.  He is one way to get the figure 8 done with code:
float x;
public float speed = 100.1f;
public int otherWay = 1;
public int count = 0;
public Vector3 startingPostion;

private Transform playerTransform = null;

void Start()
{
    playerTransform = GetComponent<Transform>();
    startingPostion = playerTransform.position;
}

void Update()
{
    x = speed * Time.deltaTime;
    playerTransform.Rotate(new Vector3(0, otherWay * 5 * funct(x) * x, 0));
    playerTransform.position += playerTransform.forward;

    if (count == 43)
    {
        otherWay = otherWay * -1;
        count = 0;
        playerTransform.transform.position = startingPostion;
    }
    count++;

}

public float funct(float u)
{
    u = Mathf.Sin(u);
    return u;
}

Thanks for sharing your solution for moving in an 8-figure path. But my question was about how to change the direction of rotation while you are still moving. Your answer taught me how to append two movement to travel along an 8-figure path.


text:
Understanding a client/server relationship
I'm currently designing a simple game in C# and want to implement online multiplayer support. Before venturing onto doing something like this, I just had a few questions about clients and servers.

Is a server responsible for sending and receiving data to and from clients?
If a client wants to send data to another client, should it send the data to the server, and let the server send that data to the specified client?
When it comes to handling data, should the server have access the same classes the client does? This way the server can convert the bytes sent in, to a specific class? Or should the server just handle all the data in bytes, and send it back out if necessary?

Sorry if there are to many questions, any help would be appreciated!

I have quite a bit of experience in this, but its kinda hard to answer this without knowing what type of game your trying to make multiplayer. a RPG? a RTS? or a FPS? etc. some types of games require whats called an authoritative server where some don't so kinda need a type at least :)

If you're thinking something that will have one global league, like pokemon go, league of legends - things where scores area compared - then you need the communications to go client-server only.
There are a bunch of ways this will make it easier, but among them are that your clients can know the address of the server, and with peer to peer it would be virtually impossible to prevent cheating.
If you're thinking of  a LAN game sort of thing where a bunch of people set up a game together, play for a bit and close it down,  then you could do peer to peer. This introduces a few problems, the body being network related: discovering the other clients and routing.  Often discovery is done using UDP and this doesn't cross network boundaries well.
I'd use the minecraft model myself. (Pretty sure the original Doom did similar back in the day).
Basically one machine gets dubbed the server and coordinates objects - location, velocity, creation destruction motivation inventory.
When a client joins they need the address of the server. Minecraft makes it easy for the user to set up a LAN game by telling the person on the server the address to use.
In terms of responsibility, I'd say it goes both ways, but you don't have to agree. Depending on your protocol, some things will be easier to implement.
If you can have open sockets/long connections then both ways will be really efficient. Client tells server when an event happens - a purchase, a death, initiating a ballistic path. Server then tells all of the clients who then update their local data.
You'd probably want to chase this option if you're doing real time action.
It might be simpler though to have your clients polling the server for state change. Your comms code might be simpler but you'd have to think real hard about minimizing the amount of data you transmit.
For same / different classes - it depends. I'd start with the same. At some stage you'll find data that is only needed by the server or the client and you'll have to decide whether to have it on both anyway (which would make switching a local game to multiplayer and back easier ) or separate them (which gives you more code to manage but may improve security).  I'd leave that decision as late as possible.

The answer to all of these questions is "It depends".
1.) and 2.): There are two types of networking, one is a traditional one, it only has 1 server and every client is connected to this. The data always goes through the server. This is generally considered as the safer method.
The other method is called peer-to-peer (or P2P) networking. It doesn't have a main server, every client (peer) sends data to the other clients directly. This can be much faster than the first method if the peers live close to each other. It's less safe than the normal method, because the users can modify the data they send. You'd usually implement this with UDP, because with TCP you'd need a
separate server and client socket for each peer and you need to store the IPs.
3.) Sometimes the client and server even share most data classes, but you generally want to avoid sending anything other than the input from the client to the server to avoid cheating.


text:
How to fold a view from 2 3D cameras in Unity?
I need to combine view from 2 or more 3D static cameras. Let's say I have 3 humans standing in line side by side.

The first camera is viewing the left person and the left half of the middle person.
The second camera is viewing the person on the right and the right half of the middle person.

Now I need to see the whole middle person.
Any ideas how I can do this?
I don't need to see code or some finished implementation, I just need some ideas, because I can not find anything on this.

i tried using unity forum, but the community there is not so wide

Maybe you need to use Camera.Viewport?

You could create two cameras and create a split-screen-like view:
Left camera has a ViewportRect Width of 0.5 and the right camera has a ViewportRect Width of 0.5 and X of 0.5. Now they are both visible on the screen.
Depending on what type of camera you are using, you may want to set the cameras next to each other so they have aligned boundaries or overlaps (I don't know completely what you want). But I guess this is a good start.

thank you,and do you have any advise on what to do when they are not aligned? like how to combine the view from them

Okay, so I tried to write a script that aligned the frustum using the CalculateFrustumCorners() method on the camera. It worked once, but didn't look that nice. Now I just parented one camera onto the other and rotated the child camera in a way that their frustums align. This works.
But may I ask: What do you want to use it for?

it is for my bachelor thesis, my task is to combine view from multiple 3D cameras in selected direction and im supposed to do it in unity, but im very new to this so im doing some research on what to do

Okay, so if it is for research stuff (bachelor is fun!) look at Frustums and how they are calculated, how the matrixes are calculated. Check the Unity Documentation for how you get frustum-data out of your camera.
If you need some literature to read, check out "Game Engine Architecture" by Jason Gregory, especially chapter 10.1.4 but overall the whole section about rendering.


text:
How to set up flatbuffers in Android Studio - Gradle?
Just switching over from Eclipse to Android Studio. I think I'm supposed to use Gradle to automatically download dependencies from the web. Sounds great, but I can't get it working with anything, in particular Google's flatbuffers.
So I found the link on the Maven repository, and I think I'm supposed to do something with the following:
// https://mvnrepository.com/artifact/com.github.davidmoten/flatbuffers-java
compile group: 'com.github.davidmoten', name: 'flatbuffers-java', version: '1.3.0.1'

But the comments in my project's Gradle (which is supposed to be a library by the way - but that's another story...) says I should not place my "dependencies here" (see below)
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
repositories {
    jcenter()
}
dependencies {
    classpath 'com.android.tools.build:gradle:2.1.0'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}
}

allprojects {
repositories {
    jcenter()
}
}

task clean(type: Delete) {
delete rootProject.buildDir
}

So what am I supposed to do? I've heard of "modules" - so I could load flatbuffers in as a module?

I was updating the wrong build.gradle. I was updating the gradle of the package within the "app". So having updated my build.gradle file (Module: app) to include the following last dependency:
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:24.2.1'
compile group: 'com.github.davidmoten', name: 'flatbuffers-java',
 version: '1.3.0.1'
}

it works nicely. Beginning to like AS now... hehe.
UPDATE
Been porting my stuff over to Android Studio today. I'm a total convert - very good and much easier than Eclipse.


text:
Making random spawn points fair?
If all players are spawned at random positions the same distance from adjacent players, the number of players will be proportional to the likelihood of their spawn positions being unfair.  The closer players spawn to the centre of the map, the more likely they are to encounter other players and the less likely they are to survive, compared with players on the edge of the map.  Assume all players are spawned at the same time.
Is there a way to shape spawn points, or change the map, so that:

All players have a limited number of adjacent foes.
All players have equal chance of encountering adjacent foes.
Map size does not have to increase proportional to the number of players.
These limitations are not enforced with arbitrary impassable spaces.

The answer does not have to be perfect, just obviously better than the alternative.  Out of the box thinking welcome.

Spawn in a circle?

@Zibelas Traditional approach, but violates requirement 3, and with lots of players this creates a huge map and empty interior.

It depends on your type of game. (2D/ 3D, respawn/ last man standing, etc) Perfect spawn is in that case only possible on a ball shape world (more player, closer spawn but you can guaranty they have all the same distance). On a 2D world with fixed borders you have always less bordering players since you have no place to spawn them. If its a 3D game, you can have multiple layers.

I think it would help to know what kind of game you are making. It sounds like some kind of warfare game, but what are the details? Is it a shooter? Do you start with all your weapons, or do you have to explore and find things? What is the victory condition? How long is a match expected to last?

@inappropriateCode spawn them in concentric circles, one inside the other (or multiple circles inside each other). That will mitigate the need for a 1:1 map size increase for player increase.

Not for full answer, but i think everyone is trying for "fair & balanced spawn" which... is not fun. Look at excellent PUBG (and others Battle Royale) spawning: players can "spawn" (well, jump and land...) almost anywhere they want - if you want conflict and drama, you choose place where most player land / spawn. Hight risk hight reward, but only if player want it. You can land somewhere in woods, you got time to prepare yourself - low risk low reward but some players may prefer it (like me, for example ;) ). Its NOT random, its by players choice.

@inappropriateCode Or a very crowded circle?

Along the same lines as @RothX's request for clarification:  are these initial spawns or are respawns possible?  What exactly is spawning at these locations, and how does it interact with the surrounding environment?  You already have 7 answers (ATOW), but most of them make presumptions on those conditions.

Let the players pick their start locations themselves.
At the beginning of the game, spawn all players in the center of the map, but without any means of harming the other players. They will then have to swarm out and acquire the means to engage each other (build a base, pick up a weapon, gather resources, etc.)
There is either a bit of luck or map knowledge involved in finding a good start location early (depending on whether you use procedural or handmade maps). But when and where to settle is mostly a strategic decision. Deploying early gives you a time advantage, but puts you in a dangerous position. Picking your base carefully puts you behind in the early-game, but can be a decisive advantage in the mid- and late-game.

@Shashimee Actually I believe I have seen this method first in Anno 1602. I also believe that some of the early C&C games had that as an optional multiplayer game option (but I am not sure if I recall that correctly).

@Philipp M.U.L.E. for the commodore 64 around 15 years older and let you pick as well your positions :)

You then run into the issue where you are followed to your spawn point. This could, of course, be desired game mechanic, but it could also be extremely frustrating and not something you decide you want in your game. A good idea would be to have the characters spawn invisible and player-collision-free, and find their base before starting the game.

That's the method used by the "Vampirism" and "Tree Tag" line of custom gamemodes on Warcraft 3. It works best since all players are allied (at least initially) and the opposing team is released later.

This also has the advantage of feeling less unfair. If you spawn randomly and quickly die or suffer penalties, that can feel unfair, even if it is pretty fair. If you're choosing where you spawn death or penalties can seem less unfair and punishing because choosing spawn points is a skill in itself and something you can get better at.
That said, if choosing spawn points is really hard, it could also feel unfair because higher skilled players would do a lot better at it.

Offworld Trading Company (inspired by M.U.L.E.) uses this approach in reveal mode.

How will it work if a certain strategy is known and the position is desired by many? For example, half of the players. How can we handle that?

@majidarif I would call that bad map design. But even then any advanced player will understand that when they all move to the same position, only one will get it, and those which don't will be at a severe disadvantage. In a serious competitive match they will likely break off on their own and look for a different position.

Understanding the requirements

All players have a limited number of adjacent foes.

First off, we are talking about the spawn points of the players, not the current position of the players at a given point in the game. Just getting that out of the way.
Adjacent is well defined when we talk about a graph. We can think of a map that represent navigability on the map - from now on "the graph".
If can node can have at most one spawn point, then talking of them being "adjacent" makes sense. Note: I will not constraint nodes to have one single spawn point at most, for reasons that will be apparent later.
To build the graph we will need to consider things such as walls, bridges, ladders, teleportation points, or even consider flight space if there could be player that can fly. Each node represents a traversable location; each connection represents a possible movement.
Note: know size and shape of the nodes, and work with actually adjacent nodes. Do not consider nodes a point. Do not consider connections as having length. Also, use convex nodes.
The graph could have been precompiled (the map was created by a designer); otherwise, it can be created on the fly if the map is randomly generated.

All players have equal chance of encountering adjacent foes.

I will assume foes are other players. Again, just getting that out of the way.
Assuming each player makes a random walk, the probability of finding a player at a given point - on a flat space, free of obstacles - will be given by a (Gaussian) function of the distance to the spawn point - from now on "the function".
Since we are working on the graph, we will instead annotate the values on the graph.

Map size does not have to increase proportional to the number of players.

If we had the constraint of having a single spawn point per node, then to add more player we would need smaller nodes. If we decide the graph before we know how many player we will have, we may have to subdivide nodes for the particular game.

These limitations are not enforced with arbitrary impassable spaces.

I do not intend to add obstacles to solve the problem. Au contraire, I need to work arround the obstacles. If they were not there, the implementation would be simpler.

Solution
We are trying to place N spawn points such that the chance of encountering another player at all those spawn points is equal.
We can get a measure of the error as the sum of the differences of the chances to the mean of the chances. We are trying to minimize that (in fact, we want to make it 0).
To do so, we need to know the chance of encountering a player on each node of the graph.
To compute that chance, start with zero. Since the chance of finding a player on any given node, when there are no players, is zero. And then, for each spawn point, walk the graph adding to the annotated chance the value of the function for the current spawn point.
Note 1: Adding or moving a spawn point will affect the chance of encountering a player for all the map.
Note 2: Keeping track of how much each spawn point affects the chance, will make things easier.
Note 3:  Since nodes have size, how close you can get to error = zero depends on the size of the nodes. You can be more precise by working with ranges of values (minimun and maximun chance, depending on the particular position of the spawn points within the node).
Place spawn points at random, then start moving them in such way that error becomes smaller (consider a possible movement, and if causes the error to decrease keep it, otherwise revert it). And continue doing so until we cannot improve any further (too many iterations without improvement, or error is zero).
Note 4: When moving a spawn point, you can use the chance of encountering a player (excluding the spawn point you will move) to randomly select a new position for a spawn point such that position that have a chance of encountering a player closer to the mean are more likely. I remind you that moving the spawn point will affect the mean.
The expected behavior is that spawn point that are too close together move apart and spawn points that are too far apart come closer. Until they reach equilibrium.
If at any given iteration you have multiple spawn points on a node (which is unlikely, since they should tend to move apart, but possible if you have large enough nodes), split the node and continue solving. Any division of the node is valid.

The above solution will approach error = zero, but not guaranteed to reach zero. You can do is run it until it reaches a local minimum... In theory, you can then divide nodes to make it exactly zero... Yet, that is equivalent of tweaking the spawn point coordinates!
Try simulated annealing to move the spawn point within the node. Although, honestly, it probably is not worth it to bother with such level of detail.

I want to make it clear that the result for a flat map free of obstacles will not be uniformly distributed points. Instead, if the map has edges (that is, if it does not wrap around), then there will be more spawn point closer to the edges, this is because points at the center can be reached from more directions, increasing the chance of encountering other players there. Thus, points further apart near the center to compensate.

It depends on what kind of game you want to create and how fast paced it is. The perfect evenly spaced distribution is possible on a sphere like world (for example Planetary Annihilation). But is that a fair option in your game? Even if all people are spawning on equal distance, some spawns may still have better advantage.

Closer/ better weapons in range/ more resources
Better cover/ more hidden/ overview
the 'flow' of the players, some places are more attractive than others (think of a full forest map with a single house at one place, regardless where that house is, good chance that people are checking it out)

Is your map a fixed one or a procedural generated one? And ever tried to play Age of Empires with 8 people on a 2 person map? It's not possible to scale the players infinite without making adjustment to the map size. Even an unfair start placement can bring a lot of dynamic in the game (see the Worms series). Nobody complained if you spawned right in a big cluster, as long as your one round alliance with another player lasted or you had not the most surviving worms after the first round.
(I will add a few more examples if I know more about your type of game)

Going for something not suggested so far: Make it so there is no centre of the map. What I mean by this is that the map edges join onto the opposite sides. This would take a lot of programming work, but in practise it can make the level repeat itself infinitely if you walk in one direction. This means that there is no centre, and a random spawn position will have no advantages or disadvantages.
You can do this by making a flat map which is square, and joining each edge to a copy of the opposite edge. When a player walks off the side, they are teleported without the player's knowledge to the opposite edge. Of course, theoretically you would not be able to see players on the other side of the boundary. To fix this, create clones of that player which appear to walk around on the other side of the boundary so that you can see them, and when you run towards them you teleport across and the actual player is stood where the dummy was.
Alternatively, the entire map could exist on the outside of a sphere, however this makes coordinates difficult for spawning.

Or make a map that, well, in center, you can get hunted or hunt much easier, and can also find loot easier, but again, you're much more possible to get hunted like this, and in non-center areas, make it so that players are less likely to find other users and loot, so if they want more loot they'll have to go to the center, if they want to survive longer, they'll have to stay where they are. So basically make the disadvantage of random spawns an advantage.

Here are some possible solutions:

Spawn randomly on the circumference of the circle
Spawn randomly on radii (not spawning to close the center)
Add a random spawn time component

Second image is a great option. It solves the problem of the first option where the player knows exactly where all other players are located.

@Zanon though with first image players can (and likely will) move away before someone comes there. Second one will cause unfair spawns, some close to others. Maybe something like this where there are 2 circles and the difference between smaller and bigger one is where they spawn, so like second image, but less to the center.

A few others have already discussed the limitations of your requirements (map will need to scale at some point to prevent overcrowding, etc.), and have ultimately eluded to the fact that there likely isn't a "perfect" placement algorithm. When there likely is no "perfect" algorithm, I always look towards heuristics. You have several criteria that are either directly or indirectly at odds with eachother, along with a very complicated search space. Finding an optimal solution may not be feasable or practical, but with a little tuning, a statistical approach can perform very well the majority of the time.
Addressing your third and fourth criteria: "The map shouldn't have to expand."
I would make sure at the beginning you have an over-abundance of nodes (ie: as dense as a navigation mesh for path-finding). This makes calculating the distance to other players more expensive (not directly neighboring nodes), but this is not a process that will happen more than once per round (I assume). A bonus of this is you can use a pre-rolled nav library for most of your operations. Additionally this will respect traversal around obstacles in a fair manner where euclidean distance may not (players in a maze might be placed closer together than in an open field)
Calculate heuristics for your desired spawn characteristics:
After randomly placing all the players, calculate the performance of the surrounding nodes based on your criteria (distance from other players, distance to spawn, etc.) The weights of your values can be tweaked, and manipulated to be nonlinear to tune exactly the performance you want in a sanitized ideal case (flat rectangular grid with no obstacles), and the performance should be similar when you add the world back in. From there you can decide how many nodes to search, what is the threshold for moving a starting point, and how many iterations you want to perform before finalizing the spawn and beginning the game.

If the playing field is a topological torus (i.e. a rectangle where going “out of bounds” means entering at the opposite side), this is likely to be a good answer: player j spawns at x = (pjW/N) mod W, y = (qjH/N) mod H, where W,H are the dimensions of the rectangle, N is the number of players, and p,q are integers to be determined; they are distinct, (probably) relatively prime, and not too far from sqrt(N).  The spawn points form an oblique ‘wallpaper’ pattern.
That's supposing that the players spawn only at the beginning of the game.  If they spawn later, I guess you'd want to put them as far as possible from any player's current position – at a vertex of the Voronoi diagram defined by the other players.

Fundamentally I believe this is a graph distribution problem. Assuming a deathmatch situation (every other player is an enemy), you need to model your maps as an interconnected graph, and track which node on the graph each player is closest to. Not every node need be a spawn point, but you need the complex graph to model distances between spawn points. At spawn time, you're then iterating the graph and scoring each spawnable-node based on whether it nearby nodes have players.
The ideal node then has:

No players currently in it
More than zero players in nodes nearby (some small number of links away)

Imagine that your graph has been regularised, and you're drawing concentric zones around each node. You penalise the node if the inner zones already have players in them, and reward nodes that have players at the right distance away. You want to encourage spawning near enough to other players that they can find interest quickly, but not so near that they get jumped on before they've had a chance to get their bearings.
You will need to increase the map size as the number of players grows, but the k need not be 1 or greater. Your worst case is still going to be that every node on the graph has at least one player - in which case there are no good nodes to use, and you're going to have to suffer that case and spawn a player knowing that they will land right on top of another. The scoring algorithm should still weight the nodes so that you spawn in the node with the fewest other players.
Bear in mind that your map graph will have to be carefully built, with knowledge of the map, its routes, any chokepoints, and effective distance between node points, not actual distance. As in, use something like measured time to traverse between nodes rather than distance, to account for more difficult terrain. Also you need to account for open-ness vs cover; two nodes might be physically far apart, but because they are very open, spawning a player at each node might mean they are equally as vulnerable as if you'd spawned them right next to each other.
Refinements:

Add a temporary penalty to score if a player has spawned in that node recently, to stop chokepoints from forming (an endless stream of players coming from the same direction and getting picked off)
Add randomness within a range (e.g. pick the best 3 nodes and then randomly choose between them with equal probability) to get more variation.
Add an initial weight to the centre of the map (or the most interesting points) when no-one has yet spawned, so that you spawn in known places, even when every node has a score of zero because no other players are present.

How about:
Each player is surrounded by a non-spawning box (or circle).
As in, there's a square of a certain size that spawns around every player and follows that player around - no other player can spawn within that square.
These squares only affect spawning and not any other movement during the game.
This works with either initial-only spawning or continuous spawning.

(Dots indicate players and green indicates possible spawn area for new players)

Map size does not have to increase proportional to the number of players

To deal with this, you can do one of two things: (or both)

Decrease the size of the non-spawning boxes based on the number of players.
Allow up to X enemy players to spawn in each box.

This number can increase as you go (starting at 0).
Variant 1: have a smaller no-spawn box and a larger limited-spawn box.
Variant 2: weight probabilities according to how close the new spawn is to this player (if inside the box) - might be hard to implement efficiently.


text:
How to integrate admob ads in Unity 5.6.2f1
I made the game space shooter. But i don't know how to integrate admob ads in Unity. I downloaded Google Admob ads Plugin for unity. But where i write the code don't know and how to implement it!!

There is no short answer to your long question, please study one of guide given below.
Ads Implementation in Unity Using AdMob
ADMob for Unity By Google
Unity-Admob Github
Unity Forums Thread On AdMob


text:
Space Ship Move Left and right side but its not stop (stable or like vibrate) in the corner
I made the game space shooter. In my space shooter its move left and right but not stop in the corner( Stable or vibrate). I don't know how it will be stopped.
Player Movement. cs
using UnityEngine;
using System.Collections;

public class PlayerMovement : MonoBehaviour {
    public float speedMove = 3;
    public float bonusTime;
    private Rigidbody rb;
    private float _limit = 0;

    // 1 for right and -1 for left.
    private float _direction = 1;

    // You can call it as speed
    private float _speed = 0.01f;

    private bool toLeft = true;
    private bool toRight = true;

    public GameObject shield;
    public GUIText bonustimeText;

    private bool counting = true;
    private float counter;

    private Weapon[] addWeapons;

    public Sprite strongShip;
    public Sprite normalSprite;
    public Sprite shieldSprite;

    private SpriteRenderer sRender;
    private Weapon weaponScript;

    void Start () {

        counter = bonusTime;
        rb = GetComponent<Rigidbody>();

        sRender = GetComponent<SpriteRenderer> ();
        addWeapons = GetComponentsInChildren<Weapon> ();
        foreach (Weapon addWeapon in addWeapons) {
            addWeapon.enabled = false;
        }

        weaponScript = GetComponent<Weapon>();
        weaponScript.enabled = true;
    }

    // Update is called once per frame
    void Update () {

        transform.position = Vector3.MoveTowards (transform.position, new Vector3 (transform.position.x + _direction, transform.position.y, transform.position.z), _speed);

        if (Input.GetMouseButtonDown (0))
            _direction *= -1;
    }

    void OnCollisionEnter2D(Collision2D coll)
    {
        if (coll.gameObject.tag == "StrongMode") {
            Destroy (coll.gameObject);
            counting = true;
            StrongMode();
            Invoke ("Downgrade", bonusTime);
        }

        if (coll.gameObject.tag == "ShieldMode") {
            Destroy (coll.gameObject);
            counting = true;
            ShieldMode();
            Invoke("Downgrade", bonusTime);
        }

        if (coll.gameObject.tag == "Life") {
            GUIHealth gui = GameObject.Find ("GUI").GetComponent<GUIHealth> ();
            gui.AddHealth();
            SendMessage("AddHp");
            SoundHelper.instanceSound.PickUpSound();
            Destroy(coll.gameObject);
        }

        if (coll.gameObject.tag == "Enemy") {
            SendMessage("Dead");
        }
    }

    void Downgrade()
    {
        SoundHelper.instanceSound.BonusDownSound ();
        counting = false;
        bonustimeText.text = "";
        counter = bonusTime;

        sRender.sprite = normalSprite;
        weaponScript.enabled = true;
        foreach (Weapon addWeapon in addWeapons) {
            addWeapon.enabled = false;
        }
        weaponScript.enabled = true;
        shield.SetActive (false);
    }

    void StrongMode()
    {
        SoundHelper.instanceSound.BonusUpSound ();
        sRender.sprite = strongShip;
        foreach (Weapon addWeapon in addWeapons) {
            addWeapon.enabled = true;
        }
        weaponScript.enabled = false;
    }

    void ShieldMode()
    {
        SoundHelper.instanceSound.BonusUpSound ();
        sRender.sprite = shieldSprite;
        shield.SetActive (true);
    }

//  void OnDestroy()
//  {
//      bonustimeText.text = "";
//  }
}

From what I understand, you did not reset _direction and so it will always move to the right based on the Update function. You had a GetMouseButtonDown but it would just set _direction to be -1 so your spaceship will move left as it is now going in the negative x axis.
I think what you need is a way to set _direction to be 0 to stop it from moving.


text:
How to block the player from moving left and right from two empty game objects?
I made the game space shooter in that game my spaceship move left and right but its not stop in right and left corner. When its move to left its go out of the screen. how i stop/block in the left and right screen edges.
using UnityEngine;
using System.Collections;

public class PlayerMovement : MonoBehaviour {
    public float speedMove = 3;
    public float bonusTime;
    private Rigidbody rb;
   private float _limit = 3;

    // 1 for right and -1 for left.
    private float _direction = 1;

    // You can call it as speed
    private float _speed = 0.01f;

    private bool toLeft = false;
    private bool toRight = false;

    public GameObject shield;
    public GUIText bonustimeText;

    private bool counting = true;
    private float counter;

    private Weapon[] addWeapons;

    public Sprite strongShip;
    public Sprite normalSprite;
    public Sprite shieldSprite;

    private SpriteRenderer sRender;
    private Weapon weaponScript;

    void Start () {

        counter = bonusTime;
        rb = GetComponent<Rigidbody>();

        sRender = GetComponent<SpriteRenderer> ();
        addWeapons = GetComponentsInChildren<Weapon> ();
        foreach (Weapon addWeapon in addWeapons) {
            addWeapon.enabled = false;
        }

        weaponScript = GetComponent<Weapon>();
        weaponScript.enabled = true;
    }

    // Update is called once per frame
    void Update () {

        transform.position = Vector3.MoveTowards (transform.position,new Vector3 (transform.position.x + _direction, transform.position.y, transform.position.z),_speed);

        if (Input.GetMouseButtonDown (0))
            _direction *= -1;

    }

    void OnCollisionEnter2D(Collision2D coll)
    {
        if (coll.gameObject.tag == "StrongMode") {
            Destroy (coll.gameObject);
            counting = true;
            StrongMode();
            Invoke ("Downgrade", bonusTime);
        }

        if (coll.gameObject.tag == "ShieldMode") {
            Destroy (coll.gameObject);
            counting = true;
            ShieldMode();
            Invoke("Downgrade", bonusTime);
        }

        if (coll.gameObject.tag == "Life") {
            GUIHealth gui = GameObject.Find ("GUI").GetComponent<GUIHealth> ();
            gui.AddHealth();
            SendMessage("AddHp");
            SoundHelper.instanceSound.PickUpSound();
            Destroy(coll.gameObject);
        }

        if (coll.gameObject.tag == "Enemy") {
            SendMessage("Dead");
        }
    }

    void Downgrade()
    {
        SoundHelper.instanceSound.BonusDownSound ();
        counting = false;
        bonustimeText.text = "";
        counter = bonusTime;

        sRender.sprite = normalSprite;
        weaponScript.enabled = true;
        foreach (Weapon addWeapon in addWeapons) {
            addWeapon.enabled = false;
        }
        weaponScript.enabled = true;
        shield.SetActive (false);
    }

    void StrongMode()
    {
        SoundHelper.instanceSound.BonusUpSound ();
        sRender.sprite = strongShip;
        foreach (Weapon addWeapon in addWeapons) {
            addWeapon.enabled = true;
        }
        weaponScript.enabled = false;
    }

    void ShieldMode()
    {
        SoundHelper.instanceSound.BonusUpSound ();
        sRender.sprite = shieldSprite;
        shield.SetActive (true);
    }

//  void OnDestroy()
//  {
//      bonustimeText.text = "";
//  }
}

The easiest solution would probably be to put some box colliders at the edges of the screen. Then collision will prevent your ship from passing through and force it to stay on screen.

Although you could use just box colliders as already suggested, it's pretty much killing a fly with a canon.
A simple approach through code is to compare player's position to camera boundaries position, so if the next position to move to is out of bounds, you don't apply it.
Following this link to the Unity3D forums, you can get an idea of how to get World's position out of screen's.
Then, you just compare the next player's position to corners', and you apply the movement if it won't get out of boundaries.
int leftUpBoundX = x; //Calculate using link
int leftUpBoundY = y; //Same
int movX = -10
int movY = 5
if (playerX + movX >= leftUpBoundX
    && playerY + movY <= leftUpBoundY) {
    playerX += movX;
    playerY += movY;
}

You just do this for the 4 corners and X/Y coords. If you wanted to move in 1 axis even if  you can't move in both, you just split X/Y if statements too.
This may seem complicated or CPU consuming but it's actually just adding and comparing integers.
Besides that, have in mind that you can extract this to a common script and use it to both player and/or enemies as well, having no more work than sending the appropiate object's position parameters.


text:
How to make it my game level tough?
I made the game space shooter. In my game the boss take too much time to fire and the enemy not even come in the screen. So how to manage the fire speed and make the level tough.Click the link on 2 and 3 also for image view.
shootscript. cs
using UnityEngine;
using System.Collections;

public class ShootScript : MonoBehaviour {

    public int dammage = 1;
    public bool isEnemyShot = false;
    public Sprite lightDestroy;
    public float laserTime;
    private float increament;

    void Update()
    {
        laserTime -= Time.deltaTime;
        if (laserTime <= 0) {
            Destroy(gameObject);
        }
    }

    void FixedUpdate()
    {
        if (!isEnemyShot) {
            this.transform.Translate (Vector2.up * 6 * Time.deltaTime);
        } else {
            this.transform.Translate (Vector2.up * -6 * Time.deltaTime);
        }
    }

    void OnCollisionEnter2D( Collision2D coll)
    {
        if (coll.gameObject.tag == "Player" || coll.gameObject.tag == "Enemy")
        {
            gameObject.transform.localScale = new Vector2 (1, 1);
            gameObject.GetComponent<SpriteRenderer> ().sprite = lightDestroy;
            gameObject.GetComponent<BoxCollider2D> ().isTrigger = true;
            Destroy (gameObject, 0.05f);
        } else {
            Destroy(gameObject);
        }
    }
}

Weapon.cs
using UnityEngine;
using System.Collections;

public class Weapon : MonoBehaviour {

    public Transform laserPrefab ;
    public bool isEnemyWeapon = false;
    public float shootDelay = 1.0f;
    private float waitToShoot;

    public bool firingContinously = true;
    float nextFire = 0;
    float fireDelay = 400; // 100 milliseconds between each bullet

    void Start () {
        waitToShoot = 0f;
        firingContinously = true;
    }

    void Update () {
        if(Input.GetKeyDown(KeyCode.G)){
            firingContinously = !firingContinously;
        }

        if(firingContinously && !isEnemyWeapon)
        {
            if(Time.time * 1000 > nextFire){
                nextFire = (Time.time * 1000) + fireDelay;
                Fire();
            }
        }

        if (waitToShoot > 0) {
            waitToShoot = Time.deltaTime;

        }

        if (Input.GetKeyDown (KeyCode.Space) && isEnemyWeapon == false) {
            Fire ();
        }

        if (isEnemyWeapon == true && EnemyAttack == true) {
            waitToShoot = shootDelay;
            var shootLaser = Instantiate (laserPrefab) as Transform;
            Vector2 pos = shootLaser.transform.position;
            pos.x = transform.position.x ;
            pos.y = transform.position.y - 0.1f;
            shootLaser.transform.position = pos;
//          SoundHelper.instanceSound.EnemyLaserSound();

        }
    }

    public void Fire()
    {
        var shootLaser = Instantiate(laserPrefab) as Transform;
        Vector2 pos = shootLaser.transform.position;
        pos.x = transform.position.x;
        pos.y = transform.position.y + 0.5f;
        shootLaser.transform.position = pos;
        //SoundHelper.instanceSound.PlayerLaserSound();
        Debug.Log("Fire Method");

    }

    public bool EnemyAttack
    {
        get
        {
            return waitToShoot <= 0f;
        }
    }
}

[][1[Boss Laser[]2]3

If I am correct, your enemy will never shoot because Time.deltaTime is never <= 0. But that could simply be a typo here on Stackoverflow. So make sure you use
if (waitToShoot > 0) {
    waitToShoot -= Time.deltaTime;

instead of
if (waitToShoot > 0) {
    waitToShoot = Time.deltaTime;

And to achieve a higher fire rate from the boss you can change shootDelay to a smaller number.
And to make the level though I guess there are like a thousand possibilities. I would make some special bullets like those you can see in some bullet hell games (e.g. bullets that spawn new bullets in different directions, faster bullets, etc.) and give the boss a lot of health so you really have to battle him for a while and you have to avoid a lot of bullets. Maybe you can add some smaller enemies as well if your boss is too weak or shoots too less bullets. Something like this.


text:
Imitate a textured sphere in 2D
I'm writing planet generator, using pico8. I got surface generation done:

And the last thing to do is to map the texture onto a sphere.
Pico8 has no triangle function. So my question is, how do I make a sphere in my 2d space, and how do I apply a texture on it?
Looking for an effect like this (with no lighting, of course!):

I have really bad knowledge of 3d space manipulations.
The full list of available API functions can be found here.
Update 4:
Solved!

Try it live here.

Great question! As a note: you may need to fix your planet generation a little bit, too. The land on the right joins up to the land on the left, but look at the bit at the bottom! If the entire bottom of the image is the south pole, your land at the moment is forming a triangle. Take a look at Antarctica on a rectangular map and you should see what I mean.

With the bottom part is fine, that part will be just really tiny on the sphere. I resize texture near the poles. Added another image with generator output.

I've used simplex noise for generating. I have a 2d array with this texture. Also, I can access screen memory with pset / pget.

Ironically, the polar regions of the animation shown in your question are moving more quickly than the equatorial regions. This is backwards. Either the generated terrain is stretched out to be rectangular, in which case it moves at the same speed or its not, in which case the equator is longer and needs to move more quickly to keep up.

This is current formula fail. If I just do tx=round(((x-cx)/64+0.5)*128) it looks ok. http://imgur.com/a/dUOey

You may find it interesting to see how this was done in Star Control II, by scrolling masks along a pre-shaded sphere sprite. :)

Very nice work! It looks great! If you want to make the sparkling at the edge slightly less noticeable, you can reduce the threshold on magSq just a bit below 1 to crop out the outermost ring of pixels (possibly scaling up px & py first so you still fill your target square)

You can try it live now! https://egordorichev.itch.io/planet-generator

Added lighting.

Here's a rundown of a few different ways we can sample a panning texture to make it look like a globe...

Since I'm not deeply familiar with Pico-8 syntax & conventions, I'll try to present these as pseudo-code that should be reasonably straightforward to translate / token-reduce as needed.
// iterate over each pixel in the discSize x discSize bounding square
for x = left...left + discSize
    for y = top...top + discSize

        // convert pixel position into a vector relative to the center,
        // normalized into the range -1...1
        px = (x - left) * 2/discSize - 1
        py = (y - top) * 2/discSize - 1

        // get the squared magnitude of this vector
        magSq = px * px + py * py

        // if we're outside the circle, draw black/background and skip ahead
        if ( magSq > 1 )
           plotPixel(x, y, BLANK)
           continue

        // TODO: warp our local offset vector px py to imitate 3D bulge

        // convert our local offsets into lookup coordinates into our map texture
        u = time * rotationSpeed + (px + 1) * (mapHeight/2)
        v = (py + 1) * (mapHeight/2)
        // wrap the horizontal coordinate around our map when it goes off the edge
        u = u % (2 * mapHeight)

        // look up the corresponding colour from the map texture & plot it
        color = lookupFromMap(u, v)
        plotPixel(x, y, color)

If you just use this as-is, you'll get the left version: it's cropped to a circle and wraps around, but it's very flat-looking.
By tweaking px and py where it says "TODO" we can get different bending effects.
Here's an equivalent implementation of Bálint's suggestion in this form:
widthAtHeight = sqrt(1 - py * py)
px = px / widthAtHeight

If we want an exactly correct sphere as viewed by an orthographic camera, we can use inverse trig functions to convert to latitude & longitude:
widthAtHeight = sqrt(1 - py * py)
px = asin(px / widthAtHeight) * 2/3.141592653589
py = asin(py) * 2/3.141592653589

(This assumes asin's return value is in radians. If using another unit, divide by whatever value corresponds to 90 degrees, instead of by pi/2. The idea is to map asin(-1)...asin(1) back into the range -1...1)
This gives the version second from the right, which you can see is a very good match for rendering a real 3D sphere (far right). The downside is that transcendentals like the arcsine function can be expensive. This may or may not be an issue in your case.
If you're looking for something to give a more bulgy look without the trig, you can use something like a lens distortion for a cheap hack:
scale = 0.35 * magSq + (1 - 0.35)
px = px * scale
py = py * scale

At the edges of the disc, scale is 1 so there's no difference versus the flat version. Closer to the center, this shrinks the length of our local offset vector (down to a controllable minimum set by the 0.35 linear interpolation constant), which has the effect of magnifying features close to the middle.
Of course these are just a few different ways you could get a bulged look. You could try all kinds of other formulae, or even go for a perspective camera look instead of the orthographic version I've shown here.

Man, the last three look amazing. One question: how do you do create the real sphere? I thought about generating the 3d vector the pixel corresponds to then using the good ol' divide by z trick, but I thought it would use up a huge amount from the 8k token limitation

One thing more, ~1000 is used for generating the surface. Really looking forward to the explanation :D

These aren't rendered in Pico8 — I used a 3D engine so I could quickly iterate with shader code that's more familiar to me. So the last one is actually a polygonal sphere rendered with traditional texture mapping, as a check that the latitude/longitude math was working right (it looked funny to me so I wanted to be sure). @egordorichev what's the ~1000 mean? As I mentioned above I don't know a lot about Pico8 specifics unfortunately. ^_^;

It means, that I have 7000 tokens space. https://stackoverflow.com/questions/4448661/what-is-the-exact-definition-of-token That's a lot, so you shouldn't care.

@egordorichev Lua is a compiled pointer based language, so for examole the lines local a = 10 and local b = sin(a) consists of around 10 tokens

local doesn't count. So we got three: a, =, 10. ( plus ) is one token. That's pico8 feature. In local b = sin(a) is 5 tokens: b, =, sin, (), a

Thank you so much! Last two look identical :D That's really good!

Almost got working latitude & longitude method, the only thing is, that it shows really scaled pixels. Probably, will need to multiply u/v by something. Will debug that later.

Here is the result: http://imgur.com/a/yzyNA Any ideas, how could this be fixed?

See the result in the update.

Hmmm... my best guess off the top of my head is the asin function is returning a value in degrees instead of radians, in which case you'd want to divide by 90 instead of pi/2. I'm assuming pixel lookups are done in pixel coordinates (eg 0...128), not normalized 0....1 coordinates?

Yes, from 0 to 128. But v and u don't seem to be from 0 to 1.

My asin() currently returns value from -0.25 (arg==-1) to 0.25 (arg==1).

Fixed by multiplying it by 6.2

It sounds like your trig functions are using a custom angle system, where a full circle of rotation is 1.0, so dividing by 0.25 (ie. multiplying by 4) instead of by pi/2 should get the right result, rather than needing another magic multiplier number to compensate.

First of all, this is going to cut corners, as this API is very small (I have concerns about the maximum 8192 tokens rule, which technically makes this non-turing-complete). The algorithms you need to use are the pythagorean theorem (√(x² + y²)) and the width of a circle at a specific height (2√(r² + |y - cy|²) where cy is the y coordinate of the circle).
So, you need to loop through the square that contains the circle. If the radius of the sphere is r and the center of it is (cx; cy), then you need to loop through the coordinates between (cx - r; cy - r) and (cx + r; cy + r). Let the coordinates of the current pixel be (x; y).
If √((x - cx)² + (y - cy)²) is less then or equal to the radius of the sphere, then the pixel is inside the 2d projection of the sphere.
Next we need to map this coordinate to a coordinate on the texture. Here we use the circle width formula. Get the width of the circle at the current position, let's name it segmentWidth Because we usually see around half of a sphere, we can just say that the coordinates of the pixel on the texture is
x = round(((x - cx) / segmentWidth + 0.5) * textureWidth / 2)
y = round(((y - cy) / r / 2 + 0.5) * textureHeight)

Comments are not for extended discussion; this conversation has been moved to chat.


text:
Problem in Splash Screen (Libgdx)
I made the game in libgdx and i want the splash screen in the starting but its show splash screen but not move to the game screen. I don't know what was the problem even the run time error also not occur.
GameScreen. java
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL20;
import com.gamestudio24.martianrun.stages.GameStage;

public class GameScreen implements Screen  {

    private GameStage stage;

    public GameScreen() {
        stage = new GameStage();
    }

    @Override
    public void render(float delta) {
        //Clear the screen
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        //Update the stage
        stage.draw();
        stage.act(delta);
    }

    @Override
    public void resize(int width, int height) {

    }

    @Override
    public void show() {

    }

    @Override
    public void hide() {

    }

    @Override
    public void pause() {

    }

    @Override
    public void resume() {

    }

    @Override
    public void dispose() {

    }

}

GdxSplashScreenGame. java
import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.utils.Timer;

public class GdxSplashScreenGame extends Game {

    private static long SPLASH_MINIMUM_MILLIS = 2000L;

    public GdxSplashScreenGame() { super(); }

    @Override
    public void create () {
        setScreen(new SplashScreen());

        final long splash_start_time = System.currentTimeMillis();
        new Thread(new Runnable() {
            @Override
            public void run() {

                Gdx.app.postRunnable(new Runnable() {
                    @Override
                    public void run() {
                        long splash_elapsed_time = System.currentTimeMillis() - splash_start_time;
                        if (splash_elapsed_time < GdxSplashScreenGame.SPLASH_MINIMUM_MILLIS) {
                            Timer.schedule(
                                    new Timer.Task() {
                                        @Override
                                        public void run() {
                                            GdxSplashScreenGame.this.setScreen(new SplashScreen());
                                        }
                                    }, (float)(GdxSplashScreenGame.SPLASH_MINIMUM_MILLIS - splash_elapsed_time) / 1000f);
                        } else {
                            GdxSplashScreenGame.this.setScreen(new SplashScreen());
                        }
                    }
                });
            }
        }).start();
    }

    @Override
    public void dispose() {
        // DISPOSE ALL RESOURCES
        getScreen().dispose();
        Gdx.app.exit();
    }
}

SplashScreen. java
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;

public class SplashScreen extends GameScreen {
    private SpriteBatch batch;
    private Texture ttrSplash;

    public SplashScreen() {
        super();
        batch = new SpriteBatch();
        ttrSplash = new Texture("assets/splash.png");
    }

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

        batch.begin();
        batch.draw(ttrSplash, 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
        batch.end();
    }

    @Override
    public void hide() { }

    @Override
    public void pause() { }

    @Override
    public void resume() { }

    @Override
    public void show() { }

    @Override
    public void resize(int width, int height) { }

    @Override
    public void dispose() {
        ttrSplash.dispose();
        batch.dispose();
    }
}

MartianRun. java
import com.badlogic.gdx.Game;
import com.gamestudio24.martianrun.screens.GameScreen;
import com.gamestudio24.martianrun.screens.SplashScreen;
import com.gamestudio24.martianrun.utils.AssetsManager;
import com.gamestudio24.martianrun.utils.AudioUtils;
import com.gamestudio24.martianrun.utils.GameEventListener;
import com.gamestudio24.martianrun.utils.GameManager;

public class MartianRun extends Game {

    public MartianRun(GameEventListener listener) {
        GameManager.getInstance().setGameEventListener(listener);
    }

    @Override
    public void create() {
        AssetsManager.loadAssets();
        setScreen(new SplashScreen());
        setScreen(new GameScreen());

    }

    @Override
    public void dispose() {
        super.dispose();
        AudioUtils.dispose();
        AssetsManager.dispose();
    }
}

I think you're over complicating things by using threads and timers. You can use your GdxSplashScreenGame as the main parent class which controls which screen should be shown. Then when you create a screen your simply pass the parent (GdxSplashScreenGame) to the screens and let the screens control when they are finished.
If you change your main game class to include a static var for each screen and a method to change screens like this:
import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;

public class GdxSplashScreenGame extends Game {

    // one for each possible screen
    public static final int SPLASH_SCREEN = 0;
    public static final int GAME_SCREEN = 1;
    public static final int GAME_OVER_SCREEN = 3;

    public GdxSplashScreenGame() { super(); }

    @Override
    public void create () {
        changeScreen(SPLASH_SCREEN);
    }

    @Override
    public void dispose() {
        // DISPOSE ALL RESOURCES
        getScreen().dispose();
        Gdx.app.exit();
    }

    public void changeScreen(int screen){
        if(screen == SPLASH_SCREEN){
            this.setScreen(new SplashScreen(this));
        }else if(screen == GAME_SCREEN){
            this.setScreen(new GameScreen(this));
        }
    }
}

Then when you pass the this class to your screens you can simply call
parent.changeScreen(GdxSplashScreenGame.GAME_SCREEN);

Now instead of using a thread and a timer to change the screen after a certain time. You can use the built in delta time supplied in the render method to use as a countdown timer like this:
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;

public class SplashScreen implements Screen {
    private SpriteBatch batch;
    private Texture ttrSplash;
    private GdxSplashScreenGame parent;

    private float timeToShowSplashScreen = 2f; // 2 seconds

    // pass the parent game to this screen so this screen can tell the parent its finished
    // and tell it to load the next screen
    public SplashScreen(GdxSplashScreenGame p) {
        super();
        parent = p;
        batch = new SpriteBatch();
        ttrSplash = new Texture("assets/splash.png");
    }

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

        batch.begin();
        batch.draw(ttrSplash, 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
        batch.end();

        timeToShowSplashScreen -= delta; // remove delta from time
        if(timeToShowSplashScreen <= 0){ // 2 seconds are up
            // tell parent to change screen
            parent.changeScreen(GdxSplashScreenGame.GAME_SCREEN);
        }
    }

    @Override
    public void hide() { }

    @Override
    public void pause() { }

    @Override
    public void resume() { }

    @Override
    public void show() { }

    @Override
    public void resize(int width, int height) { }

    @Override
    public void dispose() {
        ttrSplash.dispose();
        batch.dispose();
    }
}