# Question
Title: How can I get data from the previous frame in OpenGL 2.0 with GLSL?
First off, this is a Uni assignment, but the lecturer is stumped too.

I am trying to imitate a heat lamp. The goal is to mimic what a thermal camera might see while looking at the sphere which is under the influence of the heat lamp.

To do this I need to get information about the heat values of the vertices/fragments from the previous frame, I know that OpenGL doesn't provide a way to do this so I need to 'export' the values back to C++ so that C++ can forward them to the next frame. How do I do that? I was thinking with a texture but ran into some problems, likely related to the ones mentioned in another issue I've been having with the code.

Here is the fragment shader:

```
const float     lightWeighting = 0.75;
const float     textureWeighting = 0.25;

const float     PI = 3.14;
const float     lightIntensity = 1.0;
const float     constFudge = 0.025;
const float     linearFudge = 0.025;
const float     quadraticFudge = 0.05;

float rend  = 250.0;
float rstart = 50.0;

uniform float       Intensity;
uniform sampler2D   grabTexture;
//varying   sampler2D   HeatValues

varying vec3        Normal;
varying vec3        Vertex;
varying vec2        texCoord;

void main(void)
{
  vec3 pigPos = Vertex;
  vec3 normPigPos = normalize(pigPos);

  vec3 lightPos = vec3(gl_LightSource[0].position.xyz);

  vec3 normLightPos = normalize(lightPos);

  float effectiveIntesity;

  vec3 normNormal = normalize(vec3(Normal.xyz));

  vec3 t = vec3(pigPos - lightPos);

  float distToLight = length(t);

  float d = dot(normNormal.xyz, normLightPos.xyz);
  if(d > 0.0)//facing the light
  {
    float falloff;

    if( distToLight < rstart )
      falloff = 1.0;
    else
    if( distToLight > rend )
      falloff = 0.0;
      else
      {
      falloff = rend-distToLight / rend-rstart;
      }

    effectiveIntesity = d*lightIntensity * falloff;

    effectiveIntesity = d*lightIntensity * (1.0/(constFudge + (linearFudge*distToLight) +(quadraticFudge*distToLight*distToLight)));

  }
  else
  {
    effectiveIntesity = 0.0;
  }

  //TODO: change the colour of the pixel
  vec4 lightingColour = vec4(vec4( 1.0 ) * effectiveIntesity); //TODO: improve

  //gl_FragColor = lightingColour;

  //texturing stuff
  //http://www.opengl-tutorial.org/beginners-tutorials/tutorial-5-a-textured-cube/
  vec4 textureColour = vec4(texture2D(grabTexture, texCoord.xy)); // TODO: why is this blank?

  vec4 col = vec4(textureColour.rgb, 1.0);
  col.r *= 1.0;
  col.g *= 1.0;

  gl_FragColor = (col);

  //gl_FragColor = (lightingColour * lightWeighting) + (textureColour.rgb * textureWeighting);

  //simple check to make sure that shader compiles
  vec3 lP = vec3(abs(gl_LightSource[0].position.x/100), abs(gl_LightSource[0].position.y/100), abs(gl_LightSource[0].position.z/100));
  vec4 r = vec4( lP.x, lP.y, lP.z, 1.0 );
  gl_FragColor = r;

  gl_FragColor = (lightingColour * lightWeighting) + (r * textureWeighting);
}

```

# Edit:

I've had a go at doing what was suggested by user111821 and this is where I am now. My new issue is trying to get the heat texture to render to confirm that the shader can use it, however doing so causes the skin texture to render.

The final version of this will need both textures being used with some lighting contributing to the final pixel values of the sphere.

Revised Fragment Shader:

```
const float     lightWeighting = 0.5;
const float     textureWeighting = 0.25;
const float     heatWeighting = 0.25;

const float     PI = 3.14;
const float     lightIntensity = 1.0;
const float     constFudge = 0.025;
const float     linearFudge = 0.025;
const float     quadraticFudge = 0.05;

float rend  = 250.0;
float rstart = 50.0;

uniform float       Intensity;
uniform sampler2D   grabTexture;
uniform sampler2D   HeatValues;

varying vec3        Normal;
varying vec3        Vertex;
varying vec2        texCoord;

void main(void)
{
  vec3 pigPos = Vertex;
  vec3 normPigPos = normalize(pigPos);

  vec3 lightPos = vec3(gl_LightSource[0].position.xyz);

  vec3 normLightPos = normalize(lightPos);

  float effectiveIntesity;

  vec3 normNormal = normalize(vec3(Normal.xyz));

  vec3 t = vec3(pigPos - lightPos);

  float distToLight = length(t);

  float d = dot(normNormal.xyz, normLightPos.xyz);
  if(d > 0.0)//facing the light
  {
    float falloff;

    if( distToLight < rstart )
      falloff = 1.0;
    else
    if( distToLight > rend )
      falloff = 0.0;
      else
      {
      falloff = rend-distToLight / rend-rstart;
      }

    effectiveIntesity = d*lightIntensity * falloff;

    effectiveIntesity = d*lightIntensity * (1.0/(constFudge + (linearFudge*distToLight) +(quadraticFudge*distToLight*distToLight)));

  }
  else
  {
    effectiveIntesity = 0.0;
  }

  //TODO: change the colour of the pixel
  vec4 lightingColour = vec4(vec4( 1.0 ) * effectiveIntesity); //TODO: improve

  //gl_FragColor = lightingColour;

  //texturing stuff
  //http://www.opengl-tutorial.org/beginners-tutorials/tutorial-5-a-textured-cube/
  vec4 textureColour = vec4(texture2D(grabTexture, texCoord.xy)); // TODO: why is this blank?

  //vec4 col = vec4(textureColour.rgb, 1.0);
  //col.r *= 1.0;
  //col.g *= 1.0;

  gl_FragColor = (textureColour);

  vec4 heatColour = vec4(texture2D(HeatValues, texCoord.xy));

  gl_FragColor = heatColour;

  //gl_FragColor = (lightingColour * lightWeighting) + (textureColour * textureWeighting) + (heatColour * heatWeighting);

  //simple check to make sure that shader compiles
  vec3 lP = vec3(abs(gl_LightSource[0].position.x/100), abs(gl_LightSource[0].position.y/100), abs(gl_LightSource[0].position.z/100));
  vec4 r = vec4( lP.x, lP.y, lP.z, 1.0 );
  //gl_FragColor = r;

  //gl_FragColor = (lightingColour * lightWeighting) + (r * textureWeighting);
}

```

This a snippet of the class which is doing a bunch of C++ side of OpenG, the header file has been prepended for reference:

```
#pragma once
#include "stdafx.h"

class NA_Pig
{
private:
  object_type pigObj;
  unsigned char* rawLoadedTexture = NULL;
  unsigned char* heatValuesPsudoTexture = NULL;
  GLuint heatValuesTexID;
public:
  NA_Pig();
  ~NA_Pig();

  void draw();

  //void loadShader();

  vec3 pos;

  int pigShader = 0;

  void init();

};

void NA_Pig::draw()
{
  glMatrixMode(GL_MODELVIEW);
  glPushMatrix();
  glLoadIdentity();
  glTranslatef(pos.x, pos.y, pos.z);
  glShadeModel(GL_SMOOTH);

  extern cRenderClass graphics;

  //Shader Stuff
  //cShader *pList = graphics.ShaderInfo.getList();
  //int shdr = 1;

  //if (shdr >= graphics.ShaderInfo.shaderCount())
  //{
  //    printf("Error: Can't access requested shader\n");
  //    shdr = 0;
  //}

  //// enable shader program..
  //glUseProgram(pList[shdr].program());

  //glUniform1fv(glGetAttribLocation(shaderID, variableNameAsString), sizeOfArray, valueAsArray)
  //glUniform1f(glGetAttribLocation(shaderID, variableNameAsString), value);

  //glUseProgram(shaderID);

  //glutSolidSphere(12, 120, 2);
  int size = 50;
  glScaled(size, size, size);

  // MATERIAL PROPERTISE
  GLfloat ambient[4] = { 1.0,1.0,1.0,1.0 };
  GLfloat diffuse[4] = { 1.0,1.0,1.0,1.0 };
  GLfloat specular[4] = { 1.0,1.0,1.0,1.0 };

  //glMaterialfv(GL_FRONT, GL_AMBIENT, ambient);
  //glMaterialfv(GL_FRONT, GL_DIFFUSE, diffuse);
  //glMaterialfv(GL_FRONT, GL_SPECULAR, specular);

  // activate texture for application is shader
  //https://www.opengl.org/archives/resources/code/samples/glut_examples/examples/examples.html
  glEnable(GL_TEXTURE_2D);

  //apparently the shader needs this
  glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
  glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
  glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);

  glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 4, 4, 0, GL_RGBA, GL_UNSIGNED_BYTE, rawLoadedTexture);

  glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
  glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
  glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);

  glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, SCREEN_WIDTH*SCREEN_HEIGHT, 0, 0, GL_RGB, GL_UNSIGNED_BYTE, &heatValuesPsudoTexture);

  glActiveTexture(pigObj.id_texture); //the shader can use this texture
  glActiveTexture(heatValuesTexID);

  cShader *pList = graphics.ShaderInfo.getList();
  glUseProgram( pList[1].program()); //shader on: no pig // fixed, was vertex shader being empty, replaced it with intensity.vert
                    //shader off: ambient light only (tiny amount of diffuse or an illusion?)
  extern NA_MathsLib na_maths;
  float intensity = (float) na_maths.dice(100);

  glUniform1i(pList[1].get_grabLoc(), pigObj.id_texture);
  glUniform1f(pList[1].intensity(), intensity);
  glUniform1f(pList[1].get_heatValueGrabLoc(), heatValuesTexID);

  //glutSolidSphere(2, 15, 2);
  pigObj.render();

  glActiveTexture(GL_TEXTURE0);
  glDisable(GL_TEXTURE_2D);
  glUseProgram(0); //disable pig heatlamp shader
  glPopMatrix();

}

void NA_Pig::init()
{

  int x, y, comp;

  rawLoadedTexture =  stbi_load("Pig/pig.bmp", &x, &y, &comp, 4);
  if (rawLoadedTexture == NULL)
    std::cout << "NA_Pig::init - stbi_load returned null\n";

  //https://open.gl/textures
  //https://open.gl/content/code/c3_multitexture.txt

  //texturing stuff
  glActiveTexture(GL_TEXTURE1);
  GLuint tex;
  glGenTextures(1, &tex);
  glBindTexture(GL_TEXTURE_2D_ARRAY_EXT, tex);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
  float color[] = { 1.0f, 1.0f, 1.0f, 1.0f };
  glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, color);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, x, y, 0, GL_RGB, GL_UNSIGNED_BYTE, rawLoadedTexture);

  //heat lamp psudo texture
  glActiveTexture(GL_TEXTURE2);
  GLuint heat;
  glGenTextures(1, &heat);
  glBindTexture(GL_TEXTURE_2D_ARRAY_EXT, heat);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
  float heatColor[] = { 1.0f, 1.0f, 1.0f, 1.0f };
  glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, heatColor);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

  heatValuesPsudoTexture = new unsigned char[SCREEN_HEIGHT*SCREEN_WIDTH];
  memset(heatValuesPsudoTexture, 255, sizeof(unsigned char)*SCREEN_HEIGHT*SCREEN_WIDTH);

  glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, SCREEN_WIDTH*SCREEN_HEIGHT, 0, 0, GL_RGB, GL_UNSIGNED_BYTE, &heatValuesPsudoTexture);
  heatValuesTexID = GL_TEXTURE2;

  pigObj.objloader("Pig/pig.obj");
  pigObj.id_texture = GL_TEXTURE1; //https://gamedev.stackexchange.com/questions/144828/why-is-my-texture-not-applied-correctly-in-opengl-2-0-with-glsl

  extern NA_MathsLib na_maths;
  na_maths.seedDice();
}

```

