# Question
Title: Issues to display a texture loaded with libPNG with opengles 3.0
I'm trying to load a texture loaded with libPNG on a XY coordinates. I know the width and the height of the texture (32x32).

The texture is already loaded successfully and I have his Id.

Here is my function to print any (32x32) texture on a XY position :

```
void printTexture(GLuint idTexture, GLfloat x, GLfloat y) {
    glActiveTexture(GL_TEXTURE0);
    glBindVertexArray(this->VAO[0]);
    glUniform1i(this->mTagShaderHandle, 0); //to execute a particular code on the Pixel Shader
    glUniform1i(this->mTextShaderHandle, 0); //the uniform Sampler2D from my Fragment Shader bound to 0.

    GLfloat xpos = x;
    GLfloat ypos = y;

    GLfloat w = 32;
    GLfloat h = 32;

    GLfloat vertices[6][4] = {
            { xpos,     ypos + h,       0.0, 0.0 },
            { xpos,     ypos,           0.0, 1.0 },
            { xpos + w, ypos,           1.0, 1.0 },

            { xpos,     ypos + h,       0.0, 0.0 },
            { xpos + w, ypos,           1.0, 1.0 },
            { xpos + w, ypos + h,       1.0, 0.0 }
    };

    glBindTexture(GL_TEXTURE_2D, idTexture);
    checkGlError("glBindBuffer");

    glBufferSubData(GL_ARRAY_BUFFER, GL_ZERO, sizeof(vertices), vertices);
    glDrawArrays(GL_TRIANGLE_STRIP, GL_ZERO, 6);
    glBindVertexArray(GL_ZERO);
    glBindTexture(GL_TEXTURE_2D, GL_ZERO);
}

```

Here is how I initialize my VAO and VBO :

```
glBindVertexArray(this->VAO[0]);
glBindBuffer(GL_ARRAY_BUFFER, this->VBO[0]);
glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * 6 * 4, GL_ZERO, GL_DYNAMIC_DRAW);
glEnableVertexAttribArray(GL_ZERO);
glVertexAttribPointer(GL_ZERO, 4, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), GL_ZERO);
glBindVertexArray(GL_ZERO);

```

Here is how I set up my texture:

```
glTexImage2D(GL_TEXTURE_2D, GL_ZERO, GL_RGB, temp_width, temp_height, GL_ZERO, GL_RGB, GL_UNSIGNED_BYTE, image_data);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);

```

And my Vertex Shader :

```
const char           gVertexShader[] =
        "#version 320 es\n"
        "layout (location = 0) in vec4 vertex;\n"
        "out vec2 TexCoords;\n"
        "uniform mat4 projection;\n"
        "uniform int tag;"
        "void main() {\n"
                "  gl_Position = projection * vec4(vertex.xy, 0.0, 1.0);\n"
        "  if (tag > 0) {\n"
        "      TexCoords = vertex.zw;\n"
        "  } else {\n"
        "      TexCoords = vertex.xy;\n" //here is the code that should be executed by the pixel shader program because Tag = 0.
        "  }\n"
        "}\n";

```

The texture is not displaying at all. I tried a lot of things but nothing change. I **should keep** this **pixel shader** because I have some functions to print texts so that's why I have the **if/else** statement on my Pixel Shader code.

What's wrong with my code ?

Thanks a lot for help.

# Answer
The line of the vertex shader that you've highlighted is setting the texture coordinates to be the same as the vertex coordinates. So if you're drawing a quad at `(96,96)` to `(128, 128)`, then your texture coordinates will be `(96, 96)` to `(128, 128)`. But since you're using the `GL_TEXTURE_2D` target, the texture coordinates should be normalized. Otherwise, you'll be seeing just the edge color of the texture repeated across the quad. That probably not what you want. You probably do want to use 0-1 as the texture coords in both x and y directions.
> 0 votes

---
Tags: shaders, textures, opengl-es, vertex
---


# Question
Title: Create a game start-up menu screen with Lua/love 2d
I just got started programming games and decided to try out love2d since I'm learning lua.

I was wondering if anyone knows how I can create just a simple 2-3 button menu when you start up the game.

All I want to do is make a start up menu.

I have 2 files and nothing else:

* **main.lua**, in which I have the game code and the level design
* **conf.lua**, in which I have the title screen code and the icon of the game

I couldn't find any wiki page to help me for coding for the **first time** a splash screen and a overall game screen !!

now i have only one screen the ***game screen*** and i want to have 3 screens : **1** splash screen in wich i want to draw a image background and 3 buttons **PLAY,EXIT,TITLE** with coding mousepress! **2** game screen! **3** game over screen with an other background image!

# Answer
There isn't a built-in menu system for love2d. The developers take a 'do-it-yourself' approach to a lot of such things. Here's an example of how I ended up rigging my menu for my first time:

```
function love.load()
    currentScreen = 'menu'
end

function love.update(dt)
    if currentScreen == 'menu' then
        menuUpdate(dt)
    else
        gameUpdate(dt)
    end
end

function love.draw()
    if currentScreen == 'menu' then
        menuDraw(dt)
    else
        gameDraw(dt)
    end
end

function menuUpdate(dt)
    if love.mouse.isDown(1) then
        local x, y = love.mouse.getX(), love.mouse.getY()
        --check to see if the mouse is within the option box. If it is, set currentScreen to 'game'
    end
end

--all the other stuff(gameUpdate,gameDraw,menuDraw)

```
> 3 votes

---
Tags: lua, love2d, menu
---


# Question
Title: Why do I only receive the first message I send with SDLNet?
I am sending two messages from server.exe like this:

```
sprintf( buffer,"%d %s",1,data1);
SDLNet_TCP_Send(clientSocket, buffer, strlen(buffer)+1); // first message

sprintf( buffer,"%d %s",2,data2);
SDLNet_TCP_Send(clientSocket, buffer, strlen(buffer)+1); // second message

```

and I am reading messages from client.exe like this:

```
if(SDLNet_CheckSockets(socketSet, 0)>0)
{
    if(SDLNet_SocketReady(clientSocket)>0)
    {
        if(SDLNet_TCP_Recv(clientSocket, buffer, 5000)>0)
        {
           //there i take only first message
        }
    }
}

```

Why am I not receiving all sent messages in the client?

# Answer
Your client code is executed only once. I think you want `while` loop at the inner most `if`-statement instead, so something like:

```
if (SDLNet_CheckSockets(socketSet, 0)>0)
{
    if (SDLNet_SocketReady(clientSocket)>0)
    {
        while (SDLNet_TCP_Recv(clientSocket, buffer, 5000)>0)
        {
        }
    }
}

```
> 1 votes

---
Tags: c++, sdl
---


title: How to avoid using static variables

text:
# Question
Title: How to avoid using static variables
When developing with libGDX, you can often read, that your should not use static variables if you plan to eventually release your game on android later.

But while trying to follow that rule, I often ran into problems where I need to use an object only once and keep it accessible from everywhere at the same time.

For example, Im developing on a game which uses an ECS-Approach where different Systems need to use the EventManager-Object to communicate with each other. By default, I would make EventManager static so I can call it from multiple Systems like that `EventManager.register(EventType.TYPE_01, this)` and `EventManager.callEvent(EventType)`.

How can I avoid using static variables? Is there a best practice design pattern for something like that?

# Answer
First off, you might not be able to completely avoid using static variables. You can limit their use, but in some cases they are necessary.

One way to isolate & restrict them is to consider the singleton pattern \- it restricts the instantiation to one object & is useful when exactly one object is needed across the system (which is basically what global data does).

According to this SO post, it's what the Google Android team recommended in 2014.

That being said, singletons are controversial, largely for all the same reasons as global data. They make unit testing harder, hide dependencies & allow undisciplined programmers to bypass the black box programming model favored by object oriented paradigms.

Use your singletons wisely:

* Will every application use the object / data class **exactly** the same way?
* Will every application ever need **only** one instance?
* Should the clients of the object / data be unaware of the application they are part of?

Ideally, the singleton should only be used if all three of the above conditions are met. Otherwise, it is probably being used as an antipattern.

For use in a game development context, I strongly recommend reading about singletons in Game Programming Patterns. It covers some options such as the Service Locator pattern & piggybacking on existing global data. Depending on your specific situation, they might be better choices.

Again, singletons won't completely eliminate the need to use static variables - they merely provide a design pattern for using them in a disciplined manner.
> 2 votes

# Answer
If you use dependency injection wisely, you will never need to use global variables of any sort.

For communication, for example, you can inject in each system by constructor a mediator that will let the systems communicate between each other.

Let's put it in another way, let's assume that your EventManager is not a static class/singleton, but an instance that you created in your application composition root, that you can pass by constructor in your systems (your systems should also be created in the composition root).

If you create just one instance of the EventManager, there isn't much difference with what you have done. The problem about global variables is the lack of scope, which leads to spaghetti code. This means that you should give a specific responsibility to each EventManager you want to create and inject them only in specific systems. A simple example, just to clarify what I am saying, is that you can have a GUIEventManager that you can inject only in your systems that deals with GUI.

All that said, there are different approaches to solve communication, although all of them rely on injection. For example in Svelto.ECS I use the concept of "sequencer", which is a way to declare that a list of systems is part of a specific communication flow and let each single system to communicate to the next one in the flow.

Communication can happens also through data change. ECS is very prone to this kind of communication, as it can happen through the entity components. Usually it happens through polling, but polling can be awkward. In Svelto.ECS I created a sort of data binding system to communicate through data pushing instead of polling.
> 2 votes

---
Tags: java, libgdx, architecture, design-patterns, ashley
---


# Question
Title: How can I have more values in array on X axis than Y axis in my tilemap?
Following my old question Array of map data renders the map the opposite way after I got the answer to it and fixed my problem, I got another problem that occurs. If my `mapArray[]` is bigger on X axis than Y axis, I get

> script.js:113 Uncaught TypeError: Cannot read property '0' of undefined

So if my array looks like this, for example:

```
[2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],
[2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],
[2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],
[2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],

```

I get an error. If I change it to this:

```
[2, 2, 2, 2, 2, 2,],
[2, 2, 2, 2, 2, 2,],
[2, 2, 2, 2, 2, 2,],
[2, 2, 2, 2, 2, 2,],
[2, 2, 2, 2, 2, 2,],
[2, 2, 2, 2, 2, 2,],
[2, 2, 2, 2, 2, 2,],
[2, 2, 2, 2, 2, 2,],
[2, 2, 2, 2, 2, 2,],

```

(more values vertically) it works fine. I know that it has to do with my loop condition:

