# Question
Title: Cannot connecting texture to heightmap using mapped uniform location
In my shader program, I have my attributes and uniforms added to a map for each. What I have displayed is a heightmap, but cant seem to connect the graphic texture to display.

`mUniformList` *(std::string, GLuint)* contains all the uniforms added from my shader (8 total). The problem is that retrieving and connecting the sampler2D named "groundTexture."

```
void Terrain::init()
{
    ....
    ....

    // VAO
    glGenVertexArrays(1, &mVAO);
    glBindVertexArray(mVAO);

    // VBO
    glGenBuffers(1, &mVBO);
    glBindBuffer(GL_ARRAY_BUFFER, mVBO);
    glBufferData(GL_ARRAY_BUFFER, sizeof(mVertices), &mVertices[0], GL_STATIC_DRAW);
    glEnableVertexAttribArray(shader["position"]);
    glVertexAttribPointer(shader["position"], 3, GL_FLOAT, GL_FALSE, 0, (void*)0);

    // IBO
    glGenBuffers(1, &mIBO);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mIBO);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(mIndices), &mIndices[0], GL_STATIC_DRAW);

    // Load Heightmap texture
    mTexture.loadTexture(heightMapFilePath, mHeightMapTextureID, 0);

    // Texture coordinates
    glGenBuffers(1, &mTexCoordID);
    glBindBuffer(GL_ARRAY_BUFFER, mTexCoordID);
    glBufferData(GL_ARRAY_BUFFER, sizeof(mTexCoords), &mTexCoords[0], GL_STATIC_DRAW);
    glEnableVertexAttribArray(shader["texCoord"]);
    glVertexAttribPointer(shader["texCoord"], 2, GL_FLOAT, GL_FALSE, 0, (void*)0);

    // load ground texture
    mTexture.loadTexture(groundTextureFilePath, mTextureID, 0);

    shader.connectTexture(mTextureID);
}

```

With connectTexture being:

```
void TerrainShader::connectTexture(GLuint id)
{
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, id);
    glUniform1i(mUniformList["backgroundTexture"], 0);
    glBindBuffer(GL_ARRAY_BUFFER, 0);
}

```

**UPDATE** Fixed dereferencable error pertaining to the `mUniformList`. No errors of any kind whatsoever, but still nothing displayed.

**terrainfrag.glsl**

```
#version 330 core

layout (location = 0) out vec4 color;

smooth in vec2 TexCoord;
smooth in vec3 Normal;

uniform sampler2D backgroundTexture;

void main()
{
    vec3 normalized = normalize(Normal);

    color = texture(backgroundTexture, TexCoord);
    color += vec4(1, 1, 1, 1);
}

```

# Answer
To be able to debug OpenGL errors I highly suggest you use a `CheckGLError` function to check for errors after OpenGL calls.

My assumption is that you are getting an OpenGL error before your call to connectTexture. I believe that error is because you are not setting a proper offset when passing texCoord data to OpenGL. When you are setting 0 as the offset, and passing `vec2` instead of the expected `vec3` for `position`. You want to have an `offset` for the texCoords. *(With the assumption that position is at location 0, and texCoords are at location 1)*

To load a model with texture coordinates into OpenGL you want to use code similar to this:

```
glVertexAttribPointer(shader.texCoord, // index
                      2,               // size [ Use 4 if you can ]
                      GL_FLOAT,        // type
                      GL_FALSE,        // normalized
                      bytesInOneVertex,// stride [ sizeof( Vertex_p3t2 ) ]
                      (GLvoid*)byteOffsetToUVCoords );  // You are missing this?
// Check for OpenGL error

```

To send a texture to your glsl shader you want to use code similar to this:

```
glActiveTexture(texNameID);
glBindTexture(GL_TEXTURE_2D, texID);
glUniform1i(textureUniformLocation, texID/*-1*/); // might need to -1 for proper id.
// Check for OpenGL error

```

**For future consideration**

Using `shader["..."]` and `find("....")` uses a string comparision which will take up a lot of computation time and will slow your program down when you start to have a lot more calls to it. I suggest you change it to direct variables from an array or object instead.
Also I suggest to take advantage of OpenGL by passing vertices of size 4 instead of 3 or 2.

**Resources**

glVertexAttribPointer: https://www.opengl.org/sdk/docs/man/html/glVertexAttribPointer.xhtml
CheckGLError: glDrawElements Crash

**UPDATE**

In your connectTexture method try changing it to `glUniform1i(mUniformList["backgroundTexture"], id);`. Also try `id-1` if that doesn't work. Your texture id's start at 1, and 2. So if it is using "2" it won't be reading it from "0".

**Edit #2** Here is more detailed code for your reference: Terrain shader from heightmap opengl GLSL
> 1 votes

---
Tags: opengl, c++, heightmap
---


title: Slick2D Networking Crash

text:
# Question
Title: Slick2D Networking Crash
This is my first post, so I apologize if it's been put in the wrong place or something. Anyways, here's my problem:

I've run into an issue with running my client-side code in one of my game-states. The game crashes because the update method isn't able to keep running. I know it's because the program waits for a connection, stalling the rest of the program. This line is responsible:

```
connection = new Socket(InetAddress.getByName(serverIP), port);

```

My game-state is a standard BasicGameState with an init(), a render(), and an update(). I don't know where to put the connection code into the game-state class. Here's the game-state code if you need it:

```
public class ConnectState extends BasicGameState {

private UnicodeFont ufont;
private Client client = new Client();
private final int ID;

public ConnectState(int state) {
    ID = state;
}

@SuppressWarnings("unchecked")
@Override
public void init(GameContainer container, StateBasedGame game) throws SlickException {
    try {
        Font font = new Font("Sitka Small", Font.BOLD, 70);
        ufont = new UnicodeFont(font, font.getSize(), font.isBold(), font.isItalic());
        ufont.addAsciiGlyphs();
        ufont.addGlyphs(400, 600);
        ufont.getEffects().add(new ColorEffect(Color.WHITE));
        ufont.getEffects().add(new OutlineEffect(5, Color.RED));
        ufont.loadGlyphs();
    } catch (SlickException e) {
        e.printStackTrace();
    }
}

@Override
public void render(GameContainer container, StateBasedGame game, Graphics g) throws SlickException {
    g.setFont(ufont);
    g.drawString(client.displayMsg, container.getWidth() / 2 - ufont.getWidth(client.displayMsg) / 2,
            container.getHeight() / 2 - ufont.getHeight(client.displayMsg) / 2);
}

@Override
public void update(GameContainer container, StateBasedGame game, int delta) throws SlickException {
    Input input = container.getInput();
    boolean isRunning = false;

    if (!isRunning) {
        client.run();
        isRunning = true;
    }

    if (input.isKeyPressed(Input.KEY_F1))
        if (container.isShowingFPS())
            container.setShowFPS(false);
        else
            container.setShowFPS(true);
    if (input.isKeyPressed(Input.KEY_ESCAPE))
        container.exit();
}

@Override
public int getID() {
    return ID;
}}

```

Here's the Client code if you need it as well:

```
public class Client {

public String displayMsg = "";

private ObjectOutputStream output;
private ObjectInputStream input;
private String serverIP = "localhost";
private Socket connection;
private boolean shouldExit = false;
private Object recievedData;

public void run() {
    try {
        connect();
        setupStreams();
        whileConnected();
    } catch (EOFException e) {
        showMessage("The client closed the connection!");
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        close();
    }
}

public void setShouldExit(boolean should) {
    shouldExit = should;
}

private void connect() throws IOException {
    System.out.println("So far...");
    showMessage("Attempting to connect...");
    System.out.println("...so good?");
    connection = new Socket(InetAddress.getByName(serverIP), 1337);
    showMessage("Connection successful! ^_^");
}

private void setupStreams() throws IOException {
    output = new ObjectOutputStream(connection.getOutputStream());
    output.flush();
    input = new ObjectInputStream(connection.getInputStream());
    showMessage("The streams have been setup! Don't cross 'em!");
}

private void whileConnected() throws IOException {
    do {
        try {
            recievedData = input.readObject();
            //send or do stuff
        } catch (ClassNotFoundException e) {
            showMessage("Something square was shoved through the circular tube...");
        }
    } while (!shouldExit);
}

private void close() {
    showMessage("Closing...");
    try {
        output.close();
        input.close();
        connection.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

private void sendData() {
    //TODO
}

private void showMessage(String message) {
    displayMsg = message;
}}

```