# Answer
It occurs to me that what you're trying to do may be a little more difficult than originally anticipated. But I think it could be done in a 2-pass way. First, create a texture with a 2:1 aspect ratio. (The actual resolution is up to you.) This will be an equirectangular projection of the surface of your sphere.

You would first create an offscreen framebuffer and attach the 2:1 texture to it that you will draw to. Draw a quad the size of the texture and in the fragment shader, at each point, project it back onto the sphere and get it's distance to the heat source. Calculate its temperature (or whatever you're calculating) there.

Next you draw the scene with the texture you just made projected onto the sphere.

When you start the next round, you use the existing texture as your "previous frame" and draw to a new texture into the offscreen frame buffer. You can actually ping-pong back and forth between 2 textures. It never needs to be read back to main memory if you do it this way.
> 1 votes

# Answer
For the values being stored for the next frame, as mentioned already, you may be able to do this with a texture.

do you really need to do the calculations in the shader? an easy option could be to do your calculations per-vertex in C++, and pass the values to the vertex shader, which can then interpolate them to the fragment shader for use in rendering.

You may also have an easier time storing values calculated in the vertex shader than fragment shader if you don't want to do the work in C++ - but I must admit I am not sure on the correct way to do this.

also, the falloff calculation looks a bit odd?

```
falloff = rend-distToLight / rend-rstart;

```

this is understood as the compiler as

```
falloff = rend - (distToLight / rend) - rstart;

```

and may result in something like `250 - 0.5 - 50 == 199.5` should perhaps be

```
falloff = (distToLight - rstart) / (rend - rstart)

```
> 0 votes

---
Tags: opengl, c++, glsl
---


# Question
Title: Change alpha value of object if it's closer to the camera than the player
Ok, so - I'm a complete idiot when it comes to shader programming, and while I suspect someone with some experience here may find this easy, I'm at a bit of a loss.

I'd like to create a shader that would be applied to walls, and if the wall was closer to the camera than the player is, the wall would gain alpha transparency (probably 10-20% visible). I had tried some things with a camera that pans, zooms, and moves overhead as needed to not occlude the player, but it's sloppy and just doesn't feel very nice. I had used an x-ray shader, that showed an outline of the player through the wall, and while it was "cool", it also didn't quite feel right. The camera and player will always be a fixed distance and angle apart (well, at least at a given resolution). Is there some way to use the draw buffer or otherwise calculate world space position to determine when alpha should be applied?

Any help is very much appreciated. Thanks!

EDIT: I was looking and found a lot of solutions like this one: https://forum.unity3d.com/threads/global-shader-to-apply-transparency-on-objects-depending-how-far-is-the-camera.188632/

But I'd rather have it contained entirely in the shader. Preferably something I could build into a copy of the Standard (Specular Setup) shader in Unity - that copy being applied only to wall objects.

EDIT #2: I understand that this could be done with two separate materials, using code to swap them with Raycasting (though it seems that that would only work specifically for objects directly between the camera and the player rather than objects closer to the camera than the player). But I'm growing more uncertain that the shader can be told anything about the position of the player as an object.

# Answer
> 1 votes
So, I ended up going this route: http://www.labyrintheer.com/2017/07/20/how-to-see-your-player-making-walls-transparent/

Basically I have my playerController setting a float for it's distance from the camera and making that publicly available through a method. Then on any objects I want to make transparent when they occlude the player, I have another script that takes an original material and a transparent material and swaps them when their distance to the camera is less than that of the player.

It's definitely a work in progress and needs some refinement, but I think it's a decent solution.

The script on objects that need to become transparent:

```
using UnityEngine;

public class TransMaterialSwap : MonoBehaviour {

     public Material _original;
     public Material _transparent;
     private GameObject player;
     private playerController pC;
     private Renderer rend;

     void Start()
     {
         player = GameObject.FindWithTag("Player");
         pC = player.GetComponent<playerController>();
         rend = this.GetComponent<Renderer>();
     }

     void Update()
     {
         if ((transform.position - Camera.main.transform.position).sqrMagnitude < pC.Dist())
         {
             rend.material = _transparent;
         }
         else
         {
             rend.material = _original;
         }
     }
 }

```

---
Tags: unity, shaders
---


# Question
Title: unity android output is about 120mb even with just an empty scene
there is a lot of content in my project but as a test I just chose a empty scene with one sprite to build but the apk output size is about 120mb.

I think there is an options or setting or platform support that makes it much big but I don't know what it is.

thank you for helping

# Answer
> 2 votes
Even with an empty scene, anything inside any folder named `Resources` that is anywhere within the Assets directory will be included, regardless of whether or not it is in the scene or not.

This is due to it being having to be available via `Resources.Load()`.

---
Tags: unity, android
---


# Question
Title: Is there a reason to inherit both generic and non-generic version of an interface?
I've just gotten into some C# programming and decided to expand my knowledge of how games are made in C# by looking through some open-source frameworks. While doing this I noticed something very odd; classes that they make would implement both generic and non-generic interfaces that represent the same data structure. For example:

```
public class SomeSpecialList<T> : IList<T>, IList {
    ...
}

```

I couldn't find any explanation to this - Is this something I should be thinking about when programming games in C#? Why? Is it a performance thing?

# Answer
By implementing both `IList` and `IList<T>` you allow your type to have maximum (or at least, *more*) generality. Code that expects an `IList` (generally older code that predates the introduction of generics) can accept instances of your type.

In game development, this isn't *as much* of a compelling reason as it might be elsewhere. Most of the time backwards compatibility with some of the legacy APIs that accept non-generic collections isn't a huge deal. If you're writing framework-level code, especially framework-level code you intend to distribute to the wider internet (so you don't know precisely who will be consuming it and what their personal needs will be), that provides a stronger rationale for why you'd want to implement both. That may explain why you've come across it in a lot of available frameworks.

If you're just writing game-specific, non-reusable code? It's not a big deal (and you should prefer to implement the generic version as its nicer to use). On the other hand, the extra work needed to implement the non-generic version is usually quite small, so maybe why not?
> 2 votes

---
Tags: c#, data-structure
---


# Question
Title: How can I toggle enabled on a specific script within an object in Unity?
I have the CarController script inside my car GameObject. I need to set it to disabled at the start so the countdown timer can start the race.

I thought I knew how to do it but once again I have failed :/

Any ideas why this doesn't work??

```
void TogglePlayerEnabled(bool b)
{
    playerCar.GetComponent<CarController>().enabled = b;
}
void ToggleAiCarEnabled(bool b)
{
    aiCar.GetComponent<CarController>().enabled = b;
}

```

If I use a print line saying "Toggled" or something, that appears in console as expected. But the CarController script seems like it stays active as both me, and the AI car can just drive whilst the countdown is happening still.

Here's the full class:

```
public class GameManagerControl : MonoBehaviour {

public GameObject playerCar;
public GameObject aiCar;

public int sceneChangeZValue;

private string countdown = "";
private bool showCountdown = true;

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {
    // TODO: This will change the scene when the track ends.
    //if (player.transform.position.z >= sceneChangeZValue)
    //      {

    //          SceneManager.LoadScene("race_track_lake");
    //      }

    if (showCountdown)
    {
        StartCoroutine(GetReady());
    }

}

// call this function to display countdown
IEnumerator GetReady()
{
    countdown = "3";
    TogglePlayerEnabled(false);
    ToggleAiCarEnabled(false);
    yield return new WaitForSeconds(1.5f);

    countdown = "2";

    yield return new WaitForSeconds(1.5f);

    countdown = "1";

    yield return new WaitForSeconds(1.5f);

    countdown = "GO";
    TogglePlayerEnabled(true);
    ToggleAiCarEnabled(true);
    yield return new WaitForSeconds(1.5f);

    showCountdown = false;
    countdown = "";
}

// GUI
void OnGUI()
{
    if (showCountdown)
    {
        GUI.color = Color.red;
        GUI.Box(new Rect(Screen.width / 2 - 100, 50, 200, 175), "GET READY");

        // display countdown
        GUI.color = Color.white;
        GUI.Box(new Rect(Screen.width / 2 - 90, 75, 180, 140), countdown);
    }
}

```

# Answer
Damn Ive done it again and fixed it just after righting up this question!! Something about typing it up here helps me fix it i dunno why lol.

Basically, I had another script attached to each can for UserControl and AiControl, and I just had to add those in with the other enable.disable calls in the Toggle methods.

Sorry to waste anyones time.... again!
> 0 votes

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


# Question
Title: Display two characters with same tag in unity 3d
I'm developing a bowling game in which I'm currently working on the winner loose scene. I have a parent gameobject which contains two character models having the same gameobject tags. For the two player game I'm using the same tag for both the players for their individual turns. Now as in the end of the game I have to display both the characters at the same time having to play the winner and the defeat animation using the same tag. How can this be done or is there any other way this can be done?

To obtain all the child characters from parent tag, this is what I've tried at runtime:

```
modelcontainer = GameObject.FindGameObjectWithTag("modelcontainer");

        findgameobjects = new GameObject[modelcontainer.transform.childCount];

        for (int i = 0; i < modelcontainer.transform.childCount; i++)
        {
            findgameobjects[i] = modelcontainer.transform.GetChild(i).gameObject;
        }

```

But it doesn't store the child gameobject which is not active at current time as per my game logic.

# Answer
Found a way to display both characters having same gameobject tag at the same time.

```
 modelcontainer = GameObject.FindGameObjectWithTag("modelcontainer");

        findgameobjects = new GameObject[modelcontainer.transform.childCount];

        for (int i = 0; i < modelcontainer.transform.childCount; i++)
        {
            findgameobjects[i] = modelcontainer.transform.GetChild(i).gameObject;
            if(i==0)
            {
                firstcharacter = findgameobjects[i];
            }
            else
            {
                secondcharacter = findgameobjects[i];
                if(secondcharacter.activeInHierarchy==false)
                {
                    secondcharacter.SetActive(true);
                }
            }
        }

```
> 1 votes

---
Tags: unity, animation, character
---


