# Question
Title: How can I manipulate a single pixel with LWJGL?
This is a very simple question. Is there a way to manipulate a single pixel?

Here's an example of what I want in pseudo-code:

```
while(gameIsOn) {
    renderAllObjects();
    setPixel(x,y,r,g,b);

}

```

Is this possible in any way? (Notice it's is not a solution to render a 1 by 1 quad, since it's too resource expensive.)

# Answer
There are a few ways to manipulate individual pixels in 3D graphics APIs.

The simplest is to render a 1x1 primitive. Contrary to what you are assuming, this is *not* that inefficient. Rendering primitives (triangles) is what the 3D graphics API and hardware are *designed to do*. If you're already rendering a bunch of geometry anyway, a few hundred extra triangles isn't going to cause a significant impact. You can use simplified vertex formats and shaders to further ameliorate what little impact there is.

If you have a relatively few number of pixels to manipulate and each pixel could be manipulated more-or-less independently, rendering small quads or triangles is a reasonable approach.

If you have many pixels to manipulate, or the manipulation requires extensive access to neighboring pixel data or other CPU-side data, the next most-typical approach is usually to render the scene normally first, into a render target texture, and then map that texture on the CPU and manipulate the appropriate pixels. Finally, you render a full-screen quad containing the manipulated texture to the screen. There are several variations to this technique. For example, if you don't need to read the existing contents of the framebuffer you can eschew that step and just manipulate CPU-side bits of a fullscreen texture, rendering that over top your normal scene using alpha blending. This approach or some slight variation thereof is what you may want to consider if you have complicated needs.

There are APIs, particularly in OpenGL, that let you "directly" manipulate the pixels of the frame buffer (`glDrawPixels`). These aren't generally a good idea, because unlike rendering 1x1 triangles, this is *not* an operation the GPU is optimized for, and reading back the framebuffer incurs not only the usual performance hit for reading data from the GPU, but a huge pipeline stall because the GPU can't concurrently manipulate the framebuffer while you are reading it and writing it back.

I would recommend you start with the 1x1 triangle approach, since unless you're already doing framebuffer readbacks or fullscreen quad passes, it will likely integrate into your rendering flow very easily. You can then verify if the performance is acceptable before possibly moving on to one of the more complicated options.
> 4 votes

---
Tags: opengl, lwjgl
---


# Question
Title: Considerations of using online portal for game testing and feedback
I am working on a fairly simple indie game. I wanted to get some live feedback before taking the game all the way to completion. I am able to release a beta version with stripped down graphics, and was thinking of putting this on an online game portal like Kongregate. If the game is popular I will carry on and make a more advanced version to release on the various app stores.

My question is, are there any pitfalls to think about regarding the above? How far along should the final game be before releasing the demo? Here are my thoughts so far:

Pro:

* Good way to test and get feedback
* Some revenue if portal features royalties

Con:

* Possibility for game to get cloned/ripped off
* Smaller audience for final game if they played the online version