```
for (let i = 0; i < mapArray.length; i++) {
    for (let j = 0; j < mapArray[i].length; j++) {

```

`j < mapArray[i].length` this is not true if `j` is bigger than `i` length. Makes sense. But if I change the comparison `<` value to `>` I don't get drawn on the canvas anything but the white bg only.

My question: How can I have a big mapArray horizontally so that I could scroll it and have big game world without making it huge on the `y` axis as well?

Code:

```
var mapArray = [
  [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],
  [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],
  [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],
  [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0],
  [0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0],
  [0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
  [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
];

function render(viewport) {
  context.save();
  if(Math.floor(boatPosX / 36) < 10) {
    context.translate(view.x, view.y);
  }

  requestAnimationFrame(render);
  var oldPosX = boatPosX;
  var oldPosY = boatPosY;

  for (let i = 0; i < mapArray.length; i++) {
    for (let j = 0; j < mapArray[i].length; j++) {

      if (mapArray[j][i] == 0) {
        this.sprite.draw(
          background,
          190,
          230,
          26,
          26,
          i * this.sprite.width,
          j * this.sprite.height,
          this.sprite.width,
          this.sprite.height
        );
      }
      if (mapArray[j][i] == 1) {
        this.sprite.draw(
          background,
          30,
          30,
          26,
          26,
          i * this.sprite.width,
          j * this.sprite.height,
          this.sprite.width,
          this.sprite.height
        );

      }
      if (mapArray[j][i] == 2) {
        this.sprite.draw(
          background,
          200,
          20,
          26,
          26,
          i * this.sprite.width,
          j * this.sprite.height,
          this.sprite.width,
          this.sprite.height
        );
      }
    }
  }
  this.ship.drawimage(boat, boatPosX, boatPosY, 50, 50);

  if(isPositionWall(boatPosX + 36, boatPosY)) {
    //boatPosX = oldPosY;
    console.log("collision");
  }
  context.restore();

};

```

I know what's causing the problem (the loop) but not sure how to fix it properly.

# Answer
Inside your for loop, you need to index `mapArray` first by `i`, and then by `j`. You are doing this correctly in the loop condition, but inside the loop you use the indices in the wrong order.

So if-statements like these:

```
if (mapArray[j][i] == 0)

```

need to be changed to

```
if (mapArray[i][j] == 0)

```
> 1 votes

---
Tags: javascript, sprites, matrix, html-canvas, spritesheet
---


# Question
Title: Getting multiple inputs in C++ simultaneously using kbhit() function
I am using Turbo C++ to make a game using the `graphics.h` library (I know it's a bit old). In this game, the player can move left, right and they can jump using *A*, *D* and *W* (just like in Super Mario).

I am using the `kbhit()` function to get inputs from user. The problem with it is that I cannot jump and move the character at the same time (so it moves in a parabolic trajectory). How can I take multiple inputs so that, for example, if I press *W* **and** *D*, character will jump towards right?

The code is given below:

```
if(kbhit())
{
    ch=getch();

    if(ch=='e'){break;}   //exit

    if(ch=='d')           //move right
    {
    ax=1;
    if(vx<vellim){vx=vx+ax*dt;}
    dx=vx*dt;
    x+=dx;
    s_mario(x,y); //This function draws the character at the appropriate place

    }

    if(ch=='a')             //move left
    {
    ax=-1;
    if(vx>-vellim){vx=vx+ax*dt;}
    dx=vx*dt;
    x+=dx;
    s_mario(x,y);
    }

    if(ch=='w'&&jumpkey==0)   //jump
    {
    vy=60;
    jumpkey=1;
    }

}

if(jumpkey==1)
{
vy=vy-g;
dy=vy*dt;
y-=dy*0.1;
if(y>400){y=399;vy=0;jumpkey=0;}
s_mario(x,y);

}

if(!kbhit())
{       vx*=c;
    dx=vx*dt;
    x+=dx;
    s_mario(x,y);
    delay(5);
}

```

# Answer
Console I/O wasn't designed for this kind of thing. You'll need a different means of handling input.

Google suggests that the `GetAsyncKeyState()` is what you're looking for:

Documentation: https://msdn.microsoft.com/en-us/library/windows/desktop/ms646293(v=vs.85).aspx

Example usage: http://www.cplusplus.com/forum/beginner/135868/#msg725863
> 1 votes

---
Tags: c++, game-mechanics, game-loop
---


title: Combining meshes up to certain sizes

text:
# Question
Title: Combining meshes up to certain sizes
I have the following spritesheet for types of terrain, with a transparent background.

To draw it on my map, I thought of doing one mesh per type, and then combine them. This is the code.

This gave me at first quite good results.

But then I started trying maps of bigger dimensions, and after a certain point (I think it was 49x49), I got suddenly different results.

As you can see, at this point only seems to render 2 kinds of terrain, and the others have disappeared completely. Size is the only factor that was changed. Materials, Sprites, settings... everything else is completely the same.

Why could this be happening?

# Answer
The problem is that there is a limit of vertices for a mesh when using **16bit**. The limit is **65535 vertices**.

The only solution here is rendering as smaller meshes, or turning on the **32bit** meshes, which gives you a limit of **4 billion**, at the cost of more memory.

More info here
> 1 votes

---
Tags: unity, mesh
---


# Question
Title: How to get a reflex edge on a non-convex mesh
I am trying to implement a convex decomposition and I need to find the convex vertex on a mesh. Is there a algorithm that I can use to find the convex vertex on a mesh.

# Answer
Here is some code that I used.

```
private static boolean isReflex(Vector3f p0, Vector3f p, Vector3f p1) {
    // TODO Auto-generated method stub
    return right(p1,p0,p);
}

private static boolean right(Vector3f a, Vector3f b, Vector3f p) {
    return Segment.getLocation(p,a,b) < 0;
}

public static float getLocation(Vector3f point, Vector3f linePoint1, Vector3f linePoint2) {
    Vector3f l = Vector3f.add(linePoint2, linePoint1, null);
    Vector3f p = Vector3f.sub(point, linePoint1, null);

    return Vector3f.angle(l, p);
}

```
> 2 votes

---
Tags: 2d, algorithm, geometry, mesh, vertex
---


# Question
Title: How do I split my screen to include a JFrame and a lwjgl screen
I a making a game and I'm going to make a little side GUI to create game items.

How can I have a window both include a Canvas element and an lwjgl window.

# Answer
You can use the AWTGLCanvas to host your LWJGL context inside your GUI.

For LWJGL3, There's this demo of putting a LWJGL context in a canvas in the source: https://github.com/LWJGL/lwjgl3/blob/master/modules/samples/src/test/java/org/lwjgl/demo/system/jawt/JAWTDemo.java
> 0 votes

---
Tags: java, lwjgl, swing, jframe
---


# Question
Title: How to scale-to-fit OGL viewport to GLFW window?
Say my window is 1280x720. I want to render my stuff to lower resolution and then stretch it to window. I've tried this:

```
glViewport(0, 0, 1280 / 2, 720 / 2);

```

When I call glViewport and pass lesser width and height than window, I get all my OpenGL rendering in left bottom 1/4 of window. I need to scale it (linear filtering preferably) back to window size so I would get a pixelated effect.

I wonder if there is such possibility within glad/glfw API.

# Answer
One way to achieve what you want is to render into a texture-backed FBO that is half the width and height of the window, then draw that texture into the window at the full size.

You say:

> I need to scale it (linear filtering preferably) back to window size so I would get a pixelated effect.

This is a contradictory statement. If you want pixelation, you probably want nearest neighbor filtering. Linear filtering will cause it to be smoothed out.
> 0 votes

---
Tags: opengl, glfw
---


# Question
Title: What is the average cost of hiring a programmer mid development to implement online features?
I guess my real question is more specific than that.

I'm working on a game by myself and it has 2 player local multiplayer implemented already (it's a pretty simple 2D arcade-platformer type game). I'd like to add online multiplayer into the mix but figure it'd be more within my time frame to hire someone who already has the know-how than to learn it myself at this time.

I have no idea what the average cost of something like this would be. I figure the programmer would have to go through the original code first to get their bearings (which would take time and some back-and-forth), figure out the best way to host the players, and then centralize the already made local code around net play. Or maybe I'm way off on this. Maybe it'd be faster to learn it myself than to acquaint someone else with the game.

Any help or insight would be appreciated.

# Answer
> 2 votes
**Professional**

In terms of a cheap programmer (one who is professional but on the low end) it's $50k a year or so; which means that they cost *roughly* $1k a week (full time.)

**On the cheap**

Were you to put up flyers at a local college or five you could likely get this done for a few packs of beer (or w/e) by finding someone interested in learning netcode or geeks out on it. Getting $100 to do some task and add it to your resume is a thing nigh guaranteed to get someone's attention.

**Other hired guns**

There are many freelancing websites where you can put up the issue you have and get bids from the community. Here's an example I found in a few seconds: https://www.freelancer.com/jobs/C-Sharp-Programming/

**A word of warning**

Just keep in mind, you get what you pay for. If you have no idea how many days it would take a professional to do it, that's because you've never done it, which means it'll be difficult for you to estimate the work required. I would definitely offer a flat amount out to people so you can't be strung along. The faster they get it done, the sooner they get paid (like in the auto world) and therefore the more motivated they are to get it done ASAP.

**Advice**

I think you should get bids from a freelancing website (or multiple!) and see what the offers are. Then you'll have a good idea what an amateur\* will do it for, and go from there.

*Note: amateur here being the literal difference between a salaried or long-term contract employee and a short-term freelancer and is not intended as derogatory.*

---
Tags: unity, multiplayer, software-engineering, online, hiring
---


# Question
Title: I'm not hearing any sound even though its picked up by audioSource?
I have two sound clips that I am feeding to an audioSource via script, it seems to be working as I can see the audio clips populating the audioSource component. But the problem is that I dont hear anything.

How ever if I remove the script and manually select the audioclip in source then I can hear both clips clearly. Why is this not working when done through script:

Here is my small script, its choosing two sounds based on the `navMeshAgent` status.

```
public class KnightAudio : MonoBehaviour {

    //private Animator anim;
    private NavMeshAgent agent;

    private AudioSource knightAudio;
    public AudioClip crying; //set this in ispector with audiofile
    public AudioClip scream; //set this in ispector with audiofile

    // Use this for initialization
    void Start () {
        knightAudio = GetComponent<AudioSource>();
        agent = GetComponent<NavMeshAgent>();
        //anim = GetComponent<Animator>();
    }

    // Update is called once per frame
    void Update () {
        if (!agent.isStopped)
        {
            knightAudio.clip = scream;
            knightAudio.Play();
        }
        else
        {
            knightAudio.clip = crying;
            knightAudio.Play();
        }

    }
}

```

