title: How to drag-and-drop objects in libGDX?

text:
# Question
Title: How to drag-and-drop objects in libGDX?
I am drawing blocks of various amino acids (array of `aminoacid` objects), where one line of amino acids represents one sequence.

`aminoacid` class:

```
public void renderShape() {
    shaperenderer.setProjectionMatrix(cam.combined);
    shaperenderer.begin(ShapeType.Filled);
    shaperenderer.setColor(cc.getR(), cc.getG(), cc.getB(), 0);
    shaperenderer.rect(xpos, ypos, aawidth, aaheight);
    shaperenderer.end();
}

public void renderBatch() {
    batch.setProjectionMatrix(cam.combined);
    batch.begin();
    font.setColor(Color.BLACK);
    font.draw(batch, name, xpos+Game.AAFONTOFFSETX, ypos+Game.AAFONTOFFSETY);
    batch.end();
}

```

Now I need a way to drag and drop feature to move the individual blocks. How can I do this? Can I use the `DragAndDrop` class of libGDX? If so, how should I do it??

As a side note, I found a way to do it without libGDX:

```
public class AminoAcidDragAndDrop extends JFrame {
  private String brr_A = "EAQITAPFELSAFTGRPEWI";
  private JTable table;
  private DefaultTableModel tableModel;

  private DefaultTableModel getDefaultTableModel() {

    String[] cols = new String[brr_A.length()];
    for (int i = 0; i < brr_A.length(); i++) {
      String currentAminoAcid = String.valueOf(brr_A.charAt(i));
      cols[i] = currentAminoAcid;
    }

    return new DefaultTableModel(null, cols);
  }

  public AminoAcidDragAndDrop() {
    super("Amino Acid Drag and Drop Demo");

    tableModel = getDefaultTableModel();
    table = new JTable(tableModel);

    JScrollPane sp = new JScrollPane(table, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
        JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    getContentPane().add(sp, BorderLayout.CENTER);
    getContentPane().setPreferredSize(new Dimension(1024, 768));
  }

  private static void createAndShowGUI() {
    // Create and set up the window.
    AminoAcidDragAndDrop test = new AminoAcidDragAndDrop();
    test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    // Display the window.
    test.pack();
    test.setVisible(true);
  }

  public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
      @Override
      public void run() {
        // Turn off metal's use of bold fonts
//              UIManager.put("swing.boldMetal", Boolean.FALSE);
        createAndShowGUI();
      }
    });
  }
}

```

Can I convert it for libGDX? If so, how?

I also tried it with `Actor`s but how can I use an `Actor` array? Would an `ArrayList<>` work?

Now I can move the first aminoacid, but `DragAnDrop` needs a final int. How can I solve this for all aminoacids?

```
public void drop (Source source, Payload payload, float x, float y, int pointer) {
    aminoacidlist.get(aaiddnd).setBounds(aminoacidlist.get(aaiddnd).getXpos()+Game.AAWIDTH, aminoacidlist.get(aaiddnd).getYpos(), Game.AAWIDTH, Game.AAHEIGHT);
    minoacidlist.get(aaiddnd+1).setBounds(aminoacidlist.get(aaiddnd+1).getXpos()-Game.AAWIDTH, aminoacidlist.get(aaiddnd+1).getYpos(), Game.AAWIDTH, Game.AAHEIGHT);
}

```

The compiler tells me:

> aaiddnd cannot refer to a non-final local variable.

# Answer
You can use this, it's a simple way to implement drag and drop of an actor

```
actor.addListener(new DragListener()
{
    public void drag(InputEvent event, float x, float y, int pointer)
    {
        actor.moveBy(x - actor.getWidth / 2, y - actor.getHeight / 2);
    }
});

```

Actor will follow the drag.

If you need to drop your actor at a position and automatically place it at the right position at drop, you can do a thing with **pan** and **panStop** by implementing GestureListener.

**pan** will be triggered every frame during drag and **panStop** will be triggered once at drop. Libgdx wiki about it
> 1 votes

---
Tags: java, libgdx
---


# Question
Title: How to share some elements of array with different players on Photon in the same Room? Unity3d
I want to assign cards to different players in the room. I've a Class "Cards" that contains an array of 52 cards like this: "2\_of\_spades","3\_of\_spades"....... and so on. All i want is to assign random indexes or values to different players on the basis of which I'll instantiate Cards Sprites. How can I do that? I've heard that there are RPC calls but how do I manage to make a "Middle Man" script that would deal with different players?