# Question
Title: Many OpenGL declarations are not occured in GLESv3 gl3.h
I created a small OpenGL renderer in C++ and I want to move to Android so I prepared eclipse with all suitable platforms and create a Native Activity project then add the NDK to the includes and successfully executed and run a sample which color the screen, once I imported the files from the C++ project (copy them to jni folder) and fixed the includes I found many GL declarations are not occurred for example "Function 'glDrawBuffer' could not be resolved", I opened the gl3.h file and discovered that they are not occurred in that file, in my desktop version I use glew library and the file glew.h contains all those definitions so I tried to copy the definition from glew.h

```
GLAPI void GLAPIENTRY glDrawBuffer (GLenum mode);

```

to gl3.h

```
GL_APICALL void GL_APIENTRY glDrawBuffer (GLenum mode);

```

but still have the same error. is these functions and constants are not occurred in the ES version of OpenGL or I need to update something? I have NDK r 15, SDK 22, Eclipse neo and GCC compiler with Android Builder.

Edit:

I found this definition in the same file

```
GL_APICALL void GL_APIENTRY glDrawBuffers (GLsizei n, const GLenum *bufs);

```

I think it is the same function but different number of arguments so I can guess there are many differences between OpenGL and the ES3 so the is same code will not run and must be changed?

also is there a place where I can find the equivalent functions or constants?

# Answer
I found this site Docs GL very helpful for documenting OpenGL functions and its support in all GL versions
> -1 votes

---
Tags: c++, ndk, opengl-es3
---