In short, how do I run the aforementioned line of code in a constantly updating game-state? Also, if you know a better/easier way for tcp (I'm making a turn-based game, so tcp is fine) in slick, let me know!

# Answer
> 1 votes
Thanks for reading, turns out I just needed to spend a bit more time on my problem. For those who find this in the future, I used Kryonet to run my network code in a separate process.

---
Tags: java, networking, slick, socket
---


# Question
Title: Efficient movement of units to different points with different speeds
I have a series of units and have been given 2d points that they must go to. However they are free to go to what point they like as long as all the units get to all the points in the quickest time possible. Each unit has its own speed.

What is the best algorithm if I ignore unit collisions and terrain is perfectly flat with no obstacles.

# Answer
This appears to be an *O(2ⁿ)* problem, but I have an *O(n³)* algorithm that converges to a local optimum, which from my experiments is also usually the best solution (tested with random configurations of up to 10,000 units). Also it seems to actually run in *O(n²log(n))* mean time but I am really too lazy to try to prove this.

Here is how it goes.

First, precompute all possible travel times in an *N×N* float array `time`, *i.e.* `time[i][j]` is the time it would get for unit *i* to go to point *j*.

Then populate an integer array `plan` of size *N* where `plan[i]` is the point that unit *i* should plan to reach. Using `plan[i] = i` or initialising randomly didn’t impact my tests, the algorithm always found the best solution.

Finally, apply the following algorithm:

```
repeat:
    no_swaps_occurred = true
    for a in 0…N:
        for b in i+1…N:
            if max(time[a][plan[a]], time[b][plan[b])
             > max(time[a][plan[b]], time[b][plan[a]):
                swap(plan[a], plan[b])
                no_swaps_occurred = false
until no_swaps_occurred

```

In the end, `plan` contains the proposed optimal travel plan for all units.
> 3 votes

---
Tags: movement, rts
---


# Question
Title: Good Resources for Random World Generation
Is there a good reference or tutorials available for adding world generation into a 2D game? I've gotten to the point where I have most of the resources available to add world generation but I don't really understand the concepts of creating a random world generation based map. Any tips and guides can help.

# Answer
> 1 votes
Almost every game that features **procedural generation** uses Perlin Noise function. Perlin noise produce very **natural** looking noise and it is very **customizable**.

Implementing Perlin noise is also very easy but you need to customize it to your requirements which may take a little time and research. After you generated the noise matrix you can use any kind of conditional checks and processing on per-pixel basis to get what you want.

Here are some good **tutorial** and **references** that will help you:

http:// anthonypigeot.com/experiments-perlin-noise-2d-and-3d-worlds/

http:// devmag.org.za/2009/04/25/perlin-noise/

http://www.java-gaming.org/index.php?topic=31637.0

---
Tags: java, software-engineering, slick, open-world
---


# Question
Title: adding radial gradient to heightmap results in jagged edges
I am trying to implement a simple heightmap editor. In this editor, you can elevate the terrain by clicking on a spot in the heightmap, and holding down the mouse button. This will little by little, every frame, elevate the terrain into a hillshape. The hills created looks like this:

https://i.stack.imgur.com/f2niF.jpg

As can be observed, however, the edges of the hill has some pretty awful jagged edges:

https://i.stack.imgur.com/D84he.jpg

I am not quite sure how to get rid of these edges. For every frame that I hold down the mouse, the following code is executed:

```
float rad = 35;
for(int ix = -rad; ix <= +rad; ++ix) {

    for(int iz = -rad; iz <= +rad; ++iz) {

    // distance from center of hill.
    float dist = sqrt( (float)ix * (float)ix + (float)iz * (float)iz  );

    // if within the radius of the hill(this ensures that the hill is round)
    if(dist <= rad) {

        // the farther we get from the center, the less we increase the height.
        // this effectively results in a radial gradient being added to the
        // heightmap.
        // Note that we use "x*x" instead of "x", because this results in a
        // more round and natural-looking hill
        float x = dist / rad;
        float y = (1.0 - x*x);

        // maximum height of the hill
        float maxHeight =y * (float)MAX_HEIGHT;

        /*
          Note that cx and cz describe the center position of the hill.
         */

        if( heightData(cx+ix,cz+iz) < (float)MAX_HEIGHT) { // do not exceed the maximum height

             // if we hold down the mouse for 30 frames, the hill will reach its maximum height
             float increment = maxHeight  / 30.0;

            if(heightData(cx+ix,cz+iz) + increment > MAX_HEIGHT) {
                 // clamp the hill height so that it does not exceed the maximum height of the
                // height map.
                heightData(cx+ix,cz+iz) = MAX_HEIGHT;
            } else {
            heightData(cx+ix,cz+iz) += increment;
            }
        }

    }

    } // end for
} // end for

```

As can be observed, every frame I simply add a radial gradient to the heightmap. `MAX_HEIGHT = 65535;`, because the heightmap is a grid of unsigned shorts. And the resolution of the heightmap is 256x256. But even if I increased it to 512x512, the jaggies still remained.

# Answer
> 0 votes
The root cause of your artifact is likely the harsh cutoff at `rad`. As you accumulate elevation, the boundary gets very discontinuous.

As for solutions, I would recommend a slightly wider filter that tends toward zero outside the desired action radius, or shrink the current filter to avoid missing grid cells that are at the boundary.

---
Tags: c++, heightmap, map-editor
---


title: How do I hide UI canvas in c# Unity3d?

text:
# Question
Title: How do I hide UI canvas in c# Unity3d?
I want to display the final results at last in the game when gameobjects finish the winning(finish) line. For that I am using canvas and in that a panel onto which an image is attached. I have to hide that canvas at start of the game and then show when gameobjects cross the last finish line. How can I do this..? Please if anyone has an idea about this can help me. Thanks in advance :)

# Answer
> 1 votes
Make a variable public GameObject panel , in the script from which you want to disable the panel. Drag and drop the panel into the variable script in inspector. Disable the panel from inspector. On win do panel.SetActive(true);

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