Here is the audio source, as can be seen it is populating the `crying` clip in there as expected when the agent is stopped and it will change this to `scream` when agent starts moving. But in game I cannot hear any of these.

# Answer
Could be that since you're having the audio play every frame that it's constantly restarting the clip making it sound as though nothing is being played.
> 2 votes

# Answer
The reason it wasnt working was that I was playing it in update without any checks and it was trying to play every frame. Thats why I couldnt hear anything.

Here is the fixed code:

```
void Update () {
        if (!agent.isStopped)
        {
            if(knightAudio.clip != scream)
            {
                knightAudio.clip = scream;
                knightAudio.Play();
            }
            else if (knightAudio.clip == scream && !knightAudio.isPlaying)
                knightAudio.Play();

        }
        else
        {
            if (knightAudio.clip != crying)
            {
                knightAudio.clip = crying;
                knightAudio.Play();
            }
            else if (knightAudio.clip == crying && !knightAudio.isPlaying)
                knightAudio.Play();
        }
    }

```
> 0 votes

---
Tags: unity, audio, sound
---


# Question
Title: What is "simulated human operator" cutscene camera movement called?
I have some questions related to the non-smooth camera movement in *cutscenes* of quite a few games which appears to try and simulate the nervousness of a human operator holding it. This is opposed to camera shake in general gameplay when some event takes place, i.e. explosions, though they do also occur in the cutscenes I'm talking about.

Examples of this effect are in many games, but the best example I have seen of what I am trying to describe is the opening cutscene (and many cutscenes) of Metal Gear Solid V: Ground Zeroes. Be sure to choose 60 FPS to make the effect clearer.

**Is there a name for this "simulated human operator" effect, and do you know how this may have been achieved?**

My guess would be that the camera is being offset in both axes by some kind of random deviation function, which is always slightly elastically moving towards the origin to stop it wandering off wildly. Perhaps Brownian motion?

# Answer
Quoting the Wikipedia article on "Shaky Camera":

> Handheld camera, shaky cam, queasy cam, queasicam, run-and-gun or free camera is a cinematographic technique where stable-image techniques are purposely dispensed with.
>
> The camera is held in the hand, or given the appearance of being hand-held, and in many cases shots are limited to what one photographer could have accomplished with one camera.
>
> Shaky cam is often employed to give a film sequence an ad hoc, electronic news-gathering, or documentary film feel. It suggests unprepared, unrehearsed filming of reality, and can provide a sense of dynamics, immersion, instability or nervousness. The technique can be used to give a pseudo-documentary or cinéma vérité appearance to a film.

You can accomplish this in effectively the same way as camera shake in response to a catastrophic event, just at a lower amplitude. You track a nominal camera position and orientation, then displace the camera's actual position and orientation used for rendering using a pseudo-random function.

Generally this looks best if you use a continuous function, like a Perlin noise or even sine waves to emulate periodic vibration. This keeps the camera from jumping around too distractingly, and lets you play with a range of frequencies from slow sway at a medium amplitude to a rapid tremble at low amplitude. Mixing samples at multiple periods and amplitudes can give the motion a more complex, less mechanical-looking character.

You can also play with how you distribute the shake between translational & rotational offsets:

* translational shake affects the foreground more strongly than the background, with up/down/left/right shake being the most noticeable, and shake forward/back usually looking more subtle.
* rotational shake affects the whole image together, so it can reduce the appearance of the foreground vibrating but also has more risk of disorienting the viewer. Keep the amplitudes lower, especially for roll offsets, or you might make players seasick.
> 18 votes

# Answer
The term is "shakycam" and there are many ways of doing it. Googling for shaky cam tutorial gives many After Effects tutorials for simulating the effect in video editing software; the same principles apply to real time applications.

The basic idea is to simulate hand-held, non-stabilized camera. This is often applied after the fact to a perfectly stabilized footage in video editing for "authenticity" or to hide video editing tricks.

So the camera, as well as its target move randomly using low-frequency noise, meaning it doesn't jump in random directions frame by frame, but you could, for instance, interpolate random offsets every N frames, where N may also vary from one shake to the next.
> 3 votes

# Answer
I disagree with the idea that you should be using Perlin noise only. I think the key to make it look good (and I don't think it looks good in the opening scene you linked), is to use an underdamped system. The system (aka the camera operator) wants to aim at a certain position, but he overshoots while moving to that angle. Combine this with random pushes on the camera (like random muscle contractions and tremble), but let the underdamped system work its magic. Combine this with applying some Perlin noise to the target, to prevent it from looking like a too-perfect aim.

So, a system like the one with the damping ratio set to 0.4 to 0.7: *(Image from Wikipedia on the linked page)*
> 3 votes

---
Tags: camera, terminology, cutscene
---


# Question
Title: Why does Unity's MeshCollider only use SharedMesh?
For components like MeshRenderer, Unity uses two references to mesh through script--mesh, and sharedMesh. My understanding as of yet that setting a "sharedMesh" will affect every GameObject that uses that component, whereas "mesh" alone will only affect a particular instance of that component. Same goes for "material" and "sharedMaterial".

However, for MeshCollider, the only thing available is "sharedMesh". The field "mesh" does not exist. I can work with this, but from a policy standpoint it seems very strange to me. Is there a reason that MeshCollider is treated differently?

I may be overlooking something obvious, but a Google search didn't help me.

# Answer
The "mesh" property of a MeshFilter, like the "material" property of a renderer, is a convenience for making per-object modifications.

When you read from this property, it checks if it's already duplicated a unique instance of this mesh (or material) and, if not, it copies the current mesh (or material) it's using and hands you that copy, which is now unique to the object you're working with. This means a simple/naive script won't accidentally modify a shared asset used by multiple instances, or muck with source asset files in your project folder.

When you don't want this auto-copy behaviour, you access the sharedMesh (or sharedMaterial) to explicitly acknowledge in the code that the asset might be in use in other places, and accepting responsibility to deal with that yourself.

It's likely that for the MeshCollider case, the developers of the API didn't see making per-object variations of shared physics assets as such a common use case, compared to making purely visual changes to meshes and materials, so they didn't build-in an automatic copy. You can implement this behaviour yourself if you need it by using the Instantiate() method on the sharedMesh.
> 2 votes

# Answer
Ultimately it's just the name of the variable indicating its intention is to re-use the mesh that's part of the game object/visual representation:

> The Mesh Collider builds its collision representation from the Mesh attached to the GameObject, ... Optimization tip: If a Mesh is used only by a Mesh Collider, you can disable Normals in Import Settings, because the physics system doesn’t need them.

Setting this value won't affect every GameObject using the component.

The implication is that changing the mesh of the GameObject would affect the collider (though there appears to be some caveats to that: it won't necessarily take effect straight away).
> 1 votes

---
Tags: unity, mesh, meshcollider
---


title: not all code paths return a value

text:
# Question
Title: not all code paths return a value
I created a method in my spawn manager trying to get the maximum and minimum with of spawn to be within the screen but i keep on getting the error

> error CS0161: \`SpawnManager.GetRandomPointOnScreen()': not all code paths return a value

does anyone have an idea as to what might be causing this error

```
 Vector3 GetRandomPointOnScreen()
        {

            Camera camera = Camera.main;
            float halfHeight = camera.orthographicSize;
            float halfWidth = camera.aspect * halfHeight;

            float horizontalMin = -halfWidth;
            float horizontalMax =  halfWidth;

        }

```

# Answer
> 5 votes
Your function declaration says it's going to return a `Vector3`, but you're not returning anything.

Add `return Vector3(0, 0, 0);` or the vector you actually want returned to the end and it will work.

# Answer
> 4 votes
When you start a method declaration with `Vector3 SomeMethodName()` you're making a promise to the compiler: "I swear, by the time you get to the end of this method, I will `return` an instance of the `Vector3` data type!

When you don't `return` as promised, the compiler throws an error.

So, let's ensure we `return` a value:

```
Vector3 GetRandomPointOnScreen() {
    Camera camera = Camera.main;
    float halfHeight = camera.orthographicSize;
    float halfWidth = camera.aspect * halfHeight;
    float horizontalMin = -halfWidth;
    float horizontalMax = halfWidth;

    Vector3 randomOffset = new Vector3 (
              Random.Range(horizontalMin, horizontalMax),
              Random.Range (verticalMin, verticalMax),
              0);

    return randomOffset;
}

```

Then we can call this from inside your Spawn method from your other question, like so...

```
void Spawn() {
    for (int i = 0; i < maxBalloons; i++) {
         Vector3 randomPosition = originPosition + GetRandomPointOnScreen();
         Instantiate(balloon, randomPosition, Quaternion.identity);
    }
}

```

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


title: How do I handle Game Screens in LibGDX?

text:
# Question
Title: How do I handle Game Screens in LibGDX?
In my game the main screen is the playscreen. But because I want to draw the menu and the gameover screen on top of the playscreen, I don't create separate screens for them. But if I want to replay, I must restart the playscreen. This happens very often, so should I load all the resources and dispose them when the game is closed. Because otherwise when I restart the playscreen, I have to load resources again, which will slow down the performance. Please, give me some advice.

# Answer
> 0 votes
If you have enough resources to fill up the lowest device you are targeting (even half way) then you need to manage your assets. If you have just a couple of MB you will be fine with leaving that in memory and only dispose when you exit your game.

But you don't need to dispose your assets between screens. If you use `Assetmanager` you can finely control what to dispose and what to keep even between screens.

# Answer
> 0 votes
Here is how I handle the assets without reloading them for each screens. You should load your asset in your main game class like this

```
public class MyGame extends Game {
    private AssetManager assetManager;

    @Override public void create() {
        this.assetManager = new AssetManager();

        this.assetManager.load("level.tmx", TiledMap.class);
        this.assetManager.load(...)
        this.assetManager.load(...)

        // force the asset manager to finish loading
        this.assetManager.finishLoading()

        // inject the asset manager to your screen
        this.setScreen(new LevelScreen(this.assetManager));
    }

    @Override
    public void dispose() {
        this.assetManager.dispose();
    }
}

```

This way if I need to reload the `LevelScreen` I just need to re inject the assetManager to the new screen without reloading any ressources.

To retrieve a resource from the asset manager, just use

```
// this retrieve the tiled map from the asset manager without reloading it
TiledMap levelMap = assetManager.get("level.tmx");

```

# Answer
> 0 votes
If you're gonna reuse the same assets there is no point in disposing them before every restart. Just reset the states of whatever you have and leave the assets alone.

You should manage your assets if you have many of them that can eat up memory, otherwise you can get away with loading everything upfront (although i believe is always good practice to manage your assets).

If you have a few assets and you will use them in every state of the game, then just load them up all together and forget about it.

---
Tags: libgdx, graphics-programming, game-state, screen-management
---


title: Implementing Screen Shake

text:
# Question
Title: Implementing Screen Shake
I'm looking to implement screen shake in a 2D top down game. From an earlier Q on this exchange, I learned that noise values could be a good candidate, so I intent to try that.

But I wonder: is a screen shake more about rotating the 2D topdown camera, or about jittering the position of that camera?

Or does it really require both?

Additionally, I would like to know if a good screenshake would require motion blur? Something like rendering your world in 4 small micro-steps for each 60fps frame, maybe? Or can you shake the camera at 60fps with normal rendering and it still looks good?

The quality I am after is something like shown in this video. It's kinda hard to judge, but it seems that video does translational jitter only?

# Answer
> 3 votes
First off all, try it, see the results, and work from there. With that said, what you want is jittering, but let's be specific...

Keeping in mind that we are talking of a 2D game, the main effect is translation, you want to mainly add noise to the position of the camera.

Realistically, it is both translation and rotation, however, but the rotational effect is much harder to notice, and in particular for a 2D game, it is negligible.

---

Remember that we are simulating the camera standing on something which (or being hold by somebody who) shakes as a result of a shockwave or similar. If you imagine the camera being placed on tripod on the ground, and being hit by the shockwave, it will totter.

The camera-tripod system can rotate, with a rotation center near the ground, and a small rotation on that center, when converted to camera coordinates, will add a large translation (and about the same rotation).

Since in 2D, there is no Yaw and Pitch. Only the translation elements of these movement remains. About Roll, it will add to those translation (mainly to the horizontal one) and there will be a relatively less noticeble rotation left.

---

So, in order or magnitud:

* Horizontal movement
* Vertical movment
* Rotation

---

And who said the camera was on tripod anyway? Also, who said the world is 2D? You can always take your artistic licence on how the camera shakes. Just test it, and tweak it, and keep tweaking until you are happy with it.

---

## Addendums

**On the kind of noise**: We can also think of the system as a pendulum or a spring, and as such we want it to: 1) reduce magnitud over time, and 2) oscillate back and forth. Thus, using noise based on sine waves (such as Perlin noise) is a good idea.

**On 3D**: Translation is always more notorius than rotation. And in 3D translation in 3D can feel excessive. Thus, avoid using translation in camera shake for 3D games. Remember that we are using translation in 2D as stand-in for the missing rotations. Futhermore, moving the camera position can lead to clipping through walls.

**On Accesibility:** For some people, video games can make them feel nausea. One of the things that trigger this is camera shake. Thus, have the option to turn down and disable camera shake in your game.

**On Motion Blur**:

> Additionally, I would like to know if a good screenshake would require motion blur? Something like rendering your world in 4 small micro-steps for each 60fps frame, maybe?

You can have motion blur. It is not required for a good camera shake. However, it can improve the general visual quality of the game.

In fact, you may also want a way to turn it off independently of the camera shake. In particular for players with older hardware who may have a performance hit because of motion blur.

Thus, I would consider motion blur orthogonal to the camera shake effect.

---
Tags: camera, special-effects
---


title: TypeScript Space Shooter movement

text:
# Question
Title: TypeScript Space Shooter movement
I'm trying to create a simple space shooter game using typescript and i've got kind of stuck at checking the movement.The thing is that if i only press one key it works fine but if i press 2 keys at the same time it won't check for collisions with margins.Do i have to check for every case if i press multiple buttons or there's another way to do it? Here's the code:

```
update(canvas) {
        if (Game.keysPressed[KeyBindings.LEFT]) {
            this.xVel = -1;
            if (this.x <= 20) {
                this.xVel = 0
            }
        } else if (Game.keysPressed[KeyBindings.RIGHT]) {
            this.xVel = 1;
            if (this.x + this.width >= canvas.width - 20) {
                this.xVel = 0;
            }
        } else if (Game.keysPressed[KeyBindings.UP]) {
            this.yVel = -1;
            if (this.y + this.height <= 500) {
                this.yVel = 0;
            }

        } else if (Game.keysPressed[KeyBindings.DOWN]) {
            this.yVel = 1;
            if (this.y + this.height >= 880) {
                this.yVel = 0;
            }
        }

        else {
            this.xVel = 0;
            this.yVel = 0;
        }

        this.x += this.xVel * this.speed;
        this.y += this.yVel * this.speed;

    }

```

Thanks for helping!

# Answer
> 1 votes
I recommend trying to put the collision check outside of the if-statements of movements, because none of the collisions would have trouble been placed together.
If you put it outside them, they'll keep checking all boundaries at once. which seems to be better in your case.

Explained in code:

```
update(canvas) {
    //movement
    if (Game.keysPressed[KeyBindings.LEFT]) {
        this.xVel = -1;
    }
    else if (Game.keysPressed[KeyBindings.RIGHT]) {
        this.xVel = 1;
    }
    else {
        this.xVel = 0;
    }
    if (Game.keysPressed[KeyBindings.UP]) {
        this.yVel = -1;
    }
    else if (Game.keysPressed[KeyBindings.DOWN]) {
        this.yVel = 1;
    }
    else {
        this.yVel = 0;
    }

    //collision
    if (this.x <= 20) {
        this.xVel = 0
    }
    if (this.x + this.width >= canvas.width - 20) {
        this.xVel = 0;
    }
    if (this.y + this.height <= 500) {
        this.yVel = 0;
    }
    if (this.y + this.height >= 880) {
        this.yVel = 0;
    }

    this.x += this.xVel * this.speed;
    this.y += this.yVel * this.speed;
}

```

I've also changed your movement if-else-statements, so the else-statement will trigger correctly.

# Answer
> 1 votes
Not 100% sure about it but you don't have to put else everywhere, juste make a condition so that you can't press left if right is pressed, you can't press up if down is pressed (and vice versa)

This way if they press both the player won't move, and if only two on different axes are pressed the player will move diagonally

Also something else you can do is just say that if the player is on the margin the key press won't be accepted

Well, might be a bad solution but I use a lot of "&&" in my conditions, that's a huge gain of space, but not always readability

# Answer
> 0 votes
Here's what I've modified and now it works a little bit better but still has some moments when the ship goes out of the screen :(

```
update(canvas) {

        if (Game.keysPressed[KeyBindings.LEFT]) {
                this.xVel = -1;
                if (this.x <= 20) {
                    this.xVel = 0
                }
            }

            if (Game.keysPressed[KeyBindings.RIGHT]) {
                this.xVel = 1;
                if (this.x + this.width >= canvas.width - 20) {
                    this.xVel = 0;
                }
            }

            if (Game.keysPressed[KeyBindings.UP]) {
                this.yVel = -1;
                if (this.y + this.height <= 500) {
                    this.yVel = 0;
                }

            }

            if (Game.keysPressed[KeyBindings.DOWN]) {
                this.yVel = 1;
                if (this.y + this.height >= 880) {
                    this.yVel = 0;
                }
            }
            if (!(Game.keysPressed[KeyBindings.DOWN] || Game.keysPressed[KeyBindings.UP] || Game.keysPressed[KeyBindings.LEFT] || Game.keysPressed[KeyBindings.RIGHT])) {
                this.xVel = 0;
                this.yVel = 0;
            }

            this.x += this.xVel * this.speed;
            this.y += this.yVel * this.speed;
        }
    }

```

---
Tags: javascript, movement, shooter
---


title: Resolving Circle-Circle collision

text:
# Question
Title: Resolving Circle-Circle collision
If you have a stationary circle with radius x, and a moving circle with radius y, when a collision is detected, how can you resolve the collision, such that the moving circle stop?

I.e. What would be the 'resolved' position of the moving circle?

# Answer
> 3 votes
Let's say the moving circle \\$A\\$ has radius \\$r\_A\\$, starts at position \\$ \vec p\_A\\$, and travels with velocity \\$ \vec v \\$

And let's say the stationary circle \\$ B \\$ has radius \\$ r\_B \\$ and sits at \\$ \vec p\_B \\$

We can simplify our work a little by defining:

$$\begin{align} \vec p &= \vec p\_A - \vec p\_B\\ R &= r\_A + r\_B \end{align}$$

Now we've reduced the problem to finding where the ray from \\$\vec p\\$ in direction \\$\vec v\\$ strikes a circle at the origin with radius \\$R\\$, ie...

$$ \lVert \vec p + t \cdot \vec v \rVert = R $$

at some time in seconds \\$t\\$ after the start of the motion. Now we solve for \\$t\\$:

$$\begin{align} \lVert \vec p + t \cdot \vec v \rVert^2 &= R^2\\ \left(\vec p + t \cdot \vec v\right) \cdot \left(\vec p + t \cdot \vec v\right) &= R^2\\ \left(\vec p \cdot \vec p\right) + 2t\left(\vec p \cdot \vec v\right) + t^2\left(\vec v \cdot \vec v\right) &= R^2 \end{align}$$

which we can solve with the quadratic formula:

$$\begin{align} t &= \frac {-2\left(\vec p \cdot \vec v \right) \pm \sqrt{4 \left(\vec p \cdot \vec v \right)^2- 4 \left(\vec v \cdot \vec v\right)\left(\vec p \cdot \vec p - R^2\right)} }{2\left(\vec v \cdot \vec v\right)}\\ t &= \frac {-\left(\vec p \cdot \vec v \right) \pm \sqrt{\left(\vec p \cdot \vec v \right)^2- \left(\vec v \cdot \vec v\right)\left(\vec p \cdot \vec p - R^2\right)} }{\left(\vec v \cdot \vec v\right)} \end{align}$$

* If the expression inside the radical is negative, then the circles miss each other.
* If it's zero, then they have a glancing point contact at the sole solution for \\$t\\$.
* If it's positive, then there are two possible solutions (one collision on the way in, one on the way out), so choose the smallest positive value for \\$t\\$.

(If all solutions are negative then the collision happened "in the past," and circle \\$A\\$ is currently moving away from circle \\$B\\$)

With a positive value for \\$t\\$, you can form:

$$\vec p\_\text{A contact} = \vec p\_A + t \cdot \vec v$$

the position of circle \\$A\\$ the moment it enters contact with circle \\$B\\$.

# Answer
> 0 votes
function getColl(x1, y1, r1, x2, y2, r2)

local distance = math.sqrt(math.pow(x2 - x1,2) + math.pow(y2 - y1,2))

if distance \< r1 + r2 then return true else return false end

end

This is the function to check collision between 2 circles, the r1 and r2 are the radius of the circle

For resolving, it's going to be a bit more complex, and there are multiple ways to do it, I recommend you to learn basic rectangle with rectangle collision resolution first before circle.

if your circle can only move in 8 directions, you can make a variable to predict the next movement, if for example the next movement to the left is colliding with another circle, then you can resist that movement by making the x velocity to zero.

If you circles move in more than 8 directions, you can store the positions in an array, if the circle collide, change the circle position to the previous position.

If you also don't want that you can use the pure math mentioned above

---
Tags: collision-detection, physics, collision-resolution
---


# Question
Title: How to use Facebook Web Hosting for my Unity Game for both WebGL and GameRoom
As can be seen from the Facebook's official Docs

It says that

> To have both a Gameroom and a Facebook Web Game, you should leave your Facebook Web Games URL (https) unchanged. For example, https://friendsmashsample.herokuapp.com/

and also

> Otherwise, if you only have a Gameroom title, you should enter https://localhost/ as shown here:

I wanted to know if there is a way to get both of them working instead of hosting WebGL game on my server and putting it's URL?

I have even tried to enable the Simple Web Hosting but the toggle just reverts Back to off upon saving.

# Answer
> 0 votes
It's now fixed. Seems like the recent issue with Facebook various API deprecation and changes of terms and condition caused this.

---
Tags: unity, webgl, facebook, unity-webgl
---


# Question
Title: How can I solve the problem of attacking being disadvantageous in TBS due to entering the range of enemy attacks?
I noticed this thing in *Age of Wonders I* some time ago, but I can imagine this problem popping up in any other game system where units with equal attack range spend their move points on either moving in range or attacking.

In this game, both sides start far away from each other, not being able to hit each other. They have to spend a couple of turns advancing. At some moment it happens that one player moves their units closer to the enemy units to be able to attack them, but also ends up in the opponent's attacks' range, getting damaged before being able to attack themself. Not very good!

Sometimes it is acceptable and intended, like if I attack an army of cavalry with an army of archers, my opponent is essentially allowed a free attack because cavalry can usually move further than archer's shooting range. But if both armies have equal ranges, the game can turn into a stalemate, because nobody wants to move forward and be hit first. Getting the first strike is so important that it overshadows a strong unit stats advantage.

Even the AI knows to abuse it, waiting for an infinite amount of time before the player attacks. While it is easy to counter this *as a player against AI* by flanking the enemy ranks in such a way that only one of their units gets in range of many my units and the enemy is forced to advance, a real player could just back off with this unit and wait for me to fully advance, getting hit severely and likely even losing my upper hand if I had one.

**Thus, it feels like an example of very bad design. How do I design TBS combat in a similar system so that it is not completely disadvantageous to move in and attack unless you have a range advantage?**

The only possible solution that I see is making the ranges more different, so it is less probable to see units with similar attack ranges, but even in that case such a situation r still not impossible. I am sure that some more elegant solutions exist. So, what are they?

# Answer
> 5 votes
First move advantage, or more accurately first attack advantage, can be quite game-breaking. Extra Credits made a video about it, by the way.

A few solutions I have seen in turn-based strategy games over the years to make it less important.

* **Symmetric combat mechanics** (Battle Isle series and its spinoffs, Civilization) When a unit attacks, both units deal damage and take damage. So the only advantage of being the first to attack is that you can pick your battles... unless you find a victim which is unable to retaliate for some reason, for example because it has less range than your unit.
* **Counter-Attack** (Seen in many games, but often only as some kind of special ability granted to a few unit types) A weaker form of symmetric combat. When a unit is attacked and survives, it gets to attack back immediately (if able).
* **Simultaneous turns** (A rare solution I only remember seeing once. Unfortunately I forgot the name of the game where I saw that). Both sides make their moves simultaneously and they then get resolved simultaneously. It's a mechanic which is a bit unintuitive for the player and has a lot of edge-cases to handle, but it can also have some very interesting depths and allows to play some interesting mind-games with the opponent.
* **Action points** (classic X-Com, Jagged Alliance). Instead of allowing attacking *or* moving, give each unit a number of action points which can be spent on attacking, moving or a bit of both. The one who moves into range will have a first-attack advantage, but won't attack with full action points. The defender (should it survive) will then already be in range and can then retaliate with their full action points. So the stronger second attack partially compensates the first-move advantage.
* **Embrace it**. (the majority of turn-based strategy games) Use the classic move-then-attack mechanic. Fully accept that there is first-attack advantage and build your game around finding the strategy which gets you the first move as often as possible. You might be able to do this with move-or-attack if you add some mechanics which discourage turtling and allow to bait the enemy into traps.

# Answer
> 1 votes
40k attempted to solve this with Assault weapons, Rapid Fire weapons, and some quick fire rule I forget the name of.

In "assault weapons" case, you get to shoot even though you moved; and you could even assault on top of it (charge.) In Rapid Fire's case you could shoot even though you moved. And in the case of other weapons (heavy and their ilk) you could wing a shot out there that only had about a 33% or 25% of your normal chance to hit.

This did, over time, make the game more mobile.

---

Another option akin to this is a kind of "assault move" like throwing your javelins, having a bow show ready at a reduced speed, etc, and combining it with the move action (and maybe even for free so you can't even *not* do it.)

---

I think you may also consider things like Smoke Bombs, temporary shielding, a movement-based "Cover bonus" (harder to hit moving targets), and other forms of defense that the advancing army can use.

---

Finally, I think whatever you do, you should consider seeing if one side wins a few percentage points more often and then adjust the rules slightly until you get something within the 52% range or so. Note: even at 52%, that means that the player with advantage gets a "free win" every 12 wins or so; or in other words is a relative 8+%. Quite a difference!

# Answer
> 1 votes
One issue I see with your problem analysis is that: Range is a huge advantage.

Outranging opponents in combat is one of the most powerful tools in warfare. In a vacuum there's no reason to actually risk yourself in an attack if defending is just stronger (which it will almost always be in any system).

Even in the case were both armies are of equal range, the defender still has an advantage since the enemy has to walk into their range first, and that's natural.

So I think that the problem you're having isn't actually a problem. It's the natural consequence.

There are a couple ways I normally see this dull gameplay circumvented

* Give the players an objective. Control points on exposed locations as a victory condition, extra resources that expire over time, anything that would lead a person to decide "That thing is worth the risk". XCom: Enemy Within did this well with it's MELD. A valuable resource that expires quickly, forcing you to rush into danger to obtain it.
* Asymmetric objectives. Have one player be on the defense, and another on the attack. The defensive player wins if they hold out for X amount of turns. This forces the attacker to move into the vulnerable offensive position. It's not a TBS but Overwatch's Payload maps are great examples of this.
* Have something players need to protect. That opens the option for multi pronged attacks. If all your snipers are tied up keeping my melee forces away from the front, a small group troops can cause havoc in the economy/base/back lines.
* Provide movement options. This is probably my favorite one. If getting into range is too detrimental add ways to get into range favorably. Dropships that can ferry troops in and drop them right on the archers. Short range teleportation to cross the kill zone. Underground tunnels to get behind firing lines. Siege engines to tank the shots and slowly escort the guys in. The possibilities are endless. If players have effective offensive movement options the likelihood of stalemates decreases dramatically. Starcraft is a masterclass in this.

So what I'm saying is: Attacking into a defensive opponent is a *disadvantage* and that's fine. What is needed are effective motivations and tools for players not to stalemate eachother.

# Answer
> 1 votes
You're basically describing a form of Nash Equilibrium. Assuming you want to design a traditional turn based system and not use something like simultaneous turns as Philipp mentions (an underappreciated mechanic for sure), the easiest way is to make sure the other parts of your system work in tandem with the move and attack ranges in order to mitigate the problem - basically a variant of "Embrace it". I am going to assume though that at least melee units can both move and attack in one turn, if not necessarily move as far while attacking than not.

* Speed and Toughness: slow units might be heavily armoured and designed to withstand the first assault of the enemy while manoeuvrable light skirmishers will have to use their higher speed in order to move carefully and not be caught out by the enemy
* Defensive Setup: units may be able to move part of their range and then use some kind of blocking buff that ends their round but reduces damage. Units like spearmen might even be able to damage those charging into their formation. This way you can move into range, prepare for the enemy attack and give a good return. In modern settings with firearms, the equivalent would be the overwatch command.
* Clever Positioning: in your example of an archer and a cavalry army, why not send a unit of archers into range to pelt them with arrows while having the majority stand back ready to fire? The archers in the front are vulnerable to the cavalry's attack, but attacking them will put the cavalry into firing range of all your archers.
* Accepting Defeat: If you only have ten archers and they fight ten mounted knights, either you can position them in a fortification or on a cliff or your archers will just lose. Some units counter other units and some units are just more powerful in general. These things are usually balanced through pricing, i.e. resource investment.

Else, Philipp and Scott Maher both make excellent points, especially in terms of having objectives or time limits to force players into action. This is even more useful if there's no great penalty to retreat except for not having accomplished anything. The opponent is thusly forced into action, as they may need to destroy your army, conquer your fort or whatever it may be. If there is nothing to gain by fighting, simply retreat and restore the status quo - the player who wants to change said status is the one who *has* to move.

# Answer
> -1 votes
If you allow moving and shooting, your archers can in theory kite infinitly, if their movement range matches that of the cc fighters. If you compare it to real life, archers were standing and shooting, while the enemies where charging in to minimize the time getting hit. When the fighters were in combat range, the archers had no chance. So even heavily injured and decimated, your fighters should still win.

Two ideas (assuming your ranged fighters cant move and shoot):

1. Give your ranged units a minimal range. This way, your fighters could rush through the death zone and prepare and attack in the next turn or following. This would heavily favor cc fighters in an 1v1 situation, but would solve the problem.
2. Similar to blurrys suggestion of cover: If a fighter is in cc combat with an enemy, make it impossible to shoot on those fighters. Your archers are trained not to shot on own people, so they can't shoot into melee where they could hit own troops. This would do nothing in 1v1 scenarios, but with other troops, this could balance things out.

---
Tags: game-design, balance
---


# Question
Title: Bullet Physics too many rigid bodies framerate drops
I have a question regarding rigid bodies in bullet physics.

At the moment I have low-poly asteroids, which I create a convex Hull shape. Then I add a motion state and give them a linear velocity.

Collision and everything is working fine, if its a low amount of asteroids (less than 5).

But as soon as the amound of objects in the world get higher, my framerate starts to drop under 1 FPS.

I have a Intel i56600k and a AMD Fury. Could it be related to my hardware? Or is bullet limited in this regard? Or did I do something wrong in my program?

I'm writing the game in C++.

# Answer
> 2 votes
Apparently, the Debug Drawer i was using was responsible for the performance Issues.

When it is turned off, everything is working as expected.

---
Tags: c++, bullet-physics
---


# Question
Title: How do I test for collisions between two concave shapes decomposed into collections of convex polyhedra?
I am using convex decomposition with SAT (separating axis theorem) and I generate two arrays of convex pieces, How do I submit my arrays to my collision detection method which only takes two arguments.

```
public MTV testCollision(BroadPhasePair pair) {
    Entity entity = pair.getBody();
    Entity id1 = pair.getBody();

    List<Convex> entityConvex = ConvexDecomposer.decompose(entity);
    List<Convex> id1Convex = ConvexDecomposer.decompose(id1);
    return null;
}

private MTV testCollision(Convex body,Convex id1) {
    float overlap = Float.MAX_VALUE;
    Vector3f smallest = null;
    Vector3f[] axis1 = body.getAxis();
    Vector3f[] axis2 = id1.getAxis();

    for(Vector3f axis : axis1) {
        Projection p1 = body.project(axis);
        Projection p2 = id1.project(axis);

        if(!p1.overlapps(p2)) return null;
            float o = p1.getOverlap(p2);
            if(o < overlap) {
                overlap = o;
                smallest = axis;

        }
    }

    for(Vector3f axis : axis2) {
        Projection p1 = body.project(axis);
        Projection p2 = id1.project(axis);

        if(!p1.overlapps(p2)) {
            return null;
        }else {
            float o = p1.getOverlap(p2);
            if(o < overlap) {
                overlap = o;
                smallest = axis;
            }
        }
    }

    MTV mtv = new MTV(smallest, overlap);
    return null;

}

```

I want to be able to somehow submit my array into the testCollision method.

# Answer
> 0 votes
You just need to take every part of one body and check them against every part of the other body. Then you'll have a list of MTVs, which you need to get the smallest of the same way you do it in the SAT function (the one with the smallest overlap is the one you need)

# Answer
> 0 votes
Here is some code to help people who get stuck like me.

```
public MTV testCollision(BroadPhasePair pair) {
    Entity entity = pair.getBody();
    Entity id1 = pair.getBody();

    List<Convex> entityConvex = entity.getConvexes();
    List<Convex> id1Convex = id1.getConvexes();
    MTV mtv = null;
    float overlap = Float.MAX_VALUE;

    for(int i = 0; i< entityConvex.size();i++) {

        for(int j = 0;j < id1Convex.size();j++) {
            Convex convex = entityConvex.get(i);
            Convex convex2 = id1Convex.get(j);

            MTV temp = testCollision(convex, convex2);

            if(temp != null) {
                if(temp.getOverlap() < overlap) {
                    mtv = temp;
                    overlap = temp.getOverlap();
                }
            }
        }
    }
    return mtv;
}

private MTV testCollision(Convex body,Convex id1) {
    float overlap = Float.MAX_VALUE;
    Vector3f smallest = null;
    Vector3f[] axis1 = body.getAxis();
    Vector3f[] axis2 = id1.getAxis();

    for(Vector3f axis : axis1) {
        Projection p1 = body.project(axis);
        Projection p2 = id1.project(axis);

        if(!p1.overlapps(p2)) return null;
            float o = p1.getOverlap(p2);
            if(o < overlap) {
                overlap = o;
                smallest = axis;

        }
    }

    for(Vector3f axis : axis2) {
        Projection p1 = body.project(axis);
        Projection p2 = id1.project(axis);

        if(!p1.overlapps(p2)) {
            return null;
        }else {
            float o = p1.getOverlap(p2);
            if(p1.contains(p2) || p2.contains(p1)) {
                float min = abs(p1.getMin() - p2.getMin());
                float max = abs(p1.getMax() - p2.getMax());

                if(min < max) {
                    o += min;
                }else {
                    o += max;
                }
            }

            if(o < overlap) {
                overlap = o;
                smallest = axis;
            }

        }
    }

    MTV mtv = new MTV(smallest, overlap);
    return mtv;

}

```

---
Tags: java, separating-axis-theorem, convex
---


# Question
Title: If there is an Alpha version, and a Beta version, are the full releases called Gamma or something?
Given the first release of a game is named "Alpha", and another is named "Beta", it would be logical that the release following this one is named "Gamma".

This this the case?

# Answer
> 3 votes
No, there is no Gamma version nor do they call the final release this way. Here's the terminology for versions of a software/game:

1. Pre-Alpha
2. Alpha
3. Beta
4. Open/Closed Beta
5. Release candidate (Might not be final but has potential to be)

You can read more here: https://en.wikipedia.org/wiki/Software\_release\_life\_cycle

# Answer
> 1 votes
I have never heard anyone - in game development or software development in general - use the term "gamma version". After beta comes the "release" version.

However, the differences between "alpha", "beta" and "release" aren't very well-defined. The usual consensus is:

* An alpha is a version where many important features are still missing
* A beta version has all core features implemented, but there are still known bugs and lack of polish (missing assets, clunky UI, flaws in game balance...). Some lower priority features might not be implemented yet.
* A release version is feature-complete and *should* have no known bugs

But different teams have different ideas about what to call "alpha", "beta" and "release". The difference between alpha and beta is hard to define because it is a matter of opinion which features are "core features" and which are not. And it is very common that games get released with known bugs or missing features because the developers ran out of time and/or money.

---
Tags: terminology, alpha, beta
---


title: Unity Bowling ball physics

text:
# Question
Title: Unity Bowling ball physics
I am working on Bowling Ball game for android. And I want the Bowling Ball to feel like a Bowling ball in the real world. I've already tweaked the Rigidbody values and PhysicsMaterial but it's giving me that result. So, how do I make Bowling ball like real BowlingBall in Unity?

# Answer
I think we first need to answer How does a bowling bowl move?

This is kind of complicated. When a person throws the ball they put some forward momentum on the ball as well as some rotational momentum. The initial contact with the lane is in kinetic friction. The ball glides with almost no forces transferred between the ball and the lane. This is how a player puts a spin on the ball to make it travel in an ark. If the ball is thrown soft enough at some point it may "catch" the lane, start spinning and convert to static friction. At this point the ball will roll.

So what do we need? We need to set the ball to the right size and weight. We need to throw it with enough force, and rotational force. This may be way higher, and move way faster than looks normal. We need to set the lane to very low kinetic friction, and low static friction.

Also use the sphere collider :)

More research on bowling. A bowling ball is also not a single density object.

> The bowling ball consists of a hard outer shell with a weight block in the core (the inside of the bowling ball). The mass and shape of the weight block affects the spin of the bowling ball and how it curves as it rolls down the lane. These play an important role in the physics of bowling and (consequently) a bowler's performance, as will be discussed.

Here is a detailed write up with images https://www.real-world-physics-problems.com/physics-of-bowling.html
> 2 votes

---
Tags: unity, unityscript, physics-engine
---


# Question
Title: Is there a purpose behind the tediousness of most MMO RPGs?
As most of you probably know a lot, if not all, MMO RPG games have some element of "tediousness" in them.

By "tediousness" I mean elements in the gameplay that feel both unpleasant and needlessly complicated or long (note that grinding is simply unpleasant and therefore I do not include it in this question).

For example - introductory quests.
I don't mean the idea of introductory quests, which I think good. I mean their implementation.

For example in some games, where you can have several characters per account, each time you create a new character you have to go though the same introduction. You are not offered the option to skip it, regardless that you might already have a high leveled character. Surely there must a point to this?

For another example in some games the introduction is needlessly long. It could take an average player a few days to get past it, it doesn't add anything storywise and the game concepts have long been explained by the time the player reaches even half.

What is the rationale behind putting the player through all this, instead of giving him the option to skip the intro and/or making it only as long as it needs to be, etc.?

# Answer
> 4 votes
MMORPGs are designed to be played for a very long time. While most games aim for a total playtime somewhere in the magnitude of 10-40 hours, MMORPGs aim for several 100 to several 1000 hours until the player has seen all the content the game has to offer.

Why is that?

* Traditionally, MMOs were often monetized with a subscription model. The player pays a monthly subscription fee. In order to make the most money out of this, you need to keep the player engaged for several months. If the player can explore the whole game in under a month, then this model won't be profitable.
* Nowadays, more and more MMOs switch from subscriptions to microtransactions. But most players will only start buying stuff after playing a game for a very long time. You need to keep the players engaged until they become willing to invest money.
* MMOs live from their community. Nobody likes playing in an abandoned area. That's not what MMOs are about. You play them to interact with other players. But it usually takes a quite long time until players get the courage to interact with other players and form a community. The more hours you get out of a player, the more engaged they will become in the community-building aspects of your game (Extra Credits made a series of video about this).

By the way: This is one reason why the free-to-play model is becoming so much more popular than the subscription model: The large amount of freeloaders make the game more populated and offer more interaction opportunities for the paying customers.

But how do you provide hundreds to thousands of hours of content with a limited budget?

You do what you can to slow down the player and make sure they don't progress too fast through your content.

That's where *grinding* comes into play. Before you allow the player to explore further content, you force them to spend as much time as bearable on leveling their character with the content they have already seen.

Grinding is also a useful way to get players to invest into microtransactions. When the grind becomes tedious, they will look for ways to optimize their play in order to get through it as fast as possible. When they reached the maximum optimization possible with ideal play, then microtransactions will often be the only way to optimize further. This makes them very tempting.

But you can't just start the full amount of grind immediately, or the player will see what you are up to and quit. You need to carefully ramp it up to get the player used to it. This "getting used to grinding" process should start early. So why not already introduce the player to grinding in the tutorial?

---
Tags: game-design, mmo
---


# Question
Title: Having trouble making more than 1 clickable object
I am a student trying to figure out how to make multiple clickable objects in pygame.

I was able to make 1 working clickable object (dx,dy) work, but when I tried to make another clickable object (qx,qy), every time I run my code and click on where the object should be, nothing happens.

I don't know what I am doing wrong, so it would be great if someone could give me some advice.

```
import pygame,sys
from pygame.locals import *
display = pygame.display.set_mode([1000,600])
pygame.init()
clock = pygame.time.Clock()
dx,dy=105,470
qx,qy=750,465

while True:
    for event in pygame.event.get():
        if event.type==QUIT:
            pygame.quit()
            quit()
        elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
            mouse = pygame.mouse.get_pos()
            if mouse[0]in range (dx,dy) and mouse[1] in range (dx,dy+50):
                print("Hello love.")
            elif mouse[0] in range (qx,qy+50) and mouse[1] in range (qx,qy+50):
                print("No")

    pygame.font.init()
    fontcolor = pygame.Color("white")
    myfont = pygame.font.SysFont("Comic Sans MS",35,True,False)
    label1 = myfont.render("Draw Card",1,(200,200,200))
    d = display.blit(label1, (dx,dy))
    label2 = myfont.render("Quite",1,(200,200,200))
    q = display.blit(label2, (qx,qy))
    pygame.display.flip()

```

# Answer
Your ranges make no sense. `range(qx,qy+50)` and `range(qx,qy+50)` are empty because the first argument is greater than the second. The dx, dy range checks also don't work correctly.

You have to check if `mouse[0]` is between `dx` and `dx+50` and if `mouse[1]` is between `dy` and `dy+50` and the same for `qx, qy`.

```
if mouse[0] in range(dx, dx+50) and mouse[1] in range(dy, dy+50):
    print("Hello love.")
elif mouse[0] in range(qx, qx+50) and mouse[1] in range(qy, qy+50):
    print("No")

```

Note that the size of the clickable area will only be 50\*50 px and you should better figure out how big the text surfaces are instead of just adding `50` to dx, etc..

It would be even better to use `pygame.Rect`s. You can create the rects with the `get_rect` method of the text surfaces and then use the `collidepoint` method for the collision detection and just blit the surfaces at the corresponding rects.

Here's a minimal, complete example:

```
import sys
import pygame

pygame.init()
display = pygame.display.set_mode([1000,600])
clock = pygame.time.Clock()
myfont = pygame.font.SysFont("Comic Sans MS",35,True,False)
fontcolor = pygame.Color("white")
label1 = myfont.render("Draw Card",1,(200,200,200))
label2 = myfont.render("Quite",1,(200,200,200))
label1_rect = label1.get_rect(topleft=(105, 470))
label2_rect = label2.get_rect(topleft=(750, 465))

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
            if label1_rect.collidepoint(event.pos):  # event.pos is the mouse position.
                print("Hello love.")
            elif label2_rect.collidepoint(event.pos):
                print("No")

    display.fill((30, 30, 30))
    d = display.blit(label1, label1_rect)
    q = display.blit(label2, label2_rect)
    pygame.display.flip()
    clock.tick(30)

```
> 0 votes

---
Tags: python, pygame, mouse, selection
---


# Question
Title: Unity3D MonoBehaviour in .dll loses serialized data when dll is updated
I have a MonoBehaviour class in a compiled DLL that I have included in my Unity project. It automatically serializes public field data as expected. However, whenever I update the dll (by overwriting the existing dll) all my serialized data for the MonoBehaviour scripts are lost and the values revert to default.

1) Is this expected behavior? 2) How do I avoid this result and maintain serialized data through a dll update.

# Answer
> 1 votes
Solved. The issue was that I had renamed the class and in doing so, it provides a missing script error and dumps the data. Since my editor automatically adds the required script I did not notice this until further testing.

---
Tags: unity, serialization, dll, monobehaviour
---


# Question
Title: Benefit of using Vector2 data type over separate x & y variables
I'm really curious about why a lot of people and game engines use Vector2 as its coordinate system instead of the traditional x and y value.

Is there any benefit to this?

I feel like it's just slow me down and barely has any benefit other than organizing your code.

# Answer
> 38 votes
First of all, it's way less clutter. If you have a position, a velocity and an acceleration, that's already 6 variables you have to deal with, 9 in 3d.

Secondly, and this is the most important part, it grants you access to many ways to use or change them. For instance, getting the length of the vector, normalizing it, adding them together, dot product, cross product in 3d, etc. It's possible to do this using separate variables too, but it's much easier using vectors and follows the DRY principle much better.

As for slowing you down, I'm not sure why this would do that. Apart from having to create a new Vector instead of just 2 variables, you only have to pay attention to using vector.x and vector.y, which shouldn't be that hard and isn't much worse, than vectorX and vectorY

# Answer
> 14 votes
Compare the function signatures of both `RotatePoints` versions.

Lone variables:

```
void RotatePoints(
   float *out_x,
   int x_interleave_out,
   const float *in_x,
   int x_interleave_in,
   float *out_y,
   int y_interleave_out,
   const float *in_y,
   int y_interleave_in,
   float angle,
   int count
)
{
  float s = sinf(angle);
  float c = cosf(angle);

  while(count--){
    *out_x = *in_x * c + *in_y * -s;
    *out_y = *in_x * s + *in_y * c;
    out_x += x_interleave_out;
    out_y += y_interleave_out;
    in_x += x_interleave_in;
    in_x += y_interleave_in;
  }
}

```

Compared to using structures/classes:

```
void RotatePoints(
  Vector2 *out,
  const Vector2 *in,
  float angle,
  int count)
{
   Matrix2x2 rotation;
   rotation.SetRotation(angle);

   while(count--){
     *out++ = *in++ * rotation;
   }
}

```

You need to tell the first version if your x and y arrays are interleaved or separate:

```
float all_together[200]; // x0,y0,x1,y1,x2,y2...

```

Or:

```
float x[100];
float y[100];

```

It's a lot less messy to just have a Vector2 array and pass that and the inner code is more readable too.

And the more complex the math the messier and hairier it gets if you're not using Vector and Matrix classes;

# Answer
> 11 votes
# Readability \> Writeability

> I feel like it's just slow me down and barely has any benefit other than organizing your code.

You are correct in that it (slightly) slows you down writing *that* code. However, you write it once in the beginning and from then on *everytime* you come back you are going to read it. So optimizing the reading speed will do much more good that optimizing the writing speed.

# Naming things

Now, you might have difficulties seeing how `draw_rect(Vector2(x, y), Vector2(width, height))` is supposed to be more readable than `draw_rect(x, y, width, height)`, but to be honest, they both aren't as readable as they could be.

Look at this pseudocode:

```
position = Vector2(x, y)
size = Vector2(width, height)
draw_rect(position, size)

```

Yes, this takes 2 lines more and in the beginning I also thought that was bad. It isn't though. Giving things names makes this take less brain power to read, which you will be very thankful for as soon as the program gets more complex. *Especially* when you're debugging it. Naming things well will also improve other things and make you faster in the long run.

# The still very short, but slightly longer run

You mentioned `Object.x += 1` vs `Object.pos += Vector2(1, 0)` Again you're right, your way is faster for this (a single line). But let's just look at a minimally more complex class, you can have:

```
position;
velocity;

void UpdatePosition(){
    position += velocity;
}

```

Compare with:

```
xPosition;
yPosition;
xVelocity;
yVelocity;

void UpdatePosition(){
    xPosition += xVelocity;
    yPosition += xVelocity;
}

```

That is faster to read *and* to write. By the way, with such a small example it's not suuuper hidden, but did you notice the typo in the second version? That's easy to overlook, especially if the class is more complex than this unrealistically small example (There's a theme here...). It's one bug that *can't* happen when using Vector2.

# IDEs

> you cant shorten it by using something like Vec2 = Vector2

You might be working on a school assignment where you aren't allowed to use an IDE. If you don't, use one and look up the autocomplete shortcut (most of the time it's Ctrl+Space).

Then you can write "Vec" and use that shortcut and the IDE will show you a list of all classes that start with "Vec". I don't think any professional coder works without this, because this is so much faster. The alternative is to learn *every class* by heart, with correct typing down to the single character. Ain't nobody got time for that, especially in the business world where time is money.

# Answer
> 8 votes
Operator overloading.

```
Vector v3 = v2 + v1;

```

There is now only one place in your code where you have to write, test and debug vector addition, as opposed to tens, hundreds or thousands.

Obviously vector addition is an overly simplistic example, but there are more complex vector operations and the same applies to those too.

# Answer
> 2 votes
Using structures & classes in place of a pile of primitive variables allows us to focus more of our attention on the higher levels of problem solving.

As taken from Code Complete:

> **Reduce Complexity** \- A primary goal of software design and construction is conquering complexity. The motivation behind many programming practices is to reduce a program’s complexity, and reducing complexity is arguably the most important key to being an effective programmer.
>
> **Program in Terms of the Problem Domain** \- Another specific method of dealing with complexity is to work at the highest possible level of abstraction. One way of working at a high level of abstraction is to work in terms of the programming problem rather than the computer science solution.

Using a vector class / struct plays to both these points.

# Answer
> 1 votes
The same reasons that primitive obsession is a code smell apply to using a vector instead of separate variables. Vector2D/3D is just a special case of avoiding primitives.

# Answer
> 1 votes
Mathematically a vector is *a point in a vector space*. That's something with real physical relevance – the space we live in is basically a vector space.

**The individual components** `x` **and** `y` **are not**. They depend on a choice of coordinate frame, and generally there is no clear reason why some particular coordinate frame should be used. It's an *implementation detail*, so it's best encapsulated in an opaque type. Indeed, you'll mostly access individual components in very simple applications like 2D platformers, but in anything with somewhat serious physics handling you'll much more typically have offsets pointing in some direction that's unrelated to the coordinate axes. Doing that with coordinates would *always* require basically duplicating each calculation.

---
Tags: vector, data-structure, linear-algebra
---


# Question
Title: Determine the startposition for Perlin worms
I want to implement Perlin worms for the level generation of my 2D game and I was wondering, which options exist to find the startposition for the worms.

My idea was to randomly start zero to X (constant) worms per chunk and use random x and y coordinates for each worm. Are there other options I could try and compare to my idea?

# Answer
One other way, if you are looking for a natural look to the level (cave) you could use cellular automata. It is very easy and flexible to code and it works well when properly coded.
> -1 votes

---
Tags: procedural-generation, random, perlin-noise
---


# Question
Title: What is the general architecture of a server for a game like rust/minecraft?
If a game's client is written in Unity or UE4 or another engine, is the server usually written in the same engine? Or is it written in standalone c++?

Does the server use a database like MySQL to store the locations of deployed structures and bases etc? Or is everything stored in memory in arrays or in another way?

# Answer
There is no one solution. It depends on the requirements of your game.

Some game engines offer server components, but I have seen games where the dev team decided that these do not fulfill their requirements, so they wrote their own and communicate with it using the low-level networking features of their engine. Note that client and server don't necessarily need to use the same programming language. My last multiplayer game used a client written in JavaScript (HTML5) and a server written in Java.

Regarding storage: When your game is played in rounds of a few minutes each, you can often do without any persistence on the gameserver and keep everything in memory. But if your game has a persistent game world, you want some form of data storage on hard drive so you can resume the game when the server needs to shut down (or crashes). I have once worked on a game where the gameserver handled a small persistent world using flatfiles. It didn't work *well*, but it worked. But if you have a large number of players, you want to store any information about offline players in a proper database to allow faster login times and ensure data consistency.
> 1 votes

---
Tags: client-server
---


title: Rotate object to closest clone?

text:
# Question
Title: Rotate object to closest clone?
I'm working on a tower defense game.

I'm trying to make my gun object rotate and shoot the nearest instance of the "enemy" object.

My problem here is my gun script rotates only to the main enemy object and not at its cloned objects or even the closest one!

I need my gun to rotate and face the closest enemy to itself.

Here is my clone script:

```
public GameObject enemy;
public float spawnTime = 3.0f;
public Transform[] spawnPoints;

void Start ()
{
    InvokeRepeating ("Spawn", spawnTime, spawnTime);
}

void Spawn ()
{
    int spawnPointIndex = Random.Range (0, spawnPoints.Length);
    Instantiate (enemy, spawnPoints[spawnPointIndex].position, spawnPoints[spawnPointIndex].rotation);
}

```

Gun script:

```
private GameObject target;
private float enemy_distance;

void Update()
{
    target = GameObject.FindGameObjectWithTag("enemy");
    enemy_distance = Vector3.Distance(transform.position, target.transform.position);
    if (enemy_distance <= 20) {
            Quaternion rotation = Quaternion.LookRotation(target.transform.position - transform.position);
            transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.fixedDeltaTime * 2);
            transform.localPosition = new Vector3(transform.localPosition.x, transform.localPosition.y, transform.localPosition.z);
    }

}