# Question
Title: Check if rectangle sides overlap each other in 2d
I am drawing a rectangle. On touching the corners, I am able to resize this rectangle. Now, the issue is during resizing, opposite sides overlap and cross each other. I have to stop this overlapping and crossing of sides. The minimum width and height should be any fixed constant (let's say 10).

In below code `left, top` has `cornerId 0` and `left, bottom` has `cornerId 1` and so on. Also `left, top` and `right, bottom` makes `groupId 1` and other two sides make `groupId 2`. Here `cornerList` contains the info about all the 4 coordinates.

Any help or reference is greatly appreciated. Thanks.

Reference for resizable rectangle is How to create a resizable rectangle with user touch events on Android?

```
private void moveCorners(float x, float y) {

    cornerList.get(cornerId).setX(x);
    cornerList.get(cornerId).setY(y);
    paint.setColor(Color.CYAN);

    if (groupId == 1) {
        cornerList.get(1).setX(cornerList.get(0).getX());
        cornerList.get(1).setY(cornerList.get(2).getY());
        cornerList.get(3).setX(cornerList.get(2).getX());
        cornerList.get(3).setY(cornerList.get(0).getY());
    } else {
        cornerList.get(0).setX(cornerList.get(1).getX());
        cornerList.get(0).setY(cornerList.get(3).getY());
        cornerList.get(2).setX(cornerList.get(3).getX());
        cornerList.get(2).setY(cornerList.get(1).getY());
    }

    invalidate();

}

```

# Answer
You don't need a corner list. What you need is a side list, since you are actually dragging sides - two adjacent corners always have either the same `x` or the same `y`, so corner drag is pointless.

You do need a min and max for each axis, and a minimum size:

```
float xMin;
float xMax;
float xMinSize;

```

You do need to write a getter method for width:

```
float getXSize()
{
    return xMax - xMin; //this means your rightmost x for the rectangle, minus leftmost
}

```

When you drag (each frame), you must check if size is less than minimum and if it has become less, then clamp it, i.e. do not let it go below that minimum:

```
if (getXSize() < xMinSize)
{
    //PSEUDOCODE:
    //if currently dragged side is the right hand side (x max):
    xCurrentlyDraggedSide = xOtherSide + minWidth;
    //else if it's the left hand side (x min):
    xCurrentlyDraggedSide = xOtherSide - minWidth;
}

```

Then do similar for `y`, in all the same places.

Get this working, then build your draggable corners back in ON TOP of this, if you want them.
> 2 votes

---
Tags: java, android, physics, overlap2d
---


# Question
Title: Are huge, static objects like environment transmitted from server to client in modern multiplayer games?
I have an authoritative system, where when the player joins the match, it gets all the already spawned objects - spawned on itself (the client).

It looks like this:

1. `Client` sends the access token to the `Server`
2. `Client` receives the acceptance from the `Server`
3. `Client` switches scene to the game scene
4. `Server` sends players, crates, objects you can interact with so the `client` can spawn and display them.

But what about the ground object? For now, I have the exact same scene on the server and the client - with one static plane acting as a floor. Currently I'm adding new stuff, trees, stairs and build things together.

I thought - we're good. But shouldn't the environment be synchronized too? Be networked somehow? Owned by the server?

Let's take `League of Legends`:

It's a static environment, **probably one combined mesh** (stairs, grass, walls, shop). But is it really kept on the client or is it sent by the server during the loading screen?

# Answer
For the most part, no, art assets of any kind aren't routinely sent across the network. Generally all clients will have the same content assets locally. There may be code to ensure this is the case via checksumming the content, or similar. If you are worried about users tampering with some of their content client-side, you can implement a similar system.

The server might send directives to the client indicating it should display or hide certain assets, but it won't send the actual data of the asset. This is, in practice, too wasteful and slow, and could cause real problems with people with limited data available.

In certain cases, smaller assets may be streamed across in their entirety if the asset is somehow considered a "spoiler" or whatever. But that's uncommon. Generally what you see is that a game might download *new* content from a patch, or whatever, but that will only happen once, during the patching process at startup. Not during gameplay.
> 42 votes

# Answer
Depends on several factors, including the kind of game (I'll assume RTS here, though open world MMO also comes to mind). A base, local-to-player terrain state is either sent on connect, or is part of the client's assets - think of an RTS game where the map is either shipped with the client, or is downloaded prior to a game commencing.

Indeed, the mesh would not usually be sent, as it would already be on the client in most RTS cases. Whether or not the *collision map, which is what's really crucial for keeping the two in sync* is sent, is another question. But in most RTS, this would again be pre-stored on the client.

So really, it all depends on what your RTS ships with, whether you download maps prior to play time, or at the time when the game commences.

After that, there are a few typical ways to stay synced:

* Deltas are sent to the client - the most common and efficient way to keep the local / client world up to date with the server;
* Checksums are occasionally sent either from server to client or client to server to ensure that the world state does indeed match;
* Occasionally, full state is resent to resync the client - often as a result of technical concerns like floating point drift.
> 5 votes

# Answer
As to your exact question as asked, I do not know how League of Legends specifically handles it. I have never played that game, so I cannot suggest whether or not it needs to.

But the answer to your question, in general, is fairly simple and straightforward:

**If the data is static**, and you know *for sure* that it will *never* change (short of periodic full-game-updates, but that's separate), then why would you ever want to send that extra data? Usually you try to avoid sending whatever can be avoided. Only send data if that communication is a *need*.

On the other hand, **if the data will change over time**, or if you just want to leave that option open, then do you really have any choice in the matter? For this case, you *must* send the data. Otherwise the client does not have what it needs.

This applies to all network communications, not just terrain data. *Everything*.
> 4 votes

# Answer
No.

I have done a fair about of digging about in the source of League of Legends, and everything, including Champion models, Shopkeeper, general map background, and fluff creatures added in after the fact (like the little squirrel on some rocks and a snail in the river) are kept on the client side. The fact that the client has all these models is one of the reasons LoL is many gigabytes large.

Transferring all this data from server to client would be hellish, not to mention chew through bandwidth usage just to do it all again next game.

So how is it solved then? Each player just sends ONLY the data that matters to *other* players in the game to the server. No one needs to know whether you have 5 seconds left on Q cooldown, or that the Deep Terror Thresh Skin creates bubbles for you. Things that get passed along in-game are things like, Vel'Koz casted Q, Viktor moved to the left, etc...

More explicitly, in relation to loading screen, as you brought that up, things that happen there are things like mid patch patches, which every player needs to talk to riot's servers about before the game starts, secure connection handshakes, and anti cheating protocols.

NOTE:

If you want to look around at what stuff the client has, and therefore, the server doesn't pass you, find the C:\Riot Games\RADS\lol\_Game\_Client\Projects folder (that might be a little off, pardon me I'm working off memory right now) and find a .RAF file unpacker online. Then you can see all the stuff that's housed locally like loading screen splashes and skin textures, even champion skeletons.
> 2 votes

# Answer
An example of where this was *not* done was the Elder Scrolls Online, where it trusted the client about the altitude of *ground level*.

Gold-miners dropped ground level by several feet. They could then walk around "under" the terrain, and mining resources from below without being seen by PCs or attacked by NPCs.

Similar edits allowed them to smooth cliffs so they could walk up them, remove or route under static walls, see through all static objects, etc.

Essentially, the server trusted the client about the location of the player, calculating collision on the server side for every single player against all statics would be quite heavy.

In tile-based games like Furcadia, however, it's different: every square you move into has server-side walkabilty, and the server doesn't need to trust the client for anything: the server knows and validates every movement and user action, and the client only displays the action when the server tells it the result.
> 1 votes

---
Tags: unity, networking, maps
---


# Question
Title: SharpDX Constant buffer not passing values
I'm trying to pass values to a Pixel Shader. I've added the following to the HLSL files.

cbuffer QuadShaderValues : register(b0) { float3 PixelDropThresholds; float4 OverlayColor; uint PixelDropEnabled; }

I've added the follow structure to the C# code;

```
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct QuadShaderValues
{
    public SharpDX.Vector3 PixelDropThresholds;
    public SharpDX.Color4 OverlayColor;
    public uint PixelDropEnabled;
}

```

I've added the following code to the Initialization of the device :

```
m_ShaderValueBuffer =
            AddDisposable(new SharpDX.Direct3D11.Buffer(direct3DDevice, SharpDX.Utilities.SizeOf<QuadShaderValues>(),
                SharpDX.Direct3D11.ResourceUsage.Default,
                SharpDX.Direct3D11.BindFlags.ConstantBuffer,
                SharpDX.Direct3D11.CpuAccessFlags.None,
                SharpDX.Direct3D11.ResourceOptionFlags.None, 0));

        direct3Dcontext.VertexShader.SetConstantBuffer(0, m_ShaderValueBuffer);

```

I've added the following code to the Render Method :

```
deviceContext.UpdateSubresource(ref ShaderValues, m_ShaderValueBuffer);

```

The values do not seem to be making it into the shader.

# Answer
A couple of things, I think your pack for example needs to be 16. I usually cheat and shove a dummy float in after the vector3. I would also try to pack on borders of 16 bytes. Your current pack is to 1 byte alignment, possibly try 4 or 16.

```
[StructLayout(LayoutKind.Sequential)]
public struct PerFrameBuffer
{
    public Matrix wvpMatrix; // 16 floats
    public Matrix worldMatrix; // 16 floats
    public Matrix shadowMatrix; // 16 floats
    public Matrix decalMatrix; // 16 floats
    public Vector3 cameraPosition; // 3 floats
    float padding; // 1 float
};

```

I use the static buffer version of the call, don't think it makes a difference.

```
    D3D11.Buffer.Create(GlobalStatics.Device,
     D3D11.BindFlags.ConstantBuffer,
     ref Framebuffer,
     Constants.c_PerFrameBufferSize,
     D3D11.ResourceUsage.Default,
     D3D11.CpuAccessFlags.None,
     D3D11.ResourceOptionFlags.None,
     0);

```

My only other questions would be if you are using the same context? That is, the context you are sending your render commands to is the same one you have bound your buffer to. Will update this post if anything else comes to mind, but buffer alignment might be your first issue.
> 0 votes

# Answer
Hey thank you guys for your input. I had figured out how to get around my issue. I actually have added more values. Here is what I came up with. I actually switch to all float4.

```
/// <summary>
/// Shader Values Struct used to pass values to shader
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct ShaderValues
{
    /// <summary>
    /// The overlay color (A,R,G,B)
    /// </summary>
    public SharpDX.Vector4 OverlayColor;
    /// <summary>
    /// The pixel drop thresholds(R,G,B, Enabled)
    /// </summary>
    public SharpDX.Vector4 PixelDropThresholds;
    /// <summary>
    /// The channel settings(Mixed)
    /// </summary>
    public SharpDX.Vector4 ChannelSettings;
    /// <summary>
    /// The renderer settings (Mixed)
    /// </summary>
    public SharpDX.Vector4 RendererSettings;
}

```
> 0 votes

# Answer
If you want to pass values to a pixel shader, make sure to activate your buffer for the pixel shader.

I read

```
direct3Dcontext.VertexShader.SetConstantBuffer(0, m_ShaderValueBuffer);

```

.. which should be:

```
direct3Dcontext.VertexShader.SetConstantBuffer(0, m_ShaderValueBuffer);
direct3Dcontext.PixelShader.SetConstantBuffer(0, m_ShaderValueBuffer);

```

I ran into the same this afternoon. Putting value for light direction into the buffer, HLSL pixel shader read (0,0,0) instead, no exception occurred. This solved it.
> 0 votes

---
Tags: c#, shaders, sharpdx
---


# Question
Title: Removing unecessary permissions from AndroidManifest that Unity+Plugins put in there?
My game has a lot of unnecessary permissions added to it, I suspect some are coming from plugins and some from Unity. I've looked at all the AndroidManifest.xml files and couldn't find any that use those permissions so I suspect it's added as a post build process or some other way by the plugins wrapped up in a binary or something.

Is there a way to remove those permissions in a post process build step?

# Answer
> 1 votes
You have to build from Unity into an Gradle Android project ("Export Project") and then edit/replace the file before building the APK using Android Studio.

More info on Unity's website: https://docs.unity3d.com/Manual/android-BuildProcess.html

---
Tags: unity, android, permission
---


# Question
Title: SFML position problem when drawing a CircleShape
I am not sure but I think it's a problem with Windows 10 borderless windows The problem is when I draw the circle its always drawn with a little offset from where it should be.

In the top of the window the shape is drawn above the mouse, in the bottom the shape is drawn under the mouse and so for each side of the window

This is my code:

```
#include "SFML/Graphics.hpp"
#include <stdio.h>
int main(int argc, char **argv){
        sf::RenderWindow window(sf::VideoMode(800, 600), "SFML Application");
        window.setFramerateLimit(60);

        sf::RenderTexture renderTexture;
        renderTexture.create(800,600);
        renderTexture.setSmooth(true);
        renderTexture.clear(sf::Color(255,255,255,255));
        renderTexture.display();

        int wpoint=10;
        sf::CircleShape point(wpoint,50);
        point.setFillColor(sf::Color(255, 0, 0, 128));

        while(1){
                sf::Event event;
                while (window.pollEvent(event)){
                        if (event.type==sf::Event::MouseMoved && sf::Mouse::isButtonPressed(sf::Mouse::Left)){
                                //printf("%d\n",sf::Mouse::isButtonPressed(sf::Mouse::Left));
                                //point.setPosition(event.mouseMove.x-(wpoint/2),event.mouseMove.y-(wpoint/2));
                                //point.setPosition(event.mouseMove.x,event.mouseMove.y);
                                //auto pos=sf::Mouse::getPosition();
                                auto poswindow=window.getPosition();
                                printf("%d,%d\n",poswindow.x,poswindow.y); //This prints -8,0 when I position the window on the left-top corner (0,0)!!
                                //auto pos=sf::Mouse::getPosition(window);
                                auto pos=window.mapPixelToCoords(sf::Mouse::getPosition(window));
                                point.setPosition(pos.x,pos.y);
                                renderTexture.draw(point, sf::BlendAlpha);
                        }
                        if (event.type==sf::Event::Closed
                         || event.type==sf::Event::KeyPressed && event.key.code==sf::Keyboard::Escape)
                                return 0;
                }

                sf::Sprite canvas(renderTexture.getTexture());
                // draw
                window.clear();
                window.draw(canvas);
                window.display();
        }
        return 0;
}

```

One thing I noticed is when I tried to draw the circle on (10,10) it was painted under the title bar.

I read somewhere that it's probably a thing that only happens with some Intel drivers, I just hope that the users don't have it or I will be in troubles. It's weird because I have been working with the Winapi for a long time and the mouse coordinates have always been correct.

# Answer
> 1 votes
Do you have the same problem if you try to draw directly to the RenderWindow (`window.draw(point, sf::BlendAlpha)`), instead of drawing to a RenderTexture and then to a sprite? Because doing so is essentially doubling the buffer size for the draw unnecessarily. I would recommend you simply draw to the window for performance reasons.

I think the fact you're passing through a RenderTexture could also cause problems if you don't set the sprite's textureRect properly, or don't position the RenderTexture in the window.

Finally, keep in mind that any sf::Shape has its origin set by default to (0, 0). While this doesn't explain how the offset changes depending on where you are, it could be worthwhile, if I understand your goal properly, to set the origin to the center of the circle. You can use `point.setOrigin(point.getRadius(), point.getRadius())` to do that.

---
Tags: c++, sfml, draw-order
---


# Question
Title: How to draw texture with unlit effect on surface base texture
I am writing a shader to my Unity game and I want to have effect this type of effect:

* Base texture, for example, skin of character is a texture that will use shadows, lighting.
* Second texture, unlit, it will not be using shadows, it will be moving and changing alpha intensity.
* Second texture will be drawn after base texture.

Only unlit or surface shader looks bad, I think I must connect those two shaders, to make nice looking effect.

I wrote something this and I am stuck:

```
Shader "My/SurfaceUnlitBlend"
{
    Properties
    {
        _MainTex("Base", 2D) = "white" {}
        _MainColor("Main Texture Color", Color) = (1,1,1,1)
        _SecTex("Second Texture", 2D) = "white" {}
        _SecColor("Second Texture Color", Color) = (1,1,1,1)
        _SecTexAnimHSpeed("Second Texture Animation Horizontal Speed", Float) = 0
        _SecTexAnimVSpeed("Second Texture Animation Vertical Speed", Float) = 0
        _BlendValueModifier("Blend Value Modifier", Range(0.5, 2.0)) = 1
        _Glossiness("Smoothness", Range(0,1)) = 0.5
        _Metallic("Metallic", Range(0,1)) = 0.0
    }

    SubShader
    {
        Tags{ "RenderType" = "Opaque" }
        LOD 200

        CGPROGRAM
        #pragma surface surf Standard fullforwardshadows
        #pragma target 3.0

        struct Input
        {
            float2 uv_MainTex;
            float2 uv_SecTex;
        };

        sampler2D _MainTex;
        sampler2D _SecTex;

        fixed4 _MainColor;
        fixed4 _SecColor;

        fixed _SecTexAnimHSpeed;
        fixed _SecTexAnimVSpeed;

        fixed _BlendValueModifier;
        half _Glossiness;
        half _Metallic;

        UNITY_INSTANCING_CBUFFER_START(Props)
        UNITY_INSTANCING_CBUFFER_END

        void surf(Input IN, inout SurfaceOutputStandard o)
        {
            // Albedo comes from a texture tinted by color
            fixed2 moveVector = fixed2(_SecTexAnimHSpeed, _SecTexAnimVSpeed);
            moveVector *= _Time[1];

            //set blend modifier according to time
            float blendLevel = (cos(_Time[1]) + 1.5) * _BlendValueModifier;

            //set colors
            fixed4 col1 = tex2D(_MainTex, IN.uv_MainTex) * _MainColor / 2;
            fixed4 col2 = tex2D(_SecTex, (IN.uv_SecTex + moveVector) / 15) * _SecColor * blendLevel;

            //blend colors
            fixed4 result = col1 + col2;
            o.Albedo = result;
        }
        ENDCG
    }
    FallBack "Diffuse"
}

```

Because I don't know what to do, to have unlit effect in second texture.

# Answer
> 0 votes
I used two materials, one with fire shader second with normal shader for skin. The effect is exactly what I wanted, I read that another possible way could be subshaders, but I don't check it.

---
Tags: unity, shaders, shaderlab
---


# Question
Title: Transform.position is being changed, but character is not moving back to it when told
I'm trying to make a respawn point for my car to jump back to if it presses a button. I can see, using the Print() lines, that all the variables are correct and the methods are being triggered when expected.

But the car doesn't go back to the spawnpoint like I want it to. The velocity part seems to take effect and work ok, but the rotation and position part does nothing.

I tried several different variations of this code (ie. `GetComponent<>` and setting a public player variable (even though I am already in the player with this script)).

Like I said I tried making a public Player and setting the transform p and r on that. I also tried `GetComponentByParent<Transform>` and setting like that. I've tried a few other variations of that too. And I get the same results.

Here is the bit of code I think is relevant, if you actually need to see more please let me know.

```
public void OnTriggerExit(Collider other)
{
    if (other.gameObject.tag == "RespawnTrack")
    {
        print("respawn point added upon Trigger Exit");
        recordedTransformAtRespawnTrack = transform;
        recordedVelocityAtRespawnTrack = rb.velocity * 0.25f;
        print("rotation was: X,Y,Z=" + recordedTransformAtRespawnTrack.rotation.x + " , " + recordedTransformAtRespawnTrack.rotation.y + " , " + recordedTransformAtRespawnTrack.rotation.z);
        print("position was: X,Y,Z=" + recordedTransformAtRespawnTrack.position.x + " , " + recordedTransformAtRespawnTrack.position.y + " , " + recordedTransformAtRespawnTrack.position.z);
    }
}

public void CheckToRespawnCar()
{
    if (isRacing)
    {

        if (CrossPlatformInputManager.GetButtonDown("Jump"))
        {
            print("RESPAWN TRIGGERED BY PRESSING BUTTON");

            transform.position = recordedTransformAtRespawnTrack.position;
            transform.rotation = recordedTransformAtRespawnTrack.rotation;

            rb.velocity = recordedVelocityAtRespawnTrack;

        }

    }
}

```

# Answer
> 1 votes
What you are doing is making a **reference** to the transform object rather than a copy of it's values.

So when you copy the values later you're actually copying the current values as `recordedTransformAtRespawnTrack` points at `transform`.

C# makes a distinction between **class** (referenced objects) and **struct** (by-value objects).

Transform is a **class**. Which are referred to (using "pointer"). `a=b;` creates a **copy of the reference** (the "pointer") to the object.

Vector3 and Quaternion are **structs**. Which are copied. `a=b;` **copies the values** of the object.

This:

```
        transform.position = recordedTransformAtRespawnTrack.position;
        transform.rotation = recordedTransformAtRespawnTrack.rotation;

```

Is the same as this:

```
        transform.position = transform.position;
        transform.rotation = transform.rotation;

```

You need to save position and rotation themselves:

```
Vector3 savedPosition = Vector3.zero;
Quaternion savedRotation = Quaternion.identity;

public void OnTriggerExit(Collider other)
{
    if (other.gameObject.tag == "RespawnTrack")
    {
        print("respawn point added upon Trigger Exit");
        savedPosition = transform.position;
        savedRotation = transform.rotation;
        recordedVelocityAtRespawnTrack = rb.velocity * 0.25f;
        print("rotation was: X,Y,Z=" + recordedTransformAtRespawnTrack.rotation.x + " , " + recordedTransformAtRespawnTrack.rotation.y + " , " + recordedTransformAtRespawnTrack.rotation.z);
        print("position was: X,Y,Z=" + recordedTransformAtRespawnTrack.position.x + " , " + recordedTransformAtRespawnTrack.position.y + " , " + recordedTransformAtRespawnTrack.position.z);
    }
}

public void CheckToRespawnCar()
{
    if (isRacing)
    {

        if (CrossPlatformInputManager.GetButtonDown("Jump"))
        {
            print("RESPAWN TRIGGERED BY PRESSING BUTTON");

            transform.position = savedPosition;
            transform.rotation = savedRotation;

            rb.velocity = recordedVelocityAtRespawnTrack;

        }

    }
}

```

---
Tags: unity, c#, android, rotation, transformation
---


# Question
Title: LibGDX Tiled Map - how to get embedded objects
I am using LibGDX to learn Game Development. I have reached the phase I am learning to use Tiled Maps.

In Tiled map editor, there is a feature where we can pick a tile in the tile set, go to View -\> Tile Collision Editor, and add shape objects to a tile.

I can see that the shapes are saved in the tmx file and associated to the tile.

For testing purpose, I have also made the tile animated (similar option is available under view menu) and the OrthogonalTiledMapRendered automatically animated it (so this information is being accessed somehow).

I wanted to find out if there is anyway to retrieve other information embedded at tile level like the embedded shapes and objects.

Here is the sample xml from the tmx file.

```
<tile id="7">
    <properties>
        <property name="customProp1" value="customValue1"/>
    </properties>
    <image width="16" height="16" source="black_hole_swallow_4.png"/>
    <objectgroup draworder="index">
        <object id="0" x="0.25" y="0">
            <polyline points="0,0 15.625,-0.25"/>
        </object>
    </objectgroup>
    <animation>
        <frame tileid="5" duration="300"/>
        <frame tileid="7" duration="200"/>
    </animation>
</tile>

```

# Answer
There are documents in libGDX's github wiki https://github.com/libgdx/libgdx/wiki/Tile-maps According to this page, you can get your objects by finding the layer contains them.

```
MapLayer layer = map.getLayers().get("my-layer");

```

Find your objects

```
MapObjects objects = layer.getObjects();

```

And get the object

```
objects.get("object_name");

```

There are many information you can get from the object

```
String name = object.getName();
float opacity = object.getOpacity();
boolean isVisible = object.isVisible();
Color color = object.getColor();

```

For more details you can go to the link above.

There are many more functions, like checking if the object is RectangleMapObject or PolygonMapObject etc.
> 1 votes

# Answer
LibGDX doesn't support `<objectgroup>` inside `<tile>`, yet. However, it could come, soon.

Please see Add handling of in in the `com.badlogic.gdx.maps.tiled` package #3751 and Tiled map tiles objects support #4542 for details.
> 0 votes

---
Tags: java, libgdx, tiles, tilemap, tiled
---


title: Use Python scripts in my C++ game?

text:
# Question
Title: Use Python scripts in my C++ game?
So I have this game project which is going very well for now. I implemented OpenGL stuff, animations, interfaces, and a lot of very nice things that I'm glad I've finally gotten around.

So now that the skeleton of my game engine is made and is solid, I'd like to add AIs to make my entities more lively. Because I like the idea of a game being simple to mod, I would really like to write the AIs in Python files, that would then be read and executed from my C++ code.

So my questions are the following :

* It's a game, so performance is a concern. Is it a good idea to write the AIs in scripting files ?
* I've heard that there were some JIT compilers such as PyPy, are they easy to use from a C++ program ?
* Finally, how easy is it to send C++ objects to be treated in the Python code ?

# Answer
This is definitely possible, see Pandas3D for a fairly robust example of what you're asking in action. There's some important things to mention though, Python cannot reliably be sandboxed. What this essentially means, is that you cannot pick and choose which python library features you want to expose to your modders. In other words any mod packages that they share with each other could be full of malicious actions, and there's nothing you can do as a developer to prevent this. Knowing however, that this is true about any Python script, maybe you want to leave that aside and ignore it. If not, there is some fairly similar languages to Python, that ARE sandboxy or at least already 'safe' enough to support what you're asking.

Suppose that you don't care if modders write malicious code, and just want to cover yourself with some sort of "this is provided as is, anything from anywhere else isn't my responsibility" clause, then great.

Assuming you choose to go with Python, you'll need to look into the two different options for doing so. One being "embedding" python, and the other being "extending" python. There's a couple of variants to each and they're all pretty fun to work with but have some fundamental differences. Learn about them here. That's going to be your guide if you choose to take this route.

If you decide that you still want to extend your engine by adding a scripting language, but don't mind looking into other options there's a few that have syntaxes similar to python so the learning curve wouldn't be rough. I don't know whether these are safer to sandbox, but I know that they're a bit more targeted at being embedded than Python is.

1. Cobra
2. Nim
> 1 votes

# Answer
Without getting into the nitty-gritty...it's possible.

The Python 2.x docs have a short guide on how you could do this. Basically, it involves including the python library and invoking it when you need to. As for using python in a pthon-y way in your program, you will need to hook it up to something like CVars.

Creating scripting files for AI's are not a bad idea, but you will want to make sure you load and unload them in a smart way. You will also need to figure out a serialization scheme to work for you, in order for python to work with C++. The guide I posted touches on that.
> 2 votes

---
Tags: c++, python, scripting
---


title: Network game like MMO - TPC or UDP

text:
# Question
Title: Network game like MMO - TPC or UDP
I saw this subject several times, however I will wish better understand.

I am working on the development of a 2d game like a little MMO. (Currently I only do research). I see people who says it's easier to use TCP for all the game. But is it really viable ?

In my mind, what I would have made is to use UDP in multicast. What about this solution ?

Thank you !

# Answer
For a reasearch project TCP is fine but really most large scale network games use UDP and write some kind of reliable Messaging system overtop. This is done to address some of TCP's shortcomings:

* Bad latency due to buffering (can be somewhat overcome by disabling nagel algorithm)
* Bandwidth-heavy guaranteed delivery mechanism
* Stream based API means messages are blocked until previous messages are sent, even if they are old
* No way to have application-defined priority of messages that can be thrown away if packet loss occurs

As for multicast - it doesn't work reliably in the wilds of the internet so is not realistically useful.

Gaffer Games has great details on this stuff.
> 1 votes

# Answer
I would use TCP because UDP is not guaranteeing that your data will be correctly received, there is no way to check that because UDP is not connecting with other clients, it only sends data.

TCP server can listen to the port, so if another host will trying to connect and send data to it, you can check that.

UDP is old and for game TCP is better, you can do multicasts too, storing clients in some data container and next sending data to them all via loop.
> -6 votes

---
Tags: networking, c, socket
---


# Question
Title: Unity Deactivating Keyboard Input Interpolation
I'm working on a game in Unity, and it is a little jarring to use with keyboard controls. I'm using the built in Input Manager, where I have a set of axes mapped to the left and right keys. When the player is using the keyboard instead of a joystick, I'd like it to simply be -1 when hitting left, 1 when hitting right, and 0 otherwise, but this isn't the case. I've found that for the first few frames of the button being held, Unity automatically builds up to the value-- for example, if I'm holding right, the value wouldn't go straight from 0 to 1, but rather from 0, to 0.25, to 0.5 and so on, continuously up to 1. Can I deactivate this? If so, how? Thanks in advance.

# Answer
You can use the built-in method Input.GetAxisRaw

From the docs:

> Returns the value of the virtual axis identified by axisName with no smoothing filtering applied.
>
> The value will be in the range -1...1 for keyboard and joystick input. Since input is not smoothed, keyboard input will always be either -1, 0 or 1. This is useful if you want to do all smoothing of keyboard input processing yourself.
> 3 votes

---
Tags: unity, input, keyboard
---


# Question
Title: How to detect line break in a String using UnityScript?
Code:

```
var i:int=0;
var text:String;
var compare:String="";
var isFound:boolean=false;
function Start(){
text=AssetDatabase.LoadAssetAtPath("Assets/words.txt",TextAsset).text;
}

function Update(){
    if(!found)
   com("textToSearch");
  }

 function com(s:String){
    if(i<text.Length){
    comText=comText+text[i];
    if(//condition for line break)
    if(comText==s){
       print("found");
       found=true;
    }
   else{
         comText="";
      }
   i++;
   }

 }

```

In the text document each word ends with a line break. So if I just found a condition for a line break then I can easily search through the document.

# Answer
Line breaks are '**\n**' or '**\r\n**' depending on the file you are reading.

So your conditions would be something like :

```
if(myLine.Contains("\n")){
    //DoSomething
}

```
> 1 votes

---
Tags: unity, unityscript
---


# Question
Title: How to handle collision when using sprites in a 3d environment in Unity?
In games like AoE2, they've used sprites for the buildings and they've handled the collisions very well. How would I achieve something like that in Unity?

Currently, I've tried using box colliders along with the sprite renderer in a child game object. It didn't worked out well though.

# Answer
> 0 votes
Finally after doing much research and tests, we came up with a solution.

We've used the same 3d mesh but with the mesh renderer turned off. Overlaying the sprite over the mesh, we've managed to come up with something decent.

The mesh would then work as the collider but without the extra high poly cost. So now, interactions could work perfectly.

---
Tags: unity, collision-detection, sprites, rts
---


# Question
Title: How to use multiple shaders with LibGdx + SpriteBatch
I'm programming a 2D game libgdx. I'm using a `SpriteBatch` of course to draw some `Sprites`. Now I wanted to use multiple `ShaderPrograms` with the `SpriteBatch`, but unfortunately you can set only one \`ShaderProgram at a time. For example, I wanted to draw the whole scene with a specific color and wanted to add a parallax effect to some sprites by manipulating the texCoords in the shader. I know in native OpenGL you can just enable as much shaders as you want before your draw call. But it seems that in libgdx it is not possible.

# Answer
You can first render your scene to a texture with the first shader, then render the texture with the second shader. This will apply both shaders to your scene. You render to texture using a `FrameBuffer`.

```
SpriteBatch batch = new SpriteBatch();
FrameBuffer fbo = new FrameBuffer(Format.RGBA8888, width, height, hasDepth);
TextureRegion fboTexture = new TextureRegion(fbo.getColorBufferTexture());
fboTexture.flip(false, true); // Have to flip on Y axis

public void render(float delta) {
    // Draw scene to texture
    batch.setShader(shader1);
    fbo.begin();
    // If you're having issues with the drawing try doing glClear right after fbo.begin().
    batch.begin();
    // Draw here
    batch.end();
    fbo.end();

    // Draw scene to screen
    batch.setShader(shader2);
    batch.begin();
    // Draw here
    batch.end();
}

```

The much simpler way would be to just combine the two shaders into one shader, though.
> 4 votes

---
Tags: libgdx, shaders, spritebatch
---


title: Clan, guild, team, faction or group?

text:
# Question
Title: Clan, guild, team, faction or group?
I don't know if this is the right question for Stackexchange because it is based on opinion, so excuse me if it's not.

I'm currently developing a mobile leisure game in a cartoon style where players build and expand their kingdom, in a medieval setting. Users can be part of a group to help each other, trade goods, communicate together, and support each other when attacked. The game is NOT a fight game only. Developing and maintaining your city and the citizens is an important aspect, socializing with other players is key, and the target audience are both men and **women**.

I'm really confused how I should name such groups where you can be part of. Clans, guilds, teams, groups or factions: all of them are possible. When should I use which name? And what would fit my situation the best? It's really important to let users feel they are part of a group. Not just a fighting group, but a group both men and women feel attracted to. A fraction for example would not be the best I think.

I realize this heavily depends on opinions. Buy are there any sources that could help me? What do you feel attracted to? What fits my situation the best?

# Answer
> 1 votes
There is no standard. I have seen all kinds of names used for different kinds of player-groups. Which one is appropriate mostly depends the scenario of the game and how you intend players to interact with each other and how you expect them to interact as a group with the rest of the game world.

When your game has a medieval theme, you might want to look how historic cooperations of medieval rulers called themselves: Empires, Alliances, Federations, Pacts, Leagues.

Another way to come to a conclusion is to ask yourself how *the players* would call their groupings.

# Answer
> 0 votes
Or even better, you could do a survey with your current players or with players of similar games as the one that you are building.

---
Tags: user-experience
---


# Question
Title: How to delay a timer when it's run the first time in update method not using a coroutine
In the code below I am resetting a timer after a duration `maxiTime` within the update method. I want to delay the timer before it begins to run for a certain duration. I believe this could be done with a coroutine, but I am using `StopAllCoroutines`, so I need to do this within the update method. How can I get the delay only before the first run?

```
        timeElapsed +=1;
    if(timeElapsed >= maxiTime) {

        timeElapsed = 0;

        Debug.Log ("Thank You!");
    }

```

# Answer
For something like this you can just start the timer at a negative value. It's easy, simple, and gets the job done.

```
Start() {
    timeElapsed = -1;
}

```
> 0 votes

---
Tags: unity
---


# Question
Title: How to put a reference to my player (already instanced) into a prefab that will be instantiated later
I'm making an enemy in my game. He stands at the side of road with a rocket launcher and fires when you get close. It nearly all works fine, except I just need a reference to the players position so that I can make his rocket explode when it reaches the same height on the map as the player car.

The enemy is a prefab which is NOT instanced at build-time, there a several spawn-points all with n% chance of spawning a guy there using the prefab. The player IS instanced at build-time. And here is my problem..

Although I have put a "public GameObject player" into my variables in the script on the prefab, it doesnt let me drag the already instanced player into it. I've read about a bit, and I see that Unity will not allow this (or at least thats what I gathered!)

So after much searching I came up with

```
player = GameObject.FindGameObjectWithTag("Player");

```

But i havent even tested yet because the source where i got that advice in the very next comment the guy says I shouldnt do this because it takes too much system resources up.

***EDIT: I have tested it with that line, it does work. But is there a better way***

But he doesnt say the way that it should be done! And the thread is about 6 years old. So I thought I'd write here again and ask you fine folks for more help.

I hope I explained the problem clearly enough, I think i got the terminology right. Basically, the RocketerEnemy prefab is going to be instantiated in runtime, but the PlayerCar is already instantiated by my dragging it into the heirarchy at the beginning of the project. This is stopping me from dragging the PlayerCar object into the box in the Inspector (for the Enemy prefab) . All I really need is the PlayerCar.transform.position.Y value for each frame.

THANKS IN ADVANCE !

# Answer
# You can't and shouldn't

Prefabs don't exist until they've been instantiated. As such, they cannot hold references to anything in a scene (things that do exist) because when they *are* instantiated those things might not exist any more! It could have been destroyed, it might be in a different scene, etc. etc.

You have to find the object you want to reference (the player) either when you instantiate the object, eg.:

```
GameObject go = Instantiate(myPrefab);
go.GetComponent<MyAwesomeScript>().thePlayer = someRefToPlayer;

```

Or figure out what it is in that prefab's script's `Start()` method:

```
Start() {
    thePlayer = GameObject.Find("Player");
}

```

Note that `Find()` is slow (you may also want to use `FindWithTag()` instead).
> 1 votes

---
Tags: unity, c#, gameobject, instancing
---


# Question
Title: How to design a Skill/Monster/Item etc. dictionary for a game?
I am trying to build a turn-based RPG where party members and enemies can cast skills and use items. How could I implement a modular list of skills/items/monsters (and maybe character classes, if I get there) so that each PartyMember or Enemy could choose a skill/item from the list and cast it?

My first attempt was this:

```
public static Dictionary<int, Skill> SkillDictionary = new Dictionary<int, Skill>
{
    {1, new Skill1()},
    {2, new Skill2()},
    {3, new Skill3()},
};
public abstract class Skill
{
    int skillIndex;
    public abstract void CastSkill();
}
public class Skill1 : Skill
{
    public Skill1(){skillIndex = 1;}
    public override void CastSkill(){};
}
public class Skill2 : Skill
{
    public Skill2(){skillIndex = 2;}
    public override void CastSkill(){};
}
public class Skill3 : Skill
{
    public Skill3(){skillIndex = 3;}
    public override void CastSkill(){};
}

```

As my code currently stands, each skill is instantiated only once, before Main (due to the dictionary being static). Is there a way to do lazy loading so I won't have to instantiate the skill until called? Is lazy loading favorable to what I have so far? (in case I get to the point where I have LOTS of items, monsters, etc.) Furthermore, suppose I were to make a MonsterDictionary. Then would it be wise to call a Clone method in order to make a new instance of a monster? Perhaps:

```
public Monster
{
   string name;
   int otherStats;
   public Monster(Monster clone)
   {
      this.name = clone.name;
      this.otherStats = clone.otherStats;
   }
}

```

And to create a new instance of the monster in battle, for example:

```
Enemy e = new Monster(MonsterDictionary["Slime"]);

```

Or - the golden question - is there a better design pattern altogether? Would an Enum be adequate instead of a dictionary in some of these cases? I'm relatively new to C# and game development, so I would like some feedback if possible. I'm curious to see how others organized their game data.

# Answer
> 1 votes
For one I would suggest doing a data-driven approach for your skills instead of individual classes. It will make your game much more consistent and manageable in the long run. You also get the bonus of being able to easily pull out your skill data from the code into an easily moddable format like JSON or YAML.

One article that really demonstrates this concept is this custom ability guide for Dota2.

One way that to solve your skill problem is to create two classes, one that holds shared data (attack name, attack type, range, base damage etc.) and one that holds instance specific state (uses this turn, remaining cooldown etc.) as well as a reference to look up the shared data object in the dictionary.

So when I want to add a skill to a unit, I would just need to create a new skill instance object that would just contain a reference to the dictionary that holds the skill data.

For your monster example, the same concept can be utilized.

---
Tags: c#, design-patterns, data-structure
---


# Question
Title: How can i detect if the player is inside an explosion radius?
I'm making a driving game, there are enemies which spawn on the side of road and when my player car gets close, they fire a rocket in front of the player. I need to detect if the car is within a certain radius of the explosion center. So when I can detect that I'm assuming I can then use rb.AddExplosiveForce to make the car fly a bit or something.

What is the recommended way to get the blast radius collider (or equivalent) and detect if the player is inside it?

# Answer
For an instantaneous radius check, you can use the OverlapSphere method like so:

```
Collider[] hits = Physics.OverlapSphere(
          explosionCenter,
          explosionRadius,
          layerMaskToCheck );

```

This gives you an array containing all colliders touched by the explosion's spherical volume. You can then iterate through that array to apply forces & damage to their corresponding objects.

For better control over performance, you can use the NonAlloc version where you prepare a reusable buffer in advance, so it can fill that existing array with its results instead of allocating new ones and creating garbage to collect later.

However, if only the player is affected, then you can skip the physics queries entirely and just use a distance check to detect whether the Player object is within a given radius of the hit point:

```
 if((player.transform.position - explosionCenter)
   .sqrMagnitude < explosionRadius * explosionRadius)

```

(Here using a common trick of comparing squared values to skip an unnecessary square root operation — this isn't terribly important if you're only doing it a few times, just a habit a lot of us are in)
> 4 votes

---
Tags: unity, collision-detection, gameobject
---


# Question
Title: Any other method available in libgdx for android than "Gdx.input.istouched()" method?
can someone explain me this.I need to know whether any other methods can be implemented to deal with user touch inputs instead of "Gdx.input.istouched()" Iam a noob and learning android game development using libgdx.I have used above method which is not satisfied for the desired output.Is there anyone to help.I will share my code if so

# Answer
> 0 votes
You can create your own `InputProcessor` and use that to catch **all** touch events.

```
public class YourGame extends ApplicationAdapter {
    public void create() {
        Gdx.input.setInputProcessor(new InputProcessor() {
            @Override
            public boolean touchUp(int screenX, int screenY, int pointer, int button) {
                // Handle touch up here
                return false;
            }

            @Override
            public boolean touchDragged(int screenX, int screenY, int pointer) {
                // Handle dragging here
                return false;
            }

            @Override
            public boolean touchDown(int screenX, int screenY, int pointer, int button) {
                // Handle touch down here
                return false;
            }

            @Override
            public boolean scrolled(int amount) {
                return false;
            }

            @Override
            public boolean mouseMoved(int screenX, int screenY) {
                return false;
            }

            @Override
            public boolean keyUp(int keycode) {
                return false;
            }

            @Override
            public boolean keyTyped(char character) {
                return false;
            }

            @Override
            public boolean keyDown(int keycode) {
                return false;
            }
        });
    }

```

---
Tags: android, libgdx
---


# Question
Title: How do I render a PNG with transparency in LibGDX?
I'm building a simple tic-tac-toe example with LibGDX. I have simple images: cross, circle and board, all `png`s created with GIMP with a transparent background.

How can I render them as a `Texture` with transparency?

I've tried with GL10 enable feature, but it seems not to work.

# Answer
SpriteBatch#enableBlending

before rendering:

```
batch.enableBlending();
batch.begin();
//draw stuff
batch.end();

```
> 5 votes

# Answer
Create Sprite and assign Texture to it, Then use Sprite setColor to adjust its alpha, like so,

```
Texture yourTexture = new Texture("image.png");
sprite = new Sprite(yourTexture);
//RGBA
sprite.setColor(1, 0, 0, 0.2f);

```

and in render() loop use SpriteBatch

```
sprite.draw(spriteBatch);

```
> 2 votes

# Answer
If you put

```
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);

```

at the beginning of your render() loop is should refresh the screen with the colour black. So if any images have transparency in them it will be noticeable.

so your render() loop would possibly look like this

```
public void render(float delta) {
  Gdx.gl.glClearColor(0, 0, 0, 1);
  Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);

  // Update logic & etc.

  batch.begin();

  // Place your render calls
  // In this I use a Sprite object named "sprite" and all you need to do is call .draw();
  // on it and it will render at 0,0, unless told differently with .setPosition();

  sprite.draw(batch);

  batch.end();
}

```
> 1 votes

# Answer
I tried to render a .png with transparency as well. With the basic setup (blending not activated) it didn't render properly.

I never activated blending, but I did add this:

```
Gdx.gl.glClear(GL20.GL_ALPHA_BITS);

```

My issue was the alpha was never cleared. Meaning if I rendered with 0.1 alpha, it would take 10 frames until the alpha was "stacked" back up to 1. Adding the call above cleared the alpha, just like you would clear color.

I know this is an old question, so the solutions then were different. enableBlending should still work, but I am not sure if this prevents "stacking" of alpha. Clearing the alpha bits is probably the easiest way to prevent the solid look.

As for the actual rendering, that is the same as always.

```
//Viewport, camera, logic, etc
batch.begin();
//draw your image(s) here
batch.end();

```
> 0 votes

---
Tags: java, libgdx, lwjgl, transparency
---


# Question
Title: How to program an experience-based levelup system where experience carries over to the next level?
I'm new into programming, and i've tried to do a system of level up. Here it is :

```
if ($exp >= $max_exp)
{
        $query=$db->prepare('UPDATE users SET level_up = 1 WHERE username = "'. $username .'"');
        $query->execute();
        $query->CloseCursor();
}

if ($level_up >= 1)
{
        $query=$db->prepare('UPDATE users SET exp= 0, level = (level + 1 * level_up), max_exp = (max_exp * 1.2), spoint = (spoint +5 * level_up), level_up = 0 WHERE username = "'. $username .'"');
        $query->execute();
        $query->CloseCursor();
}

```

Explaination :

* If the user get more xp (exp) than xp needed to level up (max\_exp), he get a level up (level\_up)
* When the user level up, his XP is set to 0, his level goes up by (1 * the number of times he leveled up), same thing for his spoint (Special points). And next, his xp needed to level up goes up by 1.2.

Here are the problems with my badly coded system :

* If max\_exp is 100 and the user get 1000 xp, he will only get 1 level and loose the 900 xp because when he level up, the xp go down to 0. Any way to fix this ?
* If the user level up twice, the max\_exp will only multiply once by 1.2, so if a user is level 1 and level up to 3, he will get the max\_exp of a level 2 user.
* If there is another way than doing it without the level\_up, i will gladly take it.

Thanks for the help !

# Answer
> 3 votes
Solution A: Don't store the level or the experience points from the last levelup. Only store the total number of experience points the player collected from the start of the game. When you want to know the character's level, calculate it from the experience.

Solution B: Replace `exp= 0` with `exp = exp - max_exp`. That way excess experience will be carried over to the next level. If you want one call to this code section to result in more than one levelup, you need to replace the `if ($exp >= $max_exp)` with a `while ($exp >= $max_exp)` loop, so you do levelup events until the experience points are used up:

You should avoid doing that many SQL updates. Each UPDATE requires a network roundtrip to the database and a search query on the database server. Those latency times add up! Do everything you need to do with the player-object in your PHP code and then do *one* UPDATE with *all* the changed fields when you are finished.

This is how I would have written this:

```
$hadLevelup = false;

while ($exp >= $max_exp) {
   // update level
   $exp = $exp - $max_exp;
   $level = $level + 1;
   $max_exp = $max_exp * 1.2;

   // update player stats
   $spoint = $spoint + 5;

   $hadLevelup = true;
}

if ($hadLevelup) {
   // persist the character to the database
    $query=$db->prepare('UPDATE users SET exp= (1), level = (2), max_exp = (3), spoint = (4) WHERE username = (5)');
    $query->bindParam(1, $exp);
    $query->bindParam(2, $level);
    $query->bindParam(3, $max_exp);
    $query->bindParam(4, $spoint);
    $query->bindParam(5, $username);
    $query->execute();
    $query->CloseCursor();
}

```

By the way: Another thing you might notice is that I am using placeholders and `bindParam` instead of just concatenating strings to an SQL statement. The reason for that is that if you don't use placeholders, you miss out on the main reason why PHP deprecated the old `$mysql_` API and introduced the new `$mysqli` API with its prepared statements: What if I name my character `"; DROP TABLE users`?

---
Tags: mathematics, php, mysql
---


title: how to make a timer on JavaScript?

text:
# Question
Title: how to make a timer on JavaScript?
I have a JS game similar to snake how can i set a timer for the game where when the game ends it displays game over, shows the score of the player, and has a play again button?

# Answer
> 0 votes
# Use `setTimeout`

```
setTimeout(function(){code here},seconds*1000)

```

The code will run after X seconds.

---
Tags: javascript, timer
---


# Question
Title: How to distinguish multiple same element already in place on a minecraft map
I am currently working on a minecraft plugin using spigot. It's a sort of a race between players where checkpoints validation is needed.

I have a minecraft map edited on MCEdit and I have severals signs already set on the map that serves as "checkpoints".

All I need is to find a way to distinguish the signs.
I would like to get x y z coordinates of each signs but I've thought that there could be map makers that wouldn't name their signs the same way I do, so I need to find another way to distinguish the signs.

I have a debut code but i don't have any ideas to get it forward.

```
@EventHandler
public void onClick(PlayerInteractEvent e){

        if(e.getItem().getType() == Material.SIGN){

            //I'll have to getlocation() the signs
            //And maybe store the locations in an array

            e.setCancelled(true);
        }

}

```

Any ideas?

# Answer
So I've bypassed the problem just by setting a new checkpoint on clicking on a sign. Here's the code in case it helps someday :

```
Location checkpoint;

public void setcheckpoint(int x, int y, int z, Player p) {

    Location checkpoint = new Location(p.getWorld(), x, y, z);
    this.checkpoint = checkpoint;

}

@EventHandler
public void onClick(PlayerInteractEvent e) {
    Player p = e.getPlayer();
    if (e.hasBlock() && e.getAction() == Action.RIGHT_CLICK_BLOCK) {
        if (e.getClickedBlock().getType() == Material.SIGN) {
            setcheckpoint(e.getClickedBlock().getX(),e.getClickedBlock().getY(),e.getClickedBlock().getZ(),p);
        }

    }

}

```

The checkpoint the player clicked on gets it's coordinates stored into the checkpoint Location, which is much simpler.

Sorry on having taken your time and thanks for the help !
> 0 votes

---
Tags: java, minecraft-modding, plugin, bukkit
---


# Question
Title: Is it possible to not pack asset files into archives when building a Unity game?
When I build a game in Unity, it packs the assets into strange data files with strange extensions like .split2 or .split1.

But what if I want to give the player the ability to replace textures and modify the game without reverse engineering these files?

I want the Assets folder as I see it in the editor to be accessible with the same files in the build.

# Answer
> 3 votes
This process Unity uses is called "data baking" and it accomplishes a lot of useful things for your game:

* It converts the textures into appropriate sizes for your build target (scaling huge or non-power-of-two source assets into something practical for runtime use).
* It packs sprites into atlas textures for drawing lots of them efficiently.
* It converts the textures into GPU-friendly formats that can be pushed straight into video memory (possibly using compressed formats to save space). GPUs don't speak jpeg/png directly, so you pay this transcoding cost any time you want to turn an image into a texture.
* Similar tricks happen with sounds, meshes, fonts, etc - preparing them all into the format that the destination platform likes best.
* Finally, it packs-together assets that are used together into batches that can be loaded all at once, instead of going file-by-file, making more efficient use of disc access and memory space.
* Now that all the files are in known offsets inside these batches, game content referencing them can do so directly by ID, without needing to know the whole asset path or going through extra indirection steps.

All of this adds up to faster loading times and more predictable performance when the game is being played. By doing the complicated data transformations at build time, the runtime's job is much simpler: just pull this data off disc and start using it, no extra translation required.

So while you can load arbitrary unbaked files at runtime, using for example the WWW class, doing so puts all of this work right in the middle of when the player is trying to play the game, slowing down the game for everyone. It also increases the complexity of your scripts, since you're now responsible for figuring out when an asset needs to be loaded, which objects should reference which of these runtime-loaded assets, and when those assets can be unloaded safely.

One way you can open the game to modding without impacting all of your load times is to think of it as a runtime asset *swap*:

1. You build your game normally, with all the assets loaded from packed files as usual - so you get fast load times and the usual convenient scene authoring.
2. You add an extra script that, on startup, looks for a "mod manifest" text file that the player can put in a specific location.

* This file can be created & edited by the player to say things like "all `Enemy 1` textures should instead use `C:\Users\PlayerName\Documents\MyAwesomeNinja.jpg`"
    * If the file is missing, then you skip over it, and the player gets the "vanilla" version of the game with minimal extra overhead.
3. If the mod manifest file is found, your script parses it to figure out what the modder wants to change, and loads their replacement assets into an index.
4. Whenever you want to use one of these moddable assets, check this index for a replacement - if it has one, then use the modder's replaced asset instead.

This means a little extra load time and memory use for the modders, since they're pulling in all the (fast) baked assets AND the (slow) custom assets, but at that point the slowness is opt-in, and it's on the modders to make their mods efficient with appropriate texture formats/sizes/etc, without impacting the base game experience much at all.

Here's a simplistic version that works for replacing the main texture for a collection of materials:

```
// Put this script on any GameObject that needs to use custom materials.
public class ModdableMaterial : MonoBehaviour {
    public Renderer targetRenderer;

    private void Start() {
        targetRenderer.sharedMaterial =
            ModMaterialCache.GetModdedVersion(targetRenderer.sharedMaterial);

        // My work here is done.
        Destroy(this);
    }
}

// Use this script to load the mod manifest and generate mappings
// of original to replaced assets.
public class ModMaterialCache : MonoBehaviour {
    // Singleton reference for ease of lookup.
    public static ModMaterialCache _instance;

    // Where should we expect the player to put the mod manifest?
    // (Relative to the game's persistent data path)
    public string manifestPath = "mod_manifest.txt";

    // Expose a mapping of names to materials to populate in the Inspector.
    [System.Serializable]
    public struct ModdableMaterial {
        public string name;
        public Material originalMaterial;
    }
    public List<ModdableMaterial> moddables;

    // Keep a mapping of materials with active mods applied.
    Dictionary<Material, Material> _activeMods
        = new Dictionary<Material, Material>();

    // And let other scripts request the modded versions.
    public static Material GetModdedVersion(Material originalMaterial) {
        // If there's no mod cache in the scene, then just use the original.
        if (_instance == null)
            return originalMaterial;

        // If there is a mod cache, then check it for a replacement.
        Material modded;
        if (_instance._activeMods.TryGetValue(originalMaterial, out modded))
            return modded;

        // No replacement found - keep using the original.
        return originalMaterial;
    }

    // Ensure this has time to load all its materials before you instantiate
    // any assets that use them. Putting it on a title screen with
    // DontDestroyOnLoad can be a good way to choreograph this.
    IEnumerator Start() {
        // Quick Singleton pattern to make a unique instance of this script
        // easy to find & reference when we need it.
        if (_instance != null) {
            Destroy(gameObject);
            yield break;
        }
        _instance = this;
        DontDestroyOnLoad(gameObject);

        // Construct the full path to our mod manifest:
        var manifest = new WWW(Application.persistentDataPath + manifestPath);

        // Let the game run a frame or so until this file has been loaded.
        yield return manifest;

        // If there's no manifest, carry on - but log the issue just in case.
        if(string.IsNullOrEmpty(manifest.error) == false) {
            Debug.LogWarningFormat(
                "Error loading mod manifest: {0}", manifest.error);
            yield break;
        }

        // Walk through each line of the manifest, looking for mods.
        foreach(var line in manifest.text.Split('\n')) {

            // A mod line has the form "name = path/to/the_asset.extension"
            // so we skip lines without an equals sign past the 1st character.
            int separator = line.IndexOf('=');
            if (separator <= 0) continue;

            // Pull out the name of the modded material.
            string name = line.Substring(0, separator).Trim();

            // Check if that name is one in our material list.
            int index = moddables.FindIndex(m => m.name == name);
            if (index < 0) {
                Debug.LogWarningFormat("Unknown moddable name: {0}", name);
                continue;
            }

            // Prepare a modded version of the material:
            Material original = moddables[index].originalMaterial;
            Material modded = Instantiate<Material>(original);

            // Store the original-> modded mapping for ease of lookup later.
            _activeMods.Add(original, modded);

            // Fire off another coroutine to asynchronously load
            // the modded texture to populate this material.
            string path = line.Substring(separator + 1).Trim();
            StartCoroutine(LoadMod(modded, path));
        }
    }

    IEnumerator LoadMod(Material material, string path) {
        // This takes time because we're reading a file off the disk,
        // and translating it to a GPU-friendly format.
        var loader = new WWW(path);
        yield return loader;
        // TODO: error checking...

        // Note that this loads the image as uncompressed ARGB32.
        // You can instead use LoadImageIntoTexture to apply compression.
        material.mainTexture = loader.texture;
    }
}

```

---
Tags: unity, modding, build-process
---


# Question
Title: Finding which tiles are intersected by a line, without looping through all of them or skipping any
I've been staring at this problem for a few days now. I rigged up this graphic to help me visualise the issue: (from the graph, we know that the line intersects \[1, 1\], \[1, 2\], \[2, 2\], \[2, 3\], ending in \[3,3\])

I want to step along the line to each grid space and check to see if the material of the grid space is solid. I feel like I already know the math involved, but I haven't been able to string it together yet. I'm using this to test line of sight and eliminate nodes after a path is found via my pathfinding algorithms - my agents cant see through a solid block, therefore they cant move through one, therefore the node is not eliminated from the path because it is required to navigate a corner.

So, I need an algorithm that will step along the line to each grid space that it intersects. Any ideas?

I've taken a look at a lot of common algorithms, like Bresenham's, and one that steps at predefined intervals along the line (unfortunately, this method skips tiles if they're intersecting with a smaller wedge than the step size).

I'm populating my whiteboard now with a mass of floor() and ceil() functions - but its getting overly complicated and I'm afraid it might cause a slowdown.

# Answer
If you know starting block (you know point X and you dind't include block \[0,1\] in block list, so I suppose you know also the starting block), I think you should surely use Bresenham's algorithm. You wrote, you looked at it.

It's suitable algorithm for this problem. It can be also written in a way, it computes only with integers. You can find a lot of implementations out there on the web.

*EDIT:*

I'm sorry, I haven't realized that Bresenham won't find all blocks. So I found better solution. There is also code written in C++, but I think it shouldn't be hard to understand :)
> 6 votes

# Answer
The code in the example that the accepted answer links to needs some adjustment for perfectly diagonal lines. Here's a complete demo application written with Qt (C++ and QML).

Relevant C++ code:

```
void rayCast()
{
    if (!isComponentComplete())
        return;

    mTiles.clear();
    mTiles.fill(QColor::fromRgb(255, 222, 173), mSizeInTiles.width() * mSizeInTiles.height());

    const QPoint startTile = startTilePos();
    const QPoint endTile = endTilePos();
    // http://playtechs.blogspot.com/2007/03/raytracing-on-grid.html
    int x0 = startTile.x();
    int y0 = startTile.y();
    int x1 = endTile.x();
    int y1 = endTile.y();

    int dx = abs(x1 - x0);
    int dy = abs(y1 - y0);
    int x = x0;
    int y = y0;
    int n = 1 + dx + dy;
    int x_inc = (x1 > x0) ? 1 : -1;
    int y_inc = (y1 > y0) ? 1 : -1;
    int error = dx - dy;
    dx *= 2;
    dy *= 2;

    for (; n > 0; --n)
    {
        visit(x, y);

        if (error > 0)
        {
            x += x_inc;
            error -= dy;
        }
        else if (error < 0)
        {
            y += y_inc;
            error += dx;
        }
        else if (error == 0) {
            // Ensure that perfectly diagonal lines don't take up more tiles than necessary.
            // http://playtechs.blogspot.com/2007/03/raytracing-on-grid.html?showComment=1281448902099#c3785285092830049685
            x += x_inc;
            y += y_inc;
            error -= dy;
            error += dx;
            --n;
        }
    }

    update();
}

```
> 3 votes

---
Tags: java, algorithm, raycasting
---


title: Curved Screen for Monitor in Blender?

text:
# Question
Title: Curved Screen for Monitor in Blender?
I'm trying do get a curved plane for an oldschool monitor but have still no clue how to achive this, even not after hours of searching with Google.

This is what I currently have and I need to curve this plane to look like the curved screen of an tube monitor.

Any ideas how I can achieve this? Thank you in advance! :)

# Answer
> 1 votes
Here is a quick tutorial I made about making a curved surface. Maybe play around with the proportional falloff type: https://screencast-o-matic.com/watch/cbi3oHlUDh

---
Tags: unity, blender
---


# Question
Title: With a rolling pawn, how can I have a component that follows its rotation, but stays upright and only rolls?
I'm using the UE4 rolling pawn to create a Metroid Prime morph ball style pawn. I've got it set up with a ribbon particle component on a spring arm, inheriting yaw, but if I set it to inherit roll, the axes invert and cause the particle emitter to flip and break the ribbon trail.

I'm sure there's some kind of rotation math that it needs, but it's beyond me. I've tried doing various math things to the axes, but I haven't been able to get it to click at all.

# Answer
> 1 votes
Resolved by using "get actor right vector" on the pawn, then "make rot from x", then applying that rotator to the particle component with "set world rotation".

---
Tags: rotation, unreal-4
---


# Question
Title: How do I distribute an executable for a c++/opengl game that uses dynamic libraries?
I have a makefile that compiles everything fine but I'm wondering how I can package the dynamic libraries with the executable for distribution.

# Answer
First you will have to check the license for each individual libraries regarding redistribution.

Then for Linux you will need a launch script that sets the library search path to where you packaged the libraries before launching the executable itself. The environment variable `LD_LIBRARY_PATH` is what you want to set to where you put the libraries.

Your launch script can do extra checks to launch the proper executable for 32 or 64bits, x86 or 10+ variations of ARM, etc.

For Windows you can package the DLLs in the same directory as the executable.

On OSX the libraries are packaged inside the "application" (which is actually a directory) by XCode.

Note: you do not want to include the OpenGL libraries. Those depend on the graphic driver installed so you must use the system's installed libraries.
> 1 votes

---
Tags: c++, distribution
---


# Question
Title: Box2d topdown racing game - killing "residual" forces
I'm making top-down race game in GM:S with Box2D, the car is controled in unusual way: player sets direction and engine's speed, and the car uses them: turns to the desired direction and reaches speed. But the question is about the "residual" speed after the turn. Here is what I mean:

I make rotation by applying torque and move with applying force. I don't have tyres, it's just one plain object.
So how can I get rid of this momentum? I'm working in GM:S, but I'd like to hear any solution, I can adapt it easily.

**Movement code:**

```
var ad = angle_difference(phy_rotation, desiredDir);
physics_apply_torque((angleTorque) * -sign(ad)); // rotate the car

dx = lengthdir_x(spd, -phy_rotation);
dy = lengthdir_y(spd, -phy_rotation);

physics_apply_force(phy_position_x, phy_position_y, dx, dy);  // move the car

```

# Answer
## Combination of Forces

Instead of using a Torque force to steer the car, apply force perpendicular to the direction it is traveling. This is very roughly how the physics actually works.

When you apply the force perpendicular to the forward direction, the forward force and the perpendicular force will combine over each physics update to change the direction of the car. In this way, the forward force is "negated" by being added to the perpendicular force, creating a new direction for the car.

Torque forces and linear forces do not combine in this way. So using torque to turn is actually not affecting the forward force at all.

You may also need to manually apply a rotation to the car to keep it pointed the same direction as it is currently being moved.

## GML Notes

I haven't worked much with physics in Game Maker, however, I'd look at the local physics functions.

https://docs.yoyogames.com/source/dadiospice/002\_reference/physics/forces/physics\_apply\_local\_force.html

With this it'd probably be easiest to setup three "forces" and apply them as needed for acceleration, left, and right turn.

Forward (assuming from your picture that `0,1` is forward):
`physics_apply_local_force(0, 0, 1, 0)`

Left Turn:
`physics_apply_local_force(0, 0, 0, 1)`

Right Turn:
`physics_apply_local_force(0, 0, 0, -1)`

You should swap out the "1" or "-1" for magnitude of the force.

Game Maker example for handling the rotation:
https://docs.yoyogames.com/source/dadiospice/002\_reference/physics/physics%20variables/phy\_rotation.html
> 1 votes

---
Tags: physics, box2d, game-maker, racing
---