# Question
Title: Computing a full revolution for an arbitrary orbit?
I'm making a game in which the goal is to get as many planets as possible to orbit around a star. The user launches planets at **any distance away** from the sun (as long as it's on-screen), and in **any direction** (possibly even directly at the sun, though their game won't last very long).

This means orbits can be circular, elliptical, or--more than likely--irregular, something like this:

(Image originally from here)

The rules for my game that the player may launch planets as frequently as s/he likes...but they will **only** score a point for their **first revolution** (so spamming planets isn't likely to score very much).

Right now, the gravitational force is just `F = ma` (i.e. a constant force towards the sun). I'm trying to figure out when a planet in arbitrary orbit has completed a full revolution. This is how I'm doing it currently...

```
// If this planet is active...
Vector2 a = _body.position.normalized;
Vector2 b = (a + _body.velocity).normalized;

float angle = Vector2.Angle (a, b);
this._total_angle += angle * Time.deltaTime;

if (this._total_angle >= 360) {
    // If this planet has made a revolution...
    ++this._revolutions;
    this._total_angle = 0;
    this.OnRevolution.Invoke (this);
}

```

However, this is incorrect for anything besides circular orbits. No good.

**Given all of this (and my near-total unfamiliarity with orbital mechanics), how can I tell when a planet in an arbitrary orbit has completed one full revolution?**

**EDIT:** No, the planets will *not* affect each other's orbits (though they can collide into one another, but they'll just explode).

# Answer
Assuming realistic Newtonian gravity (i.e. that the gravitational force between two bodies is inversely proportional to the square of their distance), and that the planets don't interact gravitationally with each other, but only with the sun, then the planets will always follow Kepler orbits (which, if closed, will always be elliptical).

Conversely, if the planets *do* affect each other via gravity, then you're dealing with the full *n*-body problem, which can have all sorts of crazy solutions like figure of 8 orbits or even planets accelerating to infinite velocities. Admittedly, those particular examples are mainly mathematical curiosities that you're unlikely to see in your game, but still, you should not expect there to be a single, unambiguous definition of an orbit for general *n*-body dynamics.

The best you can do is probably to just pick some arbitrary, pragmatic definition and stick to it. For example, in two dimensions, you could simply declare that a planet has completed a full orbit when its angle, as seen from the sun, equals the angle of its starting position (after actually looping around the sun). You could simply track this angle for each planet, adjusting it incrementally as the planet moves, and declaring a complete orbit when it hits ±360°; this way, you won't end up with false positives for planets that e.g. loop around each other and reverse direction without actually going around the sun.

If the above seems too easy, you could also require that the planet must return to approximately the same position *and* velocity as it had before. (Again, you'll probably want to also track the sun angle, to make sure that the planet has actually gone around the sun and not just, say, around another planet.) This probably requires you to track the trajectory of each planet (which, of course, you may want to do anyway for visualization purposes) and to come up with some fairly efficient scheme for finding near matches (e.g. using spatial binning).
> 3 votes

# Answer
Maybe the easiest approach would be to just create checkpoints. Seperate the space around the sun into, for example, 4 sectors:

* -x, -y
* +x, -y
* +x, +y
* -y, +y

Knowing the relative coordinates of the planet you can easily compute in which sector it currently is. You can assume the planet to have revoluted the sun once it has visited all four sectors.
> 1 votes

# Answer
Another approach may be considering max and min potential energy, or min and max orbit velocity on respect the sun:

Keep track of velocity maximum and velocity minimum.

```
If reached minimum velocity
 next time a minimum velocity is reached (maybe not the same minimum value) an  orbit has  occurred
end if

If reached maximum velocity
 next time a maximum velocity is reached (not the same maximum) an  orbit has  occurred
end if

```

**Pros**: you do not depend on angles and trajectories; suites for 2d and 3d

**Cons** : interaction with other bodies(planets) may generate false minimum and/or false maximum.

**Cons 2** : orbit starts at a minimum or maximum and not when you release the planet

Final note **resolving Cons2**: when you reach min velocity (call it minP) and max velocity point (maxP) you can estimate semimajor axis (usualy called a ) as the sum of the distance from sun of minP and maxP divided by two.

```
a= (distance(sunP ,minP) + distance(sunP ,maxP))/2

```

So you can establish (aproximated) the orbital period as

\\$ T = {2}{\pi}{\sqrt \frac{a^3}{\mu}} \\$

where

\\$ \mu = G * M \\$

at this point when your time from planet release reaches T , you get one orbit.
> 0 votes

---
Tags: unity, physics, mathematics, algorithm, orbit
---


# Question
Title: How can I change my RangeAttribute during in my script?
I have an int which I want to be between 0 and an unknown number. This unknown number is max in the example below. I want this max number to change when another number changes in the editor. How can I accomplish this? This is my best attempt, but it won't let me use an unknown value for my range.

```
[Range(1, 10)]
public int multiplier;

[Range(0, max)]
public int x;

void OnValidate(){
    max = 10 * multiplier;
}

```

# Answer
> 1 votes
GetCustomAttributes will most likely only give you a copy of the original Attribute. Changing that will have no effect at all in the editor.

What you need is a custom inspector: https://unity3d.com/learn/tutorials/modules/intermediate/editor/building-custom-inspector. This will allow you to customize the inspector any way you like.

# Answer
> 0 votes
You can access and change attributes using reflection, something like:

```
var attrs = (RangeAttribute[])typeof(myScript).GetCustomAttributes (typeof(RangeAttribute), false);
attrs [0].max = 10;

```

should work - more or less.
Question is, why would you even wanted that? The only point of `Range` attribute I see is changing textbox to slider in designer (or is there something more to it?). In case you dont need to access the field in editor you could use properties instead, it even gives you more flexibility(you can define "overflow" logic):

```
[Range(1, 10)]
public int multiplier;
public int _x;
public int X {
  get { return _x; }
  set { _x = Math.Min(10 * multiplier, value); } //clamp for example
}

```

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


title: UDP server and two clients

text:
# Question
Title: UDP server and two clients
So - my whole knowledge comes from google and stackoverflow. I'm trying to create an UDP server (with two slots per new instance of the game) and clients.

My problem is here that I totally don't know where to start. I can't find and tutorial that shows how to connect two players with a server via UDP - and yes - it has to be UDP cause of the game mechanics. I wrote this:

```
public class Server {

   private static HashSet<Integer> ports = new HashSet<Integer>(); // these     are player's IDs
   static ArrayList<InetAddress> addresses = new ArrayList<InetAddress>();
   public static boolean player1_active = false, player2_active = false;
   public static PlayerCredits p1, p2, temp;
   public static void main(String[] args) throws Exception {

   // The default port
    int serverport = 8888;

    DatagramSocket udpServerSocket = new DatagramSocket(serverport);
        DatagramPacket sendpacket;
    System.out.println("Server started...\n");

    while(true)
    {

        byte[] receiveData = new byte[1024];

        DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

        udpServerSocket.receive(receivePacket);

        String clientMessage = (new String(receivePacket.getData())).trim();

        System.out.println("Client Connected - Socket Address: " + receivePacket.getSocketAddress());
        System.out.println("Client message: \"" + clientMessage + "\"");

        InetAddress clientIP = receivePacket.getAddress();
                    addresses.add(clientIP);

        System.out.println("Client IP Address & Hostname: " + clientIP + ", " + clientIP.getHostName() + "\n");

        // Get the port number which the recieved connection came from
        int clientport = receivePacket.getPort();
        System.out.println("Adding "+clientport);
        ports.add(clientport);

        // Response message
        String returnMessage = clientMessage.toUpperCase();
        System.out.println(returnMessage);
        // Create an empty buffer/array of bytes to send back
        byte[] sendData  = new byte[1024];

                    temp = new PlayerCredits(clientport, clientIP);

                    if(!player1_active){
                     p1 = new PlayerCredits(clientport, clientIP);
                     player1_active = true;
                    }

                    if(temp.port != p1.port && temp.ad != p1.ad)
                     if(!player2_active){
                        p2 = new PlayerCredits(clientport, clientIP);
                        player2_active = true;
                    }

                    DatagramPacket sendPacket;
                     if(p2 == null){
                         String awaiting = "WAITING FOR SECOND PLAYER";
                         sendData = awaiting.getBytes();
                          sendPacket= new DatagramPacket(sendData, sendData.length, p1.ad, p1.port);
                            udpServerSocket.send(sendPacket);
                     }
                         else{
                         String awaiting = "SECOND PLAYER INCOMING";
                         sendData = awaiting.getBytes();
                            if(p2!=null){
                            sendPacket = new DatagramPacket(sendData, sendData.length, p2.ad, p2.port);
                            udpServerSocket.send(sendPacket);
                            }
                            sendPacket = new DatagramPacket(sendData, sendData.length, p1.ad, p1.port);
                            udpServerSocket.send(sendPacket);
                     }

        }

}
public static class PlayerCredits{
    int port;
    InetAddress ad;
    public PlayerCredits(int p, InetAddress a){
        this.port = p;
        this.ad = a;
    }
}

```

So - for now I have two people connected - but as you will probably say - it's WRONG. Cause I know - it is :D I need to somehow implement every player on the Multisocket or something (or connect them via TCP and then listen on a new thread with a new datagram).

If there is someone that could help and tell me, how it should be done like in 3 steps like (I don't need code):

1. Connection with TCP
2. Create new threads with players and listen on UDP
3. Start the game when 2 players are connected

Also, how to stop the 'third connection' and redirect it to a new game instance? (cause it's 1v1).

I would be so grateful. I will have networking in two years in college, but I want to learn it.

# Answer
> 2 votes
The reason for the roadblock you are hitting is that you try to do something which does not exist. As a stateless protocol, UDP doesn't have "connections".

Because a UDP datagram is not explicitly tied to a connection, you need to find out by yourself from which client an UDP datagram originates. One way to do this is by calling `getPort()` and `getAddress` on the DatagramPacket and use that information to find out from which player it originates.

When you then want to forward the information from that datagram to the other players, you send them new datagrams with their respective ports and address of those players.

Because UDP is stateless, you need to implement your own state management to keep track of which players are currently connected. A good way to do this is by having some collection of currently connected players. When you receive a new message, check if a player with that IP and port is already in the collection. If not, add them. Remove players when they send a special "disconnect" message or when they didn't sent any messages for X seconds (timeout).

---
Tags: networking, multithreading
---


title: Little question about glPolygonOffset

text:
# Question
Title: Little question about glPolygonOffset
q1. After passing stencil test, depth test, etc. what version of "depth" of fragments after primitive rasterisation will be written to depth buffer? With shifted values or without? (Due to documentaion as I see it will be shifted version)

q2. Code in fragment shader will receive shifted version of `gl_FragCoord.z`, isn't it?

# Answer
> 6 votes
The short answer is: Don't use glPolygonOffset.

It's not portable in the sense that you have no control over how the values are applied by the driver, so even on the same platform (eg Windows), different drivers will give different results.

sadly glDepthRange is also not usable for this purpose due to clamping.

You should shift the depth yourself **using the projection matrix** or a uniform value in your **vertex shader**. Avoid doing it in the pixel shader as it disables early-Z and hi-Z GPU optimizations.

One good way to shift depth is to multiply it by a factor slightly above or below 1 ( eg 1.015625 or 0.984375 (1.0 +/- (1.0/64.0)), depending on which direction you want to shift your pixels and direction of your depth buffer) this works well with both fixed and floating point depth buffer rounding issues as the "shift" scales up and down with depth values.

in your vertex shader:

```
vtx *= pvm_matrix; // transformation to screen-space
vtx.z *= 1.0 + shift_value * abs(vtx.w); // counter w division for shift

```

or just pre-calculate the shift value into pvm\_matrix without the vtx.w correction.

Ideally you want to use a shift increment value that is 1.0/N where N is a power of two (eg 1/64 = 0.015625) this plays better with binary rounding errors.

```
float shift_value = int_layer / 1024.0f;
glUniform1f(loc, shift_value);

```

the value to use depends on the depth buffer's precision, most are 24bits fixed point (1/65536 is a decent value to shift on these) but some platforms use 24bit float which leaves only 15~16 bits of mantissa precision (1/1024 or 1/512 is a good value for those).

You need to leave enough bits of precision "below" your shift value unless you're rendering flat 2D UI planes. The less perpendicular to the camera the more bits you need to leave "below" your shift value (larger shift value) in the depth buffer.

It's possible to adjust the shift amount in the vertex shader according to the angle of the triangle by using the normals.

---

But really, as much as possible the best way is to completely avoid having to shift depth values by using multi-texturing, or 2nd pass using 100% identical triangles (merged vertex) and a depth test of equal.

If the vertices are identical the interpolation will also be identical and won't cause any depth fighting but this may not be possible in all situations.

---
Tags: opengl
---


# Question
Title: Nothing happens when I press play in Unity3D
Hello everyone I am making my first game, things were going well but suddenly nothing happens when I press play, I have already update to the newest unity version but it persists.

I have the main camera selected, layers seem fine, I rested the camera position and also tried to switch to 3d view. Do you have any idea on how to fix this?

You can download the game project file here: https://www.dropbox.com/s/0c64y0ats33f79i/Energy%20Manager.rar?dl=0

Any help is very much appreciated.

# Answer
> 1 votes
Your scene is empty. You didn't save the scene, where you did all the work. When you get done with work, then save the scene (Ctrl + S). It will save a scene file through that Unity maintains the scene work.

# Answer
> 0 votes
It does not appear that you have any scripts attached to the main camera (or any other game object). Scripts need to be attached to a GameObject to run.\*

\*There are exceptions to this, as with any rule. But in the situation you are in, what's important is that *no* scripts are attached, meaning their `Update()` method does not run.

# Answer
> 0 votes
I solved it by Opening "scene1" and adding it to the project. This way:

Double click "scene1" to open

File -\> Build Settings -\> Add Open Scenes

Thanks for the help!

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


title: XNA makes the console flicker

text:
# Question
Title: XNA makes the console flicker
I create a Window XNA game project from the template in Visual studio 2015. Then I right click and set the property to console application because I think it is convinient to use Console.WriteLine() for debugging.

In the game constructor I add

```
graphics.PreferredBackBufferWidth = 1920;
graphics.PreferredBackBufferHeight = 1080;
graphics.IsFullScreen = true;

```

Now the console text flicker. I use Console.Clear() the first thing I do in Update(). When I run the game in a window then the console text do not flicker. I even add counter to not update the text every time Update() is called and the console text still flicker in full screen mode. The same problem is there when I start form Windows Powershell. (The exact same thing do not flicker with MonoGame though.)

# Answer
The flicker you see is the result of clearing the console which is being displayed by the graphic card, then text get drawn and "reappear".

It's only by sheer luck that it didn't flicker before.

Using the Console.Clear() command will "always" make the console text flicker. It's not designed to redraw text like this.

Invest time in making your own virtual terminal console that you can display in a separate window or as an overlay over your game with the option of writing the text to a log file and possibly a command line.

It'll make it easier later to test your game by typing cheat commands.

You can probably get this done in a day or two.
> 1 votes

# Answer
Utilize double buffering when you draw to eliminate flickering. Instead of displaying debug information through the console draw your own output onto your game screen in whatever way you see fit.
> 0 votes

---
Tags: c#, xna, console
---


# Question
Title: Inline If failing to update variable value
So, I have a toggle button to change a bool value, in this script 't1Bool'. The toggle button is working because when I use a Debug.log I can see the value changing from true o false when I press the button. When using the Debug.log with the variable turbina1 the value is always zero. I already checked the if condition syntax and don't know why this value is not being updated.

```
using System;
using UnityEngine;
namespace Assets.Code.PowerPlants
{
    public class HydroElectric
    {
        public bool t1Bool;
        public bool t2Bool;
        public bool t3Bool;

        int turbina1;
        int turbina2;
        int turbina3;

        public float prod;

        public HydroElectric ()
        {
         t1Bool = true;
         t2Bool = true;
         t3Bool = false;
         prod = 0f;
        }

        public float HydroControlPanel ()
        {
            turbina1 = t1Bool ? 2 : 0;
            turbina2 = t2Bool ? 3 : 0;
            turbina3 = t3Bool ? 1 : 0;

            prod = turbina1 + turbina2 + turbina3;
            Debug.Log (turbina1);
            return prod;
        }
    }
}

```

This is the code for the button:

```
public void ShowIt()
{
            ec.t1Bool = GUI.Toggle (new Rect (25, 55, 100, 50), ec.t1Bool, "Turbina 2 MW");

            ec.t2Bool = GUI.Toggle (new Rect (25, 95, 100, 50), ec.t2Bool, "Turbina 3 MW");

            ec.t3Bool = GUI.Toggle (new Rect (25, 135, 100, 50), ec.t3Bool, "Turbina 1 MW");

            GUI.Box (new Rect (Screen.width - 100, 60, 80, 25), ec.prod.ToString ());      // PRODUCED ENERGY

        }

```

This is where the object instance is created (it is in the same script as the button):

```
public class PlayState : IStateBase
    {
        private StateManager manager;
        private HydroElectric ec;
        public PlayState (StateManager managerRef)
        {
            manager = managerRef;
            Debug.Log ("Constructing PlayState");
            ec = new HydroElectric();
        }

```

Any hint?

# Answer
In last line, it should be ec.HydroControlPanel().ToString() instead of ec.prod.ToString() in ShowIt method
> 1 votes

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


# Question
Title: D3D11InfoQueue Isn't filtering out messages
I have followed the Coordinator's code advice from this page on how to query and filter the messages in the debug layer but it doesn't seem to be working. You can see from the following code that I try to filter out 2 messages but they still keep zinging by in debug output. Does anyone know how to do this correctly? Here is the code:

```
void CDebugLayer::CreateD3DDebugLayer(void)
{
    if(SUCCEEDED(s_pApplication->m_spEngine->GetD3DObj()->m_spD3DDevice.Get()->QueryInterface( __uuidof(ID3D11Debug), (void**)s_spD3DDebug.GetAddressOf())))
    {
      if(SUCCEEDED(s_spD3DDebug.Get()->QueryInterface( __uuidof(ID3D11InfoQueue), (void**)s_spD3DInfoQueue.GetAddressOf())))
      {
         #ifdef _DEBUG
             s_spD3DInfoQueue->SetBreakOnSeverity(D3D11_MESSAGE_SEVERITY_CORRUPTION, true);
             s_spD3DInfoQueue->SetBreakOnSeverity(D3D11_MESSAGE_SEVERITY_ERROR, true);
             //s_spD3DInfoQueue->SetBreakOnSeverity(D3D11_MESSAGE_SEVERITY_WARNING, true);
             //s_spD3DInfoQueue->SetBreakOnSeverity(D3D11_MESSAGE_SEVERITY_INFO, true);
             //s_spD3DInfoQueue->SetBreakOnSeverity(D3D11_MESSAGE_SEVERITY_MESSAGE, true);
         #endif

         D3D11_MESSAGE_ID stHide [] =
         {
             D3D11_MESSAGE_ID_SETPRIVATEDATA_CHANGINGPARAMS,
             D3D11_MESSAGE_ID_OFFERRELEASE_NOT_SUPPORTED
             // Add more message IDs here as needed
         };

         D3D11_INFO_QUEUE_FILTER stFilter;
         memset(&stFilter, 0, sizeof(stFilter));
         stFilter.DenyList.NumIDs  = _countof(stHide);
         stFilter.DenyList.pIDList = stHide;
         HRESULT hr = s_spD3DInfoQueue->AddStorageFilterEntries(&stFilter);
         assert(hr == S_OK);

         D3D11_INFO_QUEUE_FILTER stFilter2;
         memset(&stFilter2, 0, sizeof(stFilter2));
         SIZE_T ByteLength;

         // Perform debug tracking to confirm what is being stored
         uiNumMsgs = s_spD3DInfoQueue->GetNumMessagesAllowedByStorageFilter(); // = 7
         hr = s_spD3DInfoQueue->GetStorageFilter(&stFilter2, &ByteLength);
         assert(hr == S_OK);
         uiNumMsgs = s_spD3DInfoQueue->GetNumMessagesDeniedByStorageFilter();  // = 0

         //Pass copy to Application then store in CEngine for global engine access
         s_pApplication->m_spEngine->SetDebug(s_spD3DDebug.Get());
      }
    }
} // CreateD3DDebugLayer

```

**EDIT** This is the error message I'm trying to filter out: D3D11 INFO: ID3D11DeviceContext::OfferResources: OfferResources is not supported on operating systems older than Windows 8. It is valid to call OfferResources, and an offerred resource must still be acquired with ReclaimResources before using it, however there is no benefit to calling OfferResources on this operating system besides testing the code path for Windows 8. \[ EXECUTION INFO #3146071: OFFERRELEASE\_NOT\_SUPPORTED\]

Caused by:

```
ID2D1DeviceContext->EndDraw()

```

on Windows 7 Sp1 x64. Using Windows SDK 8.1.

# Answer
> 1 votes
DirectX Control Panel overrides filters set by application.

Run DirectX Control Panel, click Edit Lists, make sure your app is not there.

*I had exactly same problem as you and it turned out this helps.*

---
Tags: directx11
---


# Question
Title: Why do Physics Engines use collision margins?
When using a physics engine in a game (such as Bullet), you usually need to define a collision margin for each object. I'm a beginner to game development, and I don't understand the purpose of a collision margin.

My basic understanding is that if you were to have two objects, each with a collision margin set to 0.01, then a collision would be detected when the two collision margins touch each other, such that the gap between the two objects is actually 0.02.

But why not just set the collision margin to 0, and cause a collision to be detected when the actual surfaces of the two objects collide? This is how physics works in reality.

One guess is the following. If a cube has a margin of 0.01, then a collision will be detected whenever a part of another object exists between 0 and 0.01 from the object's surface. This gives the simulation room for error, such that if it "misses" the point when the object passes the cube's collision margin (because the simulation step is long), then it still has time to detect a collision as the object then moves closer towards the cube's surface, within the 0.01 margin. Otherwise, if the margins are zero and a collision is missed by the simulation, you might get a situation where two solid bodies occupy the same space, which could cause problems.

Is this guess correct? Or is there another reason?

Thanks!

# Answer
> 10 votes
There are three reasons collision margins may exist in physics simulations.

1. As you suggested, a collision margin gives the physics engine some *room for error* in detecting contacts and resolving contacts, prior to actual penetration. This helps with the appearance of realism as objects do not visibly poke through the ground, etc. There are nuances here for the calculation of the threshold for when contact constraints apply Baumgarte stabilization during solving to help separate bodies.
2. As DMGregory notes, collision margins may be added to planes or triangles to provide an arbitrary *thickness* to primitives that are mathematically infinitely thin, effectively turning them them into a volume.
3. Perhaps more important is that many collision detection engines use the Gilbert–Johnson–Keerthi (GJK) algorithm to perform convex-v-convex collision detection. This algorithm is efficient when performing collision detection between disjoint pairs - even if they are very close to one another. The moment the two convex shapes actually overlap each other, the cost of the GJK algorithm increases dramatically. Furthermore, to generate an effective contact point the Expanding Polytope Algorithm (EPA) must be run, which is even more costly. As a result many physics engines (Havok, Bullet) create a shell around the convex hull, which is the usually named something like *collision margin* or *convex shell*.

Erwin Coumans, the author of bullet answers some questions here with an overview below:

> GJK doesn't calculate penetration depth by default. You can add a margin to collision shapes, which allows you to use GJK to calculate shallow penetration depth (not deeper then the added margins of the 2 involved objects). For a sphere, you can use the full radius as margin, and use a point as shape. As long as there is no overlap (without the margins) when GJK terminates, the simplex solver (either johnson or 'geometric/voronoi' can be used as world-space contact points. For deeper penetrations, use either EPA (expanding polytope algorithm) or sample the pentration depth in several directions, using the support mapping.

---
Tags: collision-detection, physics, 3d-meshes, bullet-physics
---


title: Better way to timestep?

text:
# Question
Title: Better way to timestep?
So I know how timestepping works.

As I understand it if I wanted to move a character at the same speed in real-world time I need to simply multiply the movement of the character by DT on each frame.

So code without timestepping

```
forever
{
  player.position.x += 1
}

```

and with timestepping

```
forever
{
  player.position.x += 1 * dt
}

```

I have noticed that it is frustrating in some cases to do it like this. Because lets say I had a specific distance in mind for the player to travel in the frame, without timestepping I only need to add that ammount, however with timestepping I need to find a different value that produces the same results when multiplying by a "normal" dt value.

I was wondering how I could approach the following.

I want to move the player forward one unit each frame as long as the fps is 60. So I am going to call a function with moveForward(1) every frame. However if the fps is 30 I want the player not to move one unit but instead travel 0.5 units each frame but still call moveForward(1). So basically if their is no lag it travels 1 unit each frame if their is lag it still travels at the same "real world" speed but in code travels less far each frame.

**My question is.** How would one calculate it? Perhaps you could fill in this skeleton function.

```
var targetDT = (1.0 / 60.0)
var currentDT = //**Value changes each frame to represent currenty delta time of frame**//
func moveForward(units: Int)
{
   var scalar = //**IDK what goes here something that considers the fps**//
   player.position.x += units * scalar;
}

```

This is probably very simple math I am just not figuring it out!

Also what is the relationship between dt and fps if we consider that the render loop and logic loop happen at the "same" time simultaniously?

# Answer
> 4 votes
I think you need to rethink what you're trying to do.

Look at the last lines in your example move forward code

```
var scalar = //**IDK what goes here something that considers the fps**//
player.position.x += units * scalar;

```

Now look at the normal movement scaled by time code

`player.position.x += 1 * dt`

Notice the similarity?

I understand that you have problems calculating exactly how fast a character should move. Though I usually find it easier to think of speed per second than speed per 1/60th of a second its easy to make a few helper methods to help you with that:

`speedPerSecond = speedPerFrame * 60`

With the added bonus that your game will run well even when the frame rate dips a bit.

As with all posts about time steps, please read this article: http://gafferongames.com/game-physics/fix-your-timestep/

---
Tags: mathematics, timestep
---


# Question
Title: What is more efficient: Using matrix translation to move a character, or using a vector/scalar?
In 2D or 3D, matrix transformations are used for rotation, scaling, and sheering. However, when it comes to movement, should I go out of my way to use and implement scalar/vector movement, or just stick to matrix translations? Thanks.

# Answer
> 2 votes
This depends on some pipeline details, but generally we're not *just* translating objects, our engines need to handle objects that are translated, rotated, *and* scaled, and often need to apply camera view & perspective transforms to them too.

All of these transformations can be concatenated and applied with a single matrix multiplication, so it usually makes sense just to fold translation into that matrix. There's no incremental cost to translating that way, and any object, no matter how it's transformed, can be handled identically (rather than having one path for purely-translated objects and another for everything else)

If you're making a game where nothing ever scales, rotates, skews, or perspective projects, then you might make some efficiency gains by translating alone through vector addition without a matrix — but in exchange for pretty onerous restrictions on what your engine can do. For most projects, the matrix multiply is worth the flexibility it offers.

Even where a matrix is used, it's still conventional to store the translation, rotation, and scale information separately, so that when any of those change the matrix can be rebuilt from scratch, rather than continuously modified, keeping rounding errors from accumulating & causing drift.

---
Tags: matrix, transformation
---


# Question
Title: Does Direct3D 11 enable Z-clipping/discard by default?
I'm rendering simple 2D figures in DirectX 11.1 and I cannot get Z-values to be rendered; all pixels with Z != 0 get discarded. I'm doing proper world transform as far as I know. X/Y translations work. Rotation over Z works.

Do I need to setup a depth/stencil buffer to avoid DirectX to discard all primitives with Z coordinates?

Thanks, I'll supply any additional information ,code or screens if required.

EDIT:

I've fixed D3D11\_VIEWPORT minDepth and MaxDepth members to 0.0/1.0 (I was clearing both to zero). Now pixels with 1.0 \< z \< 0.0 are discarded.

EDIT 2:

My platform is Windows Runtime App (Win8.1 / WinPhone 8.1).

EDIT 3:
**Example screenshots.**

*Rotated triangle over the Y-axis (pixels with Z\>1 discarded)*

*Triangle Vertex at (x=-0.5,y=-0.5) with z=2. Clipped and hidden.*

# Answer
As @Lars Viklund stated, I didn't multiply my vertices in the shader to apply the projection transform, so I was constrained to the bounds of the clip space Z (0..1\]. Adding a proper view and transformation matrix solved the problem.
> 0 votes

# Answer
A common mistake is to zero out `MinDepth` and `MaxDepth` of the `D3D11_VIEWPORT`, effectively clamping all depth to the near plane.

The default depth states are test enabled, write enabled, compare less. See the list at MSDN.

In Direct3D 11, normalized device coordinates in clip space after W division run from `[-1.0, +1.0]` on the X and Y axes, and `(0.0, 1.0]` on the Z axis.

If your post-projection geometry has a `Z/W <= 0.0` or `1.0 < Z/W`, the fragments will be clipped.
> 4 votes

---
Tags: 2d, directx11, depth-buffer
---


# Question
Title: Is render to texture available in blender?
I don't know is render to texture available in blender like in 3dsmax if it is available please tell me step by step method to do that thanks in advance.

# Answer
> 2 votes
Render to texture is also known as texture 'baking', which is the term used in blender.

The blender manual has some info on baking and you can find several tutorials on the subject

---
Tags: blender, 3dsmax, rendertexture
---


# Question
Title: Opengles 2.0 multi Textures fade out one by one
I have multi textures, A was drawed on top of B, B was on top of C ...., ( **like Picture 1**) .I want to fade out A first, then B will appear and fade out either... But when A fade out, background color appeared on top of B, ( **like Picture 1** )? Why? What should I do? I have enable Blend like this

`glClearColor(0, 104.0/255.0, 55.0/255.0, 1.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnable(GL_DEPTH_TEST);
glEnable(GL_BLEND);
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);`

and Fragment shader

```
"void main(void) { // 2\n"
"gl_FragColor = texture2D(Texture, TexCoordOut);\n"
"gl_FragColor  *= alpha;\n"

```

" }\n"

**Picture 1：** background color is green, A and B are both rectangle, A is on top of B

**Picure 2** When I fade out A, the result like this:

I aso try to use `glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);` but it doesn't work either.

\**Update 1 shader \**

const GLchar \*vertex\_shader\_source\_ = { attribute vec4 Position;

```
uniform mat4 Projection;
uniform mat4 Modelview;

varying vec4 DestinationColor;

attribute vec2 TexCoordIn; // New
varying vec2 TexCoordOut; // New

void main(void) {
    gl_Position = Projection * Modelview *Position;
    TexCoordOut = TexCoordIn;// New

"}

```

};

const GLchar \*fragment\_shader\_source\_ = { uniform highp float alpha; uniform sampler2D Texture;// New

```
varying highp vec2 TexCoordOut; // New

void main(void) { // 2
gl_FragColor = texture2D(Texture, TexCoordOut);
"gl_FragColor.a  = alpha;

```

} };

# Answer
Try with

```
glDisable(GL_DEPTH_TEST);

```

And render the images in back-to-front order.

Most likely the depth test is what's preventing the other images from rendering.
> 1 votes

---
Tags: textures, opengl-es2, cocos2d
---


# Question
Title: Copy a gameObject's collider at runtime (Unity)
I'm working on a small Unity 2D project in which I need to modify the collider of the player at runtime. I'm using Physics2D.Raycast to find the collider and then what I'd like to be able to do is then copy that exact collider over to the current gameObject and remove the current collider in the process. Basically when my Ray hits an object, I want my player to turn into that object.

I'm fairly new to Unity and have been digging through the API for some hints but haven't found anything yet. Any help would be appreciated.

So far all I have is as follows:

```
RaycastHit2D hit = Physics2D.Raycast(transform.position, lookDirection, Mathf.Infinity, 1 << 8);
        if (hit.collider != null)
        {

            //Change the collider somehow
            Collider2D myC = GetComponent<Collider2D>();
            myC = hit.collider; //Haha that doesn't work.

        }

```

# Answer
The answer to this really depends on exactly what you want to do. If you want the change to be permanent, you can destroy the current collider on your player and create a copy of the raycast target collider using reflection. Copying a component using reflection is covered in this answer on UnityAnswers http://answers.unity3d.com/questions/530178/how-to-get-a-component-from-an-object-and-add-it-t.html

If you only want the change to be temporary so that your player can change their form back, you could instead instantiate a copy of the raycast object with the position and rotation of your player and store it in a variable inside your player class. You could then disable the player's SpriteRenderer and Collider2D. This would make your player object invisible but would allow you to change your form back at any time by enabling the SpriteRenderer and Collider2D again.
> 1 votes

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


title: XNA collision detection between Lists

text:
# Question
Title: XNA collision detection between Lists
I have 2 lists, one is for meteors and second is for bullets. I have problem with collision detection between them, this is my code for meteor spawning:

```
      public void LoadMeteors()
    {

        int randY = random.Next(100, 400);
        if (spawn >= 1)
        {
            spawn = 0;
            if (meteors.Count() < 10)
                meteors.Add(new Meteor(Content.Load<Texture2D>("Backgrounds/meteori"), new Vector2(800, randY), new Rectangle(0,0,50,50)));

        }

        for (i = 0; i < meteors.Count; i++)
        {
           //here i check the collision between bullets and meteors.
            if (meteors[i].metRectang.Intersects(bullets[k].pulkaRectangle))
            {
                meteors[i].isVisible = false;
            }
            if (!meteors[i].isVisible)
            {
                meteors.RemoveAt(i);
                i--;
            }

        }
    }

```

and that is my bullet spawn:

```
    public void Start()
    {
        //interval timing

        for (k = 0; k < meteors.Count; k++)
        {

            if (!bullets[k].isVisible)
            {
                bullets.RemoveAt(k);
                i--;

            }
        }
    }
    public void SpawnBullet()
    {
        bullets.Add(new Bullet(Content.Load<Texture2D>("Backgrounds/pula"), new Vector2(rocket.rectangle.X+20, rocket.rectangle.Y + 20), new Rectangle(0, 0, 10, 5)));
        soundEffect.Play();
    }

```

and somwhere there is spawnBullet(); (there was only timer for interval nothing special) So, when i start game in few seconds i get this error:  ....and thanks for any help!

# Answer
You are removing elements while iterating over a collection

Even though you move an element backwards after the removal, the size of your list shrinks after you removed a meteor. The for loop is still set to iterate for the initial Count returned by the list. Therefore, it will exceed the boundaries of the list once a meteor has been removed.

I'd generally not recommend deleting elements from a collection in the first place, but you can instead iterate backwards. I.e.:

```
 for (i = meteors.Count; i >= 0; i--)
 {
     //here i check the collision between bullets and meteors.
     if (meteors[i].metRectang.Intersects(bullets[k].pulkaRectangle))
     {
         meteors[i].isVisible = false;
     }
     if (!meteors[i].isVisible)
     {
         meteors.RemoveAt(i);
     }
 }

```

This solves the issue of the value of count changing. The same goes to what you are doing in your Start method with the bullets.

However, I don't think the code does what you desire. You are checking collision between meteor i and bullet k, but the value of k never changes (in this loop). That means you are only checking one bullet against all the meteors.

And in addition to that, I doubt LoadMeteors is being called every frame. Since that method (from a logical standpoint) is only executed once, collision would only occur if a bullet and a meteor spawn on the same position.

EDIT: One other thing: as mentioned in the comment, in your other Start method, where you are iterating over the bullets, you run until meteors.Count rather than bullets.Count
> 1 votes

---
Tags: xna, collision-detection
---


# Question
Title: Text independent of screen resolution in Unity?
I have the following code that depends on the resolution of the user's display:

```
void OnGUI()
{
    GUI.Label(new Rect(432, 525, 9000, 9000), ("Hello!"));
}

```

And of course, the location of the text changes in devices with different resolutions. How can I make the text independent of screen resolution in Unity?

# Answer
You can use a canvas scaler and put UI text on it.

http://docs.unity3d.com/Manual/script-CanvasScaler.html

http://docs.unity3d.com/ScriptReference/UI.Text.html

GUI.Label on the game screen is only for quick debug hacks as far as I know.
> 2 votes

# Answer
I have a work around for this problem. Idea is to assign position in percentage instead of hard coded coordinates.

1- First find out your base resolution, on which further work will base on. Print `Screen.width` and `Screen.height`. In my case it is `428 x 321`. 2- Find out the percentage of current position with resolution. If I consider `GUI.Label(new Rect(50, 50, 300, 300), ("Hello!"));`, then it'd be `50.0f/428.0f` width percentage and `50.0f/321.0f` height percentage. 3- Now assign position w.r.t. these percentages. Like, `GUI.Label(new Rect((50.0f/428.0f) * Screen.width, (50.0f/321.0f) * Screen.height, 300, 300), ("Hello!"));`
> 0 votes

# Answer
Instead of using a gui label, you could simply add a text object to your project hierarchy (Create-\>UI-\>Text). This will automatically add a canvas object as well. Changing the UI scale mode on your canvas scaler to *"Scale with Screen Size"* will make the UI scale based on the screen resolution. You would then set the anchors/pivot of your text object depending on exactly how you want it to behave.

I recommend watching this series of videos by 3DBuzz on youtube. It goes in depth about how to set up UIs in Unity.

https://www.youtube.com/playlist?list=PLt\_Y3Hw1v3QTEbh8fQV1DUOUIh9nF0k6c
> 0 votes

---
Tags: c#, unity, resolution, text
---


title: Test if Jump can reach target

text:
# Question
Title: Test if Jump can reach target
I have an object that can jump.

When it jumps, its Y velocity becomes -600 (pixels/second).

For up to .2 seconds, it can ignore gravity.

After .2 seconds, it begins to accelerate downward at 2100 (pixels/second).

Independently from its Y velocity, the object can move on the X axis up to 220 (pixels/second) or -220 (pixels/second).

How do I calculate whether or not, with a given starting x/y coordinates it can jump to a target x/y coordinate?

Also, how do I calculate the necessary X velocity to reach its target in the proper amount of time so that it doesn't overshoot or undershoot?

# Answer
> 6 votes
You can find both at the same time:

* Pre-calculate a jump curve at maximum X velocity (blue curve)
* intersect the approximated curve on the downward side where the target platform height is the same (red dotted line)
* if the platform is further than this you can't make the jump
* scale down the curve on the X axis to match the X of the target (cyan arrow)
* that scaling applied to max X velocity gives you the needed X velocity to reach the platform in a nice arc.

If you want different possible jump heights you can calculate a few different curves and pick the best one.

You may want to add another step to check for collisions, eliminating from the list of possible trajectories.

The jump curves don't need to be calculated every time, you can generate them once when the game starts.

This applies to 3D just as easily.

Can be extended to handle double-jumps and other variations.

If X speed varies during the jump it'll require a bit of adjustment but given enough of a margin it might not matter.

# Answer
> 1 votes
You can calculate limits of your movement with these two formulas:

Maximum Altitude (Ymax) = (Initial Y velocity)^2 / 2\*(gravity)

Maximum Reach (Xmax) = (Initial X velocity) * 2 * (Initial Y velocity) / (gravity)

---
Tags: physics, mathematics
---


# Question
Title: Randomly changing game scenes in unity c#
Is there any way that I can randomly change scenes in Unity C# using arrays?

# Answer
No need for an array, you just need to know total amount of scenes you have:

```
//using UnityEngine.SceneManagement;

void LoadRandomScene(int totalSceneAmount)
{
    int random = Random.Range(0, totalSceneAmount-1);
    SceneManager.LoadScene(random, LoadSceneMode.Single);
}

```

***Note:*** *You need to add all of your scenes to build in Build Settings window.*
> 3 votes

# Answer
If you really want only that then you can do it by this way.

```
string[] scenes = new string[3]{"Gameplay1","Gameplay2","Gameplay3"};

void LoadRandomScene()
{
    string randomSceneName = scenes[Random.Range(0,scenes.Lenght)];
    Application.LoadLevel(randomSceneName);
}

```
> 2 votes

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


# Question
Title: 3ds Max Skeleton Import into Unreal Engine Fail
I tried following the "Introduction to UE4 Animation and Rigging Tools" tutorial with maya but I dislike maya and don't under stand it so I tried importing the skeleton from the "3rd Person Game with Blueprints" tutorial into 3ds max and hoping I could just edit the mesh because I want about the same skeleton.

So I imported it and just made a basic mesh to test, Then removed the old mesh

Now I did it like this hoping I could use the existing animations for the original but when I try to play an animation with it in unreal engine 4.7.3 it says it does have any with the same skeleton, then when I tested it trying to ragdoll it stays rigid and just falls over.

Please help, am I importing it wrong am I missing a step? Why doesn't it work?

# Answer
I managed to do this right just a couple of days ago, I can't guarantee that this is the right or best way to do it (most likely not), but it worked for me:

**Basic steps:**

**a)** When you open the exported mesh in 3DS, 3DS adds another bone as the parent of the two existing "bones", one being the skeleton, the other being the mesh.

*To overcome this*, you have to unparent (drag each of the two children out of that bone) the mesh and the skeleton, and delete that one. Export and import to UE4 to verify that this works as expected before touching anything else (materials will be missing, but that's not a problem at this stage).

**b)** The second issue I had, was changing mesh. Since you are anyway beginning with a primitive, I just selected the existing "editable mesh", selected the `faces` sub-selection, deleted all faces except a square composed of two triangles at the top of the head, and then went on with extruding and working from there.

**Notes:** **1)** The skin modifier is essential to remain over there if you want to play it safe. This is what binds the model to the bone, and generally does a decent job on it's own.

**2)** If you add any modifier, it will be applied after the skin modifier, I dared not try and see what would happen, I suggest you avoid it on the first try so as to be safe and minimize the suspects of any unexpected results.