# Answer
Make a CmdPullCard command for the host, send the command from the player, check if the card has been already pulled before, if not send the card string to the player. (If you're unsure on how to do this, read up on your Unity Networking).

So, something like this:

```
var num = -1;
string card = "";
[Command]
CmdPullCard(){
    While(card!=""){ //check if the card you pulled is empty or not
    num = rnd.Next(0,53);
    card = cards[num]; //pull a card from the deck
    }
cards[num]=""; //set the card as empty so it can't be pulled again
}

```

Of course this code is unoptimized and might run too many times before it gives a card, especially if the number of cards are low, since this is a random number. To avoid this, you need to actually remove the element of the array and change the random number generators max number amount but that'll take more coding.
> 1 votes

---
Tags: unity, multiplayer, card-game, photon
---


title: Cocosdenshion and Android not working

text:
# Question
Title: Cocosdenshion and Android not working
I'm trying to play sounds and music with cocos2d. When I run on iPhone and .caf files the audio is perfect, but on Android it is not playing the background music and is only playing 2 sounds of 10 files. I don't know what I'm doing wrong.

```
#include <SimpleAudioEngine.h>
bool HelloWorld::init()
{
  const char *sound;

#if CC_TARGET_PLATFORM == CC_PLATFORM_IOS
  sound = "Fun.caf";
#else
 sound = "Fun.wav";
#endif

  auto audio = CocosDenshion::SimpleAudioEngine::getInstance();

  audio->preloadBackgroundMusic(sound);

  audio->playBackgroundMusic(sound, true);

  audio->setBackgroundMusicVolume(1.0f);
}

void HelloWorld::playSound()
{
  const char *effect;

   #if CC_TARGET_PLATFORM == CC_PLATFORM_IOS
  effect = "Bomb.caf";
#else
  effect = "Bomb.wav";
#endif

    audio->preloadEffect(effect);
    audio->playEffect(effect);
}

```

# Answer
> 1 votes
Isn't `auto audio = CocosDenshion::SimpleAudioEngine::getInstance();` local and accessible to your init function, how are you reaccessing it in your `playSound()` function?

Also, why are you preloading the audio every time you play it? You should only preload once (such as when the application is first launched)

It would potentially be better to create a 'helper' singleton class (such as an AudioHelper) which when initialized preloads all sound effects based on the current platform, and then with another function to play a sound effect (where you can pass in the required sound file).

So, instead of calling

```
CocosDenshion::SimpleAudioEngine::getInstance() ...

```

You could use your helper class instead, calling

```
AudioHelper::sharedAudioHelper()->playAudio("Bomb");

```

... which will then add on the file extension based on the current platform and then access SimpleAudioEngine to play the effect. Then you'll have audio handling logic accessible throughout your project, and can then customise it to fit whatever your requirements are.

---
Tags: cocos2d-iphone, cocos2d, cocos2d-x, audio
---


# Question
Title: Particle system color not set properly in Android build in Unity.
I want to set the color of "Particle System" that I add to a game object in run time. Both game object and particle system are created in run time too.

I have the following code that works well on PC when I run it... But the problem is that in "Android" builds, color does not set correctly and particles are always "pink".

It should be:

But in Android it seen as:

Here is the code I use:

```
GameObject sphere = GameObject.CreatePrimitive(PrimitiveType.Sphere);
sphere.transform.position = new Vector3(x, y, z);
sphere.AddComponent<ParticleSystem>();
var ps = sphere.GetComponent<ParticleSystem>();
ps.startLifetime = 1;
ps.startSpeed = 0.01f;
ps.startSize = 0.03f;
ps.maxParticles = 10000;
ParticleSystemExtension.SetEmissionRate(ps, 10000);
var sh = ps.shape;
sh.shapeType = ParticleSystemShapeType.Circle;
sh.radius = 0.69f;

var cbl = ps.colorOverLifetime;
cbl.enabled = true;
Color mater = Color.green;
cbl.color = new ParticleSystem.MinMaxGradient(mater);

```

# Answer
Oh God! I change my solution and it work fine!

At first I make an empty GameObject with ParticleSystem attached, then create a prefab of that. after that, I add this prefab to my scene and set the necessary properties to it and then deactivate that.

In my script, add a public GameObject and assigned it to my gameObject (called Ring) that was created before.

Then instatiate it by the following code:

```
GameObject ps = Instantiate(Ring);

```

then make `ps` the child of `sphere`s that I was creating in code:

```
 Ring.GetComponent<ParticleSystem>().startColor = Color.green;
 GameObject ps = Instantiate(Ring);
 ps.transform.parent = sphere.transform;
 ps.transform.localPosition = Vector3.zero;
 ps.SetActive(true);

```

And that's it! It works nice!
> 0 votes

---
Tags: unity, android, textures, particles, materials
---


title: How to "hot-reload" a glsl shader

text:
# Question
Title: How to "hot-reload" a glsl shader
I am wondering if its possible to dynamically change shaders while the code is running. In my game, I want to have a development mode in which users can change the shader source and dynamically see their changes like so: https://www.youtube.com/watch?v=hlSG\_iVC6xc this is my current reload method:

```
//Shader is my shader class and shader is the current shader
//delete all resources of previous shader

if (shader->GetProgram() != 0)
    glDeleteProgram(shader->GetProgram());
if (inShader->GetVert() != 0)
    glDeleteShader(inShader->GetVert());
if (inShader->GetGeom() != 0)
    glDeleteShader(inShader->GetGeom());
if (inShader->GetFrag() != 0)
    glDeleteShader(inShader->GetFrag());

GLuint vertex_shader = glCreateShader(GL_VERTEX_SHADER);
GLuint fragment_shader = glCreateShader(GL_FRAGMENT_SHADER);
GLuint geometry_shader = glCreateShader(GL_GEOMETRY_SHADER);

//create vertex shader
glShaderSource(vertex_shader, 1, (const GLchar**)vertSource, NULL);
glCompileShader(vertex_shader);

//create fragment shader
glShaderSource(fragment_shader, 1, (const GLchar**)fragSource, NULL);
glCompileShader(fragment_shader);

GLuint program = glCreateProgram();

glAttachShader(program, vertex_shader);
glAttachShader(program, fragment_shader);
glLinkProgram(program);

Shader* theResult = new Shader(context);
theResult->SetVertShader(vertex_shader);
theResult->SetFragShader(fragment_shader);
theResult->SetGeomShader(geometry_shader);
theResult->SetProgram(program);

//replace the shader we created with the old one
*shader = *theResult;
delete theResult;
return shader;

```

The above code does one of two things when called, it either gives some undefined graphical behaviour or doesn't seem to reload the shader and use the previous ones. Is there something I'm missing regarding how I'm linking the new shaders, or is this even the right approach?

As requested i will add the shader class information:

```
//shader.h

protected:
/// Shader properties
unsigned int m_VertexShader;
unsigned int m_GeometricShader;
unsigned int m_FragmentShader;
unsigned int m_Program;
OpenGL* mContext;

public:
/// Constructor
Shader(OpenGL* context);
~Shader();

/// Getter/setters shader properties
inline unsigned int GetVert() { return m_VertexShader; }
inline unsigned int GetGeom() { return m_GeometricShader; }
inline unsigned int GetFrag() { return m_FragmentShader; }
inline unsigned int GetProgram() { return m_Program; }
inline void SetVertShader(unsigned int inValue) { m_VertexShader = inValue; }
inline void SetGeomShader(unsigned int inValue) { m_GeometricShader = inValue; }
inline void SetFragShader(unsigned int inValue) { m_FragmentShader = inValue; }
inline void SetProgram(unsigned int inValue) { m_Program = inValue; }

//shader.cpp

Shader::Shader(OpenGL* context)
: m_VertexShader(0),
m_GeometricShader(0),
m_FragmentShader(0),
m_Program(0),
mContext(context)
{}

Shader::~Shader()
{
}

```

# Answer
> 4 votes
I've done this recently, here is how I did it. It might not be the most efficient or smartest way to tackle this problem, but it has the job done. The code is not commented, just ask if something needs to be clarified.

Please not that in my real code I have a proxy enumeration between the shader types and the opengl ones (this is where `ShaderType_Count` comes from, and this is why I can use the shader type as array index, as-is this code will crash)

```
// Shader program stuff
struct Shader
{
    GLenum type;
    std::string filename;
    int id;
}

class ShaderProgram
{
public:
    template <typename Shaders...>
    void AddShaders(GLenum type, std::string name, Shaders... shaders) {
        AddShaders(type, name);
        AddShaders(shaders...);
    }

    void AddShaders(GLenum type, std::string name) {
        m_shaders.push_back(CompileShader(type, name));
    }

    void Link() {
        m_id = glCreateProgram();
        for (const auto& shader : m_shaders) {
            // OpenGL error if shader.id is 0
            glAttachShader(m_id, shader.id);
        }
        glLinkProgram(m_id);

        // Check link status
        // Detach and delete shaders
    }

    void Reload() {
        glDeleteProgram(m_id);

        // This is not efficient
        for (size_t i = 0; i < m_shaders.size(); ++i) {
            Shader new_shader = CompileShader(m_shaders[i].type, m_shaders[i].filename);
            if (new_shader.id != 0) {
                m_shaders[i] = new_shader;
            }
        }

        Link();
    }

private:
    Shader CompileShader(GLenum type, std::string filename) {
        Shader result;

        // 1. Load file content
        /* ... */

        // 2. Create shader and compile it
        result.id = glCreateShader(type);
        glShaderSource(result.id, 1, &shader_source, 0);
        glCompileShader(result.id);

        GLint compiled = GL_FALSE;
        glGetShaderiv(result.id, GL_COMPILE_STATUS, &compiled);
        if (compiled != GL_TRUE) {
            // Print error logs, etc
            result.id;
        }

        return result;
    }

private:
    GLuint m_id;
    std::vector<Shader> m_shaders;
};

// Reload stuff
class AssetManager {
public:
    AssetManager() {
        m_stopListening = false;
        m_fileChangesListener = std::thread(&AssetManager::ListenToFileChanges, this);
    }

    ~AssetManager() {
        m_stopListening = true;
        m_fileChangesListener.join();
    }

    ShaderProgram* AddShader(std::string name) {
        auto it = m_programs.insert(std::make_pair(name, ShaderProgram));
        return &it.first->second;
    }

    void ReloadData() {
        std::lock_guard<std::mutex> lock_guard(m_fileChangesMutex);
        for (auto program : m_dirtyPrograms) {
            program->Reload();
        }

        m_dirtyPrograms.clear();
    }

    void AssetManager::ListenToFileChanges()
    {
        // Available with VS2015, Recent GCC and Clang have it too
        namespace fs = std::experimental::filesystem;
        using namespace std::chrono_literals;

        while (!m_stopListening) {
            for (auto& program : m_programs) {
                ShaderTimeArray& shader_array = m_shadersLastTime[program.first];
                for (const auto& shader : shaders) {
                    // Check the last time the file was written
                    auto time = fs::last_write_time(fs::path(shader.filename)).time_since_epoch().count();
                    auto last_time = shader_array[shader.type];

                    // And compare it with the known time.
                    if (last_time != 0 && last_time < time) {
                        // If they do not match, mark the program as needing a reload
                        m_dirtyPrograms.push_back(&program.second);
                    }
                    shader_array[shader.type] = time;
                }
            }

            // Just run this code once every second
            std::this_thread::sleep_for(1s);
        }
    }

private:
    using ShaderTimeArray = std::array<int64_t, ShaderType_Count>;
    std::map<std::string, ShaderProgram> m_programs;
    std::map<std::string, ShaderTimeArray> m_shadersLastTime;
    std::vector<ShaderProgram*> m_dirtyPrograms;
};

// Usage code
int main()
{
    AssetManager mgr;
    ShaderProgram* prg = mgr.AddShader("program");
    prg->AddShaders(GL_VERTEX_SHADER, "foo.vert", GL_FRAGMENT_SHADER, "foo.frag");

    while (true)
    {
        // Reload data that needs to
        mgr.ReloadData();
        // Update
        // Draw
    }

    return 0;
}

```

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


# Question
Title: Cocos2dx launcher - how do I set a newer engine version?
Why doesn't Cocos(V3.10) detect my newer engine version (3.14) which I downloaded and placed into the engine folder? ( I mean the launcher, the all-in-one version where you can create your project much easier)

thanks in advance!

# Answer
Probably you are talking about the cocos studio launcher. It is a cancelled project, they dont give more support to it. However, you can still using cocos studio for GUI/level designing and then importing it to your 3.x newer version.
> 0 votes

---
Tags: cocos2d, cocos2d-x
---


# Question
Title: Unity 5 - Audio Source - 3D rolloff without stereo pan effects
Somebody know if it is possible to use 3D rolloff of of an Audio Source without having stereo effects (You get a stereo pan effect depending on the position of your audio listener).

I know that I can do Spatial Beld to 2D but then the 3D rolloff stops and I would have to implement my own rolloff.

# Answer
> 1 votes
In case somebody still wants to know. Just set "Spread" to 180. This makes the audio roll off/on in volume but no stereo panning anymore.

# Answer
> 0 votes
As far as I found out there is currently (Unity 5.4) no way to to this.

I will implement it by controlling the AudioSource volume by script. I will use the set audio volume in the prefab as max volume so the AudioSource volume can still be uses to reduce the the overall volume of the AudioSource component.

There might be also a possibility to use a custom Audio Spatializer but from the first look ist was more complicated.

---
Tags: unity, audio
---


# Question
Title: How can I detect if a gamepad stick has been pushed to the limit?
As in the question, really. I want to be able to detect if a gamepad has it's analogue input pushed as far as it can go in any direction.

Given x and y axis values in the range \[-1, 1\] (-1 being left and down respectively), how can I account for all of the angles between horizontal and vertical, as this means that I can't simply check `if abs(axis) == 1`.

As I'm unaware of how it might affect it, the engine I'm using is UE4, so any answer could take that into account.

# Answer
> 1 votes
Joysticks on gamepads are far from accurate. The best that you can do is designate a circular-ish region at the edge as fully pushed.

```
if(x*x + y*y > 0.9)

```

---
Tags: input, unreal-4
---


title: How accurate is Gdx.input.justTouch()?

text:
# Question
Title: How accurate is Gdx.input.justTouch()?
We're developing a game, we want to perform actions the moment the user touches the screen, delays make the game impossible to play.

We're testing on samsung S3 mini and samsung a5, we know they are low end devices and lags are to be expected. But How accurate is `Gdx.input.justTouch()`? Is it so accurate on high end phones?

* If not then how to improve the accuracy?
* Is the same problem expected from keyboard or mouse input if we publish a webapp version?

# Answer
> 2 votes
`Input.justTouched()` returns `true` if an event has occurred between the current frame and the previous. That means it's as accurate (or indeed as in-accurate) as the frame rate.

Two separate calls to `justTouched` made during one `render` call on the `ApplicationListener` will always return the same value.

---
Tags: java, android, libgdx, iphone
---


# Question
Title: Unity% Mechanim animation does not move straight
I've imported a mixamo animation into unity5.
I've also set up a trigger to move the character forward, the wierd thing is that when the animation finishes his rotation is not perfectly straight. So the next time he moves forward his rotation is a bit to the left so eventually he ends up running in a circle.

Is there a setting to assure that my character will only move forward when he during moving forward, or should I programatically change these parameters to assure that?

# Answer
Under Animations in the model Import Settings, check the **Root Transform Rotation**. There you can specify an offset until the character's forward direction is exactly at (0.000, 0.000, 1.000) - the last number may differ, since this indicates the speed at which the root motion moves in a certain direction.

The direction is indicated above or below these settings. I currently don't have a character to test it out, but remember this was how I worked around the issue.
> 1 votes

---
Tags: unity, animation
---


title: UV World mapping in shader with Unity.

text:
# Question
Title: UV World mapping in shader with Unity.
Please refer to this Answer.

DMGregory script is working for me, although I have a problem I can't fix because I don't talk shader :)

The tiling will be applied correctly on geometry aligned on XY plane BUT if you have an orthogonal plane (let's think a common room with 4 walls), the texture will stretch through the plane. Do you know how to fix that? I would like to apply world coord to texture for all 4 walls. (Note that the "plane" I am using is a simple quad made of 2 triangles.)

Here is a screenshot:

EDIT: After digging a while I found this guy here which did something similar.

My guess was to use the plane normal to set up the texture but, not knowing the syntax, the result was... well nothing :)