# Answer
> 2 votes
When you release a game it's natural that some beginner game designers will make a clone of it. It doesn't matter if it's beta or final release. But luckily for you those clones usually aren't as good as original.
I doubt that a big studio would be interested to make a clone of your game, unless they think it'll be super popular.
It's normal to be afraid of a rip off, but it's improbable that someone will make a clone of your beta version before you release the game and if you really want to avoid it just put the demo out later in development, so if there is a clone, it would be a clone of your finished version (which you can't really prevent).

And if your beta has only short gameplay the players are very probable to buy the game after playing beta version, so they could see the rest.
Putting everything in the beta version is not a good idea, unless you charge for the beta version like for the original (which is a popular way of financing games in development).

---
Tags: release, demo
---


# Question
Title: Adding obstacles & collision to canvas game
I am trying to add some obstacles to the canvas game that I've got but something seems to be wrong and I can't seem to put my finger on it.

I just want some simple walls here and there to make the game harder and collision with the walls (so that if the player hits the wall it's game over).

I have an array that I have created

```
 obstacle =  [[0,0,2,0,0,0,0,2,0,0,0,0,2,0,0,0,0,2,0,0,0,0,2,0,0]],
        //        [0,0,2,0,0,0,0,2,0,0,0,0,2,0,0,0,0,2,0,0,0,0,2,0,0],
        //        [0,0,2,0,0,0,0,2,0,0,0,0,2,0,0,0,0,2,0,0,0,0,2,0,0],
        //        [0,0,2,0,0,0,0,2,0,0,0,0,2,0,0,0,0,2,0,0,0,0,2,0,0],
        //        [0,0,2,0,0,0,0,2,0,0,0,0,2,0,0,0,0,2,0,0,0,0,2,0,0]],

```

The function for the obstacle

```
function obstacle() {
  empty.push({obstacle});

  ctx.beginPath();
  ctx.rect(obstacle);
  ctx.fillStyle = "#7a26ce";
  ctx.fill();
  ctx.closePath();
}

```

And where I would essentially call it. The initiate function.

```
function init() { // Reset and intiate game objects
  score = 0; // set start score to 0
  grid.init(EMPTY, COLS, ROWS);

  var sp = {x:Math.floor(COLS/2), y:ROWS-1};
  snake.init(UP, sp.x, sp.y); // Start direction
  grid.set(SNAKE, sp.x, sp.y);
  setFood();
  grid._grid = grid._grid.concat(obstacle);
}

```

Grid object

```
grid = {
    width: null,  // Amount of columns
    height: null, // Amount of rows
    _grid: null,  // Array
    init: function(d, c, r) { // initiation with direction, columns and rows.
        this.width = c; // Set width to number of columns (c)
        this.height = r;  // set height to number of rows (r)
        this._grid = []; // Initiate grid with empty array
        for (var x=0; x < c; x++) {
            this._grid.push([]);
            for (var y=0; y < r; y++) {
                this._grid[x].push(d); // set current column and push new value for each row in column
            }
        }
    },
    set: function(val, x, y) { // set values for the grid cells with x and y position
        this._grid[x][y] = val;
    },

    get: function(x, y) { // get the value of x and y position
        return this._grid[x][y];
    }

}

```

Snake object

```
snake = { // Creating snake
    direction: null, // Direction of snake
    last: null,      // last element in queue pointer
    _queue: null,    // queue array

    // Sets start position of snake, same initiation method as before
    init: function(d, x, y) {
        this.direction = d; // Direction set to d
        this._queue = []; // Another empty queue array
        this.insert(x, y); // Inserting x & y position
    },

    // Insert method that adds elements to queue with x and y position
    insert: function(x, y) {
        this._queue.unshift({x:x, y:y}); // unshift prepends an element to array
        this.last = this._queue[0];
    },

    // Remove function to remove and return element to queue
    remove: function() {
        return this._queue.pop(); // pop returns the last element of array
    }
};

```

Here's a \[fiddle\]\[1\] for the full code.

\[1\]:

```
var
// variables
COLS = 25, // Columns
ROWS = 25, // Rows
EMPTY = 0, // Empty Cell
SNAKE = 1, // Snake
FRUIT = 2, // Fruit
LEFT  = 0, // left direction (key)
UP    = 1, // up direction (key)
RIGHT = 2, // right direction (key)
DOWN  = 3, // down direction (key)
KEY_LEFT  = 37, // key codes for keyboard input (Codes can be found online)
KEY_UP    = 38, // key codes for keyboard input (Codes can be found online)
KEY_RIGHT = 39, // key codes for keyboard input (Codes can be found online)
KEY_DOWN  = 40, // key codes for keyboard input (Codes can be found online)
obstacle = [[0,0,2,0,0,0,0,2,0,0,0,0,2,0,0,0,0,2,0,0,0,0,2,0,0]],

// Objects
canvas,   // Canvas
ctx,   // Canvas render
keystate, // Key inputs
frames,   // frames per second
score;   // player score

grid = {
 width: null,  // Amount of columns
 height: null, // Amount of rows
 _grid: null,  // Array
 init: function(d, c, r) { // initiation with direction, columns and rows.
  this.width = c; // Set width to number of columns (c)
  this.height = r;  // set height to number of rows (r)
        this._grid = []; // Initiate grid with empty array
  for (var x=0; x < c; x++) {
   this._grid.push([]); // push obstacle into empty grid
   for (var y=0; y < r; y++) {
    this._grid[x].push(d); // set current column and push new value for each row in column
   }
  }
 },
 set: function(val, x, y) { // set values for the grid cells with x and y position
  this._grid[x][y] = val;
 },

 get: function(x, y) { // get the value of x and y position
  return this._grid[x][y];
 }

}

snake = { // Creating snake
 direction: null, // Direction of snake
 last: null,   // last element in queue pointer
 _queue: null,  // queue array

    // Sets start position of snake, same initiation method as before
 init: function(d, x, y) {
  this.direction = d; // Direction set to d
  this._queue = []; // Another empty queue array
  this.insert(x, y); // Inserting x & y position
 },

    // Insert method that adds elements to queue with x and y position
 insert: function(x, y) {
  this._queue.unshift({x:x, y:y}); // unshift prepends an element to array
  this.last = this._queue[0];
 },

    // Remove function to remove and return element to queue
 remove: function() {
  return this._queue.pop(); // pop returns the last element of array
 }
};

function obstacle() {
    empty.push({obstacle});

    ctx.beginPath();
    ctx.rect(obstacle);
    ctx.fillStyle = "#7a26ce";
    ctx.fill();
    ctx.closePath();
}

function setFood() { // Food for hungry snake
 var empty = []; // tracks all empty places in the grid
 // for loop to find all empty cells in grid
 for (var x=0; x < grid.width; x++) {
  for (var y=0; y < grid.height; y++) {
   if (grid.get(x, y) === EMPTY) {
    empty.push({x:x, y:y});
   }
  }
 }
 // variable randomposition to pick random empty cell
 var randpos = empty[Math.round(Math.random()*(empty.length - 1))];
 grid.set(FRUIT, randpos.x, randpos.y);
}

function main() { // call all the functions that we will use in the game
 // canvas
 canvas = document.createElement("canvas");
 canvas.width = COLS*20;  // Sets canvas width to columns * 20
 canvas.height = ROWS*20; // Sets canvas height to columns * 20
 ctx = canvas.getContext("2d");

 document.body.appendChild(canvas); // Adds canvas element to the body of the document
 ctx.font = "12px sans-serif"; // font
 frames = 0;
 keystate = {};

 document.addEventListener("keydown", function(evt) { // Track all keyboard input
  keystate[evt.keyCode] = true;
 });
 document.addEventListener("keyup", function(evt) { // Track all keyboard input
  delete keystate[evt.keyCode];
 });

 init(); // Initiate Game Loop
 loop(); // Start Game Loop
}

function init() { // Reset and intiate game objects
 score = 0; // set start score to 0
 grid.init(EMPTY, COLS, ROWS);

 var sp = {x:Math.floor(COLS/2), y:ROWS-1};
 snake.init(UP, sp.x, sp.y); // Start direction
 grid.set(SNAKE, sp.x, sp.y);
 setFood();
    grid._grid = grid._grid.concat(obstacle);
}

function loop() { // Game loop for rendering and objects
    update();
 draw();
 window.requestAnimationFrame(loop, canvas); // Canvas will call loop function when it needs to redraw
}

function update() { // update function
 frames++;
 // Keyboard input
 if (keystate[KEY_LEFT] && snake.direction !== RIGHT) {
  snake.direction = LEFT;
 }
 if (keystate[KEY_UP] && snake.direction !== DOWN) {
  snake.direction = UP;
 }
 if (keystate[KEY_RIGHT] && snake.direction !== LEFT) {
  snake.direction = RIGHT;
 }
 if (keystate[KEY_DOWN] && snake.direction !== UP) {
  snake.direction = DOWN;
 }
 // Update game every 5 frames.
 if (frames%5 === 0) {
  // last element from the snake queue
  var nx = snake.last.x;
  var ny = snake.last.y;
  // Updating the position of snake depending on the direction it is heading
  switch (snake.direction) {
   case LEFT:
    nx--;
    break;
   case UP:
    ny--;
    break;
   case RIGHT:
    nx++;
    break;
   case DOWN:
    ny++;
    break;
  }
  // if statement checking conditions whether game should keep running or reset aka game over
  if (0 > nx || nx > grid.width-1  ||
   0 > ny || ny > grid.height-1 ||
   grid.get(nx, ny) === SNAKE
  ) {
   return init();

  }
  // Checks the new position of the snake and if it's on a fruit item or not.
  if (grid.get(nx, ny) === FRUIT) {
   // If it is on a fruit item it will increase your score and create a new food in a random cell.
   score++;
   setFood();

  } else {
   // Takes out the tail (first item) from queue and removes identifier from the grid.
   var tail = snake.remove();
   grid.set(EMPTY, tail.x, tail.y);

  }

  // Snake identifier that is created at the new position and is added to the queue
  grid.set(SNAKE, nx, ny);
  snake.insert(nx, ny);

 }
}

function draw() { // render grid to canvas
 var tw = canvas.width/grid.width;  // Calculate tile width
 var th = canvas.height/grid.height; // Calculate tile height

 for (var x=0; x < grid.width; x++) { // for-loop loops through entire grid to draw cells
  for (var y=0; y < grid.height; y++) {
   // Depending on the identifier of each cell sets certain fillstyle defined below.
   switch (grid.get(x, y)) {
    case EMPTY:
     ctx.fillStyle = "#5a5a5a";
     break;
    case SNAKE:
     ctx.fillStyle = "#B54548";
     break;
    case FRUIT:
     ctx.fillStyle = "lightblue";
     break;
                case obstacle:
                    ctx.fillStyle = "yellow";
                    break;
   }
   ctx.fillRect(x*tw, y*th, tw, th);
  }
 }
 // Change fillstyle and show score on the screen.
 ctx.fillStyle = "#000";
 ctx.fillText("SCORE: " + score, 10, canvas.height-10);
}
// Game Start!
main();
```

**The Problem** My obstacles doesn't seem to be showing up on the grid at all, I'm not entirely sure where I have gone wrong.

# Answer
> 1 votes
In your render loop, you have a switch case that tests a cell to find out it's type, wheter is a snake, fruit or obstacle. The problem, in your case, is that you are testing an integer against a 2D array of integers (which will never match). This is caused by the fact that you use 2 different variables for the main grid and for the obstacles.

To fix the problem, you should write the walls in the grid variable with all your other cell types and in your render switch case, test for it's value (you could put 3 for a wall and define its constant at the beggining of your file).

Here is a link to your JSFidle with minor updates to show your walls (I have only placed one at the (0, 0) position in the init() function, but you can place them where you'd like) : JSFiddle

---
Tags: collision-detection, javascript, html-canvas
---


title: Using of opengl buffers

text:
# Question
Title: Using of opengl buffers
Newbie question, and sorry for my English. Suppose that we create a lot of GL\_ARRAY\_BUFFER buffers, fill them with some data. But only few of them we link with shader variables. During glDraw..., what happens with other non-linked buffers? Do they go to the pipeline as well as linked buffers?

I hear but can misunderstood, that all buffers linked to the current VAO will go to the pipeline in any case, if they are involved in the shader or not. I hope this is wrong.

# Answer
> 0 votes
The reason for using VBOs (Vertex Buffer Objects) is to keep vertex data in graphics memory and not to have to keep uploading it each time it is used. If you have a lot of vertex data and do not use VBOs your game may become bandwidth limited. You will only need to bind and attach the VBOs that you wish to use in the next draw call.
All other VBOs will be ignored by the pipeline until you bind and attach then.

VAOs hold the extra state that is needed to use VBOs without making unnecessary calls. The same principles apply to VAOs, if you have VAOs that are not bound then they are simply ignored by the pipeline until you bind them.

---
Tags: opengl
---


# Question
Title: Efficient method to export a lot of pre-rendered sprites from 3D models
I have a lot of 3D Characters and I wish to use them in a 2.5D game as Sprites; in doing this I have to render them from a fixed camera angle and since each should have its own atlas file containing animation frames, it's going to be a very time consuming job! I was thinking to write a python script (models are in Blender format) and let it render the Sprites. Since I don't know Python do you think that it is efficient of me to learn the python first and write the script to do the job for me? Does anyone have a better idea?

In brief: I am looking for an efficient method to export pre-rendered sprites from 3D models considering that they all have the same armature with the same animations.

# Answer
> 1 votes
Learning Python is very easy I found a code in the internet and customized it to render from 8 different view port while fixing the lamp and camera location, the code also scales the objects to fit in 1 meter cube so the camera and lamp can be fixed correctly.

I succeed to write the following code in one night! Thanks to Python! and Blender API Documentation. Hope this help some body. I am working on copying armatures from a .blend file into other characters meshes and rendering different POS from the 8 corresponded viewport to use them in my game as sprite sources.

```
 import bpy
 cam = bpy.data.objects["Camera"]
 cam.rotation_mode = 'XYZ'
 cam.location = (1.5,0,3)
 cam.rotation_euler = (0.5236,0,1.5707)
 alamp = bpy.data.objects["Lamp"]
 alamp.location = (1,0,1)
 alamp.rotation = (0,0,0)
 meshObj = bpy.data.objects["boss"]
 meshObj.rotation_mode = 'XYZ'
 meshObj.rotation_euler = (0,0,0)
 d = meshObj.dimensions

 # Finding maximum dim of the object
 objectScale = 1
 if d[1] >= d[2] and d[1] >= d[0]:
     objectScale = 1 / d[1]
 elif d[2] >= d[1] and d[2] >= d[0]:
     objectScale = 1 / d[2]
 elif d[0] >= d[1] and d[0] >= d[2]:
     objectScale = 1 / d[0]

 # Normalize object since some of them are bigger
 print("Scaling ",objectScale)
 meshObj.scale = (objectScale,objectScale,objectScale)

 # Rotating X axis if object is X -Z Y Convert to X Y Z
 rot = meshObj.rotation_euler
 if d[1] > d[2]:
     print("Rotating X by 90 Degree")
     rot[0] = radians(90)
     meshObj.rotation_euler = rot;
 # Initiating the Rotation/Render Loop
 rot[2] = 0  # Start from Z Rotation = 0
 meshObj.rotation_euler = rot;
 for x in range(1,8):
     angle = (x-1)*0.7854
     rot[2] =  angle
     meshObj.rotation_euler = rot;
     bpy.context.scene.render.filepath = "/Users/iman/Documents/Render/Boss00%d.png" % (x)
     bpy.ops.render.render(write_still=True, use_viewport=True, scene="Camera")

```

---
Tags: sprites, rendering, automation
---


# Question
Title: Why is Spritebatch drawing my Textures out of order?
I just started working with XNA Studio after programming 2D games in java. Because of this, I have absolutely no experience with Spritebatch and sprite sorting. In java, I could just layer the images by calling the draw methods in order. For a while, my Spritebatch was working fine in deferred sorting mode, but when I made a change to one of my textures, it suddenly started drawing them out of order. I have searched for a solution to this problem, but nothing seems to work. I have tried adding layer depths to the sprites and changing the sort mode to BackToFront or FrontToBack or even immediate, but nothing seems to work. Here is my drawing code:

```
    protected override void Draw(GameTime gameTime) {
        GraphicsDevice.Clear(Color.Gray);
        Game1.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, null, null);

        for (int x = 0; x < 5; x++) {
            for (int y = 0; y < 5; y++) {
                region[x, y].draw(((float)w / aw)); // Draws the Tile-Based background
            }
        }

        player.draw(spriteBatch, ((float)w / aw));//draws the character (This method is where the problem occurs)
        enemy.draw(spriteBatch, (float)w/aw); // draws a basic enemy
        Game1.spriteBatch.End();
        base.Draw(gameTime);
    }

```

`Player.Draw()`:

```
public void draw(SpriteBatch sb, float ratio){
        //draws the player base (The character without hair or equipment)
        sb.Draw(playerbase[0], new Rectangle((int)(pos.X - (24 * ratio)), (int)(pos.Y - (48 * ratio)), (int)(48 * ratio), (int)(48 * ratio)), new Rectangle(orientation * 48, animFrame * 48, 48, 48), Color.White,0,Vector2.Zero,SpriteEffects.None,0);
        //draws the player's hair
        sb.Draw(playerbase[3], new Rectangle((int)(pos.X - (24 * ratio)), (int)(pos.Y - (48 * ratio)), (int)(48 * ratio), (int)(48 * ratio)), new Rectangle(orientation * 48, animFrame * 48, 48, 48), Color.White, 0, Vector2.Zero, SpriteEffects.None, 0);
        //draws the player's shirt
        sb.Draw(equipment[0], new Rectangle((int)(pos.X - (24 * ratio)), (int)(pos.Y - (48 * ratio)), (int)(48 * ratio), (int)(48 * ratio)), new Rectangle(orientation * 48, animFrame * 48, 48, 48), Color.White, 0, Vector2.Zero, SpriteEffects.None, 0);
        //draws the player's pants
        sb.Draw(equipment[1], new Rectangle((int)(pos.X - (24 * ratio)), (int)(pos.Y - (48 * ratio)), (int)(48 * ratio), (int)(48 * ratio)), new Rectangle(orientation * 48, animFrame * 48, 48, 48), Color.White, 0, Vector2.Zero, SpriteEffects.None, 0);
        //draws the player's shoes
        sb.Draw(equipment[2], new Rectangle((int)(pos.X - (24 * ratio)), (int)(pos.Y - (48 * ratio)), (int)(48 * ratio), (int)(48 * ratio)), new Rectangle(orientation * 48, animFrame * 48, 48, 48), Color.White, 0, Vector2.Zero, SpriteEffects.None, 0);
    }

```

the game has a top-down perspective much like the early legend of zelda games. It draws sections of the texture depending on which direction the character is facing and the animation frame. However, instead of drawing the character in the order the draw methods are called, it ends up drawing the character out of order. Please help me with this problem.

# Answer
> 1 votes
This might be because you have them listed out of order in the `spritebatch.Draw()` section. XNA draws images onto the screen from top to bottom, meaning that the images you have further down the drawing list, the higher up they'll appear in the game.

The `Player.draw()` method does the same thing.

# Answer
> 1 votes
The way I always think of it is like photoshop layering. If layer1 is placed before layer2. When you draw them, layer2 will be in front of layer1. If you want picture1 to be on top of picture2, you have to make sure you draw it after picture2. I suggest you find a friend or someone that can draw digitally cause the way you're doing, it's going to take you decades to finish the game.

A more concrete example:

`//Base
sb.Draw(playerbase[0], new Rectangle((int)(pos.X - (24 * ratio)), (int)(pos.Y - (48 * ratio)), (int)(48 * ratio), (int)(48 * ratio)), new Rectangle(orientation * 48, animFrame * 48, 48, 48), Color.White,0,Vector2.Zero,SpriteEffects.None,0);`

`//draws the player's hair
sb.Draw(playerbase[3], new Rectangle((int)(pos.X - (24 * ratio)), (int)(pos.Y - (48 * ratio)), (int)(48 * ratio), (int)(48 * ratio)), new Rectangle(orientation * 48, animFrame * 48, 48, 48), Color.White, 0, Vector2.Zero, SpriteEffects.None, 0);`

In this case, base is in the back and it's hair is in front. According to what you have the lowest layer is the player's base and the highest layer is it's shoes. Seems ok to me, can you share a print screen of how the player is being drawn?

---
Tags: xna, graphics, spritebatch
---


# Question
Title: How can you have the Input Manager Axis values snap to 1 (or -1)?
When a selected key is pressed in Unity, the Input Manager's `Input.GetAxis("Horizontal")` function returns a gradually increasing number up to `1` (or negatively `-1`) for the length it is held down. The rate at which it increases is based on the value `Sensitivity` in the Input Manager. Similarly, the sticks on a controller return a value depending on how far they are tilted.

Is there a proper way to make the value immediately snap to -1 or 1 through the manager, or would I have to write a couple of `if` statements in my script to handle that?\

Edit: A very short and readable scripting option would be `if (Mathf.Abs(isRunning) > 0) isRunning = Mathf.Sign(isRunning);`

# Answer
> 1 votes
```
Input.GetAxisRaw("Horizontal");

```

Reference: http://docs.unity3d.com/ScriptReference/Input.GetAxisRaw.html

If you are wanting the value to be -1, 0 or 1, use GetAxisRaw for keyboard inputs.

# Answer
> 1 votes
I think you would need to do it the if statement way.

For instance...

For the value to be either 1 or -1:

```
int amount = Input.GetAxis("Horizontal") > 0 ? 1 : -1;

```

For the value to be 1, 0, or -1:

```
float f;
int amount = (f=Input.GetAxis("Horizontal")) > 0 ? 1 : f < 0 ? -1 : 0;

```

---
Tags: unity, input
---


# Question
Title: Error compiling Unity after porting to mac
I used BitBucket to move my project from a PC to a Mac, now I can't compile in my Mac, as I get the following error:

`Error building Player: Win32Exception: ApplicationName='/Users/josephtripp/Library/Android/sdk/tools/aapt', CommandLine='package --auto-add-overlay -v -f -m -J gen -M AndroidManifest.xml -S "res" -I "/Users/josephtripp/Library/Android/sdk/platforms/android-22/android.jar" -F bin/resources.ap_ --extra-packages com.everyplay.Everyplay:com.unity3d.ads.android -S "/Users/josephtripp/sens-rebooted/Temp/StagingArea/android-libraries/everyplay/res" -S "/Users/josephtripp/sens-rebooted/Temp/StagingArea/android-libraries/unityads/res"', CurrentDirectory='Temp/StagingArea'`

Any help would be of great use.

# Answer
It sounds like you are using Android based on the error. Try reinstalling/installing the Java JDK and the Android SDK on your Mac. If that doesn't work make sure you install the 32-bit and 64-bit version of those libraries.

Also, make sure you are using the Mac SDK for Android when on Android, and the Windows SDK for Android only when on Windows.
> 1 votes

---
Tags: unity, macos
---


# Question
Title: Why are all OpenGL function calls prefixed with "q" in the Doom 3 source code?
Why is every OpenGL call prefixed with a "q" in the Doom 3 source code? Are they custom functions or a different library, and if so, why use that over OpenGL? Any Google search comes up with the Qt OpenGL module, which I assume has nothing to do with it.

# Answer
For reference - Doom3's qgl.h.

OpenGL is an odd little API. You must often work with function pointers either because the standard implementation is missing new functionality or because you want to work with extensions. For instance, if you want to call `glCreateShader`, but the OS you're developing on doesn't ship with new enough GL headers, you must use `glGetProcAddress("CreateShader")` in order to load the function out of the user's driver. And then you have to store that function pointer somewhere.

Even if your development environment has a particular function the users' machines might not. And then a certain function can come in 2-3 forms (vendor extension, ARB extension, core function) and so you might have to search for a function under several different names.

Many GL "loader" libraries (like GLEW) try to stick to the GL conventions. They create "fake" functions with the usual `gl`-prefix and try to magically make your code just work on any OS or driver that supports the necessary features. Essentially, instead of `glFoo` being an actual function, it's just a global function pointer and the loader library (during initialization or first use) searches `FooEXT`, `FooARB`, and `Foo` until it finds an implementation and then assigns that to the global pointer. The client code looks like it's just calling a regular function but it magically all gets resolved at runtime during initialization in a way that deals with all the different platforms and drivers out there.

Other libraries put the functions in namespaces or otherwise vary a bit from the GL norm. id wrote their own loader, either because they didn't like the ones that existed or - more likely - Quake just predates any other library that id could have used (the `q` in `qgl` likely stands for Quake, which was the first id Tech game to use GL).

The GL spec is written with this being a possibility. The spec is written *without* prefixes; it's the implementation of OpenGL that decides on which prefix to use (`gl` being the common one, of course). Loader libraries that put the functions in namespaces or using their own prefixes are completely valid.

Doom 3, being based on the Quake engine, is completely typical and justified in using a loader library to deal with the oddities of GL on multiple platforms and in choosing to use the `qgl` prefix.
> 59 votes

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


# Question
Title: Display and render only a specific object in wireframe in Unity3D
I want to know how to view and render a specific game object (mesh) in wireframe, not the whole scene. I can change the scene to wireframe using `GL.wireframe` but the problem I want to view and render only a certain object (not the whole scene) in wireframe. Any advice please?

# Answer
> 2 votes
There is alt219's solution in Unity forum.

You can turn off mesh rendering and render wireframe only. And can remove normal and vertex extension line on this script.

This script works only non-static GameObject. If GO is static, Mesh:get\_vertices() and Mesh:get\_triangles() method are not allowed to access. Uncheck static.

```
/*
wireframe update benjamin kiesewetter 2013
faster
normals
vertex extensions
*/

using UnityEngine;
using System.Collections;

public class WireFrame : MonoBehaviour {

    public bool render_mesh = true;
    public bool render_wiresframe = true;
    public float normal_length = 1f;
    public float vertext_extention_length = 1f;
    public float lineWidth = 1;
    public Color lineColor = new Color (0.0f, 1.0f, 1.0f);
    public Color backgroundColor = new Color (0.0f, 0.5f, 0.5f);
    public bool ZWrite = true;
    public bool AWrite = true;
    public bool blend = true;

    public int size = 0;
    public int ignored =0;

    private Vector3[] points_a;
    private Vector3[] points_b;
    private Vector3[] vertices;
    private Vector3[] vertex_extensions;
    private Vector3[] normals_center;
    private Vector3[] normals;
    public Material lineMaterial ;

    /*
    ████████       ▄▀▀■  ▀▀█▀▀  ▄▀▀▄  █▀▀▄  ▀▀█▀▀
    ████████       ▀■■▄    █    █■■█  █▀▀▄    █
    ████████       ■▄▄▀    █    █  █  █  █    █
    */

    void Start () {
        if (lineMaterial == null ) {
            lineMaterial = new Material ("Shader \"Lines/Colored Blended\" {" +
                                        "SubShader { Pass {" +
                                        "   BindChannels { Bind \"Color\",color }" +
                                        "   Blend SrcAlpha OneMinusSrcAlpha" +
                                        "   ZWrite on Cull Off Fog { Mode Off }" +
                                        "} } }");
        }

        lineMaterial.hideFlags = HideFlags.HideAndDontSave;
        lineMaterial.shader.hideFlags = HideFlags.HideAndDontSave;

        // find vertices
        MeshFilter filter  = gameObject.GetComponent<MeshFilter>();
        vertices = filter.mesh.vertices;
        vertex_extensions = new Vector3[vertices.Length];

        // find wire lines and normals by triangles
        int[] triangles = filter.mesh.triangles;
        ArrayList points_a_List = new ArrayList(); //first points of wireframe lines
        ArrayList points_b_List = new ArrayList(); //second points of wireframe lines
        ArrayList normals_center_List = new ArrayList();
        ArrayList normals_List = new ArrayList();

        Debug.Log("triangles.Length:" + triangles.Length);
        for (int i = 0; i+2 < triangles.Length; i+=3)
        {
            //for rEaDaBiLiTy
            Vector3 a = vertices[triangles[i]];
            Vector3 b = vertices[triangles[i + 1]];
            Vector3 c = vertices[triangles[i + 2]];

            /* Make the Lines:
                evry line may border two triangles
                so to not render evry line twice
                compare new lines to existing*/
            bool[] line_exists = new bool[]{false,false,false};
            for (int j=0; j<size; j++){
                if (points_a_List[j].Equals(a)){
                    if      (points_b_List[j].Equals(b)){
                        line_exists[0]= true;
                    }else if(points_b_List[j].Equals(c)){
                        line_exists[2]= true;
                    }
                }else if (points_a_List[j].Equals(b)){
                    if      (points_b_List[j].Equals(a)){
                        line_exists[0]= true;
                    }else if(points_b_List[j].Equals(c)){
                        line_exists[1]= true;
                    }
                }else  if (points_a_List[j].Equals(c)){
                    if      (points_b_List[j].Equals(a)){
                        line_exists[2]= true;
                    }else if(points_b_List[j].Equals(b)){
                        line_exists[1]= true;
                    }
                }
            }
            // only add lines if they dont yet exist
            if(!line_exists[0]){
                points_a_List.Add(a);
                points_b_List.Add(b);
                size++;
            } else {
                ignored++;
            }
            if(!line_exists[1]){
                points_a_List.Add(b);
                points_b_List.Add(c);
                size++;
            } else {
                ignored++;
            }
            if(!line_exists[2]){
                points_a_List.Add(c);
                points_b_List.Add(a);
                size++;
            }
            else {
                ignored++;
            }

            // Make the Normals

            //center of triangle
            normals_center_List.Add((a+b+c)*(1f/3f));
            //normal of triangle
            normals_List.Add(Vector3.Cross(b - a, c - a).normalized);
        }

        //arrays are faster than array lists
        points_a = (Vector3[]) points_a_List.ToArray(typeof(Vector3));
        points_a_List.Clear();//free memory from the arraylist
        points_b = (Vector3[]) points_b_List.ToArray(typeof(Vector3));
        points_b_List.Clear();//free memory from the arraylist

        normals_center = (Vector3[]) normals_center_List.ToArray(typeof(Vector3));
        normals_center_List.Clear();//free memory from the arraylist
        normals = (Vector3[]) normals_List.ToArray(typeof(Vector3));
        normals_List.Clear();//free memory from the arraylist
    }

    /*
    ████████       █▄ ▄█  █▀▀▀  ▀▀█▀▀  █  █  ▄▀▀▄  █▀▀▄  ▄▀▀■
    ████████       █▀▄▀█  █■■     █    █■■█  █  █  █  █  ▀■■▄
    ████████       █ █ █  █▄▄▄    █    █  █  ▀▄▄▀  █▄▄▀  ■▄▄▀
    */

    private float vertext_extention_length_old = 0;

    void update_vertex_extension_length(){
        /* asuming the length of the vertex extensions to barely change
         * only calculate this if really nessecairy,
         * increases memory but should speed up*/
        if(vertext_extention_length_old != vertext_extention_length){
            vertext_extention_length_old = vertext_extention_length;
            for(int i = 0; i<vertices.Length; i++){
                vertex_extensions[i]=vertices[i].normalized*vertext_extention_length;
            }
        }
    }

    private float normal_length_old = 0;

    void update_normal_length(){

        /* asuming the length of the normals to barely change
         * only calculate this if really nessecairy,
         * increases memory but should speed up*/
        if(normal_length_old != normal_length){
            normal_length_old = normal_length;
            for(int i = 0; i<normals.Length; i++){
                normals[i]=normals[i].normalized*normal_length;
            }
        }
    }

    // to simulate thickness, draw line as a quad scaled along the camera's vertical axis.
    void DrawQuad(Vector3 p1,Vector3 p2 ){
        float thisWidth = 1.0f/Screen.width * lineWidth * 0.5f;
        Vector3 edge1 = Camera.main.transform.position - (p2+p1)/2.0f;  //vector from line center to camera
        Vector3 edge2 = p2-p1;  //vector from point to point
        Vector3 perpendicular = Vector3.Cross(edge1,edge2).normalized * thisWidth;

        GL.Vertex(p1 - perpendicular);
        GL.Vertex(p1 + perpendicular);
        GL.Vertex(p2 + perpendicular);
        GL.Vertex(p2 - perpendicular);
    }

    Vector3 to_world(Vector3 vec)
    {
        return gameObject.transform.TransformPoint(vec);
    }

    /*
    ████████       █▀▀▄  █▀▀▀  █▄ █  █▀▀▄  █▀▀▀  █▀▀▄
    ████████       █▀▀▄  █■■   █▀▄█  █  █  █■■   █▀▀▄
    ████████       █  █  █▄▄▄  █ ▀█  █▄▄▀  █▄▄▄  █  █
    */

    void OnRenderObject () {
        gameObject.GetComponent<Renderer>().enabled=render_mesh;
        if (size >  3){
            lineMaterial.SetPass(0);
            GL.Color(lineColor);

            if (lineWidth == 1) {
                GL.Begin(GL.LINES);
                if(render_wiresframe){
                    for(int i = 0; i<size; i++)
                    {
                        GL.Vertex(to_world(points_a[i]));
                        GL.Vertex(to_world(points_b[i]));
                    }
                }
                if(normal_length>0){
                    update_normal_length();
                    for(int i = 0; i<normals.Length; i++){
                        Vector3 center = to_world(normals_center[i]);
                        GL.Vertex(center);
                        GL.Vertex(center+normals[i]);
                    }
                }
                if(vertext_extention_length > 0){
                    update_vertex_extension_length();
                    for(int i = 0; i<vertices.Length; i++){
                        Vector3 vertex = to_world(vertices[i]);
                        GL.Vertex(vertex);
                        GL.Vertex(vertex+vertex_extensions[i]);
                    }
                }
            } else {
                GL.Begin(GL.QUADS);
                for(int i = 0; i <size; i++) {
                    DrawQuad(to_world(points_a[i]),to_world(points_b[i]));
                }
                if(vertext_extention_length > 0){
                    update_vertex_extension_length();
                    for(int i = 0; i<vertices.Length; i++){
                        Vector3 vertex = to_world(vertices[i]);
                        DrawQuad(vertex,vertex+vertex_extensions[i]);
                    }
                }
                if(normal_length>0){
                    update_normal_length();
                    for(int i = 0; i<normals.Length; i++){
                        Vector3 center = to_world(normals_center[i]);
                        DrawQuad(center,center+normals[i]);
                    }
                }
            }
            GL.End();
        }else{
            //print("No lines");
        }
    }
}

```

---
Tags: unity, unityscript
---


title: Material not changing Unity3d

text:
# Question
Title: Material not changing Unity3d
I have a `MeshRenderer mr` public variable in `script1`. I dragged `mesh1` from the assets in the `mr` place in the inspector of `script1`. `mesh1` has a material `mat1`, I try to change this material to `mat2` using this `mr.sharedMaterial = mat2;` but the material doesn't change. It only changes the material in the assets but not the one in the hierarchy, so in the runtime nothing changes. Any advice please?

# Answer
Ok, I see.

I think your GameObject is a prefab which can not modified in the runtime. So you can't apply the changes to other linked prefab objects in the runtime.

Only things that you can do is cloning and change the object's property respectively.
> 1 votes

---
Tags: unity, unityscript
---


title: XNA arcball camera steering issue

text:
# Question
Title: XNA arcball camera steering issue
I have an arcball set up to follow my model in XNA. It rotates around the target correctly when holding in the left mouse button and moving the mouse. It zooms in and our correctly with the mouse wheel. It turns so it's orientation is always the same as the character turns left and right. The one part that's missing: I want the player direction to snap to the camera direction if I press the right mouse button, so I can then steer the player with the mouse. This refuses to work, I just can't seem to get the player facing in the correct direction.

The camera update class:

```
      public Matrix UpdateCamera(GameTime gameTime, HeightMapInfo heightMapInfo, float playerFacingDirection, Vector3 playerPosition)
    {
        float time = (float)gameTime.ElapsedGameTime.TotalMilliseconds;

        Matrix cameraFacingMatrix = Matrix.CreateRotationY(playerFacingDirection);

        Vector3 targetOffset = Vector3.Transform(cameraTargetOffset,
            cameraFacingMatrix);

        Vector3 cameraTarget = playerPosition + targetOffset;

        Matrix orientation = Matrix.CreateFromYawPitchRoll(MathHelper.ToRadians(cameraRotation),
                MathHelper.ToRadians(cameraArc), MathHelper.ToRadians(cameraDistance));

        view = Matrix.CreateLookAt(cameraTarget + (orientation.Backward * cameraPositionOffset.Z), cameraTarget, Vector3.Up);

        return view;
    }

```

And a snippet of the player class (based upon the XNA heightmap collision demo off MSDN):

```
        Matrix playerFacingMatrix = Matrix.CreateRotationY(playerFacingDirection);
            Vector3 velocity = Vector3.Transform(movement, playerFacingMatrix);
        velocity *= playerVelocity;

        Vector3 newplayerPosition = GetPlayerPosition() + velocity;
        if (heightMapInfo.IsOnHeightmap(newplayerPosition))
        {
            newplayerPosition.Y = heightMapInfo.GetHeight(newplayerPosition) +
                SphereRadius;
        }
        else
        {
            newplayerPosition = playerPosition;
        }
        float distanceMoved = Vector3.Distance(playerPosition, newplayerPosition);

        int rollDirection = movement.Z > 0 ? 1 : -1;

        sphereRollingMatrix *= Matrix.CreateFromAxisAngle(playerFacingMatrix.Right,
            theta * rollDirection);

        playerPosition = newplayerPosition;

```

and then the Draw for the player model

```
            DrawModel(sphere, camera.ReturnSphereRollingMatrix() *
            Matrix.CreateTranslation(camera.GetPlayerPosition()));

```

Basically, from what's above, what do I need to set as what to make the player direction point in the same direction as the camera direction? (not vice versa)

# Answer
You might be able to determine the angle between the player's forward direction and the camera's forward direction and add that amount to `playerFacingDirection`.

```
float angleToAddToPlayerFacingDirection(Matrix view, Matrix playerFacingMatrix)
{
  Matrix camWorld = Matrix.Invert(view);
  Vector3 camForward = camWorld.Forward;
  camForward.Y = 0;
  camForward.Normalize();

  Vector3 playerForward = playerFacingMatrix.Forward;
  playerForward.Y = 0;
  playerForward.Normalize();

  float yAngleBetweenCamAndPlayer = (float)Math.Acos(Vector3.Dot(camForward, playerForward));

  if(Vector3.Dot(camForward, playerFacingMatrix.Right) > 0)//if it goes the wrong way, change the > to a <.
  {
    yAngleBetweenCamAndPlayer *= -1f;
  }

  return yAngleBetweenCamAndPlayer;//this value is in radians, add a line to change it to degrees if necessasary

}

```

It is possible (based on your current code) that you don't need to set the Y values to 0 and normalize but would be necessary if you eventually have your player or camera looking upwards or downwards.
> 1 votes

---
Tags: xna, xna-4.0, camera
---


# Question
Title: How do you categorize graphic designers for game development?
I have hired a graphic designer locally and she is good at drawing things (cartoons, characters, etc.) and good at using Photoshop and Illustrator.

However, when we come to game UIs (such as the dialogs, buttons, etc.), she is not doing ok.

For game development, do you categorize graphic designers? Do you need more than one kind of graphic designer? especially for a small team (4-5 people)?

# Answer
> 1 votes
First off, note that in game development this role is typically referred to as "artist". Referring to them as a "designer" could be misleading because a "game designer" is completely different from a "graphic designer". When you use the full title it's clear what you mean, but be careful about being unclear when shortening the term.

Second, your question is somewhat circular. I mean, you ask:

> Do you need more than one kind of graphic designer?

Well, do *you?* What *we* need is pretty much irrelevant to what *you* need. I mean, you said she's good at drawing some things and not others. Obviously then you need someone else on your team who is good at that other stuff.

---
Tags: graphics-design
---


# Question
Title: At what point of Game Dev pipeline it is good idea to start adding Oculus Rift Support?
I am still in pre-dev phase - creating Assets, editing storyline, doing OOP analysis. I plan to make game in UE 4 and would like for game to have VR support. Would it be good idea to start right away with Oculus Rift(like "mobile first" approach) or add it when I have working game prototype? Thanks

# Answer
There is no correct or incorrect answer to this question. There are so many factors to consider, that the only one who can actually answer that question is yourself.

Keep the following in mind:

1. The more integrated the headset is into gameplay, the sooner you probably need to add support: Not every game can benefit from a headset, and some are even unplayable with headsets. If the headset is a necessary item to fully experience your game idea, you probably want to add support at the prototype stage.
2. The more complex the assets in your game are, the earlier you want to add support. Rendering stuff for a headset requires you to draw everything twice (or even three times, if you also want a centered POV to display on the non-headset monitor). It would be a huge waste of time if you develop your assets extremely detailed and with very heavy shaders, only to see that when you render them twice, you're getting very poor performance, and then you have to remake everything with less detail.
3. Remember that the headset is not only a display, but a controller that lets you choose the orientation and position of the camera. You should keep this in mind since the very conception of the game, and make sure your game makes sense with such a controller.
4. Headset programming has very high demands on framerate and response time. You may not want to consider this until optimization, but if you're creating the low level aspects of your renderer so you're rendering things a few frames behind they're actually displayed, adding headset support as an afterthought will pose many challenges.
5. (Added from Phillip's comment) Many headset users seem to report that the game taking control of the camera is very uncomfortable. If you're making a game for which you're planning to support headsets, you may want to consider designing it so the game can be played without having the game take control of the camera.
6. (Added from Lars Viklund's comment) Many graphical techniques that look good on a flat display won't look quite as good on a headset. Things like effects, where you can sometimes get away with a billboard in a flat monitor won't necessarily look as good on a headset. Other elements, such as the game GUI may need a complete rethinking when using headsets.
7. A headset will let you move your head around in all directions. This may have an impact on your audio model. Maybe you could get away with a simple stereo audio system when working on a flat screen, but you probably need full 3D audio support if you want your game to be as immersive as possible.

All around, headset support, even though programming-wise may be as easy as ticking a checkbox in whatever game engine you use, has very deep implications on gameplay, art and the entire engineering of your game. The earliest you think about all this, and optimally test your ideas with an actual headset, the quicker you will find flaws and be able to solve whatever problems you may find.

I believe headset support is something you build your game around, falling back to monitor when no headset is available; not something you add at the very end as an afterthought. Because of this, and -especially- if this is your first headset game, I would recommend you add headset support as early as it is practically possible.
> 6 votes

# Answer
Start with it straight away (like mobile first). It is a fundamentally different platform, with its own very unique design constraints. If you start with a non-VR game and try and tack on VR support later, you will end up with a very poor experience that probably makes your users feel ill.

If you start with VR, then it will be possible to make a pared down non-VR experience later, far more easily than the other way around, but depending on how much you take advantage of what VR gives you, you need to face the possibility that you might not be able to support both in the same game.
> 1 votes

# Answer
I've never used OR before but it might be like mobile where you make 90% for PC then configure the rest for the specific target. This allows for fast and easy testing so you can focus on the rudimentary pieces of your game. Just keep your target platform in mind for gameplay and performance reasons.
> 0 votes

# Answer
Unless your game is exclusive for VR then you should design the game based of it. If not, then you should make sure you're game is fully operational, on the initial platform, then decide if you're going to do a port for VR
> 0 votes

---
Tags: pipeline, unreal-4, oculus
---


# Question
Title: How do you use your own tileset in Tiled?
I'd like to create a 2d platformer and I understand that using tiles helps you a lot.

I think many use the map editor "Tiled" but I can't find anywhere how do you make your own tileset from a given image that you created.

I spent most of today searching a reference for this on Google, without much luck.. The only hint comes from a couple of python scripts, but I didn't manage to make them work Am I missing something?

# Answer
(Making an answer from an earlier comment...)

From what I can tell, those Python scripts are only used if you have an image of a complete game map, and want to extract from it the set of all unique tiles, then rebuild it from those tiles.

If you already have your tileset as an image, you should be able to import it from the menus using **Map -\> New Tileset**

You'll see a window like this (from this tutorial) and can simply Browse to select the image you want to use.
> 1 votes

# Answer
To make my tilesets, I use GIMP to make a 32x32 tile (or a set of 32x32 tiles) and make a single image tile and save it. I then open Tiled and add the single image .PNG files as tilesets and then place those tiles into one large tilesheet and use Tiled's built-in "Save as image..." and save it as .png. This then is a spritesheet you can use in tiled to make a tiled map. LIBGDX can also be used with tilepacker2.
> 4 votes

# Answer
What you can do is create your tiles indiviually and then pack them together using TexturePacker.

From the provided link:

> libgdx has a TexturePacker2 class which is a command line application that packs many smaller images on to larger images. It stores the locations of the smaller images so they are easily referenced by name in your application using the TextureAtlas class

If you don't like command line, there is a GUI for TexturePacker.
> 3 votes

# Answer
You can also use CodeAndWeb's TexturePacker \- it comes with a whole bunch of optimizations to reduce artifacts on tile borders etc. Not free but work a try.
> 0 votes

---
Tags: tiles, tilemap
---


# Question
Title: Get algorithm (Chance-to-Hit) from Input and Output
I am currently working on a chance-to-hit formula for an rpg. It consists of the following parts:

* AttackSkill: The used Attribute of the Attacker (Range: 1-10)
* AttackBonus: A Modifier from Skillbonuses (Range 0.5 - 3)
* DefenseSkill: The used Attribute of the Defender (Range: 1-10)
* DefenseFitness: How suitable is this defense against the attack? (Range: 0.1 - 5)
* DefenseBonus: A Modifier from Skillbonuses (Range 0.5 - 3)

This is the Input. I am looking for a way to map this to the following Output:

* Difficulty: How hard it is for the Attacker to hit (Range 0-10 float, later round to int)

What could I do to get the algorithm out of the value pairs? If possible, the output should be biased in direction of Difficulty 6 (like a normal distribution).

# Answer
You are **constructing a function** from several inputs to meet a **desired output**. This function should factor the amount of each attribute in conjunction with the importance. Your use of value pairs for such a function also coheres excellently with a documented decision model. I believe that a **weighted sum** is in order.

The weighted sum model takes in each attribute's **value and their weight** and proceeds by multiplying the former by the latter. If an attribute carries great importance in the hit chance, then the weight should reflect this by carrying a higher value as well. For example, the AttackSkill attribute seems an important determinant, so it will be assigned a weight of 1.5. Conversely, AttackBonus impacts the positive chances much less, and is assigned 0.8. We are left with.

```
(AttackSkill*1.5)+(AttackBonus*0.8) = ATTACKPOWER

```

The same will be done on the defender's behalf accounting for an additional attribute.

```
(DefenseSkill*1.5)+(DefenseFitness*2.0)+(DefenseBonus*0.8) = DEFENSEPOWER

```

Weighted sum equations carry the advantage of modularity, allowing them to be scaled to any extent without breaking down. After the sums are obtained, they need to be referenced with each other to map these "forces" to a 0-10 chance. Here's a simple method.

We first measure the difference between the power of the attack and defense. If positive, the attack has 50% or greater of following through and vice versa. The difference is passed to a sigmoid function which presents a rather convenient chance curve.

The curve is mapped from 0-10 and voila.

```
(sigmoid(ATTACKPOWER-DEFENSEPOWER)+1.0)*5.0 = HITCHANCE

```
> 1 votes

# Answer
This may not be ideal, but I've found an answer on another Q/A-site.

1. Multiply all AttackerValues (lets call it AttackRating)
2. Multiply DefenderValues \[Without DefenseFitness, see top\] (lets call it DefenseRating)
3. Divide AttackRating with DefenseRating (lets call it Rating)
4. Divide Rating with DefenseFitness (lets call it RawDifficulty)

Raw Difficulty is a Value between 0,00333 and 600 (from the ranges in the question) This value now needs to be mapped to the range of 0-10.

5. Create a table in Excel with RawDifficulty and the required Result, for instance:

600 (easiest) needs to be mapped to 0.1, 0,0033 (hardest) needs to be mapped to 9.9. Add some values in between into the table, 1 (medium) needs to be mapped to 5 for example.

6. Get the square root of RawDifficulty (this was to dimnish extreme values somewhat)
7. Create a point diagram within excel, add a trendline (in this case logarithmic) and show the formula. Bang!

In my case the following formula does work:

**EndDifficulty = -1,6395Ln(SquareRoot(RawDifficulty)) + 5,0963**
> 2 votes

# Answer
What I usually do is just add more defense and more damage to the enemy as the difficulty increase. Since I'm no mathemagician, I just pick how much the rating it'll increase by difficulty. For example, Add 1000 to defense and 500 to damage each time they increase the difficulty. Sorta how they used to do it on classic games. But, that's just me lol
> 0 votes

---
Tags: mathematics, algorithm, rpg
---


# Question
Title: AABB of a sphere's screen space projection
What is a nice, neat way to get the AABB of a sphere's projection onto the screen? This is to determine simplified geometry for lights in deferred shading.

# Answer
Found the correct derivation of the extents on AltDevBlogADay.
> 5 votes

# Answer
Old question, but here's my version (GLSL):

```
/// <summary>
/// returns the screen-space (normalized device coordinates) bounds of a projected sphere
/// </summary>
/// <param name="center">view-space center of the sphere</param>
/// <param name="radius">world or view space radius of the sphere</param>
/// <param name="boxMin">minimum (bottom left) projected bounds</param>
/// <param name="boxMax">maximum (top right) projected bounds</param>
bool GetProjectedBounds(vec3 center, float radius, inout vec3 boxMin, inout vec3 boxMax)
{

    /// frustum culling helper
    if (ShouldCull(center,radius))
        return false;

    float d2 = dot(center,center);

    float a = sqrt(d2 - radius * radius);

    /// view-aligned "right" vector (right angle to the view plane from the center of the sphere. Since  "up" is always (0,n,0), replaced cross product with vec3(-c.z, 0, c.x)
    vec3 right = (radius / a) * vec3(-center.z, 0, center.x);
    vec3 up = vec3(0,radius,0);

    vec4 projectedRight  = Projection * vec4(right,0);
    vec4 projectedUp     = Projection * vec4(up,0);

    vec4 projectedCenter = Projection * vec4(center,1);

    vec4 north  = projectedCenter + projectedUp;
    vec4 east   = projectedCenter + projectedRight;
    vec4 south  = projectedCenter - projectedUp;
    vec4 west   = projectedCenter - projectedRight;

    north /= north.w ;
    east  /= east.w  ;
    west  /= west.w  ;
    south /= south.w ;

    boxMin = min(min(min(east,west),north),south).xyz;
    boxMax = max(max(max(east,west),north),south).xyz;

    return true;
}

```

The version I'm using performs frustum culling at the beginning (view space).

And, here's the output (my visualizer adds some padding on the right and left):

The yellow represents the undistorted bounds of the sphere. Note that the left and right half-widths (relative to the real center of the sphere, at the center of the yellow circle) are different lengths.
> 4 votes

---
Tags: mathematics, aabb
---


title: Branching quest system

text:
# Question
Title: Branching quest system
I've started working in a quest system for my game, but I stumble in a zone where I have to many, if/else conditions to handle a quest, whether you have X and Y item in your inventory, whether you have already talk with a NPC, or whether some other quest stage is a given value and so on.

This end ups making the code very unclean, hard to fix and extend.

I'm wondering what's a good way to handle this.

I've read that keeping your quest as XML file is a good practice, but I've never worked with XML before(I know what they are, but I'm unfamiliar with how to properly make one)

I made a template quest to handle fetch/talk quests in a CSV file. Which looks something like this:

But I'm not that I'll end-up shooting my own foot with this custom system.

The branches of a quest can depend on items, previous quests, npc status, player status... **So, what's a good way to deal with this?**

---

EDIT:

This is not a duplicate of this question since the answers for this question are either using XML (which I said I don't have the know-how) or use multiple if/else conditions, which is my start problem.

# Answer
> 5 votes
One way of handling this could be to implement some form of graph system:

http://en.wikipedia.org/wiki/Graph\_%28mathematics%29

Or as a state machine:

http://en.wikipedia.org/wiki/Finite-state\_machine

In both cases you describe your quest states (stages) as nodes, and the edges/transitions as the actions that can be performed to move from one state to the next.

The example you provided would lend itself quite nicely to this setup (with a bit of modification).

By using something generic like a state machine allows you to reuse the same code for everything, but the only issue area is coming up with a way of tying in player actions/conversations trees. But if you also represent your item database as a spreadsheet/in xml it becomes a bit easier.

In this article there is an example of how Grim Fandango has it's first "quest" laid out: http://www.squidi.net/three/entry.php?id=158

---
Tags: architecture, game-mechanics, quests
---


title: Sprite transparency not effected libGDX

text:
# Question
Title: Sprite transparency not effected libGDX
I am making a game using libGDX and Tween Universal Engine. My problem is as follows:
I have 2 screens so fars, a splash screen with the logo, and a second one which is the main menu.
In the splash screen I use a `SpriteBatch` and a `Sprite` with the `Texture` of the image I want (which goes through some scaling.)
Now I use the Tween engine, along with a created `SpriteAccessor` to control the alpha of the sprite. I fade the picture in, then fade it out, then change it to the next screen.
In the next screen I have a single sprite, and a single, 3 slot, sprite array. In this screen I also use the tween engine, I fade the single sprite into the screen (it's the background image) then I try to, using the same method, (`Tween.to`) to change the alpah of the sprite array (each sprite by itself.), I first set it to 0 using `Tween.set`, then using the method I change it.
This didn't work, after some tests I tried setting the alpha of a single sprite from the array to 0, and that didn't work.
It's like the program is ignoring the alpha value, I even printed out the alpha value, it saying 0, but the sprite is visible. How can I fix this, or why might it be caused?

# Answer
I just had the same problem

This is my solution

```
public class SpriteAccessor implements TweenAccessor<Sprite> {

    public static final int ALPHA = 1;

    @Override
    public int getValues(Sprite sprite, int tweenType, float[] returnValues) {
        switch (tweenType) {
            case ALPHA: {
                returnValues[0] = sprite.getColor().a;
                return 1;
            }
            default: {
                assert false;
                return -1;
            }
        }
    }

    @Override
    public void setValues(Sprite sprite, int tweenType, float[] newValues) {
        switch (tweenType) {
            case ALPHA: {
                sprite.setAlpha(newValues[0]);
                break;
            }
            default: {
                assert false;
                break;
            }
        }
    }
}

```

GameScreen class setup tweening after registering accessor and instantiate TweenManager

```
Tween.set(Art.nextButton, SpriteAccessor.ALPHA).target(0.5f).start(mTweenManager);
Tween.to(Art.nextButton, SpriteAccessor.ALPHA, 1.0f)
            .target(1.0f)
            .repeatYoyo(10, 0.2f)
            .start(mTweenManager);

```

GameScreen class render loop

```
mTweenManager.update(Gdx.graphics.getDeltaTime());
spriteBatch.setProjectionMatrix(camera.combined);
spriteBatch.begin();
Art.nextButton.draw(spriteBatch);
spriteBatch.end();

```
> 1 votes

---
Tags: java, libgdx
---


# Question
Title: What screen resolution do I make an android game in?
Is it safe to assume that most mobile phones and tablets today have moved to 1280x720 resolution and above and make the games in that resolution, scale down for smaller screens or is a smaller resolution like the often used 800x480 still the recommended way to do it and scale it up for larger devices?

# Answer
> 0 votes
You can make a script at the start of your game to get the `Screen.Width`, and `Screen.Height`, and then set your camera's scale to the same scale the user is having. You can never assume anything, maybe most mobile phones have moved to 1280x720, or 1280x800, but what about tablets? They're android devices as well, and they should be able to run your games without having some blue borders on the side because the camera can't scale.

---
Tags: android, resolution, screen, scale
---


title: unity3d model falling apart

text:
# Question
Title: unity3d model falling apart
I found something I can't understand. I'm only a beginner, so I thought I could use the CarController Scripts of the Car Demo for making a little driving game with different models. I wonder why the colliders are sub-objects and the RigidBody has "Gravity-Enabled" without falling apart. my model falls apart with the same configuration.

# Answer
> 0 votes
The way to fix this is :

1. Remove the collider and rigidbody from the parent object.
2. Select all the children of your object that are part of the car
3. Give all these children Ridigbodies, and sphere/cube/capsule // generated colliders according to your needs. And make all the rigidbodies **kinematic**. That should keep them from pushing away each other, and "glue" them in a way.

You can still address the parent now, and use forces / translations on him correctly.

---
Tags: unity, models
---


# Question
Title: How should I license my game so others may not distribute copies?
I've created a game and I'm unsure how to license it or what that means.

I've heard of Creative Commons licenses. Should I use that?

I want it so that people that download my game **cannot** remix or distribute copies, even for non commercial purposes. What should I do in such a case?

# Answer
> 4 votes
By default, you have exclusive copyright for every creative work you produce, which means nobody is allowed to distribute it except you unless you give them explicit permission.

The purpose of a license is to give the end-user rights they would normally not have. So when you don't add any license terms whatsoever, it means your end-users have no right to redistribute your software. Technically, they don't even have the right to *use* your software. That's what an End-User License Agreement is for. As you certainly know, it is common practice to have the user agree to it with a click during the installation of your game and also drop a copy in the directory where it was installed for later reference.

All the creative commons licenses allow non-commercial and unchanged redistribution, so when you want people to receive copies of your game only from you, the CC licenses are not what you are looking for.

---
Tags: legal, licensing, distribution
---


# Question
Title: CCG Design - How to define text descriptions
I'm designing a CCG/TCG game (with the Kotlin language), and I am looking for advice regarding the text of the cards.

First of all, here is an example of one card, defined in XML:

```
  <card name="Sample Card"
        type="event"
        image="tex-event"
        metalCost="1"
        energyCost="1">
        <text>
            Whenever you destroy a creature, you will gain 3 energy.

            Your stronghold does not produce energy.
        </text>
        <traits>
            <trait name="ScavengeResOnDestroy" type="energy" amount="3"/>
            <trait name="ResFlux" target="self"/>
        </traits>
    </card>

```

`ScavengeResOnDestroy`, and `ResFlux` are direct mappings to class names. Scavenge refers to the first line in the text, and ResFlux to the second.

Before I go on and design a whole lot of cards this way (then again maybe this issue would become a lot clearer AFTER I would design some more cards..) Should I attempt to tie/"hard"-code the text descriptions into the Trait-classes?

The thing is, I find it quite hard problem to "generate" the text for a Trait.. For example ScavengeResOnDestroy could have several targets:

* Self (Whenever you destroy a creature...)
* Opponent (Whenever an opponent destroys a creature...)
* Both (Whenever a player destroys a creature...)

And to complicate things even further, I could very well see a possibility to modify ScavengeResOnDestroy, like so:

* Whenever you destroy *a creature you do not control*..
* Whenever an opponent destroys *any creature*..."

Now I haven't done much research on the topic yet... but I guess I'd need to build some kind of "sentence generator" (I don't know the correct term)?

Do you think I should stick with simply defining the text for each card, as in the example, or possibly, under the `<trait>`? And perhaps generate the text only for the simplest traits? Something else?

# Answer
> 4 votes
I would say you should absolutely generate your descriptions procedurally. This will allow you to tweak your abilities and definitions to your hearts content at a later time without having to manually adjust many many descriptions.

Based on what you have shown, I would have somewhere where the *Trait* was defined **not within a specific card**, with a parameterised description, something like:

```
<traits>
    <trait name="ScavengeResOnDestroy" type="energy">
        <parameter name="amount" type="int" default="3"></parameter>
        <text>
            Whenever you destroy a creature, you will gain {parameter.amount} {type}.
        </text>
    </trait>
</traits>

```

Then, when used on a specific card:

```
<card name="Sample Card"    ... >
    <text>
        Your stronghold does not produce energy.
    </text>
    <traits>
        <trait name="ScavengeResOnDestroy" amount="3"/>
    </traits>
</card>

```

The idea here is to define each trait separately, and use some kind of templating language (either a library, or of your own creation) to allow you to dynamically generate your descriptions.

Combine this with parameterisation, the ability for your code to read in parameter values / attributes from the XML to affect how the traits etc. function and you will have the flexibility to change your traits etc:

* At the global level (the system) - just change the description in one place to match the new functionality and it will be automatically applied across your game.
* At the card level (tweaks and balance) - just change the parameters passed to the trait, and the description will be automatically updated.

To illustrate what I mean, psudo-code for rendering a card description:

* Load card definition from XML
* Look for any referenced traits \[Find: ScavengeResOnDestroy\]
* Load trait definition from XML
* Look for parameter definitions in trait definition \[Find: amount\]
* Look for parameter values in *card* definition \[Find: amount=3\]
* Get the `<text>` element from the trait definition.
* Look for placeholders in the text \[Find: parameter.amount and type\]
* Replace placeholders with their individual values \[parameter.amount --\> 3, type --\> energy\]
* Render text:

> Whenever you destroy a creature, you will gain 3 energy.

# Answer
> 1 votes
An option would be to remain quite vague in the description, but to add another section which simply states facts:

```
<card name="Sample Card"
      type="event"
      image="tex-event"
      metalCost="1"
      energyCost="1">
  <text>
    "Your coffee addiction turns you in a vampire machine"

    Whenever you destroy a creature, you will gain energy.

    Your stronghold does not produce energy.
  </text>
  <traits>
    <trait name="ScavengeResOnDestroyAny" type="energy" amount="3"/>
    <trait name="ResFlux" target="self"/>
  </traits>
</card>

```

Then the card description would look like:

> **Sample card**
>
> *"Your coffee addiction turns you in a vampire machine"*
>
> Whenever you destroy a creature, you will gain energy.
>
> Your stronghold does not produce energy.
>
> **With this card:**
>
> * Gain target: player
> * Gain resource on destruction of any creature: energy (3)

The text of the card will be hand written by you, but the "facts" will have some factual text chunks written by you, but assembled by your system. For instance, the trait name "ScavengeResOnDestroyAny" is associated with the text chunk "Gain resource on destruction of any creature", and "ResFlux" is associated with "Gain target".

I see these advantages with this approach:

* You make sure the data used by your game is the data seen by your players
* It lets you be more vague in the description
* You don't *need* to update the description whenever you add a new feature to the cards
* Integrating small chunks of text that do not need to be integrated with varying quantities (e.g. you will gain 1 energ**y** vs you will gain 2 energ**ies**) can make your life easier
* If you plan to translate your game, you might save yourself a couple of headaches with the last point as well

# Answer
> 1 votes
## Pro:

* It saves time. Writing the text is one step less you have to do when releasing a new card. This might not sound so much as long as you only support one language, but when you want to add internationalization, you will have to postpone the release until the translation into every supported language is finished, which can be quite a bottleneck when your French guy is sick, your Italian guy on vacation, your German chick just got a baby and you had to fire your Spanish dude for inserting profanity into your card texts and couldn't find a replacement yet.
* Having the text derived from the game mechanics at runtime has the advantage that you no longer have to make sure that description and mechanics stay in sync when you do balancing changes.
* Your texts will automatically be consistent between cards. With hand-written descriptions you might run into situations where one card says "kill", another "destroy" and a third "remove" which always means the same thing but could leave the players puzzled if there maybe is a subtle distinction. But with auto-generated texts, two cards which do the same thing will *say* that they do the same thing.
* When you translate the game, you also reduce the risk of mistranslations causing a card to do something different than what the text says.

## Contra:

* You will run into situations where the text derived from the game mechanics will turn out to be needlessly convoluted compared to how you could describe the effect with natural language.
* Because the descriptions are so tightly coupled to the mechanics, they will likely turn out quite sterile and formalized. This is good for understanding the mechanics, but lacks flavor and hurts atmosphere and immersion. This can be mitigated by adding a *flavor text* to cards - an additional text snippet which is irrelevant for the game mechanics but describes the card in the context of the fiction of the game universe (*Magic: The Gathering* does this very well - game mechanic effects are described in highly formalized language but flavor texts can be anything).

## To get the best out of both worlds

Have a default text derived from the game mechanics *but* allow an optional XML node in your schema which overrides and/or appends to the auto-generated description with free text.

---
Tags: card-game
---


# Question
Title: UnityEngine.PlayerPrefs corrupts string?
I need to use PlayerPrefs to store arrays of bytes for my game. For some reason, the string I save with PlayerPrefs doesn't come out with the same length.

I.e.

```
byte[] TestArray = new byte[256];
for (byte i = 0; i < 256; i++)
{
    TestArray[i] = i;
}

char[] charBuffer = new char[TestArray.Length];
for (int i = 0; i < TestArray.Length; i++)
{
    charBuffer[i] = (char)TestArray[i];
}

PlayerPrefs.SetString ("Storage", new string(charBuffer));

PlayerPrefs.Save ();

Debug.Log (new String(charBuffer).Length);
Debug.Log (PlayerPrefs.GetString ("Storage").Length);

```

Log:

```
256
5

```

Is this possibly an issue with encoding? How do I fix it?

# Answer
> 0 votes
I browsed the UForums and found a solution. It turns out, Unity serializes strings in base64 so to save/extract data to/from a string, one has to save the data in that encoding. I'm not too keen on this subject, but this is what I did to make it work:

```
byte[] TestArray = new byte[256];
for (byte i = 0; i < 256; i++)
{
    TestArray[i] = i;
}

PlayerPrefs.SetString ("Storage", System.Convert.ToBase64String (TestArray));

PlayerPrefs.Save ();

Debug.Log (System.Convert.ToBase64String (TestArray).Length);
Debug.Log (PlayerPrefs.GetString ("Storage").Length);

```

Log:

```
256
256

```

# Answer
> 0 votes
Could just be lazy and convert to hex if the bin is not too large. Best way to deal with encoding issues is to skip them.

---
Tags: unity, serialization
---


# Question
Title: Does triangle-plane clipping in 3D always produce a triangle?
When you clip a triangle against a plane, will you always get a triangle out? Are there perhaps cases where you don't get a triangle out of clipping it against a plane?

# Answer
Nope. Clipping a triangle against a plane can result in a quadrilateral, which you will need to re-triangulate (unless you don't actually care about having triangles). In fact, it *often* results in a quad, since in most cases you get a quad on one side of the plane and a triangle on the other. You only get two triangles when the plane exactly intersects one vertex.

Consider the triangle below, which exists in the XY plane (you're looking "down the Z axis"). The blue line represents a YZ plane the triangle is clipped against, resulting in a tetrahedral shape when we consider the left half-space of the plane to be the "inside" space we care about. The pink line represents one possible re-triangulation of the quadrilateral.
> 3 votes

---
Tags: 3d, geometry, clipping
---


# Question
Title: VS Graphics Diagnostic Tools and IDXGIFactory::EnumAdapters()
I have the following constructor for my main application class where i enumerate all adapters, that looks something like this:

```
CApplication::CApplication()
{
    IDXGIFactory* factory;
    CreateDXGIFactory(__uuidof(IDXGIFactory), reinterpret_cast<void**>(&factory));

    IDXGIAdapter* adapter;
    unsigned adapterIndex = 0;
    while (factory->EnumAdapters(adapterIndex, &adapter) != DXGI_ERROR_NOT_FOUND)
    {
        mAdapters.push_back(adapter);
        ++adapterIndex;
    }

    ReleaseCOM(factory);
    //...
    HRESULT hr = D3D11CreateDevice(
        mAdapters[adapterIndexToUse],
        mDriverType, nullptr,
        createDeviceFlags,
        nullptr, 0, D3D11_SDK_VERSION,
        &md3d11Device, &mFeatureLevel, &md3d11ImmediateContext);
}

```

I have Intel HD Graphics 4000 as primary display adapter and NVIDIA GeForce GT 620M as "back-up" display adapter which do all the heavy work.(i.e. rendering in games)

I want to use Visual Studio 2013 Graphics Diagnostic tools while using NVIDIA GPU, and since NVIDIA GPU is secondary adapter, this corresponds to setting `adapterIndexToUse=1`. Problem is that while enumerating adapters only Indel GPU gets enumerated.
That is, call to `factory->EnumAdapter(adapterIndex, &adapter)` returns `DXGI_ERROR_NOT_FOUND` if `adapterIndex > 0` while using Visual Studio Graphics Diagnostic tools and so my `mAdapters` class attribute which is `std::vector<IDXGIAdapter*>` have size 1 causing out of bounds exception when we try to create the Device with `adapterIndexToUse` specified as 1 (So i use my secondary NVIDIA GPU).

Only cause of this error i have come to think of is that Graphics Diagnostic tools is only supported on primary display adapter, but i don't see why that would be the case.

# Answer
**The main issue the OP is hitting is that VS Graphics Diagnostics does not support DirectX 10/DXGI 1.0 applications**.

For DirectX 10 on Windows Vista, you used `CreateDXGIFactory` and created a `IDXGIFactory` class instance. This is "DXGI 1.0".

For DirectX 11, you should use `CreateDXGIFactory1` and `IDXGIFactory1` which is DXGI 1.1.

It is also important not to mix different versions of DXGI in the same application. If you are explicitly creating a DXGI factory and enumerating the devices, then as long as you use `CreateDXGIFactory1` you should be fine.

If, however, you are creating the 'default' device and then need to get the DXGI factory that was used to create it, you should use this trick instead:

```
IDXGIFactory1* dxgiFactory = nullptr;
{
    IDXGIDevice* dxgiDevice = nullptr;
    hr = pDevice->QueryInterface( __uuidof( IDXGIDevice ), reinterpret_cast<void**>( &dxgiDevice ) );
    if ( SUCCEEDED(hr) )
    {
        IDXGIAdapter* adapter = nullptr;
        hr = dxgiDevice->GetAdapter( &adapter );
        if ( SUCCEEDED(hr) )
        {
            hr = adapter->GetParent( __uuidof( IDXGIFactory1 ),
                reinterpret_cast<void**>( &dxgiFactory ) );
            if (FAILED(hr)) dxgiFactory = nullptr;
            adapter->Release();
        }
        dxgiDevice->Release();
    }
}

```

Or a bit more succinctly using `Microsoft::WRL::ComPtr`

```
ComPtr<IDXGIFactory1> dxgiFactory;
{
    ComPtr<IDXGIDevice1> dxgiDevice;
    HRESULT hr = m_d3dDevice.As(&dxgiDevice);
    if (SUCCEEDED(hr))
    {
        // Identify the physical adapter (GPU or card) this device is running on.
        ComPtr<IDXGIAdapter> dxgiAdapter;
        hr = dxgiDevice->GetAdapter(dxgiAdapter.GetAddressOf());
        if ( SUCCEEDED(hr) )
        {
            // And obtain the factory object that created it.
            hr = dxgiAdapter->GetParent(__uuidof(IDXGIFactory1), &dxgiFactory));
            if (FAILED(hr)) dxgiFactory = nullptr;
        }
   }
}

```

See Anatomy of Direct3D 11 Create Device and DirectX Graphics Infrastructure (DXGI): Best Practices
> 1 votes

---
Tags: directx11, visual-studio
---


title: How to change the gravity with a click

text:
# Question
Title: How to change the gravity with a click
How to change the gravity of a ball upward with a click Then change it again downward with another click And so on In unity

# Answer
> 5 votes
```
void ReverseGravity()
{
     Physics2D.gravity = new Vector3(0, -1.0F, 0);
}

void ApplyGravity()
{
     Physics2D.gravity = new Vector3(0, 1.0F, 0);
}
//if you are not using 2D then use Physics.gravity = new Vector3(0, 1.0F, 0);
//you could also  use Rigidbody AddForce to get your desired effect without changing any physics.
//you can set up a bool normalGravity and use something like this in a LateUpdate()
        if(Input.GetKeyDown(KeyCode.Mouse0))
        {
            if (normalGravity)
            {
                normalGravity = false;
                ReverseGravity();
            }
            else
            {
                normalGravity = true;
                ApplyGravity();
            }
        }

```

# Answer
> 0 votes
```
Physics.gravity *= -1.0f; // :P

```

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


# Question
Title: Run some objc code very early in unity iOS game lifetime
I want to hook up a crash reporting service to my unity iOS game. It's just one line of objC to add, as early into the app lifecycle as possible, but I'm not sure how to get it to run. I know I could make a native plugin and then call that from some Awake() function in C#, but that's too late for my purposes.

I'm not a native iOS developer, but I know enough to be dangerous. I have been able to google enough that I know I want something to with UnityAppController, probably `preStartUnity()`. But that's all.

Has anyone got further resources on how to do this? Or another way, if I'm barking up the wrong tree?

edit: I'm on unity 4.6.

# Answer
This may be a blatant hack, but Unity now let's you use a custom xib for the splash/loading screen. Maybe you can attach it there.

Edit: I forgot, this feature is Pro only.
> 1 votes

---
Tags: unity, ios, objective-c
---


# Question
Title: What are the differences between using GetComponent<Transform>() and this.transform?
I've been reading some example code and working on my own stuff in Unity. I've been seeing a lot of `GetComponent<>()`, and often this will be done for the transform as `Transform _transform = GetComponent<Transform>()`.

However, I have already had access to the attached game objects transform, as `transform`, `this.transform` or `gameObject.transform`. I can understand using `GetComponent()` in most cases, but why would you specifically use the function for `GameObject` and `Transform` when the two items are accessible from the script to start with?

# Answer
> 14 votes
The Speed (fast to slow):

```
cached _transform >> Component.transform >> Component.GetComponent<Transform>

```

And If you disassemble a UnityEngine.dll C# binary, you can see transform do not call GetComponent (Component class member), just call internal mono runtime method. Here is the transform code.

```
// UnityEngine.Component
public Transform transform
{
    get
    {
        return this.InternalGetTransform();
    }
}

[WrapperlessIcall]
[MethodImpl(MethodImplOptions.InternalCall)]
internal extern Transform InternalGetTransform();

```

And Here is disassembled Component class's GetComponent Method.

```
public extern Component GetComponent(Type type);
public T GetComponent<T>() where T : Component
{
    return this.GetComponent(typeof(T)) as T;
}
[WrapperlessIcall]
[MethodImpl(MethodImplOptions.InternalCall)]
public extern Component[] GetComponents(Type type);

```

GetComponent is a kind of Finding function using generics. So it's a little bit slower than caching.

---

Original Source :

```
public class Test : MonoBehaviour
{
    Transform _transform;
    void Start()
    {
        _transform = this.transform;
        _transform = gameObject.GetComponent<Transform>();
    }
}

```

Binary Disassembled:

```
public class Test : MonoBehaviour
{
    private Transform _transform;
    private void Start()
    {
        // == UnityEngine.Component::get_transform()
        this._transform = base.get_transform();

        // == UnityEngine.Component::GetComponent<UnityEngine.Transform>()
        this._transform = base.get_gameObject().GetComponent<Transform>();
    }
}

```

# Answer
> 8 votes
As Jinbom said the main difference here is speed.

However it is important to note that this is only the case for the transform property of GameObject. Other properties such as camera and rigidbody are just convenience properties and call GetComponent\<\> under the hood so the performance is identical. It is for this reason that Unity has deprected these 'helper' properties in Unity as it is not immediately obvious that Unity is going to search for the component rather than returning a cached version.

With the exception of the transform property mentioned in the question, all other components should be cached at the first available opportunity using GetComponent\<\> and that cached value should be used thereafter.

# Answer
> 0 votes
Right now you can assume that every game object will have the Transform component due to the `this.transform` syntax. My guess is that Unity updated its API with the `GetComponent<>()` syntax was so that in the future you could have GameObjects without "special" components like Transform.

Then you can have a "purer" architecture where your GameObjects don't *have* to come with Transforms (although the editor might still add them by default as a convention).

# Answer
> -1 votes
The only reason `this.transform` works at all is because MonoBehavior implements a convenience property for the Transform component on the GameObject the behavior is attached to. ...It's rather misleading. I think `gameObject.transform` is more semantically correct, but that's splitting hairs. They do the same thing.

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


title: Get mouse/touch position for NGUI event

text:
# Question
Title: Get mouse/touch position for NGUI event
Since I am using NGUI, to capture mouse events I use their methods such as

```
void OnPress (bool isDown) {

}

```

How can I check the mouse/touch position that corresponds to this particular OnPress event?

# Answer
> 1 votes
Check out `UICamera.currentTouch.pos` or `UICamera.lastTouchPosition` in the `OnPress` method.

These will be set, whenever a touch is active, and should provide the necessary information.

---
Tags: unity, ngui
---


# Question
Title: How to debug a DirectX crash on client machine?
I have customers who are experiencing crashes which I can't reproduce on my machine.

From the minidumps they sent over, it appears that their crashes all seem to be in unexplained Direct3D calls, deep in the callstack in d3d11.dll.

How can I debug this problem? Is there any way to log client d3d error messages? I can't use the debug layer since they don't have the DirectX SDK, right?

# Answer
I still haven't been able to figure out precisely what's happening on client machines (despite having good minidumps with symbols).

I'm posting an answer to whichever poor souls might be having this similar problem. In my case the users' crashes were caused / exposed by overlay software. This includes the Steam Overlay, and a program called OverWolf. Disabling those programs "fixed" the problem.

Again, no idea what the presumed root of the issue is. I only have that workaround.
> 1 votes

---
Tags: directx, debugging
---


title: Calculate land center on grid

text:
# Question
Title: Calculate land center on grid
I have a grid based game. The main map is 2d array with land ids, something like this (here are 2 lands on the map, one formed where the 1's are and one formed by where the 2's are):

\[ 1 , 2 , 2 \]
\[ 1 , 1 , 2 \]
\[ 1 , 2 , 2 \]

I want to draw buildings on the center of each land. But how is better to calculate the center? Just calculating mean(X),mean(Y) does not work - lands can bee narrow or have dumbbell shape.

# Answer
> 1 votes
I'm aware it is not *exactly* what you're looking for, but here is a suggestion.

You could control the generation of your lands to force them to be convex.

Using this method would allow you to simply use the mean x and mean y values to place your building as you would be sure they're on the land.

Otherwise, the only options I see is 1) no random in the building placement, you place them manually, or 2) go with a more complex algorithm in determining the 'center' of the land: calculate the spot where there is, on average, the most land between the tested spot and the neighbour land or the side of the map.

# Answer
> 0 votes
Instead of getting the center of each land with mean(X) and mean(Y) (which, by the way, is not a bad solution), you could calculate a rectangular bounding box around each of your lands:

```
Land 1: Starting at (0, 0) of size (2, 3)
Land 2: Starting at (1, 0) of size (2, 3)

```

This way, you could calculate the relative center of the given rectangles:

```
Land 1: (2 / 2 + 0, 3 / 2 + 0) = (1, 1.5)
Land 2: (2 / 2 + 1, 3 / 2 + 0) = (2, 1.5)

```

If you want your buildings to be aligned with the grid, you can ceil the values

```
Land 1: ceil(1, 1.5) = (1, 2)
Land 2: ceil(2, 1.5) = (2, 2)

```

This will give you a good approximate of the center of each of your lands. THe approximation will not be very accurate for small grids (as you can see) but with bigger sizes it should give better results.

---
Tags: 2d, geometry, grid
---


title: 2D Simplex Smooth Cave Generation

text:
# Question
Title: 2D Simplex Smooth Cave Generation
So I'm creating a system of caves below my random terrain generation, and I'm using 2D Simplex Noise to do so and I have a pretty good grasp on generating the random caves. However, the cutoff from the terrain to where the cave layer starts is a bit abrupt, and I was wondering how I could prevent this.

Random Level Generation:

```
public static Level GetRandomLevel(int rows, int cols, float scale = 1f)
{
    Tile[][] tiles = new Tile[rows][];
    for (int i = 0; i < rows; i++)
    {
        tiles[i] = new Tile[cols];
        for (int x = 0; x < cols; x++)
        {
            tiles[i][x] = new Tile(0, new Vector2(x, i), scale);
        }
    }
    int left = Main.rand.Next(rows / 4, rows / 2);

    double seed = Main.rand.NextDouble() * 255;
    for (int i = 0; i < cols; i++)
    {
        float noise = Noise.Generate((float)seed);
        noise *= 7;
        int height = left + (int)noise;
        height = (int)MathHelper.Clamp(height, 0, rows - 1);
        tiles[height][i] = new Tile(2, new Vector2(i, height), scale);
        FillLower(tiles, height, i, scale);
        seed += .05f;
    }

    int[] heightmap = new int[cols];
    for (int i = 0; i < cols; i ++)
    {
        for (int j = 0; j < rows; j++)
        {
            if (tiles[j][i].TileID == 2)
            {
                heightmap[i] = j;
                break;
            }
        }
    }

    //Smoothing out terrain
    for (int i = 0; i < cols - 1; i++)
    {
        if (heightmap[i] > heightmap[i + 1])
        {
            tiles[heightmap[i] - 1][i] = new Tile(6, new Vector2(i, heightmap[i] - 1), scale);
            tiles[heightmap[i]][i] = new Tile(3, new Vector2(i, heightmap[i]), scale);
        }
    }
    for (int i = cols - 1; i > 0; i--)
    {
        if (heightmap[i] > heightmap[i - 1])
        {
            tiles[heightmap[i] - 1][i] = new Tile(5, new Vector2(i, heightmap[i] - 1), scale);
            tiles[heightmap[i]][i] = new Tile(4, new Vector2(i, heightmap[i]), scale);
        }
    }

    //Caves
    for (int y = 0; y < rows && left + 10 + y < rows; y++)
    {
        for (int x = 0; x < cols; x++)
        {
            double noise = Noise.Generate(x / (70 * scale), (y + 1) / (70 * scale));
            //Not air
            if (tiles[left + 10 + y][x].TileID != 0 && noise > 0)
            {
                tiles[left + 10 + y][x] = new Tile(0, new Vector2(x, left + 10 + y), scale);
            }

        }
    }

    return new Level(tiles);
}

```

Here is a picture demonstrating what I mean about the 'cave layer cutoff' being to abrupt.

# Answer
> 1 votes
I went ahead and looped along the starting point of the caves from left to right and used a recursive method to fill in all the caves that started at the top of the cave layer, thereby removing any cutoffs.

```
//Looping along cave layer
for (int i = 0; i < cols; i++)
{
    if (tiles[left + 10][i].TileID == 0)
    {
        FillCaves(tiles, left + 10, i, scale);
    }
}

private static void FillCaves(Tile[][] tiles, int i, int j, float scale)
{
    tiles[i][j] = new Tile(1, new Vector2(j, i), scale);
    if (i - 1 >= 0 && tiles[i - 1][j].TileID == 0)
    {
        FillCaves(tiles, i - 1, j, scale);
    }
    if (i + 1 < tiles.Length && tiles[i + 1][j].TileID == 0)
    {
        FillCaves(tiles, i + 1, j, scale);
    }
    if (j - 1 >= 0 && tiles[i][j - 1].TileID == 0)
    {
        FillCaves(tiles, i, j - 1, scale);
    }
    if (j + 1 < tiles[i].Length && tiles[i][j + 1].TileID == 0)
    {
        FillCaves(tiles, i, j + 1, scale);
    }
}

```

# Answer
> 0 votes
Foreach column , jump the air tiles over ground , then start to apply 2d noise. In pseudo code:

```
  //Caves
Foreach cols {
 Bool FoundFirstGround=false;
 Foreach rows //from top
 {
  if (FoundFirstGround){
    //APPLY YOUR 2d simplex noise logic
    ...
  }
  else
    //jump air tiles over surface
    if (! is air){
       FoundFirstGround=true;
    }
 }
}

```

---
Tags: xna, c#, 2d, simplex-noise
---


# Question
Title: Update total enemy counter after single enemy is defeated?
So I have a list that counts how many enemies are in the area. But when I kill an enemy, the list shows that that element in that array is missing, and doesn't reduce the enemy counter. How can I get it to reflect when an enemy is defeated?

**Code:**

```
using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class EnemyCount : MonoBehaviour {
public List<Transform> enemies;

void Start () {
    enemies = new List<Transform>();
}

void Update () {
    FindAllEnemies();
}

public void FindAllEnemies () {
    GameObject[] go = GameObject.FindGameObjectsWithTag("Enemy");

    foreach (GameObject enemy in go) {
        //Checks for duplicates
        if (!enemies.Contains(enemy.transform)) {
            AddEnemiesToList(enemy.transform);
        }
    }
}

public void AddEnemiesToList (Transform enemy) {
    enemies.Add(enemy);
}
}

```

# Answer
> 1 votes
If I understand correctly your question, one way to achieve it would be to clear the list each frame to make sure you list is always up to date. Please note that I do not know exactly the syntax to clear a list, but your function would look like this:

```
public void FindAllEnemies () {
    GameObject[] go = GameObject.FindGameObjectsWithTag("Enemy");

    enemies.Clear(); // Probably not the right function name...
    foreach (GameObject enemy in go) {
        enemies.Add(enemy.transform);
    }
}

```

**Edit**

In fact, you could even do something like this if it suits your needs:

```
using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class EnemyCount : MonoBehaviour {

  public List<GameObject> enemies;

  void Start () {
    enemies = new List<GameObject>();
  }

  void Update () {
    FindAllEnemies();
  }

  public void FindAllEnemies () {
    enemies = GameObject.FindGameObjectsWithTag("Enemy");
  }
}

```

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