**3)** Because of 2, you had better work with the tools in the edit panel, normally on the right side of the screen. It's not as intuitive, but you'll get used to it soon, you have all the basic stuff for a basic rig.

**Problems encountered when following this method:**

**a)** *(Solved)* The model was flickering. This has happened to too many people and thus I guess it's not exactly the model's fault. The typical solution is deleting the Physics Asset

**b)** IK bones stretch a vertice of each limb all the way to the ground, I'm still trying to beat this.

I'll also try to make a video tutorial once the last problem is solved, and I'll update with anything further I figure out. Hope this helps.
> 1 votes

---
Tags: models, windows, skeletal-animation, importing, unreal
---


# Question
Title: Generate objects on playground on random location
How can I generate an object on my play ground? Note that there are some locations where the new generated item can't be placed.

(Click on image to see the real size)

I was following a tutorial on the site from unity but now I'll add some features by my own. In the tutorial I've done anything whit the 'Navigation'-tab.

(Click on image to see the real size)

For what I need is the blue area on the screenshot above, are good locations to generate a new object on a random place.

However, there are some locations *(see red marks on image)* where the objects can't be generated because that are the places where the players enemy's spawns.

Can anyone help me to generate the objects?
Thanks in advance.

# Answer
> 1 votes
You can do this by simple trick.