Here you can see the shader. Anyway, as pointed by DMGregory, it doesn't work for all wall angles. Notice the one in diagonal, shown in the picture.

```
Shader "Diffuse - Worldspace"
{
  Properties
  {
    _Color ("Main Color", Color) = (1,1,1,1)
    _MainTex ("Base (RGB)", 2D) = "white" {}
    _Scale ("Texture Scale", Float) = 1.0
  }

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

    CGPROGRAM
    #pragma surface surf Lambert

    sampler2D _MainTex;
    fixed4 _Color;
    float _Scale;

    struct Input
    {
      float3 worldNormal;
      float3 worldPos;
    };

    void surf (Input IN, inout SurfaceOutput o)
    {
      float2 UV;
      fixed4 c;

      if(abs(IN.worldNormal.x)>0.5)
      {
        UV = IN.worldPos.yz; // side
        c = tex2D(_MainTex, UV* _Scale); // use WALLSIDE texture
      }
      else if(abs(IN.worldNormal.z)>0.5)
      {
        UV = IN.worldPos.xy; // front
        c = tex2D(_MainTex, UV* _Scale); // use WALL texture
      }
      else
      {
        UV = IN.worldPos.xz; // top
        c = tex2D(_MainTex, UV* _Scale); // use FLR texture
      }

      o.Albedo = c.rgb * _Color;
    }
    ENDCG
  }

  Fallback "VertexLit"
}

```

# Answer
Thanks for your patience. Here's a way to get decent worldspace texturing on flat/hard-edged surfaces for walls & ramps, aligning the vertical axis of the texture with the world up direction:

This won't work for purely horizontal surfaces like floors & ceilings, where world "up" points into the surface, not along it, so we'll include a fallback alignment for those cases (say, aligning the texture vertical with world "north" instead)

Here since we're in 3D I'm assuming we want to use a lit Surface Shader, so starting with a new default Surface Shader we need to do two things:

1. Find the `#pragma surface` line and add "`vertex:vert`" to the end of it, to say we want to use a custom vertex-modifying function named "vert"
2. Write a vertex shader called "vert" that takes an `inout appdata_full` argument and modifies its texture coordinates.

```
    CGPROGRAM
    // Physically based Standard lighting model, and enable shadows on all light types
    #pragma surface surf Standard fullforwardshadows vertex:vert

    void vert(inout appdata_full v) {

        // Get the worldspace normal after transformation, and ensure it's unit length.
        float3 n = normalize(mul(unity_ObjectToWorld, v.normal).xyz);

        // Pick a direction for our texture's vertical "v" axis.
        // Default for floors/ceilings:
        float3 vDirection = float3(0, 0, 1);

        // For non-horizontal planes, we'll choose
        // the closest vector in the polygon's plane to world up.
        if(abs(n.y) < 1.0f) {
             vDirection = normalize(float3(0, 1, 0) - n.y * n);
        }

        // Get the perpendicular in-plane vector to use as our "u" direction.
        float3 uDirection = normalize(cross(n, vDirection));

        // Get the position of the vertex in worldspace.
        float3 worldSpace = mul(unity_ObjectToWorld, v.vertex).xyz;

        // Project the worldspace position of the vertex into our texturing plane,
        // and use this result as the primary texture coordinate.
        v.texcoord.xy = float2(dot(worldSpace, uDirection), dot(worldSpace, vDirection));
    }

```
> 1 votes

---
Tags: unity, c#, shaders, textures, uv-mapping
---


# Question
Title: How do I get the camera's local XYZ axis in Direct X 11?
I'm currently working on quaternion rotation and I have them working, but it seems to be using the world XYZ axis to rotate around, which is an issue as the camera rotates itself around an axis.

Similar to the last image, how do I rotate the camera around its local XYZ axis rather than the world XYZ?

**Edit**:

The camera now rotates around its local axis, but when doing so, it does not change its values in world space. I can hold a key down and it will rotate around the correct axis, but once I release the key it will snap back to its original position before the rotation began. What must I do to allow the local changes to be applied to world space?

# Answer
To rotate something around it's local X, Y and Z axes instead of around the global axes you need to rotate it first and then translate it.
> 1 votes

---
Tags: camera, directx11, quaternion
---


title: My array loads in the wrong order

text:
# Question
Title: My array loads in the wrong order
I have a load all chapters script which loads up all the Chapter items in an array and instantiates the buttons in the Viewport so you can select which chapter you would like to play. The problem is the chapters load up in the wrong order, they load up as Chapter 4, Chapter 0, Chapter 1, Chapter 2, Chapter 3. Below is the code I am using.

```
void Start()
{
    menuManager = GetComponentInParent<MainMenuManager>();
    levelManager = GetComponentInParent<LevelManager>();

    chapterArray = Resources.LoadAll<GameObject>("Chapters").OrderBy(go => go.name).ToArray();

    txtStatus.text = "";
    if (chapterArray == null)
    {
        txtStatus.text = "Could not find Chapters";
        return;
    }
    else
    {
        txtStatus.text = "Loading...";
        FillChapterList();
    }
    txtStatus.enabled = false;
}
void FillChapterList()
{
    foreach (GameObject chapter in chapterArray)
    {
        GameObject listChapter = Instantiate(chapterListItemPrefab);
        listChapter.transform.SetParent(chapterListParent, false);

        ChapterListItem _chapterListItem = chapterListItemPrefab.GetComponent<ChapterListItem>();
        chapDetails = chapter.GetComponentInChildren<ChapterDetails>();

        _chapterListItem.Setup(chapDetails.chapterNumber,chapDetails.chapterName);
    }
}

```

This is not only happening with the Chapter Select, it has been happening with all the arrays I load up in this fashion. Below is the visual side of the problem where you can see it loads the last object First.

I have been struggling with this for a while and I think its stopping me from progressing forward. Thank you for reading this and taking the time out of your day to help.

# Answer
> 0 votes
Thanks to the awesome people on the GameDevLeague Discord channel, it got solved. Sitting back now its quite funny how easy it was to miss. I needed to change `chapterListItemPrefab.GetComponent<ChapterListItem>();` to this `listChapter.GetComponent<ChapterListItem>();` now it works 100%. Thank you @KingZee and @Darkon

# Answer
> 3 votes
```
 ChapterListItem _chapterListItem = chapterListItemPrefab.GetComponent<ChapterListItem>();

```

You are getting your `ChapterListItem` from the prefab, rather than the instantiated object `listChapter`. This means that you're calling the setup on your prefab repeatedly.

---
Tags: unity, android, game-design, mobile
---


# Question
Title: Unity 5 Closing Menu On Multiple GameObjects When A New Menu is Opened?
I am trying to make a menu system for each GameObject, and when a GameObject is clicked it will close all other menus and open the one for that GameObject. I am using one script for this:

```
using UnityEngine;
using System.Collections;

public class BlockMenus : MonoBehaviour
{
Vector3 point;

public Transform block;
public GameObject activeBlock;

bool buttonActive = false;
bool activeBlockActive = false;

string hitObject = "";

void Update()
{
    point = Camera.main.WorldToScreenPoint(block.position);
}

void OnMouseDown()
{
    hitObject = this.gameObject.transform.tag;

    buttonActive = !buttonActive;
    activeBlockActive = !activeBlockActive;

    activeBlock.SetActive(activeBlockActive);
}

void OnGUI()
{
    if(buttonActive)
    {
        switch(hitObject)
        {
            case "mine":
                GUI.Box(new Rect(((point.x) * (1.08f)), ((Screen.height - point.y) * (0.1f)), (Screen.width * (0.3f)), (Screen.height * (0.5f))), "");
                GUI.Button(new Rect(((point.x) * (1.08f)), ((Screen.height - point.y) * (0.87f)), (Screen.width * (0.05f)), (Screen.height * (0.06f))), "Build Mine");
                break;
        }
    }
}
}

```

# Answer
This may work/help. The best solution I can muster/find is toggling the GUI objects individually and not just setting them all at once. You don't need to do it in a switch really. This is a mix of your code and the solution I found.

```
using UnityEngine;
using System.Collections;

public class BlockMenus : MonoBehaviour
{
    Vector3 point;

    public Transform block;
    public GameObject activeBlock;

    bool buttonActive = true;
    bool activeBlock = false;

void Update()
{
    point = Camera.main.WorldToScreenPoint(block.position);
}

void OnMouseDown()
{
    buttonActive = !buttonActive; /* Turn button off */
    activeBlock = !activeBlock; /* Turn block on */
}

void OnGUI()
{
    if(buttonActive) /* Button is live */
    {
       GUI.Button("Button"); /* Put button specs in */
    }
    if(activeBlock){ /* Block is live */
       GUI.Box("Box"); /* Put box specs in */
    }
}
}

```

Also I realized the need to use the !. Makes sense if you are only using the mouseDown. Alternatively you could add an opposite mouseUp to swap things back, but both should do relatively the same thing. Although if you use the mouseUp you may end up with a very fast switch every time you click.
> 0 votes

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


# Question
Title: Intersecting dynamic bodies Box2D/Libgdx
Is that normal that while I'm jumping (by a player represented with a circle) on a dynamic bodies (boxes) they are interecting? It seems that there is some kind of diffraction. Is that any way to reduce this? Restitution is set to 0 for all.

The moment caught on a screenshot

And the moment after a collison

# Answer
A little overlap is to be expectedone with **Box2D**, try increasing the `positionIterations` parameter in the call to `World.step` (also consider experimenting with the `velocityIterations` parameter).

Increasing these values gives a more stable simulation with less collision overlap, but it comes at a performance cost.

You can also try stepping the `World` in smaller increments, Gaffer on Games's Fix Your Timestep has a good description on how to decouple the physics time from the render time.

Play around with the values and find the compromise that works best for you.
> 1 votes

---
Tags: libgdx, box2d
---


# Question
Title: How can I design an effective some sort of sequence system?
I am making a story driven game right now, and I want to create a system that will allow me to code sequences easily without creating a mess from the project. What I mean by sequences is for something like a Scene, for example, since it's story driven, the player begin in a room, which then a character walk in, display a dialogue, then walks away, does a few things, a couple of sounds and effects are played, etc.

I was wondering how I could structure a system like that, that will allow me to have hundreds of this sequences without making a big mess of my project, also, these are going to be must like scripted, is it better to keep most of the scripts in a fewer class files or it's a good idea to spread them more? (to more class files)

I hope you can understand exactly what I meant and thank you in advance.