```

# Answer
> 1 votes
I notice your script looks for enemies only inside a distance of 20 units. So we don't need to scan the whole scene for enemies using `FindGameObjectWithTag`, we can check just the immediate area.

```
public float detectionRadius = 20f;

// Using a dedicated layer for enemies makes them easy to find with physics queries.
public LayerMask enemyLayers;

// Size this array so it can handle the maximum number of enemies
// you'll ever have all in one place. It saves us some GC allocations.
static Collider[] _enemyResults = new Collider[20];

void Update()
{
    // Ask the physics engine for a list of enemies within the detection radius:
    int nearbyCount = Physics.OverlapSphereNonAlloc(
        transform.position,
        detectionRadius,
        _enemyResults,
        enemyLayers
    );

    if(nearbyCount == 0)
        return; // Nothing to shoot at nearby.

    // Rank the candidates by distance and keep the closest one.
    float lowestScore = float.positiveInfinity;
    Transform target = null;

    for(int i = 0; i < nearbyCount; i++) {
        float score = (_enemyResults[i].transform.position - transform.position).sqrMagnitude;
        if(score < lowestScore) {
            lowestScore = score;
            target = _enemyResults[i].transform;
        }
    }

    // From here on, you have the closest target
    // so put your aiming & firing logic here.
}

```

Note that your rotation blending formula contains some common errors discussed in this previous answer, so you'll want to touch that up too.

---
Tags: unity, spawning
---


title: What makes a good jump scare?

text:
# Question
Title: What makes a good jump scare?
I am working on a game and would like to include a few jump scares. So here is a rather simple question — What makes a good jump scare and when and how should they happen?

# Answer
If you give some more details about your game then someone can help you write a specific jump scare. But it's far more valuable that you understand why a jump scare works.

The correct way to utilize the jump scare is to focus on what happens before and after the jump scare. Why would the player take the world seriously enough to be scared by a poorly made skeleton jumping out of a closet?

Tension and atmosphere. You have to build a believable world, one that the player is invested in. Add stress to the player, and the actual jump scare will write itself. The jump scare is simply a release, or trigger for the player. The horror is the stuff inside the player's head as he/she is anticipating the scare.

More information can be found in this short Extra Credits video about horror games
> 28 votes

# Answer
**Fight or Flight**

Jump-scares abuse your primal instincts. A good jump-scare puts the player in an **immediately life-threatening** situation. If Pinky appeared in front of you right before you ate the last pellet, you'd be jump-scared! Game design is important to consider. It's vital that the the player is legitimatley forced to **fight or fly.**

In horror, loud sounds are usually added, amplifying the effect.

Examples of well-placed jump-scares in various genres:

* Fire-ball coming from bottom of screen in a platformer
* Mimic chest in an RPG
* Pin-ball bouncing straight down the middle
* Sudden obstical in a racing game
* Slender Man

Additionally, it's important to concider whether your jump-scare is **fair**. For example, I Want to be the Guy is all about unfair jump-scares.

https://en.m.wikipedia.org/wiki/Fight-or-flight\_response

https://en.m.wikipedia.org/wiki/Jump\_scare
> 5 votes

# Answer
I have never made a horror game, but when I play them I get most scared of unexpected jump-scares.

Having a good environment, making the player not being able to see everything clearly around you, maybe fog that stops your vision from being very effective.

Just generally making the player feel like he can't do much about it.

---

But I think it changes from person to person, this is just how I "prefer" to get scared. :P
> 4 votes

# Answer
Another technique that it very effective is to lull the player into a false sense of security by having them repeat an action several times, then jumpscaring them on the last time.

For example, in Outlast, I very distinctly remember a scene where you have to walk past a guy who is sleeping in a wheelchair. When I first played it, and in several let's play videos I have seen, the first time walking past him, you are very uncomfortable. Everybody expects him to jump up out of the wheelchair and attack you. He doesn't. 5 minutes later, when you have to walk by him a second time to get back to where you were, no one expects him to do anything. So they will just blindly walk right by him. When he jumps out of the chair and attacks you, it is a lot more terrifying because you were not expecting it.

Overall, anything you can do to make the jumpscare unexpected makes it scarier.
> 4 votes

# Answer
The best time to "jump" something to scare player, is when player doesn't expect it. I mean, it won't have a meaning to do this when all ambient sound is already scary and environment is dark, player would know something will happen in this situation. But when he is just walking across a corridor and you throw a monster from a side-door, this is a good jump scare.
> 3 votes

# Answer
You should probably build the tension first which can be achieved by good ambient sound effects. Then its just presenting the player with the unexpected jump scare :P
> 2 votes

# Answer
I believe that the most effective jump scare is when the player is focused in doing something else. If it's not unexpected it won't work.

eg. A monster jumping down the ceiling when they are in the midst of solving a puzzle to get to the next room after killing all the monsters in that area.
> 2 votes

# Answer
I think the biggest way to make a jump scare effective is to make it *random*. Especially in modern games where it's commonplace for the player to be able to respawn a few rooms back if they're killed, having a jump scare that occurs predictably in the same place every time isn't really all that scary after the first time. For each encounter, pick a dozen or so nearby places it could occur and pick one for each run-through. Not only does this heighten the impact of the scare, but it adds replay-value as they game will feel a bit different every time.
> 1 votes

# Answer
I'm not an expert, but the golden rule is don't overuse it. And also make it a total surprise, meaning don't reveal when it's expected to happen. Also, it's best used when the player is concentrating at something else, in this case, their guard will be down because they are focusing on something else, so the effect is mush bigger. I hope this helps.
> 0 votes

# Answer
To make a great in-game jump scare scene you first need to drag player's attention and concentration away from the horror theme, make him focus on some other elements in the game(challangable parts that require 100% of the players focus like searching for element; solving a puzzle...) and execute it once his doesn't expect it at all.

A good example is the one with the Batman game where the game requires 100% of the focus, you probably will fail it a couple of times and once you success you have the feeling of relaxation because you finally passed it, but all of a sudden it happens!

Someone mentioned you need to prepare the player with some pre-scenes of tension. In reality that's not the way to do it but you need to do the opposite.
> 0 votes

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


# Question
Title: Message Passing b/w “LAN Server Only” and “LAN Client” on Different Scenes in Unity
I want to pass message back and forth on client and server which are on different scenes, how can I do that in Unity?\**

Following is my Scenario:- I have 5 scenes-

1. BaseScene (2) OfflineScene (3) OnlineScene (4) ClientOnline (5) ServerOnline.

All these scenes have button having text of the names of the scenes. On Base Scene, I have add empty game object on which i have placed "customNetworkScript" which extends from "NetworkManager" script and also placed "Network Manager HUD" on it. Following is the code which i have placed in "customNetworkScript":-

```
public class customNetworkScript : NetworkManager {

        public override void OnClientSceneChanged(NetworkConnection conn)
            {
                SceneManager.LoadScene("ClientOnline", LoadSceneMode.Single);
                ClientScene.Ready(conn);
                ClientScene.AddPlayer(conn, 0);
            }

            public override void OnServerSceneChanged(string sceneName)
            {
                SceneManager.LoadScene("ServerOnline", LoadSceneMode.Single);
            }
    }

```

I have placed "OfflineScene" and "OnlineScene" in the fields, named "Offline Scene" and "Online Scene" in "Network Manager" component. Also have placed an empty prefab in "Spawn Info" in "customNetworkScript" and it has component "Network Identity" on it. Now when i run project, on one instance, I click on "LAN Server only" and on another instance, I click on "LAN Client". And I get my respective scenes on both the instances -\> "ServerOnline" appear on instance where I click "LAN Server only" and "ClientOnline" appear on other instance. What I want is, when i click on "ServerOnline" button, a message string will pass on to "ClientOnline" scene and same happens in backward direction when i click on "ClientOnline" button.

I have tried "Rpc" and "Command" but they only work when I click on "LAN Host" instead of "LAN Server Only". I have tried very hard but couldn't find anything useful. It will be a great pleasure if someone explain to me in detail along with the code, how can I achieve this.

ThankYou Very Much for Your Time.

# Answer
After hours of research and hard work, finally find a solution for my problem. I will refer to this asset if someone still stuck on it:

This asset is well documented and will tell you all about how you can do dedicated/pure server and client networking:-

Asset Link

If someone still don't understand it feel free to ask me. I will try my best.
> 0 votes

---
Tags: unity, client-server, unity-networking, unet, messaging
---