Place empty `GameObjects` where you want to spawn your object. Then take an public Array of `Transform`. Then spawn at any random `transform.position` in scripts. :)

For clear visuals, place cubes on desired places then delete collider and hide meshes, so it will work as transform only

---
Tags: unity, 3d, random
---


# Question
Title: Allegro: slow drawing lots of images in 2d sandbox
I want to know if there is any better way to do this. But i want to make a game where its 2d and made of blocks. But a test that draws blocks to the screen and its going so slow that its not even taking keyboard events anymore.

Is there a way to optimize drawing? Or save predawn parts of the map and pan it across the screen when the player moves?

the code is probably unnecessary. But basically im drawing it and p

```
for (int y = 0; y != Vertical_Block_count; y++)
           {
    for (int x = 0; x != Horizontal_Block_count; x++)
al_draw_bitmap_region(Bitmap, Sprite_Selected * BlockSize, BlockSize * sprites_on_sprite_sheet, BlockSize, BlockSize, x * 16 - 16, y * 16 -16, 0);
            }
    al_flip_display();

```

# Answer
> 2 votes
You are **creating and loading** bitmaps before the Display is created with `al_create_display`... This is causing the bitmaps to be on system RAM and not Video RAM.

When they are stored in main RAM, you don't get hardware acceleration because everything has to be drawn with the CPU then copied to the GPU already drawn...

Try creating a screen as soon as the program start and then load your bitmaps. Another option is to load them first, if that is what you want, but you then copy them to the Video RAM as soon as you have the display available. Don't forget to delete the System RAM copies after doing that!

# Answer
> 0 votes
In general, a big help when drawing tiles is `al_hold_bitmap_drawing`. Assuming your tiles are all part of a single image (a 'spritesheet' or 'tile atlas'), you should use something like:

```
al_hold_bitmap_drawing(true);
for (int y = 0; y != Vertical_Block_count; y++)
    for (int x = 0; x != Horizontal_Block_count; x++)
        al_draw_bitmap_region(Bitmap, Sprite_Selected * BlockSize, BlockSize * sprites_on_sprite_sheet, BlockSize, BlockSize, x * 16 - 16, y * 16 -16, 0);
al_hold_bitmap_drawing(false);
al_flip_display();

```

Note that while bitmap drawing is held, you want to draw only from that one bitmap -- don't jump around to different bitmaps.

> its going so slow that its not even taking keyboard events anymore.

Ideally, you want input to be processed no matter how slow your game gets. To do this, ensure you drain the event queue before drawing each frame. Take a look at the Allegro5 timer tutorial. Notice that the condition for rendering the next frame is `redraw && al_is_event_queue_empty(event_queue)`. This ensures that all input events get a chance to be heard before the next frame.

---
Tags: c++, allegro
---


# Question
Title: Libgdx - GLSL shader which uses mod doesn't seem to work properly on android
Through trial and error I've managed to come up with a scanline-ish shader I'm satisfied with. On my desktop testbed it looks like this:

Basically, every 2nd(vertical) pixel is darkened.

However, when I add the same shader to my android sprite batch the darkened lines no longer show up. I've assumed it's due to use of `mod` and float comparison since GLES is lower precision than desktop GL and it probably never evaluates `yPos == 0.5` to true. So to combat that I've created an `EPSILON` value to give a bit of leeway for float comparison but that didn't help either. However I'm certain that I've set up the shader program correctly since simple color manipulation shaders seem to work properly, only when `mod` gotten introduced into the mix things turned sour.

Here's the shader code:

scanline.vert

```
attribute vec4 a_position;
attribute vec4 a_color;
attribute vec2 a_texCoord0;

uniform mat4 u_projTrans;

varying vec4 vColor;
varying vec2 vTexCoord;

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

```

scanline.frag

```
#ifdef GL_ES
    precision mediump float;
#endif

varying vec4 vColor;
varying vec2 vTexCoord;

uniform sampler2D u_texture;
uniform mat4 u_projTrans;

const float SCANLINE_INTENSITY = 0.7; // lower is stronger, probably should call this softness
const float SCANLINE_DENSITY = 2.0; // every 2nd pixel

const float EPSILON = 0.01;

void main() {

    vec4 texColor = texture2D(u_texture, vTexCoord);

    float yPos = mod(gl_FragCoord.y, SCANLINE_DENSITY);

    vec4 retColor = vColor;

    //if(yPos == 0.5) {
    if(abs(yPos - 0.5) < EPSILON) {
        retColor *= vec4(vec3(SCANLINE_INTENSITY), vColor.a);
    }

    gl_FragColor = texColor * retColor;
}

```

What am I doing wrong?

# Answer
> 1 votes
Use the almighty `<`! Epsilon comparsion is not needed here.

```
if (mod(gl_FragCoord.y, density) < 1)
    /* Draw scanline */

```

---

By the way, this

```
retColor *= vec4(vec3(SCANLINE_INTENSITY), vColor.a);

```

is incorrect because your alpha becomes squared. Use

```
retColor.rgb *= SCANLINE_INTENSITY;

```

---
Tags: android, libgdx, shaders, opengl-es, fragment-shader
---


# Question
Title: How to rotate a triangle towards the point in Qt?
I have an issue with items rotating.

I have a point and a triangle which needs to be rotated with its apex point towards the taregt point. The right side of the picture represents how it is should to be, and the left side represents how it works. Red dashed arrows represent motion, the triangle moves along its arrow. Green dashed arrow represent rotation, the triangle should rotates along its arrow.

How do I do calculations:

**calculating desired velocity aka direction**

`velocity(direction) = Vec2DNormalize(targetPoint - locationPoint) * maxVelocity;`

**calculating angles for target point and location point**

`float angleLoc = atan2(rect->location.y, rect->location.x);`

`float angleTarg = atan2(rect->target.y, rect->target.x);`

**rotating after subtracting angleLoc - angleTarg**

`rotate((angleLoc - angleTarg) * 100);`

Here it is the source code.

`ster.cpp`

```
#include "steer.h"
#include <QPointF>
#include <QBrush>
#include <QPen>
#include <vector2d.h>
#include <QGraphicsPolygonItem>
#include <QPolygonF>
#include <QPointF>
#include <QGraphicsItem>
#include <QDebug>
#include <cmath>
#include <vector>
#include <QtWidgets>

void Steer::seek()
{
    //calculating desired velocity aka direction
    rect->desired = Vec2DNormalize(rect->target - rect->location) * rect->maxspeed;

    //calculating steering force
    rect->steer = rect->desired - rect->velocity;

    //if the steer force is bgger than maxforce
    rect->steer.Truncate(rect->maxforce);

    //adding to acceleration steering force
    rect->acceleration += rect->steer;

    //add to velocity acceleration which has steering force only
    rect->velocity += rect->acceleration;

    //if the velocity is bgger than maxspeed
    rect->velocity.Truncate(rect->maxspeed);

    //changing our position
    rect->location += rect->velocity;

    //reset the acceleration
    rect->acceleration *= 0;

    viewport()->repaint();
}

Steer::Steer(QGraphicsView *parent)
    : QGraphicsView(parent)
{
    scene = new QGraphicsScene;
    rect = new Vehicle;

    scene->setSceneRect(0, 0, 500, 500);

    polygon <<  QPointF(5.0, 0.0) << QPointF(-5.0, 0.0) <<  QPointF(0.0, 20.0);
    rect->triangle = scene->addPolygon(polygon);

    this->setScene(scene);

    timer = new QTimer(this);
    QObject::connect(timer, SIGNAL(timeout()), this, SLOT(seek()));
    timer->start();

    this->show();
}

void Steer::paintEvent(QPaintEvent *)
{
    QPainter painter(viewport());

    painter.setBrush(QBrush(Qt::green));
    painter.setPen(QPen(Qt::black));

    painter.save();

    //moving to position
    painter.translate(rect->location.x, rect->location.y);

    //calculating angles for target point and location point
    float angleLoc = atan2(rect->location.y, rect->location.x);
    float angleTarg = atan2(rect->target.y, rect->target.x);

    //rotating after substracting angleLoc - angleTarg
    painter.rotate((angleLoc - angleTarg) * 100);

    painter.drawPolygon(polygon);

    painter.restore();

    for(int i = 0; i < vec.size(); i++)
        painter.drawEllipse(vec[i].x() - 1, vec[i].y() - 1, 1 * 2.0, 1 * 2.0);
}

void Steer::mousePressEvent(QMouseEvent * click)
{
    point = mapToScene(click->pos());

    vec.push_back(point);

    rect->target.x = point.x();
    rect->target.y = point.y();
}

```

Here the whole project.

# Answer
You need to calculate a maximum angle of rotation allowed per game loop. Rather than calculating the angle the triangle needs to rotate *to* figure out only if it needs to rotate left or right, then rotate (for example) 1 degree.

The only reason to know the exact angle to point at is to calculate if the rotation required is less than the 1-degree-per-loop change (and then rotate exactly).

The "1 degree" portion can be adjusted to be more or less in order to achieve the desired change.

This is essentially doing the same thing in rotational space as you're already doing with movement. Rather than jumping to the destination, increment a little at a time until we're there.
> 1 votes

---
Tags: c++, rotation, vector, qt
---


# Question
Title: What is the most efficient method of creating a detailed 3d tileset in a 3d game that uses a grid?
Well, the most efficient method might be with how minecraft does the terrain by using a single block for a single grid, but one thing I am concerned about is that the method minecraft uses is poorly mixed near the edges where 2 different blocks meet. I would like the blocks to mix together nicely, similiar to how modern 2d games does their tiles.

I had some thoughts.

Perhaps one could adjust the alpha of the texture so that it blends well near the end? So at the edge, between 2 different blocks type, both of the blocks would exit where 1 of the block would be alpha-blended together with the other block based on the priority value of the block.

That's the idea I have currently but I have some doubts about it.

If there's any inquiry about my question feel free to ask.

Edit: Well, even though I use minecraft as an example, it's not a sandbox game, it's just I would like to use a grid style of terrain that some 2D game uses even when it's not sandbox (e.g. Mark of the Ninja) but in a 3D environment instead. An efficient method of doing that is concerned.

# Answer
> 1 votes
First of all, when you say "creating" a tileset, I presume you mean that you want all these tile transitions pre-baked into textures. I'd recommend against that as the number of transitions you need increases quadratically as your number of tile types increases, and isn't worth any extra efficiency usually.

What you want to look into is Texture Splatting and do this all runtime.

I can't think of anything in particular that would give you extra efficiency when it comes to cell types, except the usual voxel optimizations like storing voxels in an octree and optimizing that, occlusion culling, frustum culling, LOD, optimal mesh generation etc.

On that last one, as the saying goes, premature optimization is the root of all evil, but if you end up having some extra FPS, you could try rendering your cells to look more "detailed" with algorithms like marching cubes / marching diamonds (think the 3D Worms games' destructible terrain).

Edit: Here's a good read on voxel terrain meshing.

---
Tags: unity, 3d
---


# Question
Title: Browser-Based Game Design: Keeping track of NPC stats (Attack, Defense, Health, etc)
Hope this is a proper question to ask here. If not, I'd appreciate somebody pointing me to other game developer communities. Since I am creating my game by myself it'd be nice to communicate with other developers.

Is it best to keep NPC stats in the database, or calculate them using code? I store the NPC's level in my database table. So from there I could use code to calculate it's Attack & Defense, and any secondary stats.

I can't think of any "Cons" to using just code. But a "Pro" would be that I can easily adjust the NPC's stats using different algorithms.

# Answer
> 1 votes
I would say both code database. Perhaps also a software component, in the server-side, to leverage access to databases and have a kind of poor cache (the actual intention is not to do cache, but maintain objects as being alive).

With *code* you will define basic algorithms and, perhaps, rebalance the enemies in the future. Perhaps the code could involve a script loaded from database which could be maintained and modified as required (*note for purists: using code evaluation under this requirements would not be unsafe since only the application administrators could configure them. Even enterprise software like OpenERP can have code chunks for certain record types and nobody complains about that*).

With *database* you could store the *deltas* for each stat (e.g. in a Pokemon-like game, a delta would be a stat modified temporarily by an attack or an item). In a Pokemon-like game, also the permanent stats are saved into database (since there are objects that alter the permanent stats).

So your needs will depend on the type of stats for your NPCs:

* Base stats, able to be permanently and temporarily modifiable: Use code for when the NPC raises a new level (if it is the case) or for initial calculations. Use database for actual permanent values, and choose either between database or just memory for temporary modifications.
* Base stats, able to be temporarily modifiable: Use code for initial calculations. Choose either between database or just memory for temporary modifications.
* Base stats, not modifiable anyhow: Use just code for the initial calculations.

Architectural considerations: Your HTTP server should be able to maintain live objects globally between different HTTP sessions. Cases like Tornado and Twisted (for Python) or almost any java web framework can help you. For PHP you will need a database (since you cannot globally have in-memory live objects).

Notes: Maintaining live objects **It is also not the case with architecture based on worker processes** (synchronous-based servers like Python/gunicorn fall in this category) since each worker process would maintain a copy of the live objects and that would be troublesome for similar reasons than using PHP.

# Answer
> 0 votes
I would say databases would be preferable.

Let's say you build an 'arena' page of your site. The arena page randomly picks a monster for you to fight that's within 5% of the challenger's level. This would be more-easily achieved with a quick SQL statement.

Or, let's say you wanted a bestiary page so your players could search for a monster that drops X or Y. This would be difficult to achieve in code-based NPCs.

That said, if you're thinking about creating a database *only* for storing NPCs and not character credentials etc. you have to decide if the long-term maintenance, performance overhead etc. of it is worth the implementation.

# Answer
> 0 votes
If you are 100% sure that the NPC's level will always be enough to specify their stats, then level in db/calculations on client is a good option. Less hitting the db means your game scales better with the number of players.

However, it locks your design into this box. There are ways to patch on differences not related to level at a later date, but this could cause problems as the rest of your game might not be coded or designed with this in mind.

So this decision depends on how likely it is that the current design will be the final design.

---
Tags: browser-based-games, php, text-based
---


# Question
Title: How to set material to gameobject dynamically using c# script in unity?
I want to set material to a gameobject in unity using c# script.

I am using this code to set the material of mesh renderer attached to the gameobject -

```
MeshRenderer mesh = gameObject.GetComponent<MeshRenderer>();
        mesh.materials[0] = materialsCopy[0];

```

here materialsCopy is an array of type Materials which I've made public and I am attaching the Materials by drag & drop to the materialsCopy but when I run the game I get a white colored mesh instead of the set material of the 0 index materialsCopy. The 0 indexed materialsCopy has albedo set to an image. I want this image to get attached to the gameobject. How should I proceed ?

In addition to this I am also getting a warning - Tiled GPU perf. warning: RenderTexture color surface (0x0) was not cleared/discarded, doing

# Answer
> 1 votes
Try

```
Renderer rend = GetComponent<Renderer> ();
rend.material = materialsCopy[0];

```

---
Tags: c#, unity, 3d-meshes
---


title: Passing array to uniform in glsl error

text:
# Question
Title: Passing array to uniform in glsl error
Here is my attemps to pass array to uniform array:

```
struct Vector{ float x,y,z; }

float threshold[2] = { 0.5, 0.25 };
Vector *kernel = new Vector[_kernel_size]; // _kernel_size==16
// fill kernel

glUniform1fv(glGetUniformLocation(_program, "t"), 2, threshold);
glUniform3fv(glGetUniformLocation(_program, "kernel"), _kernel_size, (const GLfloat*)kernel); // because Vector contains only 3 float fields this kind of casting should be ok

```

shader:

```
uniform float t[2];
uniform vec3 kernel[16];

```

And the results are weird. Only first float or first vector are filled with proper values. For example:

```
t = {0.5, 7.1830559e-042}

```

Even when I try change only one value (name = "t\[1\]") it doesn't work. I checked this on AMD CodeXL.

My graphics card is Radeon HD 5770 and I have the newest drivers. I'm using OpenGL 3.3 and GLSL 330.

What am I doing wrong?

# Answer
Try using glUniform2fv on threshold.
> 1 votes

# Answer
I checked another simple project where passing array to uniform works and checked what CodeXL is showing. And again only first value was ok.

So I believe that this is some kind of bug/limited functionality. Maybe name of uniform which CodeXL shows (`kernel[0]`) is a hint that only first value is presented.
> 1 votes

# Answer
You have to send the data to the first address of the array, e.g. t\[0\]

```
glUniform1fv(glGetUniformLocation(_program, "t[0]"), 2, threshold);

```
> 1 votes

# Answer
Try switching every arrays to vec4:

```
uniform vec4 t[2];
uniform vec4 kernel[16];

```

And use `t[i].x` and `kernel[i].xyz` in the shader.

Upload them as vec4 on the CPU side as well (don't forget padding with `w`)

```
struct Vector{ float x,y,z,w; }

float threshold[2][4] = { {0.5f}, {0.25f} };
Vector *kernel = new Vector[_kernel_size]; // _kernel_size==16

// fill kernel

glUniform4fv(glGetUniformLocation(_program, "t"), 2, threshold);
glUniform4fv(glGetUniformLocation(_program, "kernel"), _kernel_size, (const GLfloat*)kernel);

```

It's possible the GPU and drivers only properly supports arrays of vec4 due to a hardware limitation.

Alternatively, you can use `t.x` and `t.y` as the two thresholds in the shader:

```
uniform vec4 t;

```

CPU side:

```
float threshold[4] = { 0.5f, 0.25f };
glUniform4fv(glGetUniformLocation(_program, "t"), 1, threshold);

```

If that doesn't work try uploading each uniform one by one.

```
glUniform4fv(glGetUniformLocation(_program, "kernel[0]"), 1, kernel+0);
glUniform4fv(glGetUniformLocation(_program, "kernel[1]"), 1, kernel+1);
...

```

(for-loop left out for brevity)

Mobile GPUs (ie: cell phones) tend to be scalar-based (not vector) and can access floats, vec2s and vec4s just fine. Avoid vec3 uniforms but using them as temporaries in the shader code is fine and will be faster. Use lower precisions / fixed points when possible on Mobile.

Desktop GPUs vary. Some are vector4-only internally and the driver has to put floats into vec4s. Some can access scalar uniforms at any address with a slight performance penalty.

If you have multiple arrays of floats it's a good idea to interleave them if you can

For example:

```
uniform vec4 table[8];

table[i].x // hue shift table
table[i].y // blur factor table
table[i].z // de-saturation factor table
// etc

```

If you can, invest a few bucks in getting test computers with GPUs from other manufacturers to make sure your code and shaders work on most, test regularly.

They all have quirks, some more than others.
> 1 votes

---
Tags: opengl, glsl
---


# Question
Title: Where can I find a service hosting tournaments with prize funds?
I have a game, and users are self-organizing to create tournament sites. They want to be able to create a tournament, have competitors put down a $1 each, and the winner takes all.

Are there any companies that provide a service like this that I could integrate into my game directly? Or do people usually build this themselves into their games? I don't really want to deal with maintaining escrow accounts and all that myself.

# Answer
Disclaimer: I am not a lawyer and I urge you to go get advice from one.

If people can get money out of it you're dealing with various **gambling laws** here and this is on-line so you're dealing with multiple jurisdictions as well.

This is a legal labyrinth I would stay clear of unless you have the financial means to get a bunch of lawyers specialized in this stuff.

**This is one reason why things like in-game trading cards are auctioned for service credits and the money never goes back into the player's hands**.

In many jurisdictions players receiving physical prizes can also count as gambling when a purchase is necessary.

There are also other risks that arise when going into gambling services, not just legal ones.
> 1 votes

---
Tags: multiplayer, community-management, tournament
---


title: Projection type used in videogames

text:
# Question
Title: Projection type used in videogames
I'm trying to create a web application, to display 3D objects on canvas. To represent the 3D object I'm using an array of Points (from application's point of view, a Point - is just an object containing x, y and z coordinate values). Then I'm connecting the points with lines.

So. My task is to represent 3D points on 2D coordinate system. As I understand, what I need is to implement the projection of these points (to transform point from 3D representation into 2D). I spent few hours reading about projection types and I can't really understand which type is actually suits my needs.

I created an array of points to represent a cube. Then I implemented a central projection to display my cube on cavnas. As a result, it lost it's proportions (what I got is a paralelipiped).

I would like that my cube would look like a cube after projection. I guess, that I have to use a parallel projection, but there are a lot of subtypes of it.

So the question. Which projection I need to choose and maybe you can give me a peace of advice of what should I read to get a base mathematical background about this topic?

# Answer
> 2 votes
You can project points to XY, YZ and XZ planes so simply by just changing the other value of Vector3 to "zero".

For example, assume you have 3 Vector3's as (1,2,3) (3,3,5) (9,8,7), and you want to project them to XY plane. Then you can simply make all Z values "0" and remaining vectors are your projected vectors.

An overview example of what i mean:

*Original point vectors:* (1,2,3), (3,3,5), (9,8,7)
*Projected to **XY** plane:* (1,2,**0**), (3,3,**0**), (9,8,**0**)
*Projected to **YZ** plane:* (**0**,2,3), (**0**,3,5), (**0**,8,7)
*Projected to **XZ** plane:* (1,**0**,3), (3,**0**,5), (9,**0**,7)

---
Tags: projection
---


# Question
Title: How are pocket dimensions created in multiplayer games programming-wise?
How do multiplayer games deal with multiple instances/dungeons/regions? I'm familiar with server clustering which is what larger games use such as Eve and World of Warcraft.

How do games such as Minecraft deal with the pocket dimensions such as the nether and ender with multiplayer compatibility?

Lastly, are there any existing game engines that support the single dedicated server with multiple pocket dimensions setup?

# Answer
I can answer on Minecraft, specifically, as I've done some modding, so I'm aware of the generalities.

Minecraft has a class object called `World`. This handles everything about the world of Minecraft: the blocks, the entities, the weather, etc. Anything that happens happens inside the world object. `World` contains a dynamic list of loaded chunks, chunks contain a (list of (list of(list of integers))) representing blocks (and yes, it really is that bad: blocks are actually stored as three! separate 3D arrays segmented into 16 blocks of height: one array holds the 8 LSB, another holds the 4 MSB, and another holds the 4 bit metadata).

Different dimensions have their *own instances* of a World object, which is why its often referred to by modders as a "poor name" for the class, it should be `Dimension` as more traditionally the World object is a singleton responsible for handling the primary state machine of the game.

For Minecraft, that singleton happens to be the `Minecraft` class (client side) or `MinecraftServer` (server side) \[footnote: I have a feeling I am mis-remembering the main class for the server\]. The current "integrated server, making SSP functionally SMP with 1 player" is just a little hocus pocus in having separated all of the singleton logic out of the client classes and then packaging the server classes *with* the client and calling it the "integrated server" while silently hiding the fact that the game connects to itself on 127.0.0.1 (note: I've not looked into the actual workings of this, so there's some guesswork here). All packet handling (typical for a remote connection) works as expected in this way.

Note that there is also a `WorldClient` class, which stores the state of the world for the client to reference when rendering and performing interpolation on movement, it acts just like the standard copy the server has, but changes to this `World` are not sent to the server and the server sending data back will override. New modders often make this mistake and end up with holes in the world that act like the blocks are still there (can't walk through it, make the player and other entities rubber band, etc).

So as far as the game is concerned, separate dimensions can't affect one another except through very limited ways (teleporting) so it can keep the unviewed chunks unloaded when no one is there. If someone does go there, the chunks are loaded into memory and processed just like any other chunk, but part of a separate `World` (the server maintains a list--likely a Map--of dimensions that can be accessed by integer ID). The teleportation itself is a bit of a hack, as it literally clones whatever entity went to the new dimension, spawning the new copy at the destination, and garbage collecting the old one.
> 2 votes

---
Tags: software-engineering, game-mechanics
---


# Question
Title: How to create a minecraft style world that is based of a heightmap
For my game I am trying to create a Minecraft style world that is based off a heightmap that I made In Photoshop. I am trying to make the map which is 7km squared where each cube is 1m cubed but I haven't found a way to do it. The heightmap converts to a terrain file(in unity), but my problem is that I can't create the Minecraft look.

what I have done so far looks like this

what i want looks like this

# Answer
> 1 votes
While being down voted I will tell you a professional approach to a Minecraft style terrain using heightmaps. So you should of learned by now that your heightmap should be grayscale. black = lowest point, white = highest, and the gradient in between controls height in between. there are 255 possible color combos if you include black and white. from there, each pixel is = to 1m in game.

7km\*7km = 7000m\*7000m = an image that is 7000\*7000 pixels. Programming the flat surfaces in the game is a different matter. You need to program the terrain generator (or a class that talks to the terrain generator class) to take each pixel by location, then create a flat cube like surface. for instance every 10 units in game are = to 1m. this means that the generator will generate 10x10 units in game at height A, then the next one over at B.

---
Tags: unity, terrain, voxels, minecraft-modding, heightmap
---


# Question
Title: Cannot detect input in void OnCollisionEnter()
Code:

```
void OnCollisionEnter()
{
    if (Input.GetMouseButton(0))
       {
            // do something
       }
}

```

Of course, this code does not work. What I intend to do: "After collision, if the user is pressing down, do something". How can we write this another way? I can't figure it out.

# Answer
> 2 votes
Do something like this:

```
var timeSinceCollision = 999;

void Update() {
    timeSinceCollision += Time.deltaTime;
    if(timeSinceCollision < 0.5 && Input.GetMouseButtonDown(0)) {
        // do something
    }
}

void OnCollisionEnter() {
    timeSinceCollision = 0;
}

```

The 0.5 makes it so that there's a bit of allowable tolerance for when the player collides with whatever and them being able to perform the action (no one is going to be able to press the button the same frame the collision occurs on: ideally that would be 1/60th of a second!).

Edit: Also use `GetMouseButtonDown`, which will only be true on the frame that the button is first pressed and false thereafter. It prevents the player from holding down the button, then bumping into something, and getting the effect despite doing things out of order.

# Answer
> 0 votes
I think you scenario is to stand over a special block then do something or open up the door from side panel. In block type case `OnCollision` is OK but in door type case I'd recommend `OnTrigger`, well according to your code, use `OnCollisionStay` instead of `OnCollisionEnter`

```
void OnCollisionStay(Collision col)
{
    if (Input.GetMouseButton(0))
       {
            // do something
       }
}

```

---
Tags: c#, collision-detection, unity
---


title: Binding class method to Lua

text:
# Question
Title: Binding class method to Lua
If I have class

```
class Game {
    public:
        Game() { level = new Level(); }

    private:
        Level *level;
        lua_State *L;
}

```

Where the level class has member functions such as "addObject()", how can I use that instance of the level class to bind addObject into the lua state?

The lua file may contain:

```
addObject("Player", 100, 100)
addObject("Enemy", 200, 100)

```

So to clarify, the 'Game' class contains a class 'Level' to manage things like the objects + there movement etc... Then I want to call a lua script to load the current level, which will bind the instance of 'Level' in the 'Game' class so it can call addObject() from the lua code.

I believe this is possible via LuaBind however I'm not keen on the boost dependencies, I did come across https://stackoverflow.com/questions/32416388/how-to-register-member-function-to-lua-without-lua-bind-in-c however method 1 seems to reply on 'Game' being a singleton and on method 2 I failed to bind a member method, only a normal function. If all else fails I will revert to LuaBind with it's awful dependencies.

# Answer
Okay, you can do this using user data, simple as pushing a pointer of Level onto the stack using `lua_pushlightuserdata`. Then getting the user data off the stack when the `get_object` function is called:

```
Level *lvl = (Level*)lua_touserdata(L, 1);
lvl->addObject(...);

```

http://www.gamedev.net/page/resources/\_/technical/game-programming/the-lua-tutorial-r2999
> 1 votes

# Answer
Use Luna for C++ object binding to Lua. It is essentially a single header file containing helper functions to bind a C++ class to Lua. The previous version also contains instructions as to how to get it working. The usage is very simple, but you have to write boilerplate code, a wrapper class for each of your classes you wish to bind.
> 1 votes

---
Tags: c++, lua
---


# Question
Title: Unity 4.6: sprite image automatically splits to single sprites when clicking
I'm viewing Unity tutorial. As in this tutorial, I see when author clicks to sprite image, they will automatically divide to each frame as below:

But in my Unity, I just can view this:

So. My question is: How can my sprite image automatically divides to each sprite.

Thanks :)

# Answer
You need to change the import settings (click on the spritesheet in the project view and look at the inspector) so they import as multiple sprites. Then from the sprite editor you choose options to automatically split the spritesheet by putting in the dimensions of each sprite in the sheet this will cause the sprites to be split like you see in the tutorial

Unfortunately I don't know if you can alter the default import settings for sprites so that all sheets are split when put into the project directory by predefined parameters although I personally have never seen this happen.

Edit: I found this unity answers question that relates to automatically importing sprites, one of the answers mentions a plugin which will automatically split spritesheets: http://answers.unity3d.com/questions/793730/how-to-set-default-sprite-import-settings.html
> 1 votes

---
Tags: unity
---