(I am making this in C# in Unity but I am not looking for specific code, just theory how to construct such system effectively)

# Answer
You need a good folder structure and you should keep anything you can apart and structure it like a theater play. This way, the bugs will only ever be in the scene or the act and you can easily debug when it's needed.

Since your main mechanic is "storytelling", you won't have a repeatable gameplay loop. So, have a gameplay folder where you keep all the player's actions that are not scripted (i.e. controls, options) and keep the rest in a story folder where you structure it like "Act1, Act2..." and each act has scenes which are named "Scene1, Scene2...".

Let's say the player can interact with a desk, the desk and the script for the animation of the desk and the player while they're interacting will be in the corresponding scene folder, but the ability to interact with the object (press e to interact or the UI objects) will be in the gameplay folder.

For example:

1. Player is in a room interacts with a character, character leaves room. Play sounds etc. End Scene.
2. Some other stuff happens outside, another character walks in, there's a whole lot of things that happen. End Scene.
3. Repeat scene process until you're satisfied with the story. End Act.

Now the folder structure will look a bit like this:  Repeat the process for other "acts" (Which should be your Unity scenes). For more info on this I'd suggest referring to William Shakespeare's theater plays.

Again, what I'm talking about here is not Unity scenes themselves but the scenes in an act of a theater play. You can make every single scene into a Unity scene but that would mean a whole lot of scene loading and unloading which might be a bit over the top (there's nothing wrong with doing it that way though).
> 1 votes

# Answer
You could use a generic state machine to organize when and what must interact. On a project I had a small narrative to implement so I create a state machine that handles the scripts which handled the gameobjects. You can have how many of these state machines you want but the asset will be on your folders as usual, the way you want them.
> 0 votes

# Answer
If i understand it correctly you mean that during the game, game objects are created and put in your hierarchy. if that is the case, then you only have to script something that will delete the game object after a certain time.

If this is not what you meant then please add more details to the question :)
> 0 votes

---
Tags: unity, c#, 2d
---


# Question
Title: How to make far block graphically better?
What calcules can I do to make far objects looking better?

**My game**

Here's what I see if I go back with the camera in my test-rendering scene:

As you can see the result is not one of the bests: borders are not defined well and the texture itself is not nice to see.

**Minecraft**

Here's for example an image of Minecraft far blocks rendering:

As you can see the result is better than mine. *Minecraft seem blurring far blocks or something like that.*

**Trove**

This is another game cube-based called Trove.

Here I appreciate how it defines block borders by treading them with a black line.

**TO MAKE IT SHORT:**

*EXCLUDING LIGHTS!!!*

*(I know that lights make their part in graphical improvement but I think that there is something more in mc and trove shaders)*

**1) How can I blur texture like Minecraft does? (I don't know actually if its a blur)**

**2) How can I highlight borders of the block like Trove does?**

P.s: I'm using OpenGL 3.1+!

# Answer
> 4 votes
What you see is there because the textures are in a higher resolution than what they get drawn in. This results in a very pixelated look.

To "fix" this you can generate mipmaps. Mipmaps are the smaller versions of the texture, they get drawn instead of the original size when the surface is smaller. This results in a smoother looking texture when it's farther away.

There is however one problem with mipmaps. They make the textures look blurry when they're at an angle closer to the camera. At these places OpenGL uses the smaller versions even though the surface horizontally is closer to the original size. If you use OpenGL 2+, then you can use the anisotropic filtering extension for this (GL\_EXT\_ANISOTROPIC)

To generate mipmaps, you need to call `glGenerateMipMaps(int tex)`, then use `GL_LINEAR_MIPMAP_LINEAR`, `GL_LINEAR_MIPMAP_NEAREST`, `GL_NEAREST_MIPMAP_LINEAR` or `GL_NEAREST_MIPMAP_NEAREST` when you set the minimum filter (you can't use this for the maximum filter). The first linear or nearest tells you how it interpolates between mipmaps, the second tells you how it interpolates between pixels. For a minecraft-like game, you should use `GL_LINEAR_MIPMAP_NEAREST`.

Highlighting blocks is usually done in a post processing shader. Render the normals to a texture, then sample each fragment in an x by x area, and if somewhere there's a change in the normals, then there's an edge. If you don't want edges around the cubes, then do the same with the depth.

---
Tags: opengl, shaders, graphics, voxels, fragment-shader
---


# Question
Title: Direct3D fails to render when on Laptop with nvidia optimus
I'm developing a Direct3D control which needs to run on a Dell XPS with a NVIDIA Optimus. I'm using SharpDX and C#. When I write code for the app on a workstation with only an NVIDIA graphics card it runs correctly. When I move it to the laptop, I select the NVIDIA graphics adaptor via code, however it does not render to the window. How can I get this to work correctly? Has anyone else seen this?

# Answer
> 0 votes
This is not the way Optimus works.

It's not a case of either/or; instead with Optimus you get to choose between using only the Intel, or using the Intel AND the NV. In the latter case, the NV handles most of the work, then transfers the framebuffer to the Intel for the final Present to the screen.

In other words, the NV is not capable of presenting to the screen on it's own. If you select it in code when creating a device you will get a device that is not capable of presenting to the screen. Your code is only doing what you asked it to do but you probably didn't realise or expect this.

The correct way to enable "high performance" mode with Optimus is to export the NvOptimusEnablement global.

Sample code for this and further explanation of the technology can be found in the Optimus White Paper: http://www.nvidia.com/object/LO\_optimus\_whitepapers.html

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


title: How do I move my camera in LWJGL?

text:
# Question
Title: How do I move my camera in LWJGL?
I am making a game in LWJGL (2) and slick-util (I think).

I am trying to move my map (It is a double int array that uses numbers to get the textures), but my code only moves the first texture to be drawn on the screen (top-left). how can I move ALL of my map at the same time? Here is my code:

```
package Window;

import static org.lwjgl.opengl.GL11.*;

import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

import org.lwjgl.input.Keyboard;
import org.lwjgl.opengl.Display;

import controls.TileChanger;
import Functions.renderer;
import Window.GridHandler;

public class Main {

 public static void main(String[] args) {

  renderer.begin();

  int[][] map = {
   {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
   {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
   {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
   {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
   {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
   {0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
   {0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
   {0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
   {0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
   {0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
   {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
   {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
   {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
  };

  GridHandler grid = new GridHandler(map);
  TileChanger changer = new TileChanger(grid);

  String mapSave = map.toString();
  float translate_x = 0;
  float translate_y = 0;
  int speed = 5;

  while (!Keyboard.isKeyDown(Keyboard.KEY_Q)) {

   //   while(Keyboard.next()){
   if (Keyboard.getEventKey() == Keyboard.KEY_P && Keyboard.getEventKeyState()) {
    System.out.println(mapSave);

    /*      Writer wr;
            try {
                wr = new FileWriter("map.txt");
                wr.write(mapSave);
                wr.close();
            } catch (IOException e) {
                e.printStackTrace();
            } */
   }
   //   }

   if (Keyboard.isKeyDown(Keyboard.KEY_D)) {
    translate_x += speed;
   }

   if (Keyboard.isKeyDown(Keyboard.KEY_A)) {
    translate_x -= speed;
   }

   if (Keyboard.isKeyDown(Keyboard.KEY_S)) {
    translate_y += speed;
   }

   if (Keyboard.isKeyDown(Keyboard.KEY_W)) {
    translate_y -= speed;
   }

   glClear(GL_COLOR_BUFFER_BIT);

   glPushMatrix();

   glTranslatef(translate_x, translate_y, 0);

   glEnable(GL_TEXTURE_2D);

   changer.Update();

   grid.draw();

   glPopMatrix();

   Display.update();
   Display.sync(60);
  }
  Display.destroy();
  System.exit(0);
 }
}

```

Can anyone help me out? (I need the map to move correctly when I push any of the WASD keys (W = up, A = left, S = down, D = right).

# Answer
Translating a camera is the equivalent to translating the world in the opposite direction. In other words, at the very bottom of your matrix stack, your camera's matrix exists. You need to translate this wherever your camera must be in the opposite direction.

If you wish to move up 5 paces. You translate the world down five paces.

This is typically the reason why games abstract away logical positioning, and graphical positioning.

Please see this for more information. https://www.opengl.org/archives/resources/faq/technical/viewing.htm
> 1 votes

# Answer
You need to translate and rotate the entire scene. For example, use the `glTranslatef()` and `glRotatef` functions. Obviously the process becomes more complicated when using shader files.

Note this question is answered here: https://stackoverflow.com/questions/23727493/creating-a-camera-class-with-lwjgl

Some more resources (Google search):

https://m.youtube.com/watch?v=OO\_yNzAuDe4

https://lwjglgamedev.gitbooks.io/3d-game-development-with-lwjgl/content/chapter8/chapter8.html

https://tutorialedge.net/lwjgl-3-orthographic-camera-tutorial
> -1 votes

---
Tags: lwjgl
---


# Question
Title: locking a rotation on an axis(yaw/pitch/roll) based on a parental transform
I am currently attempting to lock a non rigid body transform rotation around on an axis. It is parented to a gameobject that is rotating in 3D space. I want the Original transform to have the same rotation as the parent's but I want it to be locked on a certain certain axis. For the sake of clarifying my question I will provide some code and an example.

Example: There is a 3D model with a plane attached to the left upper arm subsegment(see hierarchy) whose initial normal is aligned with the global x-axis \<1,0,0\> or the initial right vector of the subsegment. In the context of this post, what I would like is to be able to align the normal of the plane with the subsegment's right vector but keep the plane's up axis locked.

For instance, I do not want to the yaw component of the transform to change. Trying the following code does not result in the intended effect.

```
Vector3 eulerRepresentation = parent.transform.rotation.eulerAngles;
eulerRepresentation.y = 0;
Quaternion fromEuler = Quaternion.Euler(eulerRepresentation);
transform.rotation = fromEuler;

```

This is very likely because of the duality of a rotation of Euler angles. An example is (180,0,180) is the same as (0,180,0)

When inspecting the euler values, it is exactly like I suspected. There doesn't seem to be correlation with the object's yaw and the object's euler.y value.

How would I go about locking either Yaw/pitch/roll?

# Answer
> 2 votes
I'd solve this using LookRotation. We can generalize Unity's helper method to let us point any particular local axis we want at any particular global axis, like so:

```
Quaternion GeneralizedLookRotation(
      Vector3 localExactAxis,
      Vector3 globalExactAxis,
      Vector3 localApproximateAxis,
      Vector3 globalApproximateAxis
    )
{

    // Rotate our chosen local axes into a standard orientation.
    Quaternion standardize = Quaternion.Inverse(
               Quaternion.LookRotation(localExactAxis, localApproximateAxis)
        );

    // Rotate the standard orientation to point to the chosen global axes.
    Quaternion turn = Quaternion.LookRotation(globalExactAxis, globalApproximateAxis);

    // Chain both operations to rotate the local axes to the global axes.
    return turn * standardize;
}

```

This function will take a vector in local coordinates, `localExactAxis`, and rotate it to point exactly along `globalExactAxis` in world coordinates.

That still leaves us with one degree of freedom (twisting around `globalExactAxis`), so we also provide a `localApproximateAxis` which should map as close as possible to `globalApproximateAxis`.

Here's what this looks like:

The left is normal parenting behaviour. In the other two, I added a `LateUpdate()` method (so that it runs after any animations or update scripts have rotated the parent) that adjusts the child rotation like so:

```
if (parentExact) // Middle version
{
    // Point my right vector exactly along my parent's forward,
    // and my up vector as close as possible to world up.
    transform.rotation = GeneralizedLookRotation(
          Vector3.right, transform.parent.forward,
          Vector3.up, Vector3.up
        );

    // (Effectively, yaw & pitch with parent, but don't roll)
}
else  // Rightmost version
{
     // Point my up vector exactly along world up,
     // and my right vector as close as possible to my parent's forward.
     transform.rotation = GeneralizedLookRotation(
          Vector3.up, Vector3.up,
          Vector3.right, transform.parent.forward
        );

     // (Effectively, yaw with parent, but don't pitch/roll)
}

```

# Answer
> 1 votes
There are a few approaches here.

**Freeze the axis in the Unity Inspector**

Select the object you are rotating, I am assuming a rigidbody, and go into the inspector. Find the constraints property and check off the axis you want to freeze. That will not allow the rotation or movement (whichever you check off since they're both clickable) of your object in that axis.

**Make a float to insert and lock the axis**

Create a `float lockAxis = 0;` Add it into your `Update()`

```
void Update()
{
     transform.rotation = Quaternion.Euler(transform.rotation.eulerAngles.x, lockPos, lockPos);
}

```

This is setting your specific axis to 0 every time so that is effectively locked. Sources.

**Freeze the axis using eulerAngles**

`transform.eulerAngles` can be assigned a `Vector3`.

```
 Vector3 eulerAngles=new Vector3(0, 0, 0);
 transform.eulerAngles=eulerAngles;

```

However you cannot directly assign a quaternion.

```
 Quaternion rotation=new Quaternion(0, 0, 10, 10);
 transform.eulerAngles=q.eulerAngles;

```

In contrast, `transform.rotation` can be assigned a Quaternion.

```
 Quaternion rotation=new Quaternion(0, 0, 10, 10);
 transform.rotation=rotation;

```

However you cannot directly assign a `Vector3`.

```
 Vector3 eulerAngles=new Vector3(0, 0, 0);
 transform.rotation=Quaternion.Euler(eulerAngles);

```

Sources.

**Use Quaternions R/Y/P equations**

```
 roll  = Mathf.Atan2(2*y*w + 2*x*z, 1 - 2*y*y - 2*z*z);
 pitch = Mathf.Atan2(2*x*w + 2*y*z, 1 - 2*x*x - 2*z*z);
 yaw   =  Mathf.Asin(2*x*y + 2*z*w);

```

You can use those if you directly want the roll/pitch/yaw - that's the formula for them specifically. Sources.

Also make sure that you don't end up with a Gimbal Lock :)

---
Tags: unity, rotation
---


# Question
Title: What to watch out for when creating a autobiographical game?
I plan to create a game which depicts various events from my life.

During these events, some people I know do not appear in a very positive light. I am afraid that these people might feel that it is an infraction on their personality rights. I also plan to unveil some of my own actions which they didn't know before and which could make them angry if they knew of them.

The story of the game as I currently plan it will be written in a way that if they know I made the game, they would realize that they are the ones depicted. Even if they have different names and appearance.

But despite these risks I feel that this project is important for me and might help me to cope with some events from my past.

What should I watch out for when I write and publish the game to make sure I won't ruin my relationship with these people?

# Answer
> 1 votes
## Disclaimer

Imo, this is marginally about copyright, and tangentially about games. Instead, what you need is legal advice. So disclaimer ahead:

I'm not a lawyer; this answer is not legal advice. Furthermore, I mention rights that are not universal, and may not apply in your country. I don't even know from where you are, or where you plan to publish.

**Note**: My knowledge of the law comes from my training as security information specialist. As such, I need to be aware of laws important in cyber-crime (including copyright, privacy violations and the treatment of personal information in software) in international law (because software may end anywhere on the world)... yet, this can't be considered a replacement for legal advice nor consulting your local law.

---

## Answer to the edited Question

> During these events, some people I know do not appear in a very positive light. I am afraid that these people might feel that it is an infraction on their personality rights. I also plan to unveil some of my own actions which they didn't know before and which could make them angry if they knew of them.

See "**Notes on Defamation**" below.

> What should I watch out for when I write and publish the game to make sure I won't ruin my relationship with these people?

There is always a chance that a video game will have a negative reception. This is also true for video games that are not dealing with sensitive subjects.

For your particular case, see "**Two Paths**" below.

---

## Legal Considerations

* Copyright: any **artistic work or publication** (unless stated otherwise) can be considered under copyright. If need to use any for your game, you should find out if it has been published to public domain or can be licensed to use. The license may be a periodic fee, one time payment, a fraction of the sales, etc... You may also consider fair use, for example in reporting news or real events you may be able to quote the speech or use the images of relevant people under fair use. **Note**: in the case of a deceased person, may countries still recognize copyright and the loyalties goes to the family, who may create an organization to manage these rights (for example, granting licenses posthumously).
* Privacy: each person is the owner of their personal information. Also, in your case you could consider any personal information to be sensitive; this is because making this information public may cause harm※ to those people. **You need consent to use this information in your work**. **Note**: in the case of a deceased person... for the law that I know they don't have privacy, yet, you may have to consider if the information is sensitive to somebody else.
* Image rights: each person have the rights over their likeness. If you wish to use the appearance of a person you may need to negotiate the image rights (A possible exception to this is a parody of a public figure). **Note**: in the case of a deceased person this rights belong to the family, unless given to third party either in life, by testament or posthumously by the heir.

※: If some information may open a psychological trauma, ruin a relationship; make the person target of discrimination, etc. A particular example comes to mind: Let's say that a particular person was a victim of sexual assault, this will make this person impure in the eye of various religious groups... thus an untimely reveal could damage a romantic relationship or the status in society this person has.

You have your freedom of speech and freedom of press to publish real events. Yet, this right ends where the rights of others begin. The considerations above are the same that lead to TV news obscuring faces and distorting voices.

Also, you are not a judge. If there is an unresolved crime, you should refrain from portraying a real person as guilty. This is why news will often use words such as "alleged", "presumed" and "suspected" (although some media outlets overuse these). If you have new evidence you may want to submit them to the authorities and let the case be resolved... or you may state your work as fiction.

Finally I want to repeat that this is not a replacement for legal advice, you can consider this a guideline to what to ask your lawyer.

---

## Answer To the Original Question

> People would claim a breach of privacy, if they randomly found themselves in a game. If they know i made the game, they would realize that they are the ones depicted. Even if they have different names and appearance.

Yes, this may happen. To avoid this, any personal information (starting by their names) should only be used with the approval of the person to whom it belongs. This way any private affair depicted in the game won't be associated with the person unless that person is ok with that, also no sensitive information would be disclosed by the game without authorization (including but not limited to: sexual orientation, political views, contact information, etc.)

You should also consider image rights; people have an inherent right to their likeness. Because of that (unless it is public figure, where parody right or freedom of press applies).

> People would be filled with rage now that my actions are unveiled. Before they were blind to the truth.

You decide what you publish and in which format. If the rage of the users is a concern, then take it into account. **Note**: many existing games can cause rage and frustration to its users.

Edit: In the case you get threats you should let the competent authorities know, also consider relocating away from these people.

> People would claim that i was recording their actions. I cannot analyze myself, if i don't mention key events to show how interpret myself.

Were you?

Don't tell me.

> People could say that their speech and actions they did in public places were copyrighted. For example, if i mention a bully's response, he used in his anger, would i be liable to copyright infringement?

You can always paraphrase.

Unless you are using an actual recording in your game (and as long as long you are not under a non-disclosure agreement) you may have right to quote.

It may be the case that the person in question has used his words in another work, and that work is under copyright. In that situation his words are under copyright. In this case you can still quote, yet you may have to defend your fair use. In this case you could argue that your work is a completely different, not competing with the quoted work.

Now, this is tricky, you would have to credit the source of your quote, but if the person in question doesn't want to be associated with your game that would be problematic.

Just paraphrase.

> One event would allow others to interpret their behavior and therefore expose their entire personality. Everyone would know exactly how they think.

I don't understand what you say here. Are you claiming that your game provides psychic abilities?

Edit:

> Past behaviors of others allows you to interpret their character. For example: if I know you did X, i can assume you are Y. Yes, there could be a generalization error but it provides relevant statistics to interpret his personality.

This goes into the idea of defamation I mention below.

> Several events that shaped my personality would harm those that surrounded me.

Ok, now you are claiming that your game will cause harm and you know it. This is an ethical problem, beyond the scope of this answer.

> If i mention this is a work of fiction, would it fix the legality of the game ? The problem is, once the see the developer's name, BAM, they know it is me.

You can publish your work under a pseudonym if you don't want to be associated with it.

> They could deduce it is me, by viewing too many similarities.

Of course your work would be subject to interpretation.

> \[Pure Removal of others\] If i don't mention any of the events that happened, but only how i felt about them, the entire plot becomes obscured and meaningless.

It won't be meaningless, perhaps it will be cryptic. People can assign meaning to any work. You as the author give it the first meaning, yet reinterpretations will come.

In fact, it is possible that people may take it as a metaphor for some real life problems, or could take it as a cautionary tale.

So, no, it won't be meaningless.

> Would it be cheaper to publish it anyway against their permission (they wouldn't consent, no matter the circumstances), face their wrath in a legal battle, and give them a percentage of the game's profit's. Could the penalties be above the game's profits.

I couldn't know. I don't know what the penalties would be according to your local law, nor could I predict the future profits of your game.

---

## Notes on Defamation

You haven't said it explicitly, yet I suspect your actual concern is not privacy nor copyright, but defamation.

Many courts will not defend the right to a good name when the claims against them are true. To put it bluntly: they will let you call whore a person as long as that person is actually (and not figuratively) a whore. In this case your freedom of speech wins.

As per the legal battle, you may be required to demonstrate beyond reasonable doubt that what you depict in your game is the truth. That is, that you are NOT depicting people worse than they objectively are.

You may also want to look for antecedents in the legal history of your country of famous cases where this has happened. Consult a lawyer.

---

## Two Paths

You seem to want to reveal some information, yet afraid of doing so.

There seems to be two paths here:

* Conceal the truth: change names, changed appearances, remove details, and make it pass as fiction, publish under a pseudonym. This leaves the work open for interpretation. Working with this constraint probably makes for a more artistic work, yet it may defeat the point of publishing this work.
* Embrace the truth: you may try to get as much consents and as much evidence as possible, in order to create a depiction closer to reality. You would have to defend your rights to speech and information, freedom of press, etc. I'm guessing it is harder to accomplish this way, yet, perhaps, that's better for you.

I suspect you want to make a work closer to the truth, so I suggest finding actual legal advice. You may be able to get it cheap or even free from law schools that provide this service as a way to have their students gain experience.

---

## Information about Criminals and Victims

I want to add that information published by the government can be considered under public domain. The key word here is published, if it is something that media can replicate (for example, something that appears on TV) then it is fair game.

I mention this, because after I posted the original answer I had the idea that perhaps your trouble comes from the need to portrait a criminal, and such criminal will most likely not agree to be associated with your game. In that case, if the information of the criminal was published (for example, they have asked the public for information that may aid the capture of that criminal, and along with that they published name and picture, you can use that) you can use it, and if that criminal has been taken to jail you won't have the trouble to demonstrate the crimes.

*Note that when I mention demonstrating the crimes is to get free from a defamation claim, not to bring a criminal to justice.*

**Copyright on Crimes?**

Remember that copyright applies to artistic works and publications, not to crimes. A criminal doesn't have copyright over his activities outside the law (and pretending that the government will protect such claim is absurd).

Yet, if the criminal has publishes a memoir and your game is strongly based on it, then yours is a derivative work. You may circumvent this by avoiding using material from such memoir or you may make a deal with the criminal in question.

**Note on Victims**

Again, the victims don't have any copyright to what happened to them. Those are facts, nobody owns the facts. Also again the situation of the memoir may happen with the victims.

Yet, aside from that, you need to worry about sensitive information and image rights.

Depending on your local law, you may be able to use the information of the victims but be required to remove it if you are requested to do so by the titular of that information... avoid doing (unless it a web game) because it may mean to track and recall copies and installations of the game.

---
Tags: game-design, publishing
---


# Question
Title: Pathfinding in Isometric Phaser with Tunnels
I want to create a 2D isometric game. Currently I'm looking and testing Phaser game engine with isometric plugin. Almost everything at the moment looks possible except few things. I will create a bridge/tunnel in my map so entities could go through tunnel and on the bridge. The simplest implementation of this simulation will be enough.

What kind of trickery I have to use to implement pathfinding algorithm in this situation? And is this event possible in 2D isometric games? What are your suggestions about this type of game overall and my problem?

# Answer
> 3 votes
I disagree that you have to have a 3D map for this, and depending on how far along you are and how you implemented things, it might be a lot of work or bring other problems if you try to convert your tile or map system from 2D to 3D. On the other hand, it might be appropriate for your game and even help you with other things, but that's hard to say without knowing your game and your plans very well.

If you want to stay in 2D, you'd have to implement some special logic depending on tile type. You could make certain tiles only passable in certain directions (e.g. not letting you turn left or right at this bridge/tunnel tile, or having one-way tiles that only let you pass in one direction - for example for dropping "down", like you could in older Zelda games). Your pathfinding then has to follow these rules when expanding the set of possible moves from the current tile.

The trickiest thing about this is probably the rendering, because you'd want to have elements on the bridge stay visible and those below should appear to be under the bridge. One approach would be to compose the tile of two seperate sprites, one floor and one bridge sprite, so that you can draw the bridge sprite after an object that's *below* the bridge, but before an object *on* the bridge.

# Answer
> 2 votes
So you might be rendering in 2d, but effectively by doing this your game map is no longer 2d, it is in fact 3d. You could handle this by pathfinding in three dimensions. Assuming a 3x3 grid with a tunnel going north and a bridge going east, then you effectively have two stacked tiles at (1,1). So treat them as (1, 1, 0) and (1, 1, 1). In your pathfinding logic where you consider the connectivity of tiles, you can always return false for changes in the height axis, except at the ramps down to the tunnel or up to the bridge.

---
Tags: 2d, path-finding, isometric, phaser
---


# Question
Title: Unity - Moving RigidBody to a point in a spherical world
I have a planet ( a spherical planet) that have units on the surface , that units are attracted by the planet with this

```
  public void Attract(Transform body,Rigidbody rigidBody)
    {
        Vector3 gravityUp =  (body.position - transform.position).normalized;
        Vector3 bodyup = body.up;
        Quaternion targetRotation = Quaternion.FromToRotation(bodyup, gravityUp) * body.rotation;

        body.rotation = Quaternion.Slerp(body.rotation, targetRotation, 50*Time.deltaTime);
        rigidBody.AddForce(gravityUp*gravity);
    }

```

I want them to also move to a specific point in the planet but I can't make it work, I tryed lot of things, the most "near" to the solution was this code on the Update method, but his make unit to "bounce",

```
Vector3 dir = (positionToAchieve - transform.position).normalized * speed;
rigidBody.velocity = rigidBody.velocity + dir;

```

Any idea /suggestion will be welcome, I am new in Unity and I am learning it

# Answer
> 1 votes
You could try this in your update instead:

```
public Transform target;
public float speed;
void Update() {
    float step = speed * Time.deltaTime;
    transform.position = Vector3.MoveTowards(transform.position, target.position, step);
}

```

Unity MoveTowards

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


# Question
Title: Best approach to develop a mobile version of existing browser mmo game?
our team has developed a MMO browser game (HTML5, Javascript & PHP). The game is similar to Empire GG, Clash of Kings, Game of War etc.

We want to develop a mobile version and the question is which would be the most efficient way/ process we can take advantage of?

# Answer
The quick and dirty version is to have an app consisting of nothing but a web view control which loads the web version of your game.

The user experience with this solution might not be ideal, though. It won't be much different from running your game in the mobile browser. How well that works depends on how well your game copes with smaller screen size and touchscreen input instead of mouse input and if you thought about checking for compatibility with mobile browsers when you wrote your HTML and JavaScript.

So you might get better results with a native client. But porting it to a native client means that you need to redevelop your HTML5+Javascript part from scratch. A simple one-to-one port is unlikely to lead to a good player experience. Smartphones simply have a different user experience than desktop PCs. The screen is smaller and touch-input is far less precise than mouse-input. But to make up for that they offer alternative input methods like rotation or pressure sensitivity which aren't available in a browser. That means that you need to come up with different user interface solutions. If you decide to go this route, then there are several technologies available. We don't know your game or your team, so we can not tell you which tool is the best for you.

What you can and should keep is your PHP backend and most of your assets (if they look well on the small screen).
> 2 votes

---
Tags: mmo, mobile, browser
---


# Question
Title: Raycasting with a selection rectangle box
I'm currently making a level editor for my game and want to implement a selection tool to make it easier to select multiple voxels at once. My question is what the most efficient way is to get all the selected objects? Do I just unproject the starting position and end position of the selection rectangle and create a bounding box that I then can use for intersection checking or is there a better way?

EDIT: Since I can't rotate a bounding box I need to find another way. I just need a way to find out if the bounding box of a voxel is inside the box that is formed by the four points of the selection.

# Answer
> 1 votes
I have implemented something similar in the past and I can tell you that casting a box along the camera direction will not work (unless you are using an ortho camera). For a perspective camera, you would actually need to cast a frustum :). The reason for this is because the four points that make up the rectangle in screen space (as they show up on the screen), if you were to just extrude them, for a perspective camera, they would be squashed by the perspective effect. So you would need to compensate for that by not only extruding but also enlarging them as they get further away.

The way I did it was to always keep a record of the objects which are visible to the camera. Those are the objects which you can see on the screen. Now when you need to check if the selection rectangle, intersects the objects you could write something like this (I assume you're using C++):

```
for(int objIndex = 0; objIndex < numVisibleObjects; ++objIndex)
{
    GameObject gameObject = visibleObjects[objIndex];
    AABB worldAABB = gameObject.GetWorldAABB();
    Rect2D screenRect = worldAABB.GetScreenRect();

    if(screenRect.Intersects(selectionRect))
    {
        // Object is inside selection rectangle. Do stuff.
    }
}

```

So basicly you loop through each visible object, retrieve its world AABB, and then call GetScreenRect on the AABB to return a 2D rectangle which encloses the AABB in screen space. This can be done by looping through the AABB world corner points, transform them in screen space and find the min and max points, in screen space. From there you can use that to build the rectangle.

After you have this rectangle, you can just check if it intersects the selection rectangle. If it does, it means the object is inside the selection rectangle.

Now all the above implies that you will have to implement a mechanism that is able to detect visible objects at any one time. This can get a bit more complex, but I think in the beginning, if you are using a small number of objects in the scene, you could just loop through them all and use the above code snippet (or something like it) to see how it works for you.

I hope this helps.

---
Tags: 3d, monogame, gui, raycasting
---


# Question
Title: How to make a sprite jump up and then return to original position android java
I am just starting out in game development and I am trying to make a simple android game using GDXLib. I want to make my sprite "ball" jump straight up in the air and then return to where it originally was. How would I do this? I have looked at multiple other answers from similar questions but none seem to work with my code. This is my code so far:

```
@Override
public void create () {
    batch = new SpriteBatch();
    background = new Texture("gamebackground.png");

    ball = new Texture("ball2.png");
    ball.setFilter(Texture.TextureFilter.Nearest, Texture.TextureFilter.Nearest);

    spike1 = new Texture("spike1.png");
    spike1.setFilter(Texture.TextureFilter.Nearest, Texture.TextureFilter.Nearest);
    spike2 = new Texture("spike2.png");

}

@Override
public void render () {

    batch.begin();
    float scaleFactor = 2.0f;
    batch.draw(background, 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
    batch.draw(ball, 80, 145, ball.getWidth() * scaleFactor, ball.getHeight() * scaleFactor);
    batch.end();

Gdx.input.setInputProcessor(new InputAdapter () {
        @Override
           public boolean keyDown (int keycode) {
            if(keycode==Keys.UP)
            {
               ball.setHeight(ball.getHeight()+50);
            }
            return true;

    }

@Override
public void dispose () {

}

```

}

# Answer
First of all, your ball should not **be** a texture. IMHO it should **have** a texture.

That means you should create an ball object which has a texture as an attribute. This object can then have `x` and `y` attributes as well as `width` and `height` attributes that you can change at will.

If you look at the libgdx documentation you see that `Texture` has no such thing as a `setHeight` method, and that makes sense as your texture has a set width and height.

When you have your ball object, it is not the `height` you should change, but rather the position `y`.

```
Gdx.input.setInputProcessor(new InputAdapter () {
    @Override
    public boolean keyDown (int keycode) {
        if(keycode==Keys.UP)
        {
           ball.setY(ball.getY() + 50);
        }
        return true;
    }
}

```

Like this your ball will elevate itself as long as you keep `UP` pressed. (If it is going down instead it means the `y` origin is at the top so you should do `-50` instead).

Finally you can draw the ball like this

```
batch.draw(ball, ball.x, ball.y, ball.getWidth() * scaleFactor, ball.getHeight() * scaleFactor);

```

Try making this work first, and then you can think about making the ball go down to the origin or about making the jump more "natural".
> 2 votes

---
Tags: java, android
---


# Question
Title: LibGDX's particle emitter - Multiple particles in the same effect?
Hello everyone reading this,

I've used the particle editor to edit an effect to put in my game. Is it possible to have multiple and randomly emitted images (particles) instead of one?

I don't want to create for example 3 particle effects in the same position for having the result I want.

# Answer
> 1 votes
I wanted to achieve something very similar to this. My goal was to have a particle explosion that would choose from a number of random sprites when spawning the particles.

Unfortunately this does not appear to be possible with libGDX. The particle editor appears to be designed to use multiple emitters in order to layer different effects or sprites on top of each other.

A solution to your specific problem (and the solution that I am using for mine) is to create the particle effect that you want, and then duplicate it for each different image that you want to use. You will need to adjust the count lower in order to account for the additional emitters. Then, go into each emitter and change the image to the one that you want. The preview window will show a combination of all the emitters that are active.

You can then save the filename.p and use it with libGDX. If you open it up, you will see each emitter in the file, separated by two lines. If you have the images in a different directory than the assets directory, or if you are going to use a texture atlas for the emitter anyway, you may need to change the name of the Image Path of each one to remove the full path and leave only the image name.

Here's a screenshot of one of the finished particle effects:

---
Tags: libgdx, particles, editors, effects
---


# Question
Title: Time per turn in a .NET turn-based game?
I am developing the server for a browser game, it uses an ASP.NET API for authentication, login and character creation and a websocket for the rest of the game (Microsoft.Web.WebSockets).

While on combat mode, each character will have a fixed amount of time to carry out their actions.

is there a way to keep track of the time on the server or should I create a different server to serve as time master ?

Which method/library should I use to control the time ?

# Answer
> 1 votes
Your server can keep time.

The first thing you will need is to have the server start a turn. You would then notify the client that his turn has started and how much time they have to complete their move (this can be used to present a countdown in UI).

Afterwards, one of the following will happen:

* The time is over, the server must be able to advance to the next turn even if the client has given no input or if the client has disconnected.
* The client sends the action back to the server, the server needs to check how much time has passed, accept or reject the move, and advance to the next turn.

A simple approach would then be to have a permanent object for each game session; this object will have a turn timer. Then you are creating a race condition between the timer and the client response...

---

I'd suggest to use the Reactive Extensions (MSDN) (GitHub) (NuGet). You can create an `IObservable`※ that calls its subscribers when the client sends a response (you can make one for each client, you can even use it to represent disconnection※※). Then you can use `Observable.TimeOut` to create an `IObservable` for the turn that will wait for a response from the client `IObservable` or a timeout. This way, the race condition is responsibility of `Observable.TimeOut`.

※: It is actually `IObservable<T>` where `T` is a class that represents the action of the client.

※※: You can call `OnNext` when you receive input from the client, and `OnCompleted` when the client disconnects.

The next step is to react to the `IObservable` from `Observable.TimeOut`. You will either get:

* A call to `OnNext` with an object that represents the action of the client.
* A call to `OnError` with a `TimeoutException`, which tells you that the client took too long to response.
* A call to `OnCompleted` that tells you that the client has disconnected.

You would then proceed to notify the client if whatever or not their input was in time (if the client is still connected, that is). Pick the client for the next turn, start listening to the appropriate `IObserver` and notify that client that their turn has started.

---
Tags: turn-based, .net, websocket, time-management
---


# Question
Title: How to generate a log file from a Unity WebGL build?
I want to create a log file for every time my WebGL game is played and have the errors and warnings with detail in there. I know how to make the log file I just don't know how to get the errors and warnings and their details, and I want to have the line number too.

The only way I know of getting an error is by Try Catch but that is not working in Unity or at least in WebGL build. The manual states that the log is output to the browser's JavaScript console, but I don't have access to all of my play testers and sometimes I can't reproduce the bugs they report.

# Answer
> 2 votes
As a WebGL game, you're running it in a web page.

You can edit the HTML to add an extra bit of JavaScript to intercept the browser's console log before your Unity game loads and tries to use it, as detailed in these StackOverflow answers by Denys Séguret and OneOfOne.

```
var store = [];
var oldf = console.log;
console.log = function(){
   store.push(arguments);
   oldf.apply(console, arguments);
}

```

This will let you catch everything Unity would output, even if it's not coming from one of your own scripts that you can wrap in a try...catch. Don't forget to enable exception support as described in this article from the Unity docs, as it's limited by default in WebGL builds.

Once the game ends (or encounters a problem) you can have your script bundle up the contents of its `store` array into a log file to save or transmit. You can also do this periodically in case of an unexpected shutdown, and so you don't add delays when the player is trying to navigate away or close the tab.

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


# Question
Title: How do modern game engines achieve real-time rendering vs Blender's "slow" rendering?
I'm new to both gamedev and Blender, and there's something I can't shake:

In Blender, a single render (even using the more advanced Cycles renderer) can take up to 45 seconds on my machine. But obviously, in a game, you can have amazing graphics, and so rendering is obviously happening continuously, multiple times a second in real-time.

So I'm also wondering what the disconnect is, regarding how "slow" Blender's renders seem to be, versus how game engines achieve real-time (or near real-time) rendering.

# Answer
> 119 votes
Real-time rendering, even modern real-time rendering, is a grab-bag of tricks, shortcuts, hacks and approximations.

Take shadows for example.

We still don't have a completely accurate & robust mechanism for rendering real-time shadows from an arbitrary number of lights and arbitrarily complex objects. We do have multiple variants on shadow mapping techniques but they all suffer from the well-known problems with shadow maps and even the "fixes" for these are really just a collection of work-arounds and trade-offs (as a rule of thumb if you see the terms "depth bias" or "polygon offset" in anything then it's not a robust technique).

Another example of a technique used by real-time renderers is precalculation. If something (e.g. lighting) is too slow to calculate in real-time (and this can depend on the lighting system you use), we can pre-calculate it and store it out, then we can use the pre-calculated data in real-time for a performance boost, that often comes at the expense of dynamic effects. This is a straight-up memory vs compute tradeoff: memory is often cheap and plentiful, compute is often not, so we burn the extra memory in exchange for a saving on compute.

Offline renderers and modelling tools, on the other hand, tend to focus more on correctness and quality. Also, because they're working with dynamically changing geometry (such as a model as you're building it) they must oftn recalculate things, whereas a real-time renderer would be working with a final version that does not have this requirement.

# Answer
> 113 votes
The current answer has done a very good job of explaining the general issues involved, but I feel it misses an important technical detail: Blender's "Cycles" render engine is a different type of engine to what most games use.

Typically games are rendered by iterating through all the polygons in a scene and drawing them individually. This is done by 'projecting' the polygon coordinates through a virtual camera in order to produce a flat image. The reason this technique is used for games is that modern hardware is designed around this technique and it can be done in realtime to relatively high levels of detail. Out of interest, this is also the technique that was employed by Blender's previous render engine before the Blender Foundation dropped the old engine in favour of the Cycles engine.

Cycles on the other hand is what is known as a raytracing engine. Instead of looking at the polygons and rendering them individually, it casts virtual rays of light out into the scene (one for every pixel in the final image), bounces that light beam off several surfaces and then uses that data to decide what colour the pixel should be. Raytracing is a very computationally expensive technique which makes it impractical for real time rendering, but it is used for rendering images and videos because it provides extra levels of detail and realism.

---

Please note that my brief descriptions of raytracing and polygon rendering are highly stripped down for the sake of brevity. If you wish to know more about the techniques I recommend that you seek out an in-depth tutorial or book as I suspect there are a great many people who have written better explanations than I could muster.

Also note that there are a variety of techniques involved in 3D rendering and some games do actually use variations of raytracing for certain purposes.

---
Tags: rendering, blender
---


# Question
Title: I need a map generation algorithm for towerdefense
I'm making a simple JavaScript tower defense game, I've experimented on some map generation my self, i seem to get one that works properly.

What I want is for you to provide a start point (possibly an end point) and an algorithm to generate a random path between them in a tower defense like style.

Examples

# Answer
You essential want a maze with no dead ends, sometimes also known as a unicursal maze or a labyrinth.

Jamis Buck describes a way to build rectangular unicursal maze as follows:

* Generate a maze first of half the desired final size.
* Remove the exit so only the entrance remains.
* Bisect each passage with a wall.

This makes dead-ends into u-turns, and will give you a unicursal labyrinth that is twice the size of the original maze. Here's an illustration of his process using a very small maze:

One drawback to this approach is that the resulting entrance & the exit are right next to each other. Here is a simple modification that will allow for an arbitrary entrance & exit:

* Pad the existing maze out with a wall thick enough to contain a tunnel.
* Pick an entrance & dig a tunnel to the nearest opening.
* Pick an exit & dig a tunnel to the remaining opening.

Here's an illustration that applies the modification to the previous example:  This isn't the only adaptation to fix the entrance & exit. Another somewhat more complex modification involves combining mulitple labyrinths. A more complex solution would be to partition & reconnect portions of the labyrinth.

Finally, note that while the illustrations I've used have varying wall thickness to illustrate the steps of the algorithm, all mazes are essentially (mathematical) graphs & you can adjust the representation (visual output) of the graph according to the needs of your game.
> 1 votes

# Answer
Recently I worked on the map generation algorithm for a tower defense game. The approach I took was to take a **maze generation algorithm** and use the **solution path** as the path that creeps follow.

This worked well because maze algorithms are so well-studied, there are plenty of features already there for you to adapt to the tower defense genre. For example, one major determinant of difficulty is the **length** of the path; for maze algorithms the relevant metric is **river**:

**River, from high to low**

You can read more about maze algorithm here: http://www.astrolog.org/labyrnth/algrithm.htm

Of course, you'll want to make some adaptations to suit your particular tower defense game. You may want enough space around corners to place towers there, or ways to control whether the path has lots of small turns or large turns that double back on itself.
> 5 votes

# Answer
Most AI I behavior I know of is meant to get the shortest path first type thing...aka traveling salesman problem.

I would say use the symmetry theory like in this example ... but with one caveat, you have the logic setup in order to keep the symmetry equal as long as possible. In order to induce curves and such you half the value and select a random direction, then maintain the symmetry after the turn & a few extra.

Then there's "noise theory", where you generate a map, randomly select a starting point & then the pattern is that you test for the highest or lowest value of noise for each adjacent space moving across the map.

I haven't read this one in awhile, but remember thinking it was decent
> 0 votes

---
Tags: javascript, procedural-generation, maps
---


# Question
Title: How do I go about ensuring a unique ID value?
I am using Unity and coding in C#. I have a game object called `Enemy`, which has a script called `EnemyMotor`. `EnemyMotor` has an `int` called `ID`. When `EnemyMotor` starts, I need to find an `ID` value that is not been using by any other instance of `EnemyMotor`.

For example: `Enemy` one spawns; check if an `ID` value of 1 is not being used. `Enemy` two spawns; check if an `ID` value of 1 is being been use. In this case, it is, so I need to find another `ID` value that is not being used. In this case, it should be 2. Continue with `Enemy` three, `Enemy` four and so on.

---

How do I go about ensuring a unique `ID` value?

# Answer
This is fairly simple. Just have a `static int` to record the next ID, and increment it by one after you set it. All instances of the script will reference the same `static int`. When each new instance is created, it will run it's `Start()` method, set the `nextID` value as it's own, and ensure that the *next* `nextID` value is a value that has not already been used. *Providing you only ever increment a value*, it will never physically fall back on a previous value.

---

```
static int nextID = 0;
public int iD;

public void Start()
{
    iD = nextID;
    nextID++;
}

```
> 0 votes

# Answer
IF you are instantiating your Enemies, you could put the "ID" in the name, so that in your Unity Scene Hierarchy you would see something like:

```
Enemie_1
Enemie_2
Enemie_3

```

Then your script would check for the existence of an ID's enemie.

```
int my_check_id = 0;
bool check = false;
GameObject check_game_object;

while(check == false)
{
    my_check_id += 1;

    check_game_object = GameObject.Find("Enemie_" + my_check_id);

    if(check_game_object.name == null)
    {
         //MY CEHCK ID IS NOT CURRENTLY USED.
         check = true;
    }//END IF CHECK_GAME_OBJECT.NAME == NULL
}//END WHILE CHECK == FALSE

```

This code is untested, and not super efficient. If you need to check more than one property you may want to look at using a Singleton GameControl from the unity tutorials, and store into that and check it. But this should answer your initial question.

Let me know if you have any questions, or would like clarification drop a comment, I'm happy to update my answer!
> -2 votes

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


# Question
Title: How to manage "jump" in my 2d platform game?
I'm developing a simple 2d platform game with Unity 2d. I have a problem managining my "Jump" action for the player.

I would like the player to Jump only when he has his feet on a "surface": terrain, platform, crate etc. I'm considering using colliders: when my player collides with a surface, set my `bool canJump = true`. When he jumps, I set `canJump = false` (he is midair).

My terrain has a `Rigidbody2d` is `Kinematic` and a `Box Collider 2d`. My Player has a `Rigidbody2d` is `Dynamic` and a `Capsule Collider 2d` (or a Polygon Collider.. )

The events `OnCollisionEnter2d()` and `OnTriggerEnter2d()` are never raised when Player collides with terrain.

Does anyone know what's wrong?

Thanks

EDIT: Now i'm using this to check if "something" is under my feet:

```
RaycastHit2D hit = Physics2D.Raycast(rb.transform.position, -Vector2.up, 0.1f);
        if (hit)
            canJump = true;

```

It doesn't works! hit is always true! I'm getting mad!

# Answer
> 0 votes
Your way should work, however I believe that the raycast is colliding with itself. You could start the raycast below the player.

However, a better way would probably be to use the colliders combined with the state machine.

When the player comes in contact with the ground (onCollisionEnter..), set a bool/animation state(standing or something) to mark that they are on the ground. When they jump, you can set the animation to a jumping animation and set your upward force.

Then, disallow further jumping (or add a counter for things like double jumping) if the flag/state from above is not set.

You can reset the flag/animation when you collide with the ground again.

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


# Question
Title: Multi-pass rendering using FBO and combining resulting textures
I need to render a 3D scene and then several 2D panels that i need to compose on top of the 3D render. I looked on the web for some resource that would show how people do that but couldn't find any. In my case, I don't want to use the fixed pipeline but shaders. So here is what I do:

```
Create FBO and 2 textures (say)
Attach texture1 to COLOR_ATTACHMENT0 and texture2 to COLOR_ATTACHMENT1
Render-loop {
    bind FBO
    draw into COLOR_ATTACHMENT0
    clear buffers (depth and color)
    render objects

    draw into COLOR_ATTACHMENT1
    clear buffers
    render the objects that will be the 2D overlay

    draw into default frame buffer
    draw quad to display combination of texture1 and texture2
}

```

in the quad shader I get the 2 textures and do an alpha blending using the alpha channel of the second texture.

So my question (simple):

Is this how you typically draw different scenes/content into different textures that you can combine into a final pass before displaying the results to the frame buffer? More specifically do you use the mechanism of attaching textures to different color attachment points in the render loop, then active the point you want to draw to (COL0, COL1, etc.) and then combine the textures in the end? Is that how it's typically done?

# Answer
> 1 votes
The technique you seam to be referring to in your pseudo-code is deferred shading.

It's a technique where you defer shading to a later stage by rendering to intermediary render targets and finally combine them to produce the final image.

You pseudo-code is correct and correctly uses FBOs.

In fact what you're trying to do is using MRT (Multiple Render Target) a common technique that works by attaching multiple textures to an FBO and in your shader outputing to several textures at once. This is often used for G-buffer rendering where you output normals, color, position and such to several other textures at once.

When you're done drawing to your FBO, you can then use the textures associated with it and bind them to your shader to combine them to obtain the final image.

Also, don't forget to bind your shaders (using glUseProgram or alternatives) to actually draw what you want correctly.

I can give more details if needed. Hope this helps.

---
Tags: opengl, rendering, deferred-rendering
---


# Question
Title: Projectile code reports wrong number of arguments
I'm not certain as to why my code isn't working. The error reports that the `instance_create` line uses a wrong number of arguments. What am I doing wrong?

```
if(ammo > 0)
{
    ammo -= 1;

    bullet_id = instance_create(
        x + lengthdir_x(lenx, image_angle) - lengthdir_y(leny, image.angle),
        y + lengthdir_y(lenx, image_angle) + lengthdir_x(leny, image_angle));

    bullet_id.direction = image_angle;
    bullet_id.image_angle = bullet_id.direction

```

# Answer
> 1 votes
I'm not familiar with the Game Maker API, but I believe you're missing the third argument in the `instance_create` method.

```
instance_create(x, y, obj);

```

---
Tags: game-maker
---


# Question
Title: Path finding: avoid being surrounded by enemies
I'm building a bot that plays a simplified version of *Pac-Man*. The bot does a pretty good job, but sometimes it chooses a path where it ends up surrounded by enemies.

Here is an example:

```
XXXXXXXXXXXXXXXX         XXXXXXXXXXXXXXXX         Legend:
xxxxO1   E1              xxxxPE1
XXXX XXXXXXXXXXX    ---> XXXX XXXXXXXXXXX         O Objective
E2   P        O2            E2 E3      O2         P Player
XXXXXXXX XXXXXXX         XXXXXXXX XXXXXXX         E Enemy
XXXXXXXX XXXXXXX         XXXXXXXX XXXXXXX         X Wall
XXXXXXXXE3XXXXXX         XXXXXXXX XXXXXXX         x Wall

In this situation, my bot is at the point of no return. It will choose to move
to and pick up objective one (O1), as it is the closest objective in sight,
and in theory is still a safe path. However, in doing so, enemies will surround
him and he will die. (Map on the right).

```

I'm trying to come up with ideas on how to make my bot avoid that path, and go for a safer one. The bot should determine if completing the current path (to *O1*) is a good idea or not, in advance, and make a decision.

How would I go about this? I'm using a simple A\* for path finding over a grid.

# Answer
Here is something I would try.

First, map out all the possible objectives.

Second, for each objective, use A\* to map the path there, avoiding the Enemies. But every step of the way, don't just move the player, move also the enemies, based on what you know of their behaviour.

Third, pick the path that will allow the player to survive the longest.

So basically, you have to integrate the behaviour of the enemies in your prediction.
> 2 votes

---
Tags: algorithm, path-finding
---


# Question
Title: How to render a curved horizon when rendering terrain far away
For games with long view distance, it might look at bit weird when you fly high above the ground and the horizon is all flat.

So, how can I make a crumb/bend effect, when I fly high above the surface? Can this be done in the shaders?

If you're not sure what I mean, heres a picture:

A more clear example, though it might be captured with fish eye.

What would this best way to do this? I believe you could rotate and move (using transformationMatrix) all vertices a tiny little bit according to how far they are from the camera. But would this even create the desired effect, and would it be too resource extensive? Or maybe you know a whole another way to do it.

# Answer
> 1 votes
One possible solution would be to actually curve the terrain model. If your game/physics engine wouldn't support this while the character (I assume there is a character) is on the ground, then you could have two models, one with curvature and one without, which you could switch between based on some sort of altitude threshold (supposedly the curvature of the earth becomes visible at 50,000 ft.).

# Answer
> 0 votes
You can achieve the second picture's curve quite easily by making your field of view wider in the projection matrix. Try a field of view around 180 degrees.

---
Tags: opengl, lwjgl, graphic-effects, special-effects
---