# Question
Title: How can I disable an NGUI button when I pause my game?
There is an NGUI button in my game, which when pressed increases the player's power.

When I press the escape key, my game pauses completely. But the button still functions normally. Here's how I check for pausing:

```
void Update ()
{
    if(Input.GetKeyDown("escape"))
    {
        if(isPaused && Time.timeScale == 1.0f){
            Time.timeScale = 0.0f;
            AudioListener.volume = 1;
        }
        else
        {
            Time.timeScale = 1.0f;
            AudioListener.volume = 0;
        }
    }
}

```

I'd like the button to be deactivated when the game is paused. It should be visible, but not be clickable or anything. How can I achieve that?

# Answer
> 1 votes
Just set `isEnabled` of the desired `UIButton` to false. This will just disable it's collider, and it will still be visible. :-)

# Answer
> 0 votes
I'd imagine the simplest way would be to give the Script that accesses the button knowledge about `isPaused`. Some type of static access would make sense to me in this case, since multiple scripts might need to change their behaviour based on the value of `isPaused`.

```
public class ButtonBehaviour : MonoBehaviour {

....

public void onPress() {
    if (!PauserClass.isPaused) {
        makePlayerStronger();
    }
}

....

}

```

---
Tags: unity, ngui
---


title: Handling Multiple Resolutions

text:
# Question
Title: Handling Multiple Resolutions
Recently, I was going to implement and options menu into my game, but I haven't been able to figure out how changing resolution, conceptually, would work. Do I have multiple versions of the same texture at different resolutions, do I just change the area of which the texture would render, or some other option?

# Answer
> 0 votes
Conceptually, games can adjust to screen resolutions by scaling UI elements. If you want to take the easy route and use Unity's UI, this can be done pretty easily with a Canvas Scaler.

I don't think that SFML has a canvas scaler and a well-made one can get pretty involved. A simpler canvas scaler has a reference resolution which is used to build your UI on. Then the UI elements are simply resized to the new resolution based on the one they were designed with. For example, if the reference resolution is 800x600 and the device's screen resolution is 1000x1000, elements' height would be multiplied by 1.25 and width by 1.66.

Keep in mind that pivot points matter when resizing elements.

Alternatively, you could use a GUI library mentioned here: http://en.sfml-dev.org/forums/index.php?topic=13590.0.

---
Tags: rendering, resolution
---


# Question
Title: glRotatef not rotating simple 2D triangle
I am new to OpenGL and am learning it for the purpose of some simulation that I am doing as part of my research work. I have been following the tutorials given at http://openglbook.com/chapter-2-vertices-and-shapes.html and am using the code which draws a triangle. I am trying to add some code to it so that I can rotate the triangle using mouse upon display. I am using **glTranslatef** and **glRotatef** to achieve this. I understand that glrotate takes 4 arguments first being the angle of rotation, the last three form the vector centred at origin around which rotation is intended. I am printing captured values from my motion func and the mouse input is being captured. But my triangle is not rotating. Any help will be much appreciated. Thanks! Code below.

```
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <GL/glew.h>
#include <GL/freeglut.h>
#define WINDOW_TITLE_PREFIX "Chapter 2"

int
 CurrentWidth = 800,
 CurrentHeight = 800,
 WindowHandle = 0;

unsigned FrameCount = 0;

GLuint
  VertexShaderId,
  FragmentShaderId,
  ProgramId,
  VaoId,
  VboId,
  ColorBufferId;

 // mouse controls
int mouse_old_x, mouse_old_y;
int mouse_buttons = 0;
float rotate_x = 0.0, rotate_y = 0.0;
float translate_z = -3.0;

const GLchar* VertexShader =
{
  "#version 400\n"\

  "layout(location=0) in vec4 in_Position;\n"\
  "layout(location=1) in vec4 in_Color;\n"\
  "out vec4 ex_Color;\n"\

  "void main(void)\n"\
  "{\n"\
  "  gl_Position = in_Position;\n"\
  "  ex_Color = in_Color;\n"\
  "}\n"
};

const GLchar* FragmentShader =
{
  "#version 400\n"\

 "in vec4 ex_Color;\n"\
 "out vec4 out_Color;\n"\

 "void main(void)\n"\
 "{\n"\
 "  out_Color = ex_Color;\n"\
 "}\n"
};

void Initialize(int, char*[]);
void InitWindow(int, char*[]);
void ResizeFunction(int, int);
void RenderFunction(void);
void TimerFunction(int);
void IdleFunction(void);
void Cleanup(void);
void CreateVBO(void);
void DestroyVBO(void);
void CreateShaders(void);
void DestroyShaders(void);
//Mouse Movements//
void mouse(int button, int state, int x, int y);
void motion(int x, int y);

int main(int argc, char* argv[])
{
  Initialize(argc, argv);

  glutMainLoop();

  exit(EXIT_SUCCESS);
}

void Initialize(int argc, char* argv[])
{
  GLenum GlewInitResult;

  InitWindow(argc, argv);

  glewExperimental = GL_TRUE;
  GlewInitResult = glewInit();

  if (GLEW_OK != GlewInitResult) {
    fprintf(
    stderr,
   "ERROR: %s\n",
    glewGetErrorString(GlewInitResult)
    );
   exit(EXIT_FAILURE);
  }

  fprintf(
  stdout,
  "INFO: OpenGL Version: %s\n",
   glGetString(GL_VERSION)
 );

 CreateShaders();
 CreateVBO();

 glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
 }

void InitWindow(int argc, char* argv[])
{
   glutInit(&argc, argv);

   glutInitContextVersion(4, 0);
   glutInitContextFlags(GLUT_FORWARD_COMPATIBLE);
   glutInitContextProfile(GLUT_CORE_PROFILE);

   glutSetOption(
     GLUT_ACTION_ON_WINDOW_CLOSE,
     GLUT_ACTION_GLUTMAINLOOP_RETURNS
  );

    glutInitWindowSize(CurrentWidth, CurrentHeight);

   glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA);

   WindowHandle = glutCreateWindow(WINDOW_TITLE_PREFIX);

  if(WindowHandle < 1) {
     fprintf(
     stderr,
     "ERROR: Could not create a new rendering window.\n"
    );
    exit(EXIT_FAILURE);
   }

  glutReshapeFunc(ResizeFunction);
  glutDisplayFunc(RenderFunction);
  glutMouseFunc(mouse);
  glutMotionFunc(motion);
  glutIdleFunc(IdleFunction);
  glutTimerFunc(0, TimerFunction, 0);
  glutCloseFunc(Cleanup);
 }

 void ResizeFunction(int Width, int Height)
 {
  CurrentWidth = Width;
  CurrentHeight = Height;
  glViewport(0, 0, CurrentWidth, CurrentHeight);
 }

  void RenderFunction(void)
  {
    ++FrameCount;

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
   // set view matrix
   glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
   glTranslatef(0.0, 0.0, translate_z);
     printf ("translate_x = %f rotate_x = %f rotate_y = %f  \n",rotate_x,rotate_y,translate_z);
   glRotatef(rotate_x, 1.0, 0.0, 0.0);
   glRotatef(rotate_y, 0.0, 1.0, 0.0);
  glDrawArrays(GL_TRIANGLES, 0, 3);
  glutSwapBuffers();
 }

  void IdleFunction(void)
 {
    glutPostRedisplay();
  }

 void TimerFunction(int Value)
{
  if (0 != Value) {
   char* TempString = (char*)
    malloc(512 + strlen(WINDOW_TITLE_PREFIX));

sprintf(
  TempString,
  "%s: %d Frames Per Second @ %d x %d",
  WINDOW_TITLE_PREFIX,
  FrameCount * 4,
  CurrentWidth,
    CurrentHeight
  );

glutSetWindowTitle(TempString);
free(TempString);
 }

  FrameCount = 0;
  glutTimerFunc(250, TimerFunction, 1);
  }

void Cleanup(void)
{
     DestroyShaders();
     DestroyVBO();
}

void CreateVBO(void)
{
  GLfloat Vertices[] = {
    -0.8f, -0.8f, 0.0f, 1.0f,
    0.0f,  0.8f, 0.0f, 1.0f,
     0.8f, -0.8f, 0.0f, 1.0f
   };

 GLfloat Colors[] = {
   1.0f, 0.0f, 0.0f, 1.0f,
    0.0f, 1.0f, 0.0f, 1.0f,
   0.0f, 0.0f, 1.0f, 1.0f
  };

GLenum ErrorCheckValue = glGetError();

glGenVertexArrays(1, &VaoId);
glBindVertexArray(VaoId);

 glGenBuffers(1, &VboId);
 glBindBuffer(GL_ARRAY_BUFFER, VboId);
 glBufferData(GL_ARRAY_BUFFER, sizeof(Vertices), Vertices, GL_STATIC_DRAW);
 glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, 0);
 glEnableVertexAttribArray(0);

 glGenBuffers(1, &ColorBufferId);
 glBindBuffer(GL_ARRAY_BUFFER, ColorBufferId);
glBufferData(GL_ARRAY_BUFFER, sizeof(Colors), Colors, GL_STATIC_DRAW);
glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(1);

 ErrorCheckValue = glGetError();
 if (ErrorCheckValue != GL_NO_ERROR)
 {
   fprintf(
     stderr,
     "ERROR: Could not create a VBO: %s \n",
     gluErrorString(ErrorCheckValue)
   );

   exit(-1);
 }
}

void DestroyVBO(void)
 {
  GLenum ErrorCheckValue = glGetError();

 glDisableVertexAttribArray(1);
 glDisableVertexAttribArray(0);

glBindBuffer(GL_ARRAY_BUFFER, 0);

 glDeleteBuffers(1, &ColorBufferId);
 glDeleteBuffers(1, &VboId);

 glBindVertexArray(0);
  glDeleteVertexArrays(1, &VaoId);

  ErrorCheckValue = glGetError();
 if (ErrorCheckValue != GL_NO_ERROR)
 {
   fprintf(
     stderr,
     "ERROR: Could not destroy the VBO: %s \n",
     gluErrorString(ErrorCheckValue)
   );

   exit(-1);
  }
}

void CreateShaders(void)
{
  GLenum ErrorCheckValue = glGetError();

  VertexShaderId = glCreateShader(GL_VERTEX_SHADER);
  glShaderSource(VertexShaderId, 1, &VertexShader, NULL);
  glCompileShader(VertexShaderId);

  FragmentShaderId = glCreateShader(GL_FRAGMENT_SHADER);
 glShaderSource(FragmentShaderId, 1, &FragmentShader, NULL);
   glCompileShader(FragmentShaderId);

  ProgramId = glCreateProgram();
   glAttachShader(ProgramId, VertexShaderId);
   glAttachShader(ProgramId, FragmentShaderId);
   glLinkProgram(ProgramId);
 glUseProgram(ProgramId);

  ErrorCheckValue = glGetError();
  if (ErrorCheckValue != GL_NO_ERROR)
 {
    fprintf(
      stderr,
      "ERROR: Could not create the shaders: %s \n",
      gluErrorString(ErrorCheckValue)
    );

   exit(-1);
   }
 }

 void DestroyShaders(void)
 {
   GLenum ErrorCheckValue = glGetError();

  glUseProgram(0);

    glDetachShader(ProgramId, VertexShaderId);
   glDetachShader(ProgramId, FragmentShaderId);

   glDeleteShader(FragmentShaderId);
  glDeleteShader(VertexShaderId);

  glDeleteProgram(ProgramId);

   ErrorCheckValue = glGetError();
   if (ErrorCheckValue != GL_NO_ERROR)
  {
    fprintf(
      stderr,
     "ERROR: Could not destroy the shaders: %s \n",
      gluErrorString(ErrorCheckValue)
   );

   exit(-1);
  }
}

  ////////////////////////////////////////////////////////////////////////////////
  //! Keyboard events handler
  ////////////////////////////////////////////////////////////////////////////////
 void KeyboardFunction(unsigned char key, int X, int Y)
 {
switch (key)
{
    case (27) :
        exit(EXIT_SUCCESS);
        break;
  }
}

  ////////////////////////////////////////////////////////////////////////////////
  //! Mouse event handlers
  ////////////////////////////////////////////////////////////////////////////////
void mouse(int button, int state, int x, int y)
{
 if (state == GLUT_DOWN)
 {
     mouse_buttons |= 1<<button;
 printf("Mouse Button was pressed \n");
}
else if (state == GLUT_UP)
{
    mouse_buttons = 0;
}

mouse_old_x = x;
mouse_old_y = y;
}

void motion(int x, int y)
{
float dx, dy;
dx = (float)(x - mouse_old_x);
dy = (float)(y - mouse_old_y);

if (mouse_buttons & 1)
{
    rotate_x += dy * 0.2f;
    rotate_y += dx * 0.2f;printf("ROTATE value is being set \n");
}
else if (mouse_buttons & 4)
{
    translate_z += dy * 0.01f;printf("TRANSLATE is being set \n");
}

mouse_old_x = x;
mouse_old_y = y;
}

```

# Answer
> 2 votes
`glRotatef` and `glTranslatef` are old functions meant for use with the fixed-function pipeline, so they don't work with opengl 4 shaders. Instead you need to create a matrix, send it to your shader, and multiply your vertices by it when setting `gl_Position`.

The exact process will probably be covered in one of the following tutorials on that site, so I'd recommend just continuing with them.

---
Tags: opengl, rotation
---


# Question
Title: What are the risks of targeting Steam, XBLA and PSN for game releases?
Say that I spend 6-12 months working on a game, submit it to Steam, XBLA, and PSN and I get rejected. Does that mean I just wasted 6-12 months for nothing? Seems like a really big risk in my opinion.

I need to know this because I'm planning to start a game for consoles and PC really soon, and I want to know the risks.

# Answer
I'm a professional PC / console game developer and many of my friends have moved to mobile game dev because its easier to make money there. Also, regarding getting the game working at different aspect ratios, there's lots of similar work when doing PC game Dev since each machine can be vastly different. Your other points make sense to me though. As an independent game developer, who hasn't shipped a PC or console game before its going to be difficult getting a console company to accept your game unfortunately. You basically have to prove to them you have the background to make it happen which basically means that you've shipped a PC / console game before. Console Dev has a lot of rules too about how your game has to work and behave in specific situations. It can be a tedious pain to make your game conform. It also costs significant amounts of money to submit a game (tens of thousands of dollars). As far as PC games, steam is probably not as hard to get accepted in as consoles, but that doesn't mean its easy. If you can't get accepted by steam, there are other services to release PC games. They may be leas prestigious and have fewer customers, but they exist and could be a good starting point for you. If you finish a game and can't find a way to release it, you could try to sell it to another game company to do that work for you of making it ready for a bigger stage. Lastly, worst case scenario, once you finish your game you'll have a strong portfolio item for getting into PC/ console game Dev professionally. For what its worth I've done mobile game dev too and also was not a fan (: keep chasing what you are after, you'll get there eventually!
> -1 votes

---
Tags: xbox360, steam, playstation3, xbox-live, playstation4
---


# Question
Title: Unity3D - GameObject as a static function
Newbie Unity3D/C# developer here.
I've tried learning Unity3D during my May/June college vacation and came across a problem:
Code 1:

```
CameraObj returnVoid;

void Start ()
{
    returnVoid = GameObject.Find ("Main Camera").GetComponent<CameraObj> ();
    returnVoid.ComponentType ();
}

```

Code 2:

```
GameObject returnDirectLight;

void Start ()
{
    returnDirectLight = GameObject.Find ("Directional Light");
    Debug.Log (returnDirectLight.GetComponent<DRLight>().directionString);
}

```

`CameraObj` is my custom component.
As far as I know, `GetComponent` is actually a public method. I understand the logic behind Code 2. What I fail to understand is Code 1. How does `GetComponent` become a static function here? Does it become abstract in my `CameraObj` class?

# Answer
That's not using GetComponent() on the class GameObject, it's using GetComponent() on the result of GameObject.Find()

GameObject.Find() is a static function, but it returns a specific object. Note that Code 2 is also using GameObject.Find() but then you store the result object in a variable. Code 1 uses the exact same functions but doesn't store the result of GameObject.Find() that's the only difference.
> 3 votes

---
Tags: unity, component-based, gameobject
---


title: Game is unable to load assets

text:
# Question
Title: Game is unable to load assets
I programmed a game in c++. Now I want to pack the finished product. Game runs fine from within the compiler. But how can i link the assets(like images, music etc) of the game to the exe ? When I run the executable, it says it is not able to load any assets and terminates immediately. How can I bind the assets with the executable ?

# Answer
There's no general way to do this, especially not cross-platform.

Do you really have to pack your ressources into the executable file? I'd consider deploying a small setup program instead, which would unpack the ressources next to the executable file, which is essentially what you have when running from your IDE/when debugging.

Just because you've added some file to your project doesn't mean it's actually compiled into your executabe (an impression MSVC might give you for example; there are different "build actions" for files added to the project).

Also consider making your executable bigger and reading ressources from it might slow down your program, since overpedantic antivirus solutions might cause repeated scans.

So if you really insist on packing everything into your executable, I'd do something like this:

* Compile a list of all required assets.
* Write a second tool to "pack" the assets:
    + Possibly compress and append the ressources to the final executable file, starting with some kind of index file containing all the offsets/sizes-
    + Write the starting offset of the ressources at the end of the resulting file.

Your actual program can then access ressources this way:

* Open the executable in readonly mode (random access will be blocked).
* Read the starting offset from the end of the file.
* Move to the offset and read the index file.
* Load your assets according to the index file.

Please note that this approach has its flaws, e.g. you won't be able to sign your final binary (since that would once again change the layout). There are workarounds, but it would overcomplicate things here I guess.

Of course you can use platform specific loading of embedded resources if you want to, but this won't be a cross-platform solution and requires further information regarding your goals.

**TL;DR:** Is there really some reason to do so? If you want easy deployment, use a setup programm/installer (like NSIS or InnoSetup). If you want to compress/pack ressources, do so in a separate file.
> 3 votes

---
Tags: c++
---


# Question
Title: How to detect if I click on an object (2D) using Raycast?
I need to know this for a little popup I made in my game, I want to avoid using `OnMouseDown` because I have multiple cameras so I was wondering how I'd be able to detect a mouse click event on an object using `Raycasting`, as I can't figure it out :/

Thank you!

# Answer
Add a physics raycaster to your camera and an EventSystem to your scene, then implement the IPointerX (up, down etc) handler in your script.
> 1 votes

---
Tags: unity
---


# Question
Title: How to calculate normal vector of a Bézier curve?
How I can calculate the normal vector for two dimensional Bézier curve?

(I have the control points of the curve in the x y plane)

# Answer
If vector `(x,y)` is a tangent vector of your curve, then the normal vector is simply `(y,-x)`. So you just need to find a tangent vector, and it all depends on how exactly you define the curve.

If your curve comes from a **parametric representation** `p(t) = (x(t),y(t))` which is sufficiently continuous, then a good approximation of the tangent vector at `t` is, given a very small `ɛ`:

```
       p(t+ɛ)-p(t)
v(t) = ———————————
             ɛ

         x(t+ɛ)-x(t)   y(t+ɛ)-y(t)
v(t) = ( ——————————— , ——————————— )
              ɛ             ɛ

```

This applies to *e.g.* Bézier curves.

If your curve comes from a **dense list of points** then a good approximation comes from taking the two closest points on the curve, `p0` and `p1`, and then your tangent is:

```
v(t) = (p1 - p0) / distance(p1, p0)

```

If your curve comes from a **scattered list of points** then the above method will probably exhibit too many discontinuities, but so will your curve unless you use some kind of interpolation. What I suggest is consider the interpolation function (for instance, cubic interpoltion) as a parametric function, and apply the first method.
> 3 votes

---
Tags: mathematics, linear-algebra, beziers
---


# Question
Title: Level Design: Char Traveling to and from a Site
I'm developing a 2d platformer game where your character can travel to and from sites as he pleases. To travel to and from these sites the character must travel along a path between his current location and his destination (see illustration below).

And of course the idea is that you can travel through the level backwards if you wish to return to Site One. But as you probably realize, doing this may provoke some serious problems, and will put limitations on the level design (no cliffs or long drops because then your character wouldn't be able to overcome them on the way back). I've come up with multiple ways to overcome this (such as designing two levels for the same path etc), but I was wondering if anyone else has any creative work-arounds for this problem. Any help and advice is appreciated.

# Answer
> 6 votes
There are multiple ways to solve this.

If you want to include said long drops and other one-way obstacles, that should be factored in possibly as a feature. The *Legend of Zelda* series often uses these to prevent the player from missing or giving up on important rooms of the dungeon. A simple solution is to allow the player to use an item they obtain later in the game to allow them to backtrack. This method helps to avoid the player getting "lost" in the world.

If that is not an option, implement some machinery. Obviously a long drop isn't an issue if there is an elevator to help you back up. After the player conquers the hill above and drops down, they find a lever or button that activates the elevator back up, allowing regression.

Lastly, the most expensive method is to make a second level facing backwards. The level would have an entirely different layout but add to the overall substance of the game.

# Answer
> 3 votes
Here is an idea:

You can create one-way paths, with a little tweak. If the player enters the path from "Site 2" he should see everything mirrored. This way, if he starts from Site 1 he can go to Site 2 as level was designed, but he can't change his mind mid way and return to Site 1. Of course when he reaches Side 2, he can come all the way back to Site 1, since the path (and everything in it) has been mirrored.

Another Idea:

Again with one-way paths. if your design gives you the permission, you can change how the ground looks. So that instead of firm earthy thing in the bottom of the page, it looks more like a curve mid screen. Now, you design the path, in a way that player can start from the left, and go forth till the very end in the right. In his way back though, he should start from right, but this time he should be under the that Curve shape, with gravity affecting towards top of screen. This way, if for example, there is a long jump in the end of way to Site 2, there will be a long jump right at the beginning of the way to Site 1.

# Answer
> 1 votes
In addition to the other answers, you could let the player be stranded on the far side of the trip temporarily: if they try to go back, they will start at the cliff to make it clear that they can't. Then let them find a different way back via plot or exploration, and/or let them find/earn jump boots or jetpack or whatever to get back the way they came (e.g. metroidvania character development.)

This isn't going to be appropriate in the majority of cases, but using geographic "set pieces" that fit the plot or mood or gameflow when appropriate is a good idea.

---
Tags: flash, platformer
---


title: How to make a one way trigger?

text:
# Question
Title: How to make a one way trigger?
In my game, there is a cat that jumps on pillars. When it lands on a pillar, force is applied and it jumps. There are three animation states which are just single image. The states are : idle,up and down.

When cat lands on the pillar, Collision is triggered where i set animation state to idle. Then, force is added and animation state is changed to up. But problem is, this collision and add force happens so fast, the cat switches between down and up without showing idle.

To overcome this, i added an empty child object to pillar. Then added Edge collider set as trigger. This child was placed slightly above the pillar. So when cat hit this, animation state would switch to idle. Then the cat would land on pillar and jump.

This worked except, the trigger is two way. When cat jumps from pillar, it collides with this trigger and state is changed from up to idle. I tried to add platform effector with one way, but the effector cannot be used on a trigger.

So, is there a way i can add a collider to the empty child which will let it go through aftyer setting state to idle?

# Answer
> 1 votes
If you have trouble getting a good blend in between your animation states you could break it up using Invoke() within your OnTriggerEnter(). I don't normally like to do this but it will most likely solve your state issue and give it time enough to show the idle before your jump.

```
Invoke("PillarAddForceMethod", .6f);

void PillarAddForceMethod()
{
    //ToDo : ADD FORCE
}

```

---
Tags: unity
---


# Question
Title: Which is the better way to distribute server workload for MMO server?
I'm making a server for MMO in Unity, which implies that I'll have a big world, split into maps which will be on different servers (to distribute the workload), managed by one master server.

Now I can't decide weather I should use one executable per map and have few executables run on each server or have few maps on one executable, which will have it's own server.
Second solution also would allow me to redistribute the workload by moving maps from one server to other (which shouldn't take long to do since servers don't need to load models).

Btw servers need to be made in Unity for the physics simulation and collisions...

The networking part can easily be multithreaded simply by using many threads to process the requests and generate response.
But since Unity is single threaded adding more maps would slow down the physics engine (plus the same thread has to apply all actions of the players to the game), so the first solution helps here by using multiple executables. (Edit: Note: physics engine will take considerable amount of CPU time, even while the scene is empty)

Which solution should I chose?

EDIT: On the end I decided to use both: few executables on each server, with each executable being able to run multiple maps and being able to dynamically create dungeons when needed.

# Answer
> 2 votes
Without a doubt, an executable per map would be the best option because servers run collisions detection. Collision detection increases in complexity by O(N) so a single instance with 500 objects will be much slower than 5 instances with 100 objects each.

There is a small overhead for each individual executable instance but compared to physics and other server logic, this overhead is negligible.

---
Tags: unity, networking, mmo
---


# Question
Title: Unity - How To Save Some Variable WIth PlayerPrefs?
I have a small problem. in the game that I'm creating I created an array of items, each item includes a number of variables (cost, level, etc.). my goal is to save your own variables for each item, with the use of PlayerPrefs. These are my two scripts.

in this first script I create the array called (public Item\_Manager \[\] items;), and in the second script initialize variables for each item dell'aray. I tried to save the values in the second script but then when I open the game again, all items are saved with the same variables.

Therefore, how can I do to save every variable of each item in the array with PlayerPrefs?

The variables are:

```
public float costo;
public float tickValue;
public float count;

```

This is the First Script

```
public class Proiettili_Per_Secondo : MonoBehaviour {

public UnityEngine.UI.Text bpsDisplay;
public Click click;
public Item_Manager[] items;

void Start(){
    StartCoroutine (AutoTick ());
}

void Update (){
    bpsDisplay.text = ConvertiroreProiettili.Instance.GetCurrencyInString
        (GetPallottoleOgnISecondo (), true, false);
}

public float GetPallottoleOgnISecondo(){
    float tick = 0;
    foreach (Item_Manager item in items) {
        tick += item.count * item.tickValue;
    }
    return tick;
}

public void AutoProiettiliPerSec(){
    click.proiettili += GetPallottoleOgnISecondo () / 10;
}

IEnumerator AutoTick(){
    while (true) {
        AutoProiettiliPerSec();
        yield return new WaitForSeconds(0.10f);
    }
}
}

```

This is the second script

```
public class Item_Manager : MonoBehaviour {

public UnityEngine.UI.Text titolo;
public UnityEngine.UI.Text costo_;
public UnityEngine.UI.Text livello;
public UnityEngine.UI.Text valore_da_aggiungere;
public Color standard;
public Color caricamento;
public Click click;
public float costo;
public float tickValue;
public float count;
public string costo_stringa; ///NECESSARIO PER TRASFORAMARE IL VALORE COSTO IN UNO PIU CORTO (K, MILLIOM)
public string itemName;
private float baseCost;
private Slider _slider;

void Start () {
    baseCost = costo;
    _slider = GetComponentInChildren<Slider> ();
}

void Update () {
    titolo.text = itemName ;
    costo_.text = (costo_stringa = ConvertiroreProiettili.Instance.GetCurrencyInString (costo, false, false));
    livello.text = "Liv: " + count;
    valore_da_aggiungere.text = "+ " + tickValue + "/Sec";

    _slider.value = click.proiettili / costo * 100;
    if (_slider.value >= 100) {
        GetComponent<Image> ().color = caricamento;
    } else {
        GetComponent<Image> ().color = standard;
    }
}

public void PurchasedItem () {
    if (click.proiettili >= costo) {
        click.proiettili -= costo;
        count += 1;
        costo = Mathf.Round (baseCost * Mathf.Pow(1.50f, count));
    }
}
}

```

# Answer
> 2 votes
PlayerPrefs are not designed for saving scores. They are easily modifiable by the end user in a text file. Instead, you should serialize settings, replays, etc. that players have no motivation to hack.

Knowing that, this is how you save to PlayerPrefs:

```
int Birthday;
void Start ()
{
    Birthday = 172589;
    PlayerPrefs.SetInt ("My Birthday", Birthday);
}

```

For saving an array, you can serialize it as a string then save the string to PlayerPrefs. I.e.:

```
//Serializes an int[] into a string then saves it into PlayerPrefs
void SaveIntArray (string Name, int[] IntArray)
{
    string SerializedArray = "";
    string += BytesToString(System.BitConverter.GetBytes (IntArray.Length));
    for (int i = 0; i < IntArray.Length; i++)
    {
        SerializedArray += BytesToString(System.BitConverter.GetBytes(IntArray[i]));
    }
    PlayerPrefs.SetString (Name, SerializedArray);
}

//Gets a string form player prefs and deserializes it as an int[]
int[] GetIntArray (string Name)
{
    string SerializedArray = PlayerPrefs.GetString (Name);
    byte[] SerializedArrayBytes = new byte[SerializedArray.Length]
    for (int i = 0; i < SerializedArray.Length; i++)
    {
        SerializedArrayBytes[i] = (byte)SerializedArray[i];
    }
    int IntArrayLength = BitConverter.ToInt32 (SerializedArrayBytes, 0);
    int[] IntArray = new int[IntArrayLength];

    SerializationPosition = 4;
    for (int i = 0; i < IntArrayLength; i+=1)
    {
        IntArray[i] = BitConverter.ToInt32(SerializedArrayBytes, SerializationPosition);
        SerializationPosition += 4;
    }
}

//Converts an array of bytes to a string
string BytesToString (byte[] bites)
{
   string ret = "";
   for (int i = 0; i < bites.Length; i++)
   {
       ret += (char)bites[i];
   }
}

```

Alternatively, you can use PlayerPrefsX which has many more such extensions implemented.

If you're making a game for iOS, consider using UnityEngine.Social for saving scores which will save data on a Game Center server that will be unmodifiable except through your game's code.

---
Tags: unity, savegame
---


# Question
Title: Why is my text is too large even when scaled to .05f in libGDX?
I'm trying to scale down my fonts as my game objects are also small.

I'd like to scale them down the same way as my sprites. However, if I scale them below `.05`, the font disappears!

My attempt at small, smooth text above an orange grid:

The code:

```
private void initTestObjects() {
        textures = new TextureAtlas(Gdx.files.internal("data/atlas.atlas"));//i am not using atlas params(for now -.-, I cut from texture..)

        //text texture and bitmapfont
        texturesText = new Texture(Gdx.files.internal("data/fonts_0.png"), true);
        texturesText.setFilter(Texture.TextureFilter.MipMapLinearNearest, Texture.TextureFilter.Linear);
        bitmapFonts = new BitmapFont(Gdx.files.internal("data/fonts.fnt"), new TextureRegion(texturesText), false);
        bitmapFonts.setScale(.1f);

        //grid texture and sprite
        TextureAtlas.AtlasRegion grid = textures.findRegion("grid");
        gridSprite = new Sprite(grid);
        gridSprite.setSize(SIZE, SIZE);//4x4
        gridSprite.setOrigin(gridSprite.getWidth() / 2, gridSprite.getHeight() / 2);
        gridSprite.setPosition(0 - gridSprite.getOriginX(), 0 - gridSprite.getOriginY());

        //players' textures
        o = textures.findRegion("o");
        x = textures.findRegion("x");

        line = textures.findRegion("line");
    }

```

What am I doing wrong?

# Answer
I see you use gridSprite.setSize(SIZE, SIZE);//4x4. That means that your sprite uses 4x4 units of your camera's viewportWidth and viewportHeight for drawing. And that means, that your world is scaled. If you were using viewportWidth and viewportHeight set to screen resolution in pixels, then text will be all right. But when the world is scaled, viewportWidth and viewportHeight are set in world units, for example 15x10. And for that reason you see very big text - it just remains the same, while the world is scaled. There’s no need for the sprite’s dimensions and position to be given in pixels. We could set the width and height of the sprite to 4×2 and it would still map to for example 855×480 pixel region in the texture atlas. BitmapFont doesn't do that magic for us. If you still want to draw text in your world coordinate space, one way is to change the projection matrix for the time, text is drawn:

```
batch.begin();
// here goes actual drawing of your game world
Matrix4 originalMatrix = batch.getProjectionMatrix().cpy(); // cpy() needed to properly set afterwards because calling set() seems to modify kept matrix, not replaces it
batch.setProjectionMatrix(originalMatrix.cpy().scale(getUnitsInPixel(), getUnitsInPixel(), 1));
bitmapFonts.draw(batch, "YO", 0, 1);
batch.setProjectionMatrix(originalMatrix); //revert projection

```

getUnitsInPixel() returns, for example, 1/240f when the height of the screen is 480 in pixels and you've set viewportHeight to 2 units. 2/480 equals 1/240

It is explained in libgdx book in step by step "Canyon Bunny" game creation. Here is one of the implementations I found, which looks like it is based on book: https://github.com/Gizmmo/CanyonBunny/blob/master/core/src/com/packtpub/libgdx/canyonbunny/WorldController.java There sprite is set to have 1x1 units in game space. It is done like you did - with sprite.setSize(1, 1); And here is mentioned how sprite makes magic for us: http://www.badlogicgames.com/wordpress/?p=1403 "Note that there’s no need for the sprite’s dimensions and position to be given in pixels". And after checking things out, I've found that:

## 1. SpriteBatch draw(...x, y...) methods deals with pixels.

All except one method:

```
spriteBatch.draw(texture, 0, 0, 1, 1, 0, 0,
                texture.getWidth(), texture.getHeight(), false, false); // that method draws texture taking (0, 0, texture.getWidth(), texture.getHeight()) to camera viewport at (0, 0, 1, 1) in unit space. So, if your viewport is 2 units tall, then you'll see texture taking half of all visible space in height.

```

## 2. Suppose, we have viewport in 2 units tall:

```
@Override
public void resize(int width, int height) {
    float aspectRatio = (float) width / (float) height;
    camera = new OrthographicCamera(2f * aspectRatio, 2f);
    camera.update();
}

```

Then if you've drawn some fullscreen textures before:

```
spriteBatch.draw(texture, 0, 0)

```

Then, you'll see now only 2 pixels of it! But if you drawn with sprites, all you need is just sprite.setSize(newCorrectWidthInUnits, newCorrectHeightInUnits) and after:

```
sprite.draw(batch);

```

You'll see the same picture on screen. Thats in short, how this works, as I understand. And of course there is a stage with it's own batch drawing logic inside.
> 2 votes

# Answer
It looks like you are using a scale camera for your game objects (the grid). That's fine. However fonts in libgdx are scaled in pixel dimensions and not your game world units. The best course of action here is to maintain two sperate cameras to render your game: world, and ui.

The world camera will be in your world units as you have it now. The ui camera will be in pixel units scaled to the game window. Use the project and unproject methods on the camera classes to position your ui elements correctly. Render the world using the world camera then do a ui pass over that with the ui camera.
> 3 votes

---
Tags: libgdx, fonts, scale
---


title: Comparing two strings in Unity C#

text:
# Question
Title: Comparing two strings in Unity C#
I am trying to compare two strings in C# but even though I print the strings and they are the same, the check always fails. Only one is stored in a variable and the other is hardcoded. I tried using the `==`operator and the `equals` operator. Also tried with using the `IgnoreCase` `StringComparison`option but still nothing. I also checked the length of the string in case there are leading or following spaces or something but it's the same. IF it is any help the string is coming from GlovePIE

What could be going wrong?

# Answer
If you want to be hardcore about it...

```
public static bool StringComparison (string s1, string s2)
{
    if (s1.Length != s2.Length) return false;
    for (int i = 0; i < s1.Length; i++)
    {
        if (s1[i] != s2[i]) {
            Debug.Log ("The " + i.ToString() + "th character is different.");
            return false;
        }
    }
    return true;
}

```

If this returns false, then you are 100% sure that your strings are different. If it returns true, you might have just found a tremendous bug in .NET. This method will also tell you which character is different.
> 2 votes

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


# Question
Title: How could you create an SSX style snow trail in unity3d?
So it SSX (a snowboarding game) when you are snowboarding you leave behind a dents in the snow(like a trail) .It's like how if you take a step in the snow you will leave a footprint behind but with a snowboard you leave a trail of where your snowboard has been. Can you create this or is this not supported by unity? If you can, how? Thanks in advance

# Answer
> 1 votes
Trail or line renderer: http://docs.unity3d.com/Manual/class-TrailRenderer.html. Just have a darker texture to overlay the snow and continuously set a new position for the trail renderer.

# Answer
> 0 votes
You should probably learn more about decals and take a look at this forum post. It looks like what you are trying to achieve. I hope it helps.

---
Tags: unity
---


title: Shadow mapping bone animated model

text:
# Question
Title: Shadow mapping bone animated model
I am trying to get shadowmapping right for my animated models. It works perfectly for static meshes but the animated models are just wiggeling a bit

here's the vertex shader for rendering to the depth texture:

```
#version 400 core

in vec4 inputPosition;
in vec3 inputNormal;
in vec2 inputTexCoord;
in vec4 weights;
in vec4 joint_index;

uniform mat4 bone_matrix[65];
uniform int animate;
uniform mat4 depthMVP;

void main(){
    vec4 pos = inputPosition;

    if(animate != 0) {

        pos = vec4(0);
        vec4 post = inputPosition;

        for(int i=0;i<4;i++) {
            if(weights[i]>0) {

                pos += (bone_matrix[int(joint_index[i])] * post) * weights[i];

            }
        }

    }

    gl_Position = depthMVP*vec4(pos.xyz, 1);

}

```

The animation works fine in the second pass but during the first using the vertex shader above the model vertices don't get transformed instead the whole model rotates a little so i get a depth texture with my model in binding pose rotating around the y-axis a little. Weird because i use the exact same bone transformation code as in the second pass shader. So i'm wondering am i missing something crucial in the vertex shader above

# Answer
Ok i found the problem. It came down to my misconception of when to call glBindAttribLocation. Changes made with glBindAttribLocation will only take effect after calling glLinkProgram. It hadn't been a problem before but in this particular case it got me.

For those on the same rocky path as me i found that the shadows of my animated models were scaled wrong. I'm using the astroBoy\_walk\_Max.dae file from the skeletal animation collada tutorial. The model seems to have a scale of 0.01f so i added a multiplication and a uniform to the depth vertex shader which now looks like this:

```
#version 400

layout (location = 0) in vec4 inputPosition;
layout (location = 1) in vec3 inputNormal;
layout (location = 2) in vec2 inputTexCoord;
layout (location = 3) in vec4 weights;
layout (location = 4) in vec4 joint_index;

uniform float scale;
uniform mat4 depthMVP;
uniform int animate;
uniform mat4 bone_matrix[65];

void main(){
    vec4 pos = inputPosition;

    if(animate == 1) {
        pos = vec4(0, 0, 0, 1);
        vec4 post = inputPosition;

        for(int i=0;i<4;i++) {
            if(weights[i]>0) {
                pos += (bone_matrix[int(joint_index[i])] * scale * post) * weights[i];
            }
        }
    }

    gl_Position = depthMVP*pos;

}

```

scale = 1.0f / model\_scale
> 3 votes

---
Tags: opengl, animation, maps, shadows, skeletal-animation
---


title: How to render infinite universe?

text:
# Question
Title: How to render infinite universe?
I'm curious what are the best practices in game development industry to render 3d universe?

To be more specific:

* The data points are given and static. Each point has position, color and size;
* The entire data set is much larger than available memory;
* User should be able to "zoom out" to see bigger picture at once;

The most naive approach would be to split universe into cubes and render only what's visible. I'm not sure how in this scenario should I implement the "zoom out". Should I precompute cubes for each possible zoom level? Or maybe there are better approaches?

I'm looking for technology agnostic solution.

# Answer
This is based on my speculation and skimming through Celestia's source code.

Celestia allows you to fly around a planet and zoom out to see the whole galaxy. I browsed its source code and found it used an octree, a structure to recursively divide space into 8 octants.

The renderer would render the environment by traversing the octree, and don't traverse far objects deeply.

Celestia also keep track of absolute magnitude of an octant, where the absolute magnitude of an octant is based on the absolute magnitude of the stars inside the octant. If the octant is close together, Celestia renders the stars individually, and if the octant is far away Celestia renders the octant as one star of the octant's magnitude.

Also, there can be meaningful hierarchy attached to objects. For example, if you are close (radius declared in database) to a star, its planets are rendered. If a planet is close enough (a cutoff of pixels on screen), its 3D model is drawn.

Other space games I can name of are Orbiter and Kerbal Space Program, which are closed-source. I also looked into Frontier Galaxy, which has procedurally generated star map. There is a website analyzing how the game works by its disassembly: http://www.jongware.com/galaxy1.html
> 8 votes

# Answer
There's a number of pieces to this puzzle, each of which will provide a deep and interesting rabbit hole of exploration. Some of them are:

* Level of Detail -- automatically (or "manually") choosing detailed or simplified models, or even sprites or just dots, or for objects as they are further away.
* Culling -- choosing to only draw what's needed. This might be what's in the field of view (frustum culling), what's not hidden behind other things (occlusion culling), or other ad hoc methods. (@Alan Wolfe's answer describes some of the ways to organize your data that help facilitate culling.)
* Streaming -- pulling world-data from storage into memory as needed, if it doesn't all fit in memory at once
* Sky box -- very distant objects can be pre rendered onto a sphere that is at "infinite distance" from the camera.

And your own secret sauce will be what combination of these, and other, techniques you use, and when, based on your particular application needs.
> 12 votes

# Answer
Anything that is either hierarchical and/or sparse should help you out here.

There's a lot of empty space, so not having to use storage to represent empty space is a must. A typical hierarchical approach would be something like an Oct tree which recursively subdivides space into 8 smaller cubes, and you can store objects in the smallest cube that they can completely occupy.

An octree is also pretty good for you being able to query it for a list of all objects in a view frustum which will let you get a list of only the objects that are within your viewing angle and aren't too distant. A sparse solution could be something like a sparse grid where you can ask for information about any x,y,z location, but you only have to store information for cells that aren't empty space.

Other common hierarchical approaches used include bsp trees (they split space into 2 half spaces recursively) as well as k-d trees which do similar.

I personally think an octree could be a good start for you, making sure to subdivide only as deeply as needed so you don't waste memory on empty space. also, you might end up wanting a different solution for your static objects versus your dynamic objects.

Some solutions (like bsp) can be very efficient, but take a long time to construct so aren't usually a good choice for moving / changing objects.

Hope that helps, let me know if you have any questions about the details!
> 2 votes

---
Tags: graphics, algorithm, grid
---


# Question
Title: Grab depth buffer with unlockable D3DFORMAT
I'm currently piggy backing on a mod framework (Multitheft Auto) and trying to read the depth buffer in D3DFMT\_D24S8 (DirectX9). I can read it if I change the format to D3DFMT\_D32F\_LOCKABLE and then lock the rectange but this causes the render to be blurred like so:

I'm currently open to hacky methods like finding the pointer to the buffer and reading the depths without properly locking and/or using CUDA. Any advice would be greatly greatly appreciated. Thanks!

# Answer
Turns out setting the resolution to 16 bit instead of 32 caused the blurring to go away. Figuring there was some pixel shader using the depth buffer that was able to deal with 16 bit color / 32 bit depth and 32 bit color / 24 bit depth, but not 32 bit color / 32 bit depth. Thanks @DarthMelkor for the Direct3D Ex suggestion. I may look more into that if there are more problems with changing the depth format. I don't have control over the initial device creation by GTA San Andreas though, so I'm not sure if I'd be able to use the UpdateSurface approach (I've def tried Direct3D 9 and get a format restriction error).
> 0 votes

# Answer
You can read the depth buffer in a pixel shader if you use one of the special formats described at http://aras-p.info/texts/D3D9GPUHacks.html. They are somewhat GPU vendor specific, but you can probably get away with just INTZ support.

That lets you either do what you need to do on the GPU, or to use the shader to copy it to another render target that you can read from more easily.
> 1 votes

# Answer
The old DirectX SDK outlines a method for being able to do this, but it does require that you use Direct3D 9 Ex rather than just plain-old Direct 3D 9. Since 9 Ex is only available on Vista+ this may not suit your requirements.

It's covered in the section titled **Feature Summary (Direct3D 9 for Windows Vista)** and I'll quote it in full:

> **Reading Depth/Stencil Buffers**
>
> Use IDirect3DDevice9::UpdateSurface to read or write depth/stencil data from surfaces obtained from IDirect3DDevice9::CreateDepthStencilSurface or IDirect3DDevice9::GetDepthStencilSurface.
>
> First, create a lockable, depth only or stencil only surface using IDirect3DDevice9::CreateOffscreenPlainSurface. Use one of the following formats:
>
> * D3DFMT\_D16\_LOCKABLE
> * D3DFMT\_D32F\_LOCKABLE
> * D3DFMT\_D32\_LOCKABLE
> * D3DFMT\_S8\_LOCKABLE
>
> Second, transfer data between the depth/stencil buffer and the newly-created lockable depth or stencil surface. The transfer is performed using IDirect3DDevice9::UpdateSurface.
>
> UpdateSurface will fail when both surfaces are a LOCKABLE format or both are non-lockable.
>
> Transferring non-existent data will result in an error (for example, transferring from a non-lockable depth-only surface to a D3DFMT\_S8\_LOCKABLE surface).
>
> The rest of the restrictions for IDirect3DDevice9::UpdateSurface still apply.

As @Adam suggests in his answer, you really should consider whether or not you actually *need* to read the depth buffer back to the CPU. That's not going to be a fast operation whichever way you do it.

I'd suggest that you give more detail about *why* you feel you need to do this, perhaps even making it a separate question; it may well be the case that whatever you're trying to achieve can be done without such a read-back.
> 0 votes

---
Tags: directx9, modding, depth-buffer, cuda
---


# Question
Title: Controlling the movement of player by sprite using Mouse
I want to move the player by pressing down on the mouse and moving around by dragging. The player won't move to the position of the mouse. Instead it should be relative to the players current position.

https://youtu.be/oGSpX6GEYa0?t=5m55s

The way this works, your finger can be anywhere on the screen, and when you move down, the player moves down. This is what I have so far, but it's not as elegant as I want it to be. For example, if your mouse is not moving, it still applies acceleration.

```
public static inline var EASING:Float = 0.1;

private var mouseX:Float;
private var mouseY:Float;
private var vx:Float;
private var vy:Float;
private var distance:Float;

/**
 * Function that is called once every frame.
 */
override public function update(elapsed:Float):Void
{
    if (canMove == false) {
        return;
    }

    if (FlxG.mouse.justPressed) {
        this.mouseX = FlxG.mouse.screenX;
        this.mouseY = FlxG.mouse.screenY;
    }

    // if we are pressing down, we should move ronnie
    if (FlxG.mouse.pressed)
    {
        vx = getVelocityX();
        vy = getVelocityY();
        distance = getDistance(vx, vy);

        if (distance > 0) {
            this.x += vx * EASING;
            this.y += vy * EASING;
        }

    }

    if (FlxG.mouse.justReleased) {
        //
    }

    super.update(elapsed);
}

/**
 *
 * @return
 */
function getVelocityX():Float
{
    return FlxG.mouse.screenX - this.mouseX;
}

/**
 *
 * @return
 */
function getVelocityY():Float
{
    return FlxG.mouse.screenY - this.mouseY;
}

/**
 * Return distance
 *
 * @return
 */
function getDistance(vx:Float, vy:Float):Float
{
    return Math.sqrt(vx * vx + vy * vy);
}

```

# Answer
> 1 votes
Here's one very simple way to do it:

```
package;

import flixel.FlxG;
import flixel.FlxSprite;

class Player extends FlxSprite
{
    public static inline var VELOCITY:Float = 4;

    public function new()
    {
        super();
        // enforce subpixel-rendering for smoother movement
        pixelPerfectRender = false;
    }

    override public function update(elapsed:Float):Void
    {
        velocity.x = getDistanceX() * VELOCITY;
        velocity.y = getDistanceY() * VELOCITY;

        super.update(elapsed);
    }

    function getDistanceX():Float
    {
        return FlxG.mouse.x - x;
    }

    function getDistanceY():Float
    {
        return FlxG.mouse.y - y;
    }
}

```

This doesn't take `FlxG.mouse.pressed` into account at all, but I think that makes sense for this style of input. You wouldn't want the movement to stop abruptly.

---
Tags: mathematics, physics, movement, vector, haxe
---


title: using an int to control events

text:
# Question
Title: using an int to control events
Let me explain -- I'm just looking for a way that I can link a number to a set of methods. I want to randomly generate a "difficulty" int, and pick out an event based on the number I get. IE, if I get an int of 3 I want that to point to a specific event. What's the best way to accomplish this? I was thinking of story the events in lists, but methods can't be in lists. I thought about making the methods into delegates and putting those in lists but that seems unnecessarily complicated. Also, in the future I think I'd want to put multiple events at each level which would sort of make putting them into array or lists difficult.

# Answer
Provided all the events have the same signature:

```
delegate return_type Event(parameter_list);
Event[] events = { new Event(Event1),
                   new Event(Event2),
                   //.....
                   new Event(EventN) };

//in your caller method
events[random_int](parameters);

```

Delegates are the fastest and easiest method to accomplish what you want. And if you add more events, just add them to the array. It shouldn't be too difficult ;)
> 1 votes

# Answer
So you want to generate a random integer, and use the number generated to choose between a set of events. Seems like the best thing you could use would be `switch case`?

Switch :

```
int caseSwitch = X; //your random generated integer

switch (caseSwitch)
{
    case 1:       //if it's equal to 1 then
        Console.WriteLine("Case 1");
        break;
    case 2:         //if it's equal to 2 then
        Console.WriteLine("Case 2");
        break;
}

```

Is this what you're looking for?
> 0 votes

---
Tags: unity
---


# Question
Title: Creating metadata/pack files for an existing sprite sheet
I've just bought Oryx's Roguelike Tileset pack and I use LibGDX (flixel-gdx to be precise).

My question is, given this pre-made sprite sheet format, what's the best way to integrate the sprites into the game I'm making?

LibGDX uses `TexturePacker`, but that needs a special .pack file with metadata like where the sprites are located. I can't see a way to generate these from an existing spritesheet.

Is there any other recommended technique?

# Answer
I would also be interested in hearing how other people manage their artwork in libGDX.

I'm sure most users of libGDX will encounter this as soon as they try to use spritesheets from other sources (not made in-house, with libGDX in mind).

I had the same issue, trying to use resources from OpenGameArt.org.

I have solved this problem two different ways.
The first was to use a spritesheet unpacker, which basically allows you to provide parameters for padding round the margins, the size of the tiles/sprites, then the horizontal and vertical padding between the sprites. The unpacker then extracts the individual files into a directory, which you can then re-pack using libGDX-aware utility, to take the directory of individual files (which you should rename before this, so the atlas you get back will have useful aliases) and re-build them into a single spritesheet with accompanying atlas (pack file). I can't find the one I used initially, but here's another one that's actually a bit more flexible: Alferd Spritesheet Unpacker

The second method, and the one I'm using on my current work, is to manage my assets myself for each level, via an XML file that I load at level-load-time. I implemented a custom asset manager class that takes XML files wherein I provide the spritesheets, referenced by a name, then provide named textures or sprites which take the spritesheet name, then an offset and size into that spritesheet to get the individual sprites. This sounds tedious, but once you standardize your artwork, it's very painless. Then I have another XML node-type for animations, which allows me to specify individual frames from one or more spritesheets. As long as my artist doesn't move things around, they are free to make tweaks, without having to modify the XML asset file for the level. This method works particularly well in my current project, which is a 32x32 tileset game, where I just keep my art assets in grids in .PNG files whithout any padding. Then I refer to the assets by tile coordinates, rather than pixel offsets and sizes.

Even though libGDX provides these helpful tools (packed spritesheets / texture atlases / etc...), in my limited experience, I've found I like my way better.

Your mileage may vary. If you've just got a set of fixed assets, like the set you purchased, you may want to just go through the unpack/rename/re-pack process I mention in my first method above. If you want more flexability, you'll probably wind-up doing your own asset manager as I did in method two, above, or at least a customized wrapper around libGDX's built-in asset manager.

Good luck!
> 1 votes

# Answer
You could pretty easily manually type up an atlas (the metadata pack file that TexturePacker generates.) It's just a plain text file with entries that point to specific images contained in the packed png. Look at a sample .atlas file and just Notepad++ up your own that imitates the format and points to the individual sprites on your sheets.
> 0 votes

---
Tags: libgdx, spritesheet, texture-atlas
---


# Question
Title: HLSL identity matrix multiplication not producing identical output
I'm debugging my very simple shader and it's led me to a point where, as a quick test, I'm performing a multiplication of my position vector with an identity matrix. If I *don't* perform this multiplication, my position is preserved and I get a nice-looking quad in the middle of the screen, as expected. If I multiply with an identity matrix, my quad goes away, leaving only the background. I'm sure I'm missing something, or doing something stupid (or both), but I have no idea what that is. My code is below:

```
struct VOut
{
    float4 position : SV_POSITION;
    float4 color : COLOR;
};

struct VIn
{
    float4 position: POSITION0;
    float4 color: COLOR0;
    float2 texcoord: TEXCOORD0;
    float2 pad: PADDING0;
    matrix translate: CUSTOM0;
};

matrix Identity =
{
    { 1, 0, 0, 0 },
    { 0, 1, 0, 0 },
    { 0, 0, 1, 0 },
    { 0, 0, 0, 1 }
};

VOut VSMain(VIn input)
{
    VOut output;
    float4 pos = float4(input.position.x / 4, input.position.y / 4, 0.0, 1.0);
    matrix trans = Identity;
    pos = mul(pos, trans); // <-- THIS LINE HERE DOESN'T DO WHAT I EXPECT
    output.position = pos;
    output.color = input.color;
    return output;
}

```

The line marked above should produce identical output to the `pos` input, but it does not.

# Answer
Turns out I needed to make the identity matrix `static`.
> 1 votes

---
Tags: hlsl
---


title: Unable to animate sprite renderer

text:
# Question
Title: Unable to animate sprite renderer
Why am I unable to add any of the sprite renderer's properties? How can I do it? On all the other properties like transform and so on, when I open them I have a + indicator in the right if I want to add any.

# Answer
> 1 votes
Move the bottom scroll bar to the right to reveal the plus signs

---
Tags: unity
---


# Question
Title: How could I get composite rigid body into unity
I am developing a game, in unity, that has accurate destruction physics and from my understanding unity uses plain old rigid body physics. I was wondering if there was a way to bring composite rigid body physics into unity through a plug in or library or some other way?

Thanks, nova

edit: So composite rigid body physics is almost exact like normal rigid body physics. But the main difference is that in composite rigid body physics all of the assets will not be considered physics based objects until an outside force hits them. For example a building and all of that parts it is made out of will not be processed as physics based objects until say a rocket hits it. This method of composite rigid body physics uses much less memory because it is only processing what is being affect and not everything else.

# Answer
> 1 votes
Using the same metaphor of building and rocket and assuming that as the Rocket is flying through the air doing its stuff then it will already be a dynamic, simulated object with a rigidbody, a possible quick way to do this would be to have a collider with isTrigger = true on the building.

When OnTriggerEnter() fires, you can then add a rigidbody and any other scripts needed to control it to the building using GameObject.AddComponent()

---
Tags: unity, rigid-body-dynamics
---


# Question
Title: How do I have a player also be a server? [Unity 2d]
I'm trying to make a game in Unity 2D, and I need a player to be a host because I can't afford dedicated hosting. Each client will have files that the server (and other clients) need to be able to look at through the game, and there will be a chat client. Can anyone direct me to where I need to look for this specific type of multiplayer? Everything I've seen seems to assume a dedicated host.

# Answer
Game host: The machine hosting the game
Host server: An application which manages connections and transfer of data between clients
Client: A copy of your game participating in the multiplayer game

If you wanted to do it yourself, you'd need to write a host server which is bundled with your game. When one of the clients selects 'host game' (or similar) you'll fire up the host server on the game host and have that client connect to it. From there, you'll need some way for other clients to connect to the host server (perhaps search the network for an instance of your host server and send a join game request to it)

Networking is kinda complex... Unity has a bunch of built-in networking. Taking a look at the docs is always a good starting point: http://docs.unity3d.com/Manual/net-HighLevelOverview.html
> 1 votes

---
Tags: unity, multiplayer
---


# Question
Title: Authentication between client, central server, and player ran server
I am developing an open source game that uses a client-server scheme similar to Minecraft. We will control the central authentication server that verifies an account is valid, while players will run their own servers.

Authenticating the client is simple, but **how can the server know that the user is valid, without having any access to is credentials or session token?**

For example:

* **Client \> Auth Server:** Sends user credentials.
* **Auth Server \> Client:** Responds with a session ID if valid login.

Then, the client can connect to the server, but the server has no way of verifying is the client is who it says. These servers are ran by players, which make it easy for them to modify the server and collect the user data. (Only the central auth server can be trusted)

The authentication server could accept TCP connections, but I wonder if HTTPS would be easier in this case, as getting a response is easier than establishing a listener on each side, especially for only a few requests.

# Answer
Edit: After posting this I realized it's almost the exact same answer given by Ali.S (slightly different but the overall approach is the same.) It started out as something completely different though.

This method assumes that all communications are being held over a series of secure tunnels. How you achieve this doesn't matter. I would suggest TLS, but that's just me.

1. **Client =\> Game Server** The client connects to the game server and initiates a login session.
2. **Game Server =\> Auth Server** The game server connects to the auth server and requests a session ID token from the auth server. This connection is kept open to listen for the login success/failure.
3. **Game Server =\> Client** The session ID token is sent back to the client.
4. **Client =\> Auth Server** The client sends the session ID to the auth server along with the username and password of the user, and some information about the server (IP, TLS public key, etc. See footnotes)
5. **Auth Server =\> Game Server** The auth server then sends information about the login to the game server (success state, username, stats, etc) using the session ID provided by the client.
6. **Game Server =\> Client** The game server tells the client that the auth was successful, and lets them in.
7. All connections except for the initial client to game server connection are now torn down.

Alternatively, you can give the game servers a dedicated port to listen for logins. If you choose this route, then the flow would look like this:

1. **Client =\> Auth Server** The client sends the username, password, and server IP to the auth server.
2. **Auth Server =\> Game Server + Client** If the login is successful, the auth server sends a unique token to the game server and client. Send the IP of the client to the game server too, so that the token can't be stolen.
3. **Client =\> Game Server** The client then sends the token to the game server, where it is then verified and deleted on the game server. The game server then lets the client in.

This second approach would make the overall implementation a bit easier.

Footnotes:

The reason I specify that some information should be sent about the game server to the auth server is to harden the process against spoofs. The server can verify the information to make sure that it is authorizing the connection that the player expects.

Session IDs would *not* have to be cryptographically secure, though it would make spoofing connections somewhat harder if they were.

If you do choose to go the TLS route, you can set up a signing server that signs all the certs used by your infrastructure, and add it as a trusted CA in the client/server software. So long as you don't let your signing cert get loose, you'll be able to provide some decent authentication.

For the sake of mitigating DoS attacks, make connections timeout after 20 or fewer seconds. If it lasts longer than that, then something is wrong and you don't need to wait 3 minutes waiting for the connection to timeout on its own.
> 3 votes

# Answer
The client should have a **private** and a **public** key.

The private key should be what the unique identifier that the client receives from the authentication server. The public key should be also sent to the client.

Before the client connects to a game server, it should send a message with its private key and the ip of the game server it wants to connect to, to the authentication server. The authentication server should then verify and find the match for the private key and store the public key in its records.

The game server that the client is connecting to should send a request to the authentication server after obtaining the public key of the client. If the authentication server can verify that the client wants to connect to that IP of the game server, send that it's an okay client back. The game server should then allow the client to connect.

*The private key is only used for authentication of the client so that the game server doesn't obtain the real authentication id.*
> 2 votes

# Answer
There are multiple solutions that I can think of, but here is the most secure one:

1. client connect to server.
2. client requests an authentication bridge.
3. server connects to auth server, acting as a proxy between player and auth. server.
4. client and auth server, form an SSL session over this newly formed bridge.
5. using this secure connection over bridge, client logins into auth server.
6. auth server tells game server whether the login was successful or not, over some other TCP connection. then disconnects it's bridge/login connection.
7. client and game server can now resume communication (only) over already existing connection (which was used for authentication).

Note that, in this scenario game server actually has no way of eavesdropping, even though the whole authentication is passing through it. for the same reason your ISP can't monitor what packets you send to Facebook, or are coming from facebook.
> 1 votes

# Answer
The way I would do this is by having Auth server send token to Client after login along with list of validated Game servers (so that the Client can be sure the Game server is valid).

Then the Client would send the token to the Game server, which would then send it to Auth server to confirm that this is the valid client.

Login:

1. **Client to Auth server:** username and encrypted password
2. **Auth server to Client:** token

Later when joining a Game server:

3. **Client to Game server:** the previously mentioned token
4. **Game server to Auth server:** again the token
5. **Auth server to Game server:** if token is valid then OK signal
6. **Game server to Client:** allows client to join
> 1 votes

# Answer
How about signing a JWT token with a secret only the central auth and player server knows? It lets you sign json, which can be verified later.
> 0 votes

---
Tags: c#, client-server, authentication
---


title: How to create a map from graph

text:
# Question
Title: How to create a map from graph
I want to draw a 2d polygon map based on data provided by another source to ease analysing actions on the map. The data has the following format:

```
1 ['2', '4', '5', '7', '17', '10']
2 ['1', '3', '4']
3 ['2', '11', '4']
4 ['1', '2', '3', '11', '13', '18', '5']
5 ['1', '4', '18', '17']
6 ['7', '8']
...

```

The first number is the ID of a node, the following list contains the IDs of its neighbours. As a node's number of neighbours differs I need to draw a polygon map.

So I tried to use Voronoi polygons for the map representation. The problem is: How can I determine the points to satisfy all neighbourhood relations? I guess my first try is more or less an error in my try and error cycle. I used the sfdp tool of graphviz to get the point positions of the graph:

Using the positions of the points resulted in the following map representation:

The problem of this approach is that for example nodes 4 and 1 are neighbours but in the Voronoi diagram they aren't because of the position of the nodes. So for me this approach failed.

Googling, I found a lot of tutorials generating maps with polygons or tiles but I haven't found out yet how I can create a map for my given data. I guess there is an approach using (multiple) hexagons/triangles/squares or a mixture to achieve what I need but I don't know what I shall search for.

Is there a keyword or an algorithm which can help me here?

**Update/Result**: For completeness: This is my result after using the suggestions of the accepted answer:

# Answer
> 12 votes
What you want is to produce a **dual graph**; that is, a graph produced by converting *faces* to *vertices*, and connecting them based on adjacent faces in the original graph. Example:

The problem, as you can see, is that if you want to keep the same layout of the graph, you'll get some really curvy edges in the dual graph. Also, you'll often end up with a *multigraph* \- a graph where some vertices have multiple edges between them. It is guaranteed to be planar though, so that's something.

To use your example, we can produce the dual graph in the following steps:

**Step 1: For each face in the original graph, create a vertex**

Note that we create an outer "ring" to represent the outermost "vertex" - this is so we can have a nicer looking graph at the end, without the crazy curvy edges.

**Step 2: For each edge in the original graph, connect the two face-vertices with an edge**

Also, you're going to have to do something about these edges not overlapping each other. The gap between 3 and 12 is especially problematic. These new edges may need to be bendy to make this possible. It's what you get for having a concave graph.

**Step 3: Play Risk**

# Answer
> 1 votes
If the first image, where each point is a small square with certain color, is what you are searching for, you need to build the Delaunay's triangulation.

---
Tags: algorithm, graph
---


title: 2D day night mapping

text:
# Question
Title: 2D day night mapping
I'm looking for this kind of effect MINUS the lights and snow (Another problem).

* It needs to change depending on the time of year.
* Doesn't need snow or city lights.

Now I'm pretty new to shaders (learnt them yesterday in my spare time) but so far I have achieved:

This moves across the screen display light on both sides.

Now I'm completely lost, as to how I can make it seem like a light map I.E. it needs to be more square/sharper (As it's going off the edges) & have the bottom and top times of year.. I though maybe I could pass sphere mesh to the vertex? Or do something with the map-normal. Or maybe use blending with two textures but I've looked around and it looks extremely difficult.

Code I have so far:

**Fragment / Pixel shader:**

```
    //attributes from vertex shader
varying vec4 vColor;
varying vec2 vTexCoord;

//our texture samplers
uniform sampler2D u_texture;   //diffuse map
uniform sampler2D u_normals;   //normal map

//values used for shading algorithm...
uniform vec2 Resolution;      //resolution of screen
uniform vec3 LightPos;        //light position, normalized
uniform vec4 LightColor;      //light RGBA -- alpha is intensity
uniform vec4 AmbientColor;    //ambient RGBA -- alpha is intensity
uniform vec3 Falloff;         //attenuation coefficients
uniform float lightX;         //X Position of light. Can also feed Y for times of the year.

void main()
{
    //RGBA of our diffuse color
    vec4 DiffuseColor = texture2D(u_texture, vTexCoord);

    //RGB of our normal map
    vec3 NormalMap = texture2D(u_normals, vTexCoord).rgb;

    int numberOfLights = 3;
    vec3 lightPoses[3];
    vec3 lightDirections[3];
    //LightX goes to 0, then back to 1.
    lightPoses[0] = vec3(lightX - 1.0, LightPos.y, LightPos.z);
    lightPoses[1] = vec3(lightX, LightPos.y, LightPos.z);
    lightPoses[2] = vec3(lightX + 1.0, LightPos.y, LightPos.z);

    //TODO Introduce one extra light for top and bottom. OR Figure out how to squash the Y.
    //TODO Needs to be sharper light.

    vec3 Sum = vec3(0.0);

    //Go though both lights.
    for(int index=0; index < numberOfLights; index++)
    {
        //The delta position of light
        vec3 LightDir = vec3(lightPoses[index].xy - (gl_FragCoord.xy / Resolution.xy), LightPos.z);

        //Correct for aspect ratio
        LightDir.x = LightDir.x * (Resolution.x / Resolution.y);

        //Make it bigger. (smaller the value the bigger.)
        LightDir *= vec3(0.55, 0.4, 1.0);

        //Determine distance (used for attenuation) BEFORE we normalize our LightDir
        float D = length(LightDir);

        //normalize our vectors
        vec3 N = normalize(NormalMap * 2.0 - 1.0);
        vec3 L = normalize(LightDir);

        //Pre-multiply light color with intensity
        //Then perform "N dot L" to determine our diffuse term
        vec3 Diffuse = (LightColor.rgb * LightColor.a) * max(dot(N, L), 0.0);

        //pre-multiply ambient color with intensity
        vec3 Ambient = AmbientColor.rgb * AmbientColor.a;
        //Because there are more lights, take off total ambient power.
        Ambient *= vec3(1.0 / float(numberOfLights));

        //Calculate attenuation (The amount of fade the light has.)
        float Attenuation = 1.0 / (Falloff.x + (Falloff.y*D) + (Falloff.z*D*D));

        //the calculation which brings it all together
        vec3 Intensity = Ambient + Diffuse * Attenuation;

        vec3 FinalColor = DiffuseColor.rgb * Intensity;

        Sum += FinalColor;
    }

    gl_FragColor = vec4(Sum, DiffuseColor.a);
}

```

**Vertex Shader:**

```
//combined projection and view matrix
uniform mat4 u_projTrans;

//"in" attributes from our SpriteBatch
attribute vec4 a_position;
attribute vec4 a_color;
attribute vec2 a_texCoord0;

//"out" varyings to our fragment shader
varying vec4 vColor;
varying vec2 vTexCoord;

void main() {
    vColor = a_color;
    vTexCoord = a_texCoord0;
    gl_Position = u_projTrans * a_position;
}

```

# Answer
What you need is to retroproject the point on your map, from the `inverse Mercator` into 3d space, then place the sun as a directional light (not point like your image shows), and adjust the point for earth tilting (according to earth-sun rotation plane), then you can evaluate the light.

It will automatically give you the weird valley shape that we see in airplanes navigation screen, and the little gif you point to.

You don't need to actually have 3d data. but you need to do 3d calculations in the shader. This is going to be a bit tad hard to debug because the 3d elements you will manipulate never have a visual representation. So the only way is to get the math right by trial error.

You could only avoid going to 3d space by writing the formulas created by the steps described above, and compacting the whole sequence in just one formula. It would have the same effect, but it needs harder algorithm planning (e.g. on paper).

1. take fragment positions (screen pos, via gl\_fragcoord or something)
2. retro project on the sphere with reverse mercator.
3. place in sun-space. (e.g. by using a position matrix for the earth)
4. usual directional light compute (n dot l)
5. write out color

EDIT:

I did it for you

```
uniform float time_0_X;    // day/night cycle
uniform vec2 fInverseViewportDimensions;

#define PI 3.1415926;

void main(void)
{
   // 2d coordinates from the screen. but you should take them from your quad's UV.
   vec2 coord = 0.5 * vec2(gl_FragCoord.x + 0.5, gl_FragCoord.y + 0.5) * fInverseViewportDimensions;

   float earthTilt = radians(15);   // somewhere around spring ?

   // transform into cylindrical coordinates:
   vec2 angles = vec2(coord.x * 2, coord.y) * PI;
   angles.y += earthTilt;  // apply as an offset. this is the easiest way to go.
   angles.x += time_0_X;
   vec4 sincos;
   // get sincos of both angles for later use.
   sincos.xy = sin(angles);
   sincos.zw = cos(angles);

   // make an unitary vector in the direction of the 2 angles. start pointing to z. (usual convention)
   vec3 dir = vec3(0, 0, 1);
   // make the first rotation matrix about Y axis.
   mat3 rotmat = mat3(sincos.z, 0, -sincos.x,
                      0, 1, 0,
                      sincos.x, 0, sincos.z);
   // rotate dir around Y
   dir = rotmat * dir;
   // make an orthogonal, still on the XZ plane.
   vec3 dirortho = vec3(dir.y, -dir.x, 0);
   // we are going to need to rotate about this "dirortho" axis by angles.y.
   // make a rotation about X that corresponds to the same angle:
   mat3 rotx = mat3(1, 0, 0,
                    0, sincos.w, sincos.y,
                    0, -sincos.y, sincos.w);
   // make a vertical:
   vec3 vert = vec3(0, 0, 1);
   // we have a TBN basis, make a matrix out of it to change space into this new rotated space.
   mat3 tbn = mat3(dirortho, dir, vert);
   // change the rotx matrix into this new tbn base:
   mat3 rotaboutortho = rotx * tbn;
   // finally:
   dir = rotaboutortho * dir;

   // now light it:

   vec3 sunlight = vec3(1,1,1); // white
   vec3 lightdir = vec3(0,0,1);  // come from somewhere in the plane xz

   // lambert irradiance evaluator, not normalized by PI (non physical based):
   float lambert = dot(lightdir, dir);  // dir is also the normal at your point.

   // do a trick here, we are going to amplify and saturate the lambert factor to avoid to create smooth regions
   // and make a hard gradient from day to night.
   float hard = clamp(lambert * 1000, 0, 1);
   vec3 color = sunlight * hard;

   gl_FragColor = vec4(color, 0);
}

```

You can put this in rendermonkey if you want to try. I used the GL2, screenspace samples, "nightsky" effect as a base.
The code in its current state is giving a wave of black and white, I'm not sure about the degree of correctness but it seems to look quite reasonable.
You notice I didn't use inverse mercator, but inverse cylindrical, because from the look of your earth texture, Greenland is quite compressed so it must be a cylindrical projection and not mercator.
> 4 votes

---
Tags: shaders, glsl, c, fragment-shader
---


# Question
Title: Smooth Shapes in libgdx using ShapeRenderer
I am using ShapeRenderer in libgdx to draw my only character to get rid of texture in my game. But I am not getting quality results. Circle edges are distorted. I tried with high resolution and also by reducing size of character but result was same.

I go through This answer , it is not applicable on ShapeRenderer.

Is there anyway I can apply any filter or anti-aliasing to make it look good?

Is it worth to draw using ShapeRenderer to get rid of a high resolution texture? I am able to induce 3d like effect by drawing lots of rectangle, circle, lines, curves etc. would it optimize the speed and fps of my game?

**Code:**

```
package com.test.com;

import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType;

public class shapeRenderer implements ApplicationListener {

public OrthographicCamera camera;
int w,h;

ShapeRenderer sr;
    @Override
public void create() {
//Device width and height
w=Gdx.graphics.getWidth();
h=Gdx.graphics.getHeight();
camera = new OrthographicCamera();
camera.setToOrtho(false, w, h);     // it is same as camera .setToOrtho(false);
camera.update();
sr= new ShapeRenderer();
Gdx.graphics.setContinuousRendering(false);
}
@Override
public void resize(int width, int height) {
// TODO Auto-generated method stub
}
@Override
public void render() {
Gdx.gl.glClearColor(107/255f, 107/255f,107/255f, 1);
//Gdx.gl.glClearColor(190/255f, 190/255f,190/255f, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
camera.update();

        float x1=w/3;
        float y1=h/3;
        float cc=w/2;
        sr.begin(ShapeType.Filled);
        sr.setColor(290/255f, 190/255f,190/255f, 1);
        sr.rect(x1,y1, cc,cc);
        sr.setColor(107/255f, 107/255f,207/255f, 1);
        cc=cc/2;
        sr.triangle(x1, y1, x1+cc, y1, x1, y1+cc);
        sr.setColor(290/255f, 290/255f,290/255f, 1);
        sr.circle(x1+cc,y1+cc, (cc*(2^1/2))/2);
        sr.end();
}
@Override
public void pause() {
// TODO Auto-generated method stub
}
@Override
public void resume() {
// TODO Auto-generated method stub
}
@Override
public void dispose() {
// TODO Auto-generated method stub
}
}

```

# Answer
> 7 votes
You could try turning on multi-sampling when applying the application configuration. The Multi Sampling Anti Aliasing is controlled with the `numSamples` property for `AndroidApplicationConfigration` and with the `samples` property on the `LwjglApplicationConfigurtion`. So if you want to turn on anti aliasing for the desktop version you'd do something like;

```
public static void main(final String[] args) {
  final LwjglApplicationConfiguration cfg = new LwjglApplicationConfiguration();
  cfg.samples = 4;
  new LwjglApplication(new YourGameClass(), cfg);
}

```

A higher value for `samples` will mean a higher degree of anti-aliasing, but also a lower performance. Also, if it's not supported it will just fall back to the normal behaviour.

---
Tags: libgdx, rendering
---


# Question
Title: Track two objects on the screen at the same time
I want to keep two objects visible at the same time. My current idea is to calculate a bounding box that contains the two objects and then zoom and rotate the camera so the whole box is visible, is there a different way to approach this problem?

# Answer
This article by Itay Keren excellently covers camera systems: https://docs.google.com/document/d/1iNSQIyNpVGHeak6isbP6AHdHD50gs8MNXF1GCf08efg/pub?embedded=true

He explains a plethora of 2D camera techniques, along with their advantages and disadvantages. This should let you design the perfect camera for your use case.

You'd probably be most interested in zoom-to-fit, anchoring, region-focus and multi-focal camera techniques.

As he covers too much material to summarize in a small reply here, I hope this link-only reply covers what you need.
> 1 votes

---
Tags: 3d
---


title: unity3d - Object keeps falling down

text:
# Question
Title: unity3d - Object keeps falling down
I have an object that moves towards another object using this line :

```
transform.position = Vector3.MoveTowards(transform.position, target.transform.position, speed * Time.deltaTime);

```

this is it's attributes:

It doesn't use gravity, kinematic and it's Y position is frozen, but it keeps falling to the floor and colliding with it. How do prevent that and keep it floating ?

# Answer
> 0 votes
```
transform.position = Vector3.MoveTowards(transform.position, target.transform.position, speed * Time.deltaTime);

```

You do know that if the target's position is on the ground, then your object's position will also try to match the objects's `Y` position. You can try to make an object and check all the constraints, and it will still work if you give it a Translate script, because scripts tend to override constraints.

If you want to make your object go to the target, but still keep his `Y` position, you could just make a new target vector :

```
new Vector3(target.transform.position.x, this.transform.position.y, target.transform.position.z);

```

and make this the target, so your objects keeps his `Y` position since he's already in it, and translates on the `XZ-plane` instead.

---
Tags: unity, physics, rigid-body-dynamics
---


# Question
Title: How to apply a script to multiple Objects in Unity?
In Unity, I've almost 200 or more objects. I wish to apply single script to all those objects.

I'm a beginner & learning scripts in Unity.

**Edit**: At the time of editing the scene itself.

# Answer
Here are the steps for applying scripts to multiple objects.

* Step 1. Select all your objects from `Hierarchy` panel.
* Step 2. Then from `Project` panel drag & drop your script into `Inspector` panel.
> 4 votes

# Answer
You can add script at runtime. You can create an empty objects with a script that "browse" the 200 or more objects and atach the sript to each of them

AtachScriptAtRunTime

Example: to add the script named FoobarScript to the game object use:

```
gameObject.AddComponent ("FoobarScript");

```

Clearly you must recognize all the objects. (example you can use FindGameObjectsWithTag) Full example:

```
objList = GameObject.FindGameObjectsWithTag("MeaningfullTagName");
foreach (GameObject obj in objList ) {
   obj.AddComponent ("YourScript");"
}

```
> 2 votes

---
Tags: unity, unityscript, gameobject
---


title: 3D collision for non mathematician

text:
# Question
Title: 3D collision for non mathematician
I am having an extremely hard time understanding smooth 3D collision. I have spent a month trying to figure out the math and still cannot get perfect collision detection that perform the same way as in games such as Quake.

I've resorted to a virtual 2D rectangle collision model applied to 3D plane, but it's full of bugs and doesn't handle slopes. It seems that very complex math is required like matrices and vectors. There are lots of tutorials online but they are full of mathematical symbols and it's impossible for a math novice like me to understand it, I also don't have time to go through a mathematics basics from the beginning. Is it possible to do collision without vectors or matrices or a guide somewhere that can explain in non mathematical terms how to implement smooth collision? How can a nonmathematician overcome 3D math?

# Answer
> 3 votes
If you want to calculate collision really fast, and without very complex math, use bounding spheres or cubes.

If you have a bounding sphere for each of the two objects, you would like to detect collision, it's really simple:

Sum the radius of the two sphere, and if it's less than the distance of the two objects, then are collided, else not.

---

Even the game engines don't calculate the collision for each triangle, they generate collision objects, which are simpler than the original ones

# Answer
> 2 votes
Vector math are really essential to detect proper collisions and the information to resolve it the properly. But its not that hard really:

Just 4 things you need to know about vectors to get started:

1. Its just basic addition, subtraction, multiplication with the concept of doing it on "multiple" components at once (X, Y, Z in 3D and X, Y in 2D) - but each separatly and independently.
2. Knowing that vectors are just a direction including a magnitude from a specific origin is the key to understanding it properly. Visualizing helps to understand it much better!
3. The dot product is the key to solve most of the problems you encounter. Dot products are most of the time used as vector projections.
4. Unit vectors just represents a direction the vectors points to. Every unit vector must have a magnitude of one.

# Answer
> 0 votes
Sphere collision is definitely the easiest to implement. Simply do distance checks between 2 objects. I.e.:

```
if ((ObjectA.Position - ObjectB.Position).magnitude > ObjectA.Radius + ObjectB.Radius)
{
    //Collision
}

```

For walls, you can use axis-aligned bounding boxes. For a sphere object, its bounding box min/max is its position added or subtracted its radius.

---
Tags: collision-detection
---


title: Unity Change Sceneview to camera view

text:
# Question
Title: Unity Change Sceneview to camera view
On selecting camera, I get the camera preview.

In Unity, while editing the scene, I wish to switch in such a perspective view that is exactly visible by the main camera.

Is there a short cut to change the view?

# Answer
> 2 votes
Selecting the Camera Object and `Ctrl`+`Shift`+`F` seems to do the work in Unity5.

# Answer
> 1 votes
try GameObject Menu-\>Align View To Selected.

"Select the Camera (GameObject) that you would like to look through while in the Scene view. Then go to the "GameObject" Menu and select "Align View to Selected." "

---
Tags: unity, game-design, camera, scene, view
---


title: Game Object, components priority?

text:
# Question
Title: Game Object, components priority?
So, my first attempt to create a component based game object is this:

```
class GameObject;

class GameObjectComponent
{
public:
    virtual ~GameObjectComponent();
    virtual void Update(GameObject* obj, const sf::Time& deltaTime) = 0;
};

class GameObject
{
public:
    GameObject();
    virtual ~GameObject();

    virtual void Update(const sf::Time& deltaTime);
    virtual void AddComponent(
      std::unique_ptr<GameObjectComponent> component,
      std::string componentName);
    virtual GameObjectComponent* GetComponent(std::string componentName);

    float GetVelocity();
    float AddVelocity(float velocity);
    void SetVelocity(float velocity);
    sf::Vector2f GetPosition();
    sf::Vector2f MovePosition(sf::Vector2f movement);
    void SetPosition(sf::Vector2f position);

private:
    float mVelocity;
    sf::Vector2f mPosition;
    std::unordered_map<std::string, std::unique_ptr<GameObjectComponent>> mComponents;
};

```

**The cpp**

```
#include "GameObject.h"

namespace Engine{
GameObjectComponent::~GameObjectComponent()
{
}

GameObject::GameObject()
{
    mVelocity = 0.f;
    mPosition = sf::Vector2f(0.f,0.f);
}

GameObject::~GameObject()
{
}

void GameObject::Update(const sf::Time& deltaTime)
{
    for (
      auto iterator = mComponents.begin();
      iterator != mComponents.end();
      ++iterator)
    {
        iterator->second->Update(this, deltaTime);
    }
}

void GameObject::AddComponent(
  std::unique_ptr<GameObjectComponent> component,
  std::string componentName)
{
    mComponents[componentName] = std::move(component);
}

GameObjectComponent* GameObject::GetComponent(std::string componentName)
{
    return mComponents[componentName].get();
}

float GameObject::GetVelocity()
{
    return mVelocity;
}
float GameObject::AddVelocity(float velocity)
{
    mVelocity += velocity;
    return mVelocity;
}
void GameObject::SetVelocity(float velocity)
{
    mVelocity = velocity;
}
sf::Vector2f GameObject::GetPosition()
{
    return mPosition;
}
sf::Vector2f GameObject::MovePosition(sf::Vector2f movement)
{
    mPosition += movement;
    return mPosition;
}
void GameObject::SetPosition(sf::Vector2f position)
{
    mPosition = position;
}
}

```

and it works, but now I'm worried about priority.

Let's say I have these components: Movement, Phyisic, Renderer, NetworkSync then they should run in order, otherwise the player could be rendered in the wrong spot, make a movement they should be able to do, or don't sync correctly with other players.

I'm not sure how to handle this without tanking the performance, and without losing too much flexibility.

Any suggestions?

Thank you.

# Answer
> 1 votes
One way you could achieve what you need is to add a "priority" attribute to your GameObjectComponent; then add a mComponentsInOrder vector to your GameOjbect and keep ordered references in order, and sort it when you add new components.

```
class GameObjectComponent
{
public:

    virtual ~GameObjectComponent();
    virtual void Update(GameObject* obj, const sf::Time& deltaTime) = 0;
    static bool sortOnPriority(
      const GameObjectComponent& a1,
      const GameObjectComponent& a2)
    {
      return a1->mPriority > a2-mPriority;
    }
private:
    std::string mComponentName;
    int         mPriority;
};

class GameObject
{
private:
  std::vector<GameObjectComponent*> mComponentsInExecOrder;
}

void GameObject::AddComponent(
  std::unique_ptr<GameObjectComponent> component,
  std::string componentName)
{
    mComponents[componentName] = std::move(component);
    mComponentsInExecOrder.push_back(component.get());
    std::sort(
      mComponentsInExecOrder.begin(),
      mComponentsInExecOrder.end(),
      GameObjectComponent::sortOnPriority);
}

void GameObject::Update(const sf::Time& deltaTime)
{
    for ( auto item : mComponentsInExecOrder )
    {
      item->Update(this, deltaTime);
    }
}

```

The vector does not own the components, so you have to manage it when you add and remove components to/from your game object, but they're in the proper order when you update the gameobject.

I haven't tested this exact code so I'm not sure this works out of the box (the sort infrastructure), so it might need to be refined.

Also, if all your components have a name, why isn't the name *inside* your component object instead of having to carry it around like you seem to be doing?

One more thing; you may have a design flaw: you seem to be using a sort of ECS; now I wonder why your "physics" (velocity/movement/position) properties are set on the GameObject itself and not within components. Is your graphics component required to know about the velocity?

A last observation, you might want to try and pass your strings by const-by-ref instead of plainly copying them around like your code is currently doing it; you might get a bit of speed in there!

**P.S.**

Something you should be aware of (from www.cplusplus.com):

> `unordered_map` containers are faster than `map` containers to access individual elements by their key, **although they are generally less efficient for range iteration** through a subset of their elements.

---
Tags: c++
---