# Question
Title: How do I determine the draw order of isometric 2D objects occupying multiple tiles?
My current sorting method works only for objects that occupy 1 tile and fails for multi-tile objects. For examle, the bed in the above picture occupies 1×2 tiles, and the sorting fails.

Also that bed picture is 1 whole image that covers 2 tiles.

How can I change my sort method to accomodate this?

# Answer
Here is a solution without resorting to 3D coordinates or splitting your sprite into 1x1 elements, that works if your objects occupy *rectangular* areas of tiles.

Let `(ei,ej)` be the coordinates of the bottom tile of entity `e`. I assume the x axis is pointing north-east and the y axis is pointing north-west, so that `(ei,ej)` has the smallest coordinate values among all tiles of `e`. Likewise, consider an entity `f` with bottom tile `(fi,fj)`.

In the case where `e` is made of only one tile, you would put entity `e` in front of entity `f` if `ei+ej < fi+fj`. If `ei+ej = fi+fj`, you don't care which is in front of which.

*Simple check of which object is in the lowest horizontal diagonal.*

To work with multi-tiles rectangle, you need to consider whether a tile in `f` is "behind" a tile in `e` or conversely. Since rectangle recedes uniformly from the bottom-most tile, you need to do this check only for the extremities, i.e. the left-most tile of `e`, and right-most tile of `e`. So `f` is behind `e` if you can find one tile of `f` that is behind the left-most tile of `e` or the right-most tile of `e`.

In my example, I will use the right most tile of `e`, which happens to be `(ei,ej)`. Note that if you know if `f` is "on the left" or "on the right" of `e`, you can already choose to check only the left-most or the right-most tile. Here, we only need to check using the left-most tile of `e`. However I've draw my pictures too fast and they do use the right-most check, so we'll stick with the right-most check.

Tiles "behind" a tile `(i,j)`, correspond to tiles above `(i,j)`, in the vertical diagonal passing through `(i,j)` (directly behind) or on the neighbor vertical diagonals on the left and on the right (partially behind). So the three diagonals corresponds to tiles with coordinates of the form `(i+k,j+k)`, `(i+k+1,j+k)`, `(i+k,j+k+1)`, for `k≥0`

*We want to find the green tiles i.e. the tile of `f` behind the dark orange tile of `e`.*

So for entities `e` and `f`, you need to checker whether `f` has a tile within those three diagonals. But since you use rectangular areas, you don't need to check every single tile out of `f` to see if one matches. Indeed note that if for some `k>0`, the tile`(i+k,j+k)` belongs to `f`, then you have a diagonal row of tiles joining `(fi,fj)` to `(i+k,j+k)`. If `f` is on the left of `e`, i.e. if `fi < ei`, that means that the tile `(i+(k-1),j+(k-1)+1)` belongs to `f`. If instead `f` is on the right of `e` (`fi`\>`ei`), then it is the tile `(i+(k-1)+1,j+(k-1))` that must also be part of `f`.

*To reach the purple tile, `f` must pass through the pink one*

In my example, `f` is on the left of `e` and I'll assume that in the calculations. The case of `f` on the right is symmetric. Consider the front line of `f`, starting from `(fi,fj)` and moving along the `x` axis infinitely. If `f` reaches the left-most diagonal of the three diagonals (in light blue), then the intersection tile of that front line and the diagonal must be a tile that belong to `f`. In that case, `f` is behind `e` and you should have `e` sorted before `f`. To check whether `f` reaches the diagonal, compute the distance `d` between the intersection of the lines and compare it the width `w` of the rectangle occupied by `f`.

*Find the pink intersection of the white and blue lines, i.e. the pink tile.*  *Compare the distance `d` between the intersection and the origin of `f` and the width `w` of `f`.*

If `f` is not behind `e`, then either `e` is behind `f` or neither is behind the other. In both these cases, you can safely have `f` sorted before `e`. You just want to stay consistent if you have many entities so that that "is behind" remains a well-defined order relation, so you can use a sorting algorithm.

If you allow-non rectangular area, you may have more trouble, since `e` can be in front of `f` for some parts, and `f` can be in front of `e` for another part. In that case, it's not a bad thing to split your entities into 1x1 tile entities and use you regular algorithm (as Hatoru Hansou described his/her wall)
> 7 votes

# Answer
Brief : This answer suggest to break big sprites into one by one tiles so the zPosition for each sprite which is used to sort them in depth will work correctly.

To understand my proposal you will have to stop thinking in tiles for a while, even if your finished game needs to guarantee that all objects will be tile aligned.

I suggest you to adopt the same design I'm following for my current project. Position your objects in 3D, they have x,y and z. In my case, x is positive to the right; y is positive upwards; z is positive downwards, overlaps y, and when rendering all z values are converted to y of screen coordinates by scaling by 0.5.

To help visualize it: when a character jumps in place, its position.y value changes. When a character walks, its position.x and position.z change.

To sort them at rendering time, you can use the z position alone. If you feel like doing something more complex than that, you can do a Vector3 subtraction and calculate the distance of the object origin to the camera near plane but that implies that your game must be aware of the concept of camera, near and far planes, and other things that are more from the 3D world. Just sorting by z value is enough. In my case z is positive down, so objects with higher z values will be drawn last.

Now, this design alone can achieve correct draw order of any character if you set the objects origin correctly, for characters, the recommended is between the feet, not in the head or in the top-left corner. For walls the origin should be at the down most possible position, not at the top. Your sprites will need an offset property to indicate the translation that should be applied when drawing them as the sprite rectangle center won't be most of the time at the same position that the character/entity/object origin.

Diagonal walls still suppose a problem. I handle it by dividing the diagonal walls in smaller parts, in your case these parts will have the width of a tile, each part having it own origin.

---

Some images to illustrate these concepts.

In the following image, the green circles represent objects origins.

How to build a wall? The ideal solution (in terms of design time needed to implement) is to have a unique wall tile and build walls using adjacent wall sprites. But I admit this is only possible if the wall assets are authored to be used this way. As I'm using a solid gray wall in this example gif, for me this was super easy to implement, but depending of the complexity of your walls assets, you may have problems with this. If you cannot get to solve it using only a single wall tile for each type of wall you will have to have more tan one asset for each wall type, this is OK and unavoidable in some cases.

My wall tile looks like this:

A longer wall is constructed by positioning many sprites, one per tile, all referring to the same image asset. Look at the origins of the first image, as the z position is used to decide how sprites are ordering at rendering, the result looks as intended.

Again, in my case the Z position is parallel to the Y axis, my Z is not diagonal, but if you prefer the Z to be diagonal, you can easily do that but you will have to think for a while in the required formula to go from 3D simulation space to 2D screen coordinates. To avoid having to do that is that I decided to make the Z axis parallel to the Y axis.

What I mean with objects origins? The origin is a concept borrowed from 3D engines. Sprites x, y coordinates are in screen coordinates, and they are relative to the object 3D coordinates when converted to screen coordinates during rendering. You first convert to screen coordinates the objects origins, then you look at your sprites x and y coordinates and apply a translation to draw the sprite in the correct position.
> 5 votes

---
Tags: 2d, tiles, isometric, draw-order, sorting
---


# Question
Title: Why does a UI button that is child to a canvas not appear in game view?
I am trying to place a button onto a canvas background using C# script. I want the button specific to the canvas (i.e., if I move the camera to look at another canvas, I do not want the button visible).

My C# script is below. I have attached it to an empty game object. When I run the game, the Heirarchy panel of Unity shows that the canvas and button are created OK, and that
the button is a child of the canvas. The canvas appears in game view at the right size (200 x 200).

But in game view, there is no button!

The button is definitely present ; clicking on its name the Heirarchy panel shows me a location and size in the scene view that are exactly as specified in my C# script. But nothing happens when I click the region in game view where the button is supposedly present.

Unity's Inspector panel shows that a "Button (Script)" has been attached to my button object, with Rect Transform parameters as specified in my C# code. I tried messing with the colors, but still no button. The "On Click()" window contains nothing except the message "List is Empty".

How do I make the button appear in game view?

How do I make the button work (i.e., generate the Console message "button pressed")?

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

public class TestScript : MonoBehaviour {

private GameObject myGO;
private Vector2 buttonSize;
private Vector3 buttonPosition;

void Start () {
// setup a canvas
    myGO = new GameObject ();
    Canvas myCanvas = myGO.GetComponent<Canvas> ();
    myCanvas.renderMode = RenderMode.WorldSpace;
    RectTransform parentRectTransform = myGO.GetComponent<RectTransform> ();
    parentRectTransform.sizeDelta = new Vector2 (200, 200); // set size of parent rectangle

// create and place the button
    Vector2 buttonSize = new Vector2 (10, 10);
    Vector3 buttonPosition = new Vector3 (150, -70, 1);

    CreateButton (myGO.transform, buttonPosition, buttonSize);
}  // end Start()

public void CreateButton(Transform panel ,Vector3 position, Vector2 size)
{
    GameObject button = new GameObject();
    button.name = "Button";
    button.transform.parent = panel;
    button.AddComponent<RectTransform>();
    button.AddComponent<Button>().onClick.AddListener (handleButton);
    button.transform.position = position;
}

void handleButton() {
    Debug.Log("Button pressed!");
}

} //  end class TestScript

```

# Answer
As you have already fixed the positioning problem, I'll only address the second question about the button, which appears to not function at all.

First of all, I really recommend to set this up via the inspector, it's a pain to set it up manually in a script, but here we go:

In `CreateButton(...)`, you add another `Canvas` component to your game object. Delete the following line as you already have a canvas.

```
button.AddComponent<Canvas>();

```

Your script does not create an `EventSystem` and also no `InputModule` (such as the ones shipped with Unity, `StandaloneInputModule` and `TouchInputModule`. Adding a Behaviour that inherits from `BaseInputModule` will automatically add an EventSystem component, if it doesn't exist yet. Add the following, it's probably the best if you do so before you start to build up the canvas.

```
GameObject eventSystem = new GameObject("EventSystem");
eventSystem.AddComponent<StandaloneInputModule>();

```

Last but not least, you also need a `GraphicRaycaster` component. Add this line when you added your canvas component.

```
myGO.AddComponent<GraphicRaycaster>();

```

Now you're be ready to go - so far. But i still really, really recommend to set this up via the inspector.

A small but useful tip: `AddComponent<...>` also returns the component. Use the returned reference to avoid unnecessary `GetComponent<...>` calls. Instead of

```
myGO.AddComponent<Canvas>();
Canvas myCanvas = myGO.GetComponent<Canvas>();

```

you can simply write

```
Canvas myCanvas = myGO.AddComponent<Canvas>();

```

You avoid searching for the component then as the method does not need to look it up.
> 1 votes

# Answer
The Canvas co-ordinate system is a bit different. The origin is at the centre of the canvas. And the size of the canvas gets divided evenly with respect to the origin.

So in your case the canvas width is 200 , so the left extreme co-ordinate becomes 100. Your button position is 150 which exceeds 100 hence it doesn't lie inside the canvas.
> 1 votes

# Answer
OK, here is the exact code I am using, including stuff that might not be relevant to the problem. I tested it first and then just pasted it all straight in. For me, it creates a canvas with text, and a button right in the middle. But the button does not function.

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

public class TestScript : MonoBehaviour {

private GameObject myGO, childGO;
private Vector2 buttonSize;
private Vector3 buttonPosition;

void Start () {
    // set up the camera
    Camera.main.orthographicSize = 200f;
    Camera.main.transform.position = new  Vector3 (100f, 0f, -10f);

    // create game object and name it child object
    myGO = new GameObject ("Page 1"); // create game object and name it
    myGO.AddComponent<Canvas> (); // add a canvas to the parent
    RectTransform parentRectTransform = myGO.GetComponent<RectTransform> ();
    parentRectTransform.sizeDelta = new Vector2 (200, 200); // set size of parent rectangle

    // set up a parent canvas
    Canvas myCanvas = myGO.GetComponent<Canvas> ();
    myCanvas.renderMode = RenderMode.WorldSpace;
    Sprite mySprite = Resources.Load<Sprite> ("images/parchment 2"); //Get a sprite
    myGO.AddComponent<Image> ().sprite = mySprite; //Assign The Sprite

    // set up child object
    // set child anchors for resizing behaviour
    // make a reference to the child rect transform and set its values
    childGO = new GameObject ("Text"); // create child object and name it
    childGO.transform.parent = myGO.transform; // set the child object as a child of the parent
    childGO.AddComponent<RectTransform> (); // add a recttransform to the child
    RectTransform childRectTransform = childGO.GetComponent<RectTransform> ();
    childRectTransform.anchoredPosition3D = new Vector3 (0f, 0f, 0f);
    childRectTransform.sizeDelta = new Vector2 (0f, 0f);
    childRectTransform.anchorMin = new Vector2 (0f, 0f);
    childRectTransform.anchorMax = new Vector2 (1f, 1f);

    // set text font type and material at runtime from font stored in Resources folder
    childGO.AddComponent<Text> ();
    Text textComponent = childGO.GetComponent<Text> ();
    textComponent.text = "Hello \n World"; // set the font text
    Font myFont = Resources.Load<Font> ("fonts/Open_Sans/OpenSans-Bold");
    textComponent.font = myFont;
    textComponent.fontSize = 50;

    // Add button
    Vector2 buttonSize = new Vector2 (50, 50);
    Vector3 buttonPosition = new Vector3 (0, 0, 0);
    CreateButton (myCanvas.transform, buttonPosition, buttonSize);

}  // end Start()

public  void  CreateButton(Transform panel ,Vector3 position, Vector2 size)
{
    GameObject button = new GameObject("Button");
    button.transform.SetParent(panel, false);
    button.transform.position = position;
    button.AddComponent<Canvas> ();
    button.AddComponent<Image> ();
    button.AddComponent<Button>();
    button.GetComponent<Button>().onClick.RemoveAllListeners();
    button.GetComponent<Button>().onClick.AddListener (handleButton);

}
void handleButton() {
    Debug.Log("Button pressed!");
}

} //  end class TestScript

```

The "images/parchment 2" is a jpeg image in a "images" subfolder of the "Resources" folder.
> 0 votes

---
Tags: unity, c#, gui, ui-design
---


# Question
Title: Binding and unbinding, what would you do?
Let's assume the following example

creation:

```
glBindVertexArray(vao)
   glBindBuffer(GL_ARRAY_BUFFER, vbo)
   glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indices)

   // Filling up buffers

   glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0)
   glBindBuffer(GL_ARRAY_BUFFER, 0)

glBindVertexArray(0) // Unbinding vertex array

```

This looks great from a code-beauty perspective. Each bind-unbind-pair is like parenthesis, so `{[()]}` (I am also actually using these indentions)

But it also results in a more code for rendering, because the buffers are unbound in the vao, they need to be rebound during rendering, which kind of defeats the purpose of a vao which represents a certain state you can just use whenever you need to.

Rendering would need to look like:

```
glBindVertexArray(vao)
    glBindBuffer(GL_ARRAY_BUFFER, vbo)
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indices)
        // Do your drawing
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0)
    glBindBuffer(GL_ARRAY_BUFFER, 0)
glBindVertexArray(0)

```

so it would be better to

```
glBindVertexArray(vao)
   glBindBuffer(GL_ARRAY_BUFFER, vbo)
   glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indices)

   // Filling up buffers

glBindVertexArray(0) // Unbinding vertex array
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0)
glBindBuffer(GL_ARRAY_BUFFER, 0)

```

Just to make sure the buffers are not bound for another write or anything. Code-wise this looks kind of ugly.

But rendering then is just

```
glBindVertexArray(vao)
 // Do your drawing
glBindVertexArray(0)

```

Regarding the cost, the second one uses less (un)bindings, but also it could happen that the vao is already unbound (during rendering) but the vbo and element-buffer is not, so one could write messy data in there.

Am I missing something? Which way is more error-prone? Are the costs for un/binding neglect-able and is the beauty of code worth it?

# Answer
> 8 votes
The `GL_ELEMENT_ARRAY_BUFFER` binding is part of the VAO state so it should not be unbound. The `GL_ARRAY_BUFFER` binding *isn't* so it doesn't matter whether it is unbound or rebound.

If you use DSA it's more explicit.

```
glVertexArrayElementBuffer(vao, indices);
glVertexArrayVertexAttribOffset(vao, vbo, 1, 4, GL_FLOAT, false, sizeof(Vertex), offsetof(Vertex, pos));

```

It's more efficient to not unbind the buffer as it's an extra call that will get undone later.

Code beauty is not worth the penalty of rebinding the element buffer in your main render loop.

---
Tags: opengl
---


# Question
Title: How to handle "game missions/flights" across the world map
Sorry if my title is a little vague, I wasn't entirely certain how to word this specific question.

I'm developing a small little MMORTS game, and in this game is the world map which consists of thousands of tiles (the view on the client is an isometric grid). The world map data is stored in a MySQL database table. This table stores each individual tile and the tile data. So when the player visits the world map screen, the server will load a chunk (12x12) of the world map at a time for the client to render.

Now, it's come to the point where I need to allow players to send planes from their cities that are on the world map, to other tiles around the world map. For instance, a player that owns **City 1**, which is located on tile **100,100**, wants to send a plane to an **oil well** on tile **60,60**.

How can I show the movement of that plane from the city -\> destination in real time across all clients in the most efficient manner? Let's assume each game server can have hundreds of players, so we can expect thousands of flights across the world map at a time.

When a flight is created, it would be stored in the database with data such as `destination_x`, `destination_y`, `origin_x`, `origin_y`, `flight_speed`.

And when a client loads a chunk of the world map at whatever coordinates, I can query the database on each chunk load to see if any flights are currently crossing this chunk. However, how can I do this? With the data I just mentioned that would be stored for a flight, how could I determine if a flight is currently in a given chunk? Let's assume a chunk is 12x12 tiles.

How should I go about doing this, and is my current thought-out method the most efficient approach to this problem?

~~~~~~~~~~~~

If context helps, here is a picture of the world map:

I would like for flights to show up across this world map as they are heading to a destination from a given origin. The plane should only load if it's crossing this viewed chunk by the client.

~~~~~~~~~~~

I apologize if this question is still too vague, I tried my best to explain my current situation and problem. If you have any questions, please ask. Thanks!

# Answer
> 1 votes
This should be similar to all movement in that it can be described by location, a point, and velocity, a vector. It is reasonable to assume that the flight takes a predetermined amount of time in seconds or ticks. You can calculate the velocity based on the distance and time of flight. Unfortunately this exchange does not have latex implemented so this might look a bit rough.

Plane is to travel a distance d in a given number of seconds t from point p1 to point p2 where d = \sqrt( (p2\_x - p1\_x)^2 + (p2\_y - p1\_y)^2 ).

Let us define the number of seconds per tick as q, then the number of ticks required for the flight is c = t/q.

Now we need to determine the velocity vector v, we want the slope from p1 to p2, and the magnitude from distance divided by the flight time.

First we create a unit vector pointing from p1 to p2. u = \frac{1}{d} (p2 - p1)

Then we scale the unit vector by d/c. v = \frac{d}{c} u

The planes position at any given tick (during the flight) is p = p1 + number\_of\_ticks\_in\_air * v

# Answer
> 0 votes
Using these variables

```
float elapsedTime
float totalFlightTime
float incrementTime
int numTiles

```

ElapsedTime is the current position in time and should be advanced with delta time every frame.

TotalFlightTime is the total amount of time the flight should take.

NumTiles is the total number of tiles needed to advanced to the next city.

Now set incrementTime = totalFlightTime / numTiles to get equal parts of totalFlightTime.

Then use

```
if(elapsedTime > incrementTime)
{
    // Advanced plane one tile
    elapsedTime = 0; // Reset elapsedTime
}

```

# Answer
> 0 votes
One cheaty way to do this (means the planes would not be able to be shot down etc.) is to simple store the time the plane started its journey, start and end points. You can then draw this on the client side by simply drawing a line from start point to end point and calculating how far along this line the plane should be.

In terms of finding which flights should be in a given chunk you can use the line co-ordinates against the chunk co-ordinates to see if a user might require that flight.

---
Tags: html5, node.js
---


# Question
Title: Making a text only console game in C#. Can't figure out a way to organize states
When I say states I mean like what you would call scenes in unity. As in each phase of the game. But in straight up code for a console application in C#.

Example: Name select. Race Select. Store. Help Screen.

I've tried organizing each phase by methods, and while loops, but i've run into a lot of trouble these ways. How should I do it?

# Answer
> 6 votes
Take a look at the *game state* pattern.

The basic idea is that you have a class for every state. All classes inherit a interface that ensures basic functionality like entering the state, leaving the state, updating and rendering. Each specific state implementation holds (or has references to) all necessary resources and performs what you want to do. At some point in your program you keep the current state and provide methods for changing it, which are accessible by all states. Depending on your use-case you might want to have multiple states active, but for starters a single one is usually sufficient.

You can find a good in-depth explanation on this blog entry, but searches for "game state" will bring up many good results.

---
Tags: c#, text-based
---


# Question
Title: Direct3D - Get screen coordinates for printing multiple text elements
I have a function that I use to print text `PrintText(char* text)` that stores the text to a vector, which is then displayed if the vector is not empty. I'm trying to figure out how can I correctly print multiple char\* to the screen, one under the next?

For example:
This is line one.
This is line two.

Both of those are stored in separate char\* elements in the vector. How can I use Direct3D or C++ to correctly display consecutive char\* elements as it is in the above example? As in getting the correct screen coordinates to display the next element?

Code:

```
void DrawString(char* String, int x, int y, int r, int g, int b, ID3DXFont* ifont)
{
    RECT ShadowPos;
    ShadowPos.left = x + 1;
    ShadowPos.top = y + 1;
    RECT FontPos;
    FontPos.left = x;
    FontPos.top = y;
    ifont->DrawTextA(0, String, strlen(String), &ShadowPos, DT_NOCLIP, D3DCOLOR_ARGB(255, r / 3, g / 3, b / 3));
    ifont->DrawTextA(0, String, strlen(String), &FontPos, DT_NOCLIP, D3DCOLOR_ARGB(255, r, g, b));
}

```

# Answer
> 1 votes
According to the docs for `DrawTextA`, *"the return value is the height of the text in logical units"*. So you should modify your `DrawString` function to return this value (plus one, since you draw the shadow one pixel lower). You'd then offset the calling function's `y`-coordinate by the returned value, plus whatever padding you want. So something like this:

```
void DrawString(char* String, int x, int y, int r, int g, int b, ID3DXFont* ifont)
{
    RECT ShadowPos;
    ShadowPos.left = x + 1;
    ShadowPos.top = y + 1;
    RECT FontPos;
    FontPos.left = x;
    FontPos.top = y;
    ifont->DrawTextA(0, String, strlen(String), &ShadowPos, DT_NOCLIP, D3DCOLOR_ARGB(255, r / 3, g / 3, b / 3));
    int h = ifont->DrawTextA(0, String, strlen(String), &FontPos, DT_NOCLIP, D3DCOLOR_ARGB(255, r, g, b));
    return h + 1;
}

...

int y = 0, h = 0, padding = 4;
for(auto& s : vStrings)
{
    h = DrawString(s.c_str(), 0, y, ...);
    y += h + padding;
}

```

---
Tags: directx, vector, screen, text
---


# Question
Title: How much to roll Z to make horizon level
I've got a flying camera with some arbitrary rotation. (It also has a translation, but that's not important.) It's flying along its local Z axis, traveling in some direction over the ground with some rate of climb or descent.

I'd like to gently correct it so the horizon is level. Or, equivalently, I'd like to apply rotation around camera's pointing direction (Z) until it's up-vector (Y) is as up as it can be.

That is, I want my camera X and camera Y to adjust, leaving camera Z (forward) exactly the same.

The rotation is represented as a 3x3 matrix. Quaternion solution would be fine, also...

How much do I need to rotate it to get the horizon level?

Any help appreciated!

Edit: I'm currently in c++.

Edit2: Here's a picture further clarifying... I need to rotate in the local XY plane, the grey disk, til X touches the ground plane, Y is up-ish, and Z is unchanged... which sort of suggests an approach...

# Answer
I found a way that worked. But I'll leave question open a little longer if anyone has a more, I don't know, mathematically clear approach...

From the picture above, cast the tip of red Camera-X downwards along green Camera-Y's direction til it hits the ground plane. (This is a point in the plane of the grey disc.) Then do a dot product between *that* and the Camera-X.

```
MeVec3 cameraXVector = this->cameraMatrix.column(0);
MeVec3 cameraYVector = this->cameraMatrix.column(1);

float t = cameraXVector.y / cameraYVector.y;
MeVec3 planePoint = cameraXVector - t * cameraYVector;
float thetaDot = cameraXVector.normalize().dot(planePoint.normalize());

// sometimes got 1.003 or -1.0002 from FP error, so...
thetaDot = pinRangeF(thetaDot, -1, +1);

float theta = acosf(thetaDot);
if(t > 0)
    theta = -theta;

```

Theta is then applied (gradually) as a local Z rotation to the camera.

Further, the same arithmetic can be used to orient against other planes (XY, YZ, or ZX) by changing how t is computed...

```
float t = cameraXVector[upAxis] / cameraYVector[upAxis];

```
> 0 votes

# Answer
You would need to know the angle between your camera's up vector and the global up vector. Since you didn't specify what language you're using, I won't provide code. But there should be a function like math.atan2 (that's what it's called in xna) to get the angle between a vector and the x axis. It can easily be used to calculate the angle between two vectors. When you have the angle, rotate your camera in the correct direction just a little bit each frame. Also, if the angle is smaller than 0.001 or something, you might want to snap your cam in place. Otherwise it may end up overrotating and keep shaking around the correct rotation.

Edit: what I forgot to mention is that in xna, which I use, the atan2 function returns a value between -pi and pi. This is critical since you need to know which way to rotate.
> 1 votes

# Answer
calculate the angle between your "up vector" `v1` and "world up vector" `v2=(0,1,0)`

Normalize `v1`.

So, if `v1` and `v2` are normalised so that `|v1|=|v2|=1`, then,

```
angle = acos(v1•v2)

```

where :

• = 'dot' product.

acos = arc cos = inverse of cosine function.
> 1 votes

---
Tags: mathematics, rotation, matrix, quaternion
---


# Question
Title: In GameMaker Studio, how can I make an auto-updater for my game?
I would like to let players update their copy of my game by clicking a button, which would:

1. Check for updates
2. Download the update
3. Prompt the user to restart the game

I want to do this because my friends hate to re-download my game each time I make a change.

Is this possible with GameMaker? If so, how?

I have Dropbox premium, could I take advantage of that?

# Answer
I have tried to make an update system for my game, and this is how far I got.

First, connect to my server, and download an .ini file containing the name of the newest version of the game:

`http_get_file("http://mywebsite.com/game/Versions.ini", working_directory + "/Versions.ini");`

The first part tells Gamemaker where to find the file online, and the last part tells it where to save it locally.

Now, you have to test if the file was actually downloaded:

`if file_exists("Versions.ini") {`

I’m not sure of this function is optimal for larger downloads, because I don’t know if the file exists before the download is complete, but for small downloads like this very small text file, I haven’t found any issues yet.

If it the file was downloaded, read the file:

`ini_open("Versions.ini");
global.NewestVersion = ini_read_string("Versions","Newest","ERROR");
ini_close();
}`

First the file is opened, then the string `global.NewestVersion` is set to the value that is in block “Versions” called “Newest”. And if that value doesn’t exist, set the string to `ERROR`. And then the file is closed.

By the way, the .ini file should look like this to work with the code:

`[Versions]
Newest=”1.0”`

This one will say that the newest version is version 1.0

Anyway, as soon as you have the `global.NewestVersion`, you just have to compare it to a string in the game, that tells the game what version it currently is. I usually do that by creating an object without sprites, that makes a new string called `global.CurrentVersion` when the game starts.

If the strings match, do nothing.

If `global.NewestVersion` is equal to “ERROR”, inform the user that there was an error.

If none of these things are true, start downloading the new installer, and when it’s done, execute the installer, and close the game right after executing.

Now the installer can install the new game, and everybody’s happy.

Unfortunately, I couldn’t make the last part work, because when I used the same method for downloading the .exe as I used for downloading the .ini, the .exe ended up being “damaged”.

So I figured what the heck, and instead I made my game open a website, where it said “there is a new update”, and then you could click on a link to download the update. In that way, I let the browser deal with downloading the executable, and then everything works fine!

If anybody knows how I can download an executable without damaging it, I’m all ears.

Ps. If you want to have data about how the download is going, you can store the download progress in a string, like this:

`STRING = http_get_file("http://mywebsite.com/game/Versions.ini", working_directory + "/Versions.ini");`

Now you can use a function that looks something like this to get info about how far the download is, and If there were any errors:

`ds_map_(async_load, “WHAT YOU WANT TO KNOW ABOUT”);`

But unfortunately, this never worked for me either.
> 1 votes

# Answer
I'm not sure it would be possible to do that without a "launcher" type application like Minecraft or the Battle.net app. You could most likely get the update itself easily enough, and close the game upon retrieving it, but I'm not sure how you would restart the .exe without an additional program triggering that. At any rate, here's how I'd do it:

1. On launch of the game (or the launcher) use Game Maker's networking feature to hit a page on a server which returns the current version number.
2. If your version # matches what the page said, then you're good, but if not then use the same Game Maker networking functions to grab an exe off the same server (doesn't have to be an exe, could be updated .dlls, art files, etc...).
3. Upon receipt of the file, have Game Maker replace the .exe from before with the one you just downloaded and then close the game.
4. At this point a launcher would have to control the re-opening of the game.
> 0 votes

# Answer
Maybe WinSparkle could work somehow? http://winsparkle.org "WinSparkle is an easy-to-use software update library for Windows developers. It's Open Source, available under the permissive MIT license."
> -3 votes

---
Tags: game-maker, user-experience, deployment, patching
---


title: Is Frustum culling still needed today?

text:
# Question
Title: Is Frustum culling still needed today?
I'm reading about efficient Frustum culling algorithms. I found an article about a smart method that first use the Frustum AABB (Axis Aligned Bounding Box) to eliminate most of the scene before check again against the actual frustum representing the camera.

I didn't do any performance test yet, but maybe somebody else did and can answer this question.

Let's say I'm using an Octree to quickly check again the camera bounding box. But I do not want to do a second pass again the camera planes. If I simply render everything so far, isn't that actually faster than do the second pass?

Assume object geometry is loaded into VRAM using hardware vertex buffers.

# Answer
> 5 votes
Yes. There are times when it is needed still. Its really situational and depends on the details of your game and the other data structures you have in place. (And resolution of your Octtree and such)

It's just a another tool in the toolbox but is definitely still used commonly.

Just like you wouldn't hammer a screw in or hammer the ground for no reason, you should use it when it's useful, and don't use it when it's not (:

---
Tags: opengl, performance, culling, frustum, octree
---


# Question
Title: Problem with grid generation in Unity 5.1
Using Unity 5.1 and was following a tutorial for generating a grid for a Minesweeper-style game. Link to the tutorial for reference: http://gamedevelopment.tutsplus.com/tutorials/build-a-grid-based-puzzle-game-like-minesweeper-in-unity-setup--cms-21361

Tutorial is Unity 4, but I don't think it should matter.

Here's my code:

```
public GameObject tilePrefab;
public int numOfTiles = 10;
public float distanceBetweenTiles = 1f;

void Start () {
    CreateTiles();
}

void CreateTiles () {
    float xOffset = 0f;

    for (int tilesCreated = 0; tilesCreated < numOfTiles; tilesCreated++) {
        Vector3 positionVar = new Vector3(transform.position.x + xOffset, transform.position.y, transform.position.z);
        xOffset += distanceBetweenTiles;
        Instantiate(tilePrefab, positionVar, transform.rotation);
    }
}

```

Essentially, the problem is that when I coded the spacing algorithm, Unity decided to ignore the spacing of 1f, but instead do 10,000. No matter the number I substitute for "distanceBetweenTiles", Unity spaces the cubes by 10,000 points. I'm assuming it has to do with how Unity is handling the float numbers, but I'm not quite sure, considering the number I substitute doesn't seem to matter. I've included a screenshot of Unity running the script and the inspector view of the giant X position. Thanks so much in advance\]

# Answer
> 1 votes
Check the script in the inspector (click on the object that holds it). Looks like you changed the value there, which will override the default value due to how Unity's serialization system works. Thus, the default value specified in the script will be ignored.

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


# Question
Title: Why does Unity not detect my camera attached via the inspector?
I want to use `camera.ViewportToWorldPoint()` to show the **bottom center** bounds of my screen. So, I created a script and added that component to my object that needs it.

```
using UnityEngine;
using System.Collections;

public class PathMovement : MonoBehaviour {

    public Camera cam;
    private Vector3 bound;

    void Awake () {
        cam = GetComponent<Camera> ();
    }

    void Start(){
        bound = cam.ViewportToWorldPoint (new Vector3 (0f, 0.5f));
        Debug.Log (bound);
    }
}

```

and then, I attach the `MainCamera` via the GUI

And then, when I run it, there's still an error says:

> MissingComponentException: There is no 'Camera' attached to the "RiverPath" game object, but a \>script is trying to access it. You probably need to add a Camera to the game object "RiverPath". Or your script needs to check if \>the component is attached before using it. UnityEngine.Camera.ViewportToWorldPoint (Vector3 position) (at C:/buildslave/unity/build/artifacts/generated/common/runtime/UnityEngineCamera.gen.cs:408) PathMovement.Start () (at Assets/Scripts/PathMovement.cs:21)

This is quite weird since I've attached the main camera, but somehow unity didn't detect that. I also have tried to put the `cam = GetComponent<Camera>();` on `Awake()` as well as `Start()`, but none work. :(

This is an Android app, using Unity 5.

How do I do this correctly?

# Answer
> 3 votes
i think `cam = GetComponent<Camera> ();`

is useless and wrong as you already assigned cam in the ispector.

---
Tags: camera, unity, viewport
---


title: Cross-Platform Audio API Suggestions

text:
# Question
Title: Cross-Platform Audio API Suggestions
I'm currently looking into adding sound to my game. I have seen OpenAL and SDL, but I would like to know what else is out there. Can you recommend any good cross-platform Audio APIs for game development?

# Answer
Stack Overflow question: "Cross platform sound API for games?"

I agree with the accepted answer:

> I'm a big fan of SFML Library. It does provide additional Graphic and Network features, but what is relevant to this question, is that it also has neat Audio package.
>
> Audio features are:
>
> * Uses hardware acceleration whenever possible
> * Can load and save standard sound formats : ogg, wav, flac, aiff, au, raw, paf, svx, nist, voc, ircam, w64, mat4, mat5 pvf, htk, sds, avr, sd2, caf, wve, mpc2k, rf64
> * Can load all audio resources directly from files in memory
> * 3D sound spacialization
> * Easy interface for capturing audio
> * Manages memory efficiently, so that you don't have to worry about resources lifetime or storage
> * Supports streaming for big files ; you can even write your custom streaming class for any source (network, ...)
> * Supports multi-channels formats (mono, stereo, 4.0, 5.1, 6.1, 7.1)
>
> Website: http://www.sfml-dev.org/
> 13 votes

# Answer
The sort of de-facto API for sound implementation in games these days as far as I'm concerned is FMOD.

It's free for non-commericial uses, and relatively inexpensive for "casual" (read: indie) development.

It is a bit overkill for the simple "play back this sound" requirement, but does provide a huge feature set that's well tested on all sorts of platforms.
> 10 votes

# Answer
### OpenAL

I really like OpenAL as a cross-platform audio library. The API is a bit low level but you can easily wrap it into a nicer engine friendly interface. It's truly cross platform with first class support for: iPhone, Android, MacOSX, Windows, and Linux.

Take a look at Djinn Engine sound code. Two files, maybe 300 lines between them (counting comments etc) and you'vd got a workable sound system.

I've never build an audio centric game, so OpenAL might not fit the bill if extreme control is needed.
> 9 votes

# Answer
If FMOD isn't an option then Audiere is a good open source alternative. It hasn't been updated in a long time but it's cross platform, easy to use, and has a good feature set.
> 5 votes

# Answer
Additionally to FMOD, there is Audiokinetic Wwise, which is more and more used in the game industry as a professional cross-platform sound design tool and API. It has a large selection of effects (including convolution reverb), complex sound logic system, sound layering, profiling, interactive music tools, etc... It provides a good selection of decoding algorithms and is also free for non-commercial projects.
> 4 votes

# Answer
The Kowalski engine is a data driven cross platform audio library released under the zlib license.
> 3 votes

# Answer
As you're just curious about other stuff out there, I don't see any mention of Miles on here yet. I've not used it myself (although we did use it many years ago on a game), however these games use it.
> 0 votes

# Answer
libsoundio is low level, but it is cross platform and focuses on robustness. It's a minimal layer between your game and the audio backend of the system.
> 0 votes

---
Tags: assets, sound
---


# Question
Title: pivot of a 3d model outside its mesh after importing into Unity3d
as you can see, the pivot is outside my mesh. I want to use the pivot for rotating around, for that I need to set the pivot to the real "rotating point". I know that there's the SetPivot script, but it only works with pivots inside meshes.

This mesh is part of an object which contains several meshes, I created it with Wings3d. The problem appears with .obj and .3ds as file extension.

1.How can I fix this?

2.Is there a possibility to define a second pivot which can be used in scripts to "rotate around"(maybe a vector3 which can be set in "Designer")?

# Answer
> 2 votes
You can try switching it in unity interface from pivot to center.

or you could create an empty game object and make your model a child of it and then change the position of your model that is parented to the empty game object, this will make your empty game object the pivot of your model. Hope this helps.

# Answer
> 0 votes
You could fix it some hackish way in Unity, by wrapping with a parent Transform, but the root of the problem is with the model. If you can't fix it with Wings, run it through Blender or something before importing.

# Answer
> 0 votes
You may fix this in Blender, maybe you can fix it up in Unity but I dont know that

Here it is the steps to fix it in Blender:

Open your model with Blender Select your mesh object and press Shift S to set the Z Cursur on the. center of your mesh and change pivot point from left panel by seting the Origin, if you can not see the panel press Shift T.

Export your mesh again possibly to an Obj or anything you like.

---
Tags: unity
---


# Question
Title: How to make my 2D character stand normally on slope?
I've got this character in Unity3D (2D Mode)... in a a slope which looks like this,

But I want the character to stand along the red line..Like below

How can I make it in Unity3d?

I've got this setup..

I'm using simple Addforce for movement... If I remove the z position constraint it results in weird movement like rolling and so on.... Any help would be appreciated :)

# Answer
Have you considered that it looks very odd for a person to standing perpendicular to a slope?

You need to be upright to stay in balance.

---

Some alternatives:

* Treat his feet as a separate object and rotate them to be parallel to the slope. (A raycast will find the angle's normal, as dnk described. The angle for the feet is *that + 90°*.)
* Fake it, by moving the whole character a little downwards.
> 26 votes

# Answer
Try using RaycastHit.normal on ground to get normal. Them put char.up = normal
> 2 votes

---
Tags: 2d, physics, unity, rotation, procedural
---


# Question
Title: How do I make a sine wave without using an infinitely-increasing time value as input?
I have a basic understanding of sine wave generation. The problem I am facing is that as the input parameter for time gets larger, my sine wave falls apart and starts to look really ugly.

I'd like to calculate a sine wave without depending on an ever increasing time value. How can I do this?

# Answer
> 8 votes
You could restart your time value every 2pi:

```
if(time > 2*pi)
  time -= 2*pi;

```

If is still okay to increase your time variable infinitely but the input for the sine is to large, just use `fmod(time, 2*pi)`.

---
Tags: c++, trigonometry, timestep
---


# Question
Title: Why does Forge not find my texture for my custom background?
I am creating a minecraft mod that improves the main menu for my minecraft server. At first I wanted to create the background, but somehow when I try to start minecraft it closes and I get a nullpointerexception because minecraft didn't find my background.

```
public class ThundrialMenu extends GuiScreen {

    @Override
    public void initGui() {

    }

    @Override
    public void drawScreen(int mouseX, int mouseY, float partialTicks) {
        Random rnd = new Random();
        int background = rnd.nextInt(3)+1;
        String backgroundLocation = "/assets/thundrial/gui/Background"+background+".png";
        this.drawBackground(mc.renderEngine.getTexture(new ResourceLocation(backgroundLocation)).getGlTextureId());
        super.drawScreen(mouseX, mouseY, partialTicks);
    }

    @Override
    public void updateScreen() {
        super.updateScreen();
    }
}

```

This is the folder where the pictures are located:

Why does Minecraft not find those pictures?

# Answer
Firstly, the correct way to create a resource location is as so:

```
new ResourceLocation("thundrial", "gui/Background" + background + ".png");

```

The first parameter of ResourceLocation is your Mod-ID/assets directory. From your image I can see this is "thundrial". This should find your assets correctly. The second parameter is the path from `"assets/thundrial/"` to your image.

My second point is, what you're doing wont render your background image. The method `drawBackground(i)` is used by MC to draw the default options menu and not your own custom background. The `i` parameter is a UV value, not an image id.

For as far as I know the easiest and most simplistic way to do what you're doing is to render over the background by using the bind method: `mc.renderEngine.bindTexture(location)` and then using the gui's `drawTexturedModalRect(x, y, u, v, w, h)` to draw the image over the top.
> 2 votes

---
Tags: gui, minecraft-modding
---


# Question
Title: How can I handle position in an entity system where position can be 2D or 3D?
I'm working on a game engine to learn how it's done (so I might better take advantage of the techniques involved and other, similar engines in the future), and I've run into a problem when handling position when it should be able to be either 2D or 3D.

Since the physics updating the position must also affect the rendering of the graphical components' positions, I need to hold the position of the entity itself separately. Since it is used by most systems anyway, it is fine to break the purity of the design for this bit.

However, I can't decide a default position component type as the engine is meant to have both 2D and 3D capabilities. I know Unity has both 2D and 3D systems and uses a similar Entity-Component system, and there may be other engines that have a similar setup. How is it determined what type of position component to use in those systems? Or rather, what would be the best way to handle this sort of conflict (in terms of simplicity and memory)?

I'm using C++ with a little bit of inheritance with the components, where every component has an `update` method that is defined per component that does any sort of batching or default updating behavior (e.g. the `SpriteComponent` class's `update` will send the necessary data to the `SpriteBatcher`). However, the `Entity` class simply stores them all in a `std::unordered_map<std::string, Component*>` and iterates through them, calling their `update` methods.

**Edit:** I should mention I'm using GLM for my vector types, mostly out of convenience and to keep everything consistent with OpenGL (which I'm using for rendering). Since some functions are defined for 2D but not 3D and vice versa, I can't just use a 3D vector for 2D operations without constructing a new, temporary 2D vector from the 3D vector, which is inconvenient for various reasons (memory usage, construction time, not saving state correctly or having to convert data to save state, etc).

# Answer
**Use a 3D vector**. For your 2D components, simply ignore the third component.

The extra "cost" of an unused `float` is trivial in comparison to the rest of your architecture, and things like `std::unordered_map<std::string, Component*>` are of far greater performance and memory concern than an occasionally-unused `float` anyway.

---

You say that this would be

> inconvenient for various reasons (memory usage, construction time, not saving state correctly or having to convert data to save state, etc).

That's largely irrelevant.

The memory impact of the temporary 2D vectors is transient, on the stack (in almost all reasonable cases) and easily budgeted for since it exists only for the duration of a single update (thus the upper limit is some constant times your concurrent object update limit). Plus, the impact is going to be *small*. If you cared about memory footprint that much you wouldn't be using the memory-guzzling `std::unordered_map` with `std::string` keys.

The conversion, being transient, should have no impact on state saving. You can easily disregarding the ignoring component during state serialization if you can know enough about the object to at that time to know it's only using two of the three components, also. The performance impact of having to convert from a three- to two-component vector during any kind of serialization is likely to be dwarfed by the IO overhead, so that shouldn't matter.

The performance cost of the conversion at runtime for the actual use of the 2D-only math functions pales in comparison to the performance cost of the hashing of the string keys you'll need to be doing just to fetch the object, and likely to the cache-miss-thrashing you are incurring by using what appears to be a "for each entity, for each component, update" style of loop with a cache-inefficient data structure.
> 7 votes

# Answer
I see two possible solutions.

One, is to use a 3D Vector even in a 2D space, and keep one of the coordinates fixed to the same number.

Another one, is to create two different classes, *Vector2* and *Vector3*, both inheriting from a base *Vector* class, and make your systems work with this *Vector* class directly, looping trough its components.
> -1 votes

# Answer
Another solution, tough much more memory demanding is to simply use matrices. A 4x4 matrix can hold both a position and an orientation, its directly used by the rendering system(usually) so you can just simply read its last row to get position you want.

I think the memory demand is still manageable because even with 10000 objects you use only 10000 * 16 * 4 = 625 KB of memory.
> -1 votes

---
Tags: 2d, 3d, physics, graphics, entity-system
---


title: GLUT multiple windows FPS drop sharply

text:
# Question
Title: GLUT multiple windows FPS drop sharply
When only the main window is created, the fps is able to reach above 1000.However creating 1 more window, resulted in the fps dropping significantly down to about 100. The draw callback draws a blank black screen and writes the fps onscreen.

> Q1) What is the reason behind the sharp drop in fps?
>
> Q2) Any possible ways to improve on this fps?

```
int main(void){
        int mainwindow,otherwindow1;
        glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);

        glutInitWindowSize(640,480);// set the initial window  size
        glutInitWindowPosition(0,300);//set the initial window position

        mainwindow = glutCreateWindow("main window");
        glutDisplayFunc(Draw);

        glutReshapeFunc(ChangeWindowSize);

        otherwindow1 = glutCreateWindow("Other window");
        glutDisplayFunc(Draw);
        glutReshapeFunc(ChangeWindowSize);

        setVsync(0);

        glutMainLoop();
}

void Draw(){
    glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT);

    getFPS();

    glutPostRedisplay();
    glutSwapBuffers();
}

```

# Answer
> 1 votes
Switching rendering contexts can have a huge overhead with some 3D drivers.

Another reason could be that the non-foreground window needs 2D clipping applied when displaying the image. Even if it is not covered the driver has to check for window overlap which it can safely skip for the top window when displaying the 3D frame buffer.

Yet another possibility is that the first 3D frame buffer is internally displayed using a hardware overlay with zero copy, while the 2nd one has to be copied (and clipped) to the main display buffer.

There isn't much you can do about that.

If the issue is some context/render target switch you'll have to replace GLUT with your own code and get down and dirty with window manager graphic calls (GDI, Cocoa, X11, etc) to implement a work-around that very well may not improve things at all.

Possible work around: Draw to an off-screen surface using the same context and do a 2D native API pixel copy (bitblt) call to display the buffer on the other window (or both). It may end up being much worse due to synchronization issues and image format mismatches.

Its a lot of effort and unlikely to result in an improvement.

---
Tags: opengl, glut
---


# Question
Title: How can I calculate the bounding box of a 3D model?
I am making a game in OpenGL and Blender and trying to use JBullet as the collision manager. I am using `BoxShape`s for collisions, which requires a `javax.vecmath.Vector3f` representing half of the box to create.

How do I calculate the dimensions (width, depth and height) of a Blender model in-game?

# Answer
When you're reading the model into your game, you'll be iterating through each vertex of the model. Simply keep track of the max/min for each X, Y and Z axes. Using these values you can find the center of your model as well as the extents. The width is the distance between X min and X max, the depth and height are similarly calculated depending on which axis you're using for which dimension.
> 7 votes

---
Tags: opengl, collision-detection, models, blender, bounding-boxes
---


title: Generate Mesh of Shadow Volume

text:
# Question
Title: Generate Mesh of Shadow Volume
Given a mesh, I want to generate another mesh that is effectively a shadow volume of this mesh.

I am looking for an algorithm/solution/implementation/reference that can do this under the following constraints:

1. I have a *single*, *point* light source. Thus:
    * Not a polygon;
    * I want hard edges/faces (not soft shadows)
2. The light source is at infinity, in fact can be assumed to by directly above the mesh. Thus:
    * The projection is actually orthographic and depends only on a single direction.
3. I want an exact solution.
    * The result mesh is not used for display so cannot be based on resolution dependent rasterization as many algorithms are.

A naive algorithm is to extrude all mesh triangles in the direction away from the light, e.g. downward, and do a CSG union of all these extruded "prisms".
The drawback here is that:

1. It does this for *all* triangles and not just the visible ones (how to do exact visibility?);
2. it requires a massive amount of CSG operations which are expensive.

I'm looking for a more efficient algorithm.

# Answer
(Geometry shader option at the end. General concept stays the same. Not all platforms support geometry shaders yet and the vertex shader option might still be faster on some systems)

Mesh pre-processing:

1. Copy the original mesh.
2. Break/Split each vertex to be unique per poly.
3. Set each vertex normals to the polygon's normal (making the mesh flat-shaded).
4. insert collapsed quads (2 triangles, shown as the green line) inside every edges between the original triangles reusing each triangle's vertices (quick if the mesh is indexed, just add to the index array).

The normals on each side of the quad "edge" must match the triangle on each side (see the yellow normals in the picture).

Then, in the vertex shader (pseudo code, assuming all coordinates are in world space):

```
if (dot(light_normal, in.normal) <= 0){
    out.position = in.position;
} else {
    out.position = in.position + light_normal * volumetric_shadow_distance;
}

```

or the 1-line version (that may or may not be faster depending on GPU/drivers):

```
out.position = in.position + (light_normal * volumetric_shadow_distance) * max(0, sign(dot(light_normal, in.normal)));

```

This is for a directional light. For point & spot lights `light_normal` = `normal(in.position - light_position)`

This will expand the shadow mesh away from your light source. It only requires vertex shader support.

If you have **geometry shader** support you can generate the edge quad geometry on the fly (skip step 4 above) by adding only 1 triangle per edge per source triangle in the geometry shader. The other source triangles will add the 2nd half of the quad for every edge (as long as they are oriented the same way: all CW or all CCW). You don't need full adjacency data, only the normal of the neighbor triangle for that edge's half-quad which you can put in the regular vertex data as a 2nd normal, a custom attribute, or stash it in the tangent, color, or 3D uv depending on the engine you use. Just make sure the 2 normals matches exactly (loses the same amount of precision) or you'll have visual glitches when only one half of the quad edge expands.
> 1 votes

---
Tags: 3d-meshes, shadows, shadow-mapping, computational-geometry, volumetric-light
---


# Question
Title: Quaternion.LookRotation() not rotating 360 degrees
In my scene I have two cubes one has a tag "Respawn" and another one has the following script attached:

```
using UnityEngine;
using System.Collections;

public class NewBehaviourScript : MonoBehaviour {

    void Update () {
        transform.rotation = Quaternion.LookRotation (
            GameObject.FindGameObjectWithTag("Respawn").transform.position
        );
    }
}

```

When I run it and move around my second cube with "Respawn" tag the first cube doesn't always looks at it, at certain point it just starts rotating the opposite side as if it has bounds to it's rotation. What am I doing wrong?

# Answer
> 1 votes
Instead of using Quaternion.LookRotation, use this instead:

```
transform.LookAt(GameObject.FindGameObjectWithTag("Respawn").transform.position);

```

This will automatically rotate the object to look at the desired position, which in this case is the position of the Respawn object.

I would also really recommend storing the Respawn object as a variable instead of searching for it every frame.

EDIT: Ignore the stuff above. If you want to be able to use Quaternion.LookRotation so you can, for example, use Lerp or Slerp, you just have to make the position relative as david van brink pointed out, so it will look like this:

```
Vector3 diff = (GameObject.FindGameObjectWithTag("Respawn").transform.position) - transform.position;
transform.rotation = Quaternion.LookRotation (diff);

```

---
Tags: unity, c#, rotation, quaternion
---


title: Best field of view

text:
# Question
Title: Best field of view
What is the best value for field of view for an FPS?

# Answer
Configurable.

The best field of view depends on many variables. For instance, how large the monitor is, are you using eyefinity, is the aspect ratio nonstandard, how far you are from the screen.

Besides that, different people have different preferences for it, leading to some people feeling simulation sickness at 90 FOV while others feel it at 75 FOV.
> 3 votes

---
Tags: unity, camera, first-person-shooter, view, third-person-view
---


# Question
Title: How do I move an object with an accelerometer in libGDX?
I am working on a game which uses the accelerometer to move an object called "plane". I know how to add an accelerometer, but I can't get the plane to move.

```
package com.wyvern.pp.states;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.wyvern.pp.PPlane;

public class PlayState extends State{
    private boolean peripheralAvailable;

    private Texture walls;
    private Texture bg;
    private Texture plane;

    public PlayState(GameStateManager gsm) {
        super(gsm);

        walls = new Texture("walls.png");
        bg = new Texture("bg.png");
        plane = new Texture("plane_left.png");

        cam.setToOrtho(true);

        peripheralAvailable = Gdx.input.isPeripheralAvailable(Input.Peripheral.Accelerometer);
    }

    @Override
    protected void handleInput() {

    }

    @Override
    public void update(float dt) {
        handleInput();

        float xRot;
        if(peripheralAvailable) {
            xRot = Gdx.input.getAccelerometerX();
        }
    }

    @Override
    public void render(SpriteBatch sb) {
        sb.begin();
        sb.draw(bg, 0, 0, PPlane.WIDTH, PPlane.HEIGHT);
        sb.draw(walls, 0, 0);
        sb.draw(plane, xRot, 15 ); // gives an error
        sb.draw(walls, PPlane.WIDTH - walls.getWidth(), 0);
        sb.end();
    }

    @Override
    public void dispose() {

    }
}

```

How do I get the plane to move left and right on the X axis?

# Answer
> 1 votes
It gives an error because it doesn't know what `xRot` is. In your method declaration of `update()`, you define `float xRot;`. Because you defined it within the declaration, it only exists within that declaration—it's a local variable.

To fix the error, just move the variable's declaration (`float xRot;`) up to where all the other fields (variables declared at the top of the class) are, like this:

```
package com.wyvern.pp.states;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.wyvern.pp.PPlane;

public class PlayState extends State{
    private boolean peripheralAvailable;

    private Texture walls;
    private Texture bg;
    private Texture plane;

    private float xRot; // here

    public PlayState(GameStateManager gsm) {
        super(gsm);

        walls = new Texture("walls.png");
        bg = new Texture("bg.png");
        plane = new Texture("plane_left.png");

        cam.setToOrtho(true);

        peripheralAvailable = Gdx.input.isPeripheralAvailable(Input.Peripheral.Accelerometer);
    }

    @Override
    protected void handleInput() {

    }

    @Override
    public void update(float dt) {
        handleInput();

        // no "float xRot" here

        if(peripheralAvailable) {
            xRot = Gdx.input.getAccelerometerX();
        }
    }

    @Override
    public void render(SpriteBatch sb) {
        sb.begin();
        sb.draw(bg, 0, 0, PPlane.WIDTH, PPlane.HEIGHT);
        sb.draw(walls, 0, 0);
        sb.draw(plane, xRot, 15 ); // no longer gives an error
        sb.draw(walls, PPlane.WIDTH - walls.getWidth(), 0);
        sb.end();
    }

    @Override
    public void dispose() {

    }
}

```

---
Tags: java, libgdx
---


# Question
Title: How much a game can borrows from a franchise before becoming a fangame/infringing the copyright
Let's say you like the theme/world of a franchise, for example SpongeBob SquarePants, and you want to make it into maybe a business game where you hold an underwater restaurant. Make burgers, invent recipes, have fishes as customers etc. How much can you borrow from the original franchise before crossing the red line ? I know that the names are the first to be copyrighted, but if for example your cook looks like a yellow square sponge, is that an infringement ? Even more, if you want to implement the concept of "Special Formula" as in the anime (without naming it in the same way), is that an infringement ?

Thanks.

# Answer
There's no hard and fast answer. In the end, the courts decide, if and when it gets to that. But really, in many jurisdictions it depends on whether a typical person might mistake one for the other. It also depends on the originality of an idea.

For example, cities under the sea are an old concept. Atlantis, Arielle, ... Spongebob wasn't the first. Similarly, American-style Diners are an existing thing, as are secret ingredients/recipes, having those in an undersea world that reflects what we have above is not really unusual either. Neither are business simulations like rollercoaster tycoon, so a restaurant under the sea isn't by itself an issue.

The problem arises when the combination is too similar to something else. Sea sponges are actual animals, but if on top of all the above your character is a yellow square-shaped thing (possibly a sponge) as well, most people would probably consider it a rip-off, even if the name was different.

But in general, the rule is that copyright applies to concrete works. Not to ideas. OTOH names are not under copyright, and are covered by trademark law.

So, a genre, even a game mechanic can not be copyrighted. That said, sometimes people try to get around this. E.g. Lego registered a lego brick as a trademark (company logos can be trademarked as well, not just names) and sued everyone who created Lego-compatible bricks, until a court finally struck that practice down, so it's better to stay away from being too similar to some existing franchise.

It's also a smart thing to do: If your game is successful, wouldn't you want people to be able to tell it from other games? IMHO that's why I would want my game to have unique names, character designs, maybe even some special game mechanic of its own. If you just imitate, it's just "one of those Sponge Bob games".

It doesn't take much. Make your own character designs. Pick different water animals, a different art style, choose different names (maybe even from a different country or culture than the original). AFAIK, anyone may make a Tetris clone. You just can't call it Tetris or the bricks Tetromino, or a name that sounds too much like it, and need a slightly different screen design.

Disclaimer: I'm not a lawyer. If you want actual legal advice, hire a *lawyer*.
> 2 votes

---
Tags: legal, copyright
---


title: Adding two classes with arithmetic math

text:
# Question
Title: Adding two classes with arithmetic math
I'm trying to figure out how to add two classes together with a simple arithmetic addition

The class i've written is a Vector3 class it looks like this

```
public class Vector3 {

public float x, y, z;

public Vector3(){
    x = 0.0f;
    y = 0.0f;
    z = 0.0f;
}

public Vector3(float _x, float _y, float _z){
    this.x = _x;
    this.y = _y;
    this.z = _z;
}
public Vector3 add(Vector3 other){
    Vector3 temp = new Vector3(this.x+other.x, this.y+other.y, this.z+other.z);
    return temp;
}

}

```

I have added the add method in order to be able to add vectors together temporarily. but i really want to be able to just type vectorA+vectorB instead of having to type vectorA.add(vectorB)

is there a way to do this. i know you can do it in python.

# Answer
> 6 votes
To put it bluntly, you can't. Java does not allow the user to define operator overloads. You will have to continue to use the `Vector3::add(Vector3)` method that you have already created.

Java is Java, Python is Python (C++ is C++, and C is C); they are all different languages that do different things. You shouldn't expect one thing to work because it works in another language.

# Answer
> 1 votes
Java doesn't support operator overloading, but a similar language, C#, does. (C# and Java are very similar and are usually compared with each other)

The Unity engine, which uses C# scripting, already defines a Vector3 class, with several overloaded operators (including + and -).

There, you can do something like:

```
Vector3 result = new Vector3(1, 2, 3) + new Vector3(4, 5, 6);

```

Of course, if you cannot change your programming language (either by choice or because of the framework used), then this is not an option, and you should stick to using the `add()` method.

---
Tags: java
---


# Question
Title: Easy method of obtaining texture coordinates for sprite sheet
In my (OpenGL ES 2.0 Android) game, I use 2 types of Sprite Sheets. In one type all sprites/frames are of equal size and in the other they are all different shapes and sizes.

It is the latter one to which this question pertains. Basically, I've created a sprite sheet and I currently use Paint.net to find the coordinates a particular frame sits at. I then have to work out the texture coordinates by dividing the pixel by the width (for X) or height (for Y) so, if my image is 2048 x 2048 and a particular frame is at 300, 500, I work it out like so:

```
300/2048 = 0.146484375
500/2048 = 0.244140625

```

So, my X (or S) is 0.146484375 and my Y (or T) is 0.244140625.

I use the same method to work out the width and height.

I then code this using a method like so:

```
setTexCoords(0.146484375f, 0.244140625f, 0.048828125f, 0.048828125f);  //X, Y, Width, Height

```

When working with lots of sprites, this is a very tedious process.

The main problem however, is if I, at a later date, want to add sprites to the sheet and make it bigger to accommodate the extra sprites, I have to revisit every sprite and work out it's new texture coords based on the new bitmap size.

Is there any method I can use to make this process easier?

Even if it's just a program where I can hover the mouse over a bitmap and it tells me the texture coordinate (between 0-1). Even that would take a little of the work out of it.

Any suggestions welcomed.

**I have read a similar question on here however, none of the answers really helped**

# Answer
> 2 votes
Here's a really simple improvement:

Define a method that sets the texture coordinates as pixels. Something like:

```
void setTexCoordsI(int x, int y, int w, int h) {
    float TEXTURE_SIZE = 2048.0f;
    setTexCoords(x/TEXTURE_SIZE, y/TEXTURE_SIZE, w/TEXTURE_SIZE, h/TEXTURE_SIZE);
}

```

Then call:

```
setTexCoordsI(300, 500, 100, 100);

```

instead of:

```
setTexCoords(0.146484375f, 0.244140625f, 0.048828125f, 0.048828125f);

```

# Answer
> 0 votes
Doing this manually is insane.

You need a tool that will take a folder full of images, pack them into atlases AND write a file containing all the coordinates. So then in your game you could address any image by its index or name or whatever and get its atlas coordinates (in pixels or UV).

---
Tags: opengl, android, textures, coordinates, texel
---


title: C++ friend class, rendererer and mesh

text:
# Question
Title: C++ friend class, rendererer and mesh
I often hesitate to use friend classes in C++. Since it often does not feel right, or just seems to be an indicator of bad design. Though, in this case I think a friend class might improve the design. Let me explain:

Let us say I have a very simple mesh class:

```
class Mesh {
    friend class Renderer;
public:
    using Vertices = std::vector<Vertex>;
    Vertices::iterator begin() {
        return vertices_.begin();
    }
    Vertices::iterator end() {
        return vertices_.end();
    }
    void invalidate(){
        valid_ = false;
    }

private:
    Vertices vertices_
    bool valid_;
}

```

The renderer looks something like this:

```
class Renderer {
public:
    void render(Mesh & mesh){
        if (!mesh.valid_){
            //The mesh has changed, update internal data.. GL buffers etc.
            mesh.valid_ = true; // Mesh becomes valid again.
        }
        //render...
    }
}

```

So, this is of course a very simplified example. My question is, if this is a good design in this case? Clients can only call `invalidate()` on meshes. And only the renderer is allowed to "validate" a mesh again. Without a friend class, A public setter would have to be used in the Mesh class. Hence providing a "leaky" interface. Allowing clients to "validate" meshes, which I do not want.

**Edit to clarify**

A *valid* mesh in this sense means that its corresponsing data in other subsystems is the same. The renderer has its own mesh data in its own form (a GL buffer). Therefore, only the renderer should be able to *validate*, since it knows about its own mesh data. Clients can edit meshes, and *invalidate* them only.

# Answer
The obvious approach to me would be to invert the interaction between `Renderer` and `Mesh`, making the `render()` method a member of `Mesh` instead, which would take a renderer reference. A `Mesh` is a higher level concept that the renderer doesn't have to know about, while the mesh obviously has to know about the renderer to be able to draw itself, so it should be a one-way dependency.

YMMV, but I think the renderer should only deal with basic geometry primitives or perhaps even simpler, just vertices and buffers (plus the other low level stuff like shaders and render states, of course).

### Example:

```
class Mesh {
public:
    void render(Renderer & renderer) {
        if (!valid_) {
            renderer.updateVertexBuffer(vboHandle_, vertices_);
            valid_ = true;
        }
        renderer.drawVertexBuffer(vboHandle_);
    }
private:
    // data ...
};

```
> 4 votes

# Answer
This is one reason why the friend keyword exists.

Both Mesh and Renderer are part of the same system: You can't really use Mesh without Renderer and vice-versa.

You should probably still use a getter `mesh.IsValid()` and setter `mesh.MarkValid()` in case you need to add functionality later, rather than access valid\_ directly.

It would be nice if C++ had access groups so we could mark only some members public to only a certain group and retain some access protection. In theory its possible to get close to this with multiple inheritance but it becomes a bigger maintenance mess than using self discipline.

Cheers,
> 3 votes

# Answer
I do not think that allowing clients to validate a mesh is a problem, this allows for a clean api and maintainable code. It makes it extensible for example if later you want to add some code into the validation step etc. (However the last part could also be handled with private functions and a friend class)

Remark that if clients cannot validate / prepare a mesh then what is the point to know if it is in a valid state from a client perspective ? Should this be kept in the api ?

*That said*, there are alternatives to enforce the validation (or visibility scope) here:

* create a member function that uploads the data to the gpu when in dirty state;
* use some sort of opaque RendererData object that only the renderer can use (not exposed in the public api);
* store the dirty flag in the renderer (I often use handles for resources which would make this approach efficient with a constant time access, O(1) vs. O(log(n)) (see Game Programming Gems vol.1) ).
> 1 votes

# Answer
I'm not sure if this is what Stephane is talking about when mentioning multiple inheritance, but you could theoretically create a base class that is a friend to the mesh class and implement functions that access mesh internals there, called, say, `MeshPrivateAccess`. You can then derive classes like the renderer from that (eg. `class Renderer : protected MeshPrivateAccess`) so that accidental access is prevented, but other classes can access the data without needing to update the `Mesh` class to include friend declarations (impossible if `Mesh` was designed to be part of a library for example).

It's a bit cleaner that way, but I wouldn't recommend this solution here since it doesn't solve the fundamental design problem.

If you really want to store per-mesh data inside of a renderer, I'd probably store the `valid_` variable inside of the renderer as well. Conceptually, that variable has got nothing to do with the mesh data structure itself, as it is related to a cache that exists somewhere in the renderer, and with the current design, changing the implementation of the rendering process or caching mechanism would require changes to the Mesh class. Storing any `isChanged` variable inside the renderer instead solves that.

That leaves the question of how to best update it.

I'd probably use something like the observer pattern or delegates to notify the renderer when a mesh has been modified. It can then update its `isChanged` status for the mesh as a response, or do anything else you may want to do in the future.

That mechanism could for example be used to also notify the renderer when the mesh is deleted so it will be able to free the associated caches and so on. And you could re-use that infrastructure if you want other actions to happen that are implemented in other parts of your code, like, say, auto-saving a mesh whenever it is changed, or having a physics simulator mark its cached bounding volume calculation as invalid, initiate the redraw of a view when you are running in an editor mode, and so on. It would also allow it to scale if one day you needed to run multiple renderers concurrently (say, for running on multiple displays that use different graphics API contexts and thus can't share resources). All that without ever having to touch the `Mesh` class.

Depending on what type of process changes the mesh, you might also consider having that code issue the change notification instead of having the mesh do it, but most likely the `Mesh` itself would be the best solution.
> 0 votes

---
Tags: c++
---


# Question
Title: CubeMap - Why size of skybox cube has no effect?
I have normal skybox via CubeMap, but i noticed that the size of the cube has no effect. I would expect that when i have cube size 20.0, i will see different result than with cube of size 1000.0 (same as if you have texture 20x20 on 20x20 face and on 1000x1000 face).

It is probably because the CubeMap works somehow different, but i don't know where to find how.

# Answer
A skybox is already simulating a sky infinitely far away from you. If you would increase the size, wouldn't you expect to be the same?

Cube mapping works by sampling a special cube texture (consisting of six 2D textures, one for each face) by normalized 3d vector coordinates. If you get 3D coordinates from a cube scaled by 1000, and normalize those, you get the same coordinates as you would from a unit cube.
> 2 votes

# Answer
Imagine you're in the center of a flat square rectangle. If you look North you'll look at an edge. If you look Northeast, you'll see a dot representing the corner connected by two edges- the horizon. Now the distance of that corner is not relevant, you will always see a straight line with a dot representing the corner.

Apply this to a cube: if you're in the center of a cube, the corners are always in the same location, no matter how big that cube is. So the 'look' is not changed by the size of the cube. Since the skybox moves with the camera- you're always in the center of that cube.

The only reason for a bigger cube is the clipping plane. You want the gameworld to be INSIDE the cube to be visible. Thus, the size of the cube is only relevant for the clipping part not the 'looks' part.
> 2 votes

---
Tags: opengl, cubemap
---


# Question
Title: Finding specific coordinates on a rotating line
I'm currently working on a mobile game which mainly consists of a rotating line and a ball. The line rotates 0.500 degrees clockwise around its center every frame. The ball is at first positioned in the centre of the line. When the user touches the screen, the ball should move along the line and when the user stops touching the screen the ball should move in the opposite direction.

I have the line rotation, and the coordinates of the line(top-left corner).

I need to find the position of the ball if the ball moves along the line at a speed of 5.

# Answer
> 1 votes
If the ball didn't move on the line, its path would be a circle. You know the popular parametric equation of circle (=how you usually generate points on circle)?

```
x = r * cos(θ)
y = r * sin(θ)

```

It is all you need - just plug in the right numbers. First, the angle theta `θ` is, as you said 0.5 degrees a frame. Second, you said the ball moves along the line at speed of 5 (I assume you meant units per frame since your angle is per frame), not surprisingly the ball's distance from center is `r` or more precisely frames times speed. And lastly if your line does not start(the rotation center) form origin, you need to translate the results:

```
Vec2 getBallPosition(Vec2 center, float angularSpeed, float ballSpeed, int frames)
{
  Vec2 result;
  result.x = (ballSpeed * frames) * cos(angularSpeed * frames);
  result.y = (ballSpeed * frames) * sin(angularSpeed * frames);
  result += center;
  return result;
}

```

---
Tags: mathematics, rotation
---


title: Making a 2d sprite based game in Unity?

text:
# Question
Title: Making a 2d sprite based game in Unity?
I'm looking at developing a 2D sprite based platformer. Usually I make games in Gamemaker, because I find it very easy to use. I have never used Unity before but have heard a lot of good things. So, just wondering whether you can easily make this type of game in Unity?

# Answer
Yes. Yes you can. You can do this in Unity.
> 1 votes

# Answer
You can make a sprite based game in Unity, and it can be considered easy, but it is not the same kind of easy as Gamemaker's.

Even learning Unity can be daunting if you don't have somebody knowledgeable to help you out or at least experience with different ways of programming.

Once you know it, getting a basic game running in Unity will take a lot more work than it would in Gamemaker. Gamemaker is designed to make these kinds of games - they have more of your game already baked into the project from the start. Unity is much more general, basically meaning you need to specify more to get a game. There are also some artifacts of Unity being a 3d engine - a 2d game is actually a 3d game that is only shown from one angle in Unity.

However, Unity is very good at keeping large projects organised, and C# is more suitable for big projects. In both Unity and Gamemaker I experience a slowdown in my development speed as my project gets bigger, but with Gamemaker the curve is sharper and sooner. And finally, knowledge gained in Unity is more applicable elsewhere.
> 1 votes

# Answer
Yes Unity has added lot of features to support 2D games.

* Automatic Sprite Slicing
* Automatic Sprite Animation
* Alpha Cutout
* Sprite Packer 2D physics

Here is a link to start with Unity 2D :)

https://unity3d.com/learn/tutorials/topics/2d-game-creation
> 0 votes

---
Tags: unity, 2d, sprites, platformer
---


title: How to calculate attacks

text:
# Question
Title: How to calculate attacks
I am making a android game, and it is supposed to have attacks.(Note, this game is 2D). I have implemented things like movement to the base, but I am not too sure about the actual attack algorithm. There are supposed to be to bases, one attacker and one defender. I have tried multiple ways, but I cannot get it realistic enough. Here is what has to be a part of it:

```
    public void attackCalculations(){
        Random r = new Random();

        int[] aa = att.ARMIES;
        int[] ab = def.ARMIES;

    }

```

I thought about making random casualties based on who have more troops(attacker or defender), but it will not work(tested it, and the casualties were often 0, and it was a loss for the attacker...) There are ten troops(the ARMIES-variable is a array-int with a max of 10)

```
    int ARMIES = new int[10];

```

So, how can I calculate who wins based on all the troops(cannot make a single integer due to different troops)?

# Answer
First of all, I would make your troops into just an integer: the number of units. If you don't want to do that, just use the array length as a gauge for their troop sizes.

Now the easiest way to do this would be to just take the amount of attacking troops away from the amount defending troops. If the result is negative, the attackers win.. yet if the result is positive, the defenders win and if it's 0 its a draw.

Then to add random casualties, you just add a randomly generated number from -1 to 1 and add it to the result.

```
Random random = new Random();
int result = defender - attacker;

result += (random.nextInt(3) - 1);

System.out.println(result);
if(result < 0) {
    System.out.println("Attacker Wins");
} else if(result == 0) {
    System.out.print("Draw");
} else if(result > 0) {
    System.out.print("Defender Wins");
}

```

This is good because, if you ever have 10 Attackers battling 9 Defenders, you have a larger bias towards the attackers (because they have more troops) and yet it still gives the possibility for there to be a stalemate.

As you see these results below show how each of 10 battles turned out, with the attacker having 10 troops and the defender having 9:

As expected, the attacker has won most times because they have a greater amount of troops, and yet there is still a small chance for a draw to occur.

If your troops all have different stats, you can then just take and add them to the result variable as you please.
> 0 votes

# Answer
Try a risk like aproach. N dice launch from attackers sorted by result. M dice launch from defenders sorted by result. For each pair of results count att casualities and def casualities. In risk with the same result defender wins. You can set a max number of comparations per turn
> 0 votes

---
Tags: java, android
---


title: Add force towards a point in Unity3d?

text:
# Question
Title: Add force towards a point in Unity3d?
I have a Vector2 and want to move an object towards it... (this vector2 is the mouse position when clicked and I made sure I get only one position when its clicked)

My initial thought was to apply

> Rigidbody2D.Addforce(my vector2)

but it acting strangely... How can I push anything towards a point?

N.B: I wanna use physics for it.... because I want to get the pushing feel!

# Answer
Nevermind :p I found it!

it works after this

> rigidbody.AddForce((whateverObject.transform.position - transform.position).normalized * someFactor);
> 2 votes

---
Tags: 2d, physics, unity
---


title: C++ vsnprintf formatting issue?

text:
# Question
Title: C++ vsnprintf formatting issue?
I'm working on a roguelike and attempting to write the message system. When I attempt to format a const char\* with vsnprintf, it seems to somehow format it incorrectly to the point where it is corrupted.

```
void Gui::render()
{
    for(auto iter = log.begin(); iter != log.end(); iter++)
    {
        terminal_printf(1, 45, (*iter));
    }
}

void Gui::message(const char *text, ...)
{
    char buffer[256];
    va_list argptr;
    va_start(argptr, text);
    vsnprintf(buffer, 256, text, argptr);
    va_end(argptr);
    log.emplace(log.begin(), buffer);
}

```

If I call puts() in message() with buffer as an argument after it has been formatted, it is correctly formatted. If I directly emplace the text, it isn't corrupted, but it obviously isn't formatted. If puts is called in the iteration loop on the iterator, it outputs the corrupted data.

# Answer
### Stop using format functions in C++

TL;DR: They are unsafe, vulnerable to all sorts of buffer overrun exploits and a pain to debug when you make a mistake.

`std::cout` and the standard C++ streams are much more robust than `printf` and the C IO library and formatting functions. Format strings tend to be more readable and there is some value in separating the data from the presentation, but unfortunately, they are a C mechanism that is incompatible with C++'s object model. So you cannot, for instance, pass a C++ class type to one of those functions (don't even think about passing it a `std::string!`).

Format strings are also not type safe, since you wave compile-time type inference and rely on manually matching the type of each parameter with the `%`s in the format string. In the end, that's a recipe for disaster and these issues outweigh any gains in readability. Having to manually specify the type in the format, when the compiler always knows the type of the variable passed in, is also a violation of the DRY principle.

Better options exist, beside the C++ streams, if you really don't dig the `<<` operator syntax:

---

That said, let's look at your code. What could be wrong?

It could be a buffer overflow in `Gui::message()`. The buffer is sized to 256 characters, if the string is longer than that, you run into trouble.

What you can do is increase the buffer size and test. Also, make sure to manually terminate the string, just in case:

```
char buffer[1024];
va_list argptr;

va_start(argptr, text);
vsnprintf(buffer, sizeof(buffer), text, argptr);
va_end(argptr);

buffer[sizeof(buffer) - 1] = '\0';

```

This code also seems suspicious:

> ```
> void Gui::render()
> {
>     for(auto iter = log.begin(); iter != log.end(); iter++)
>     {
>        terminal_printf(1, 45, (*iter));
>     }
> }
>
> ```

There's not enough information here to be certain, but what are the contents of `log`? chars, strings?

If `(*iter)` is returning a `char`, then the correct way to print it with a format is:

```
terminal_printf(1, 45, "%c", (*iter));

```

If it contains a `char *` string (array of chars), the correct print call is:

```
terminal_printf(1, 45, "%s", (*iter));

```

Assuming the signature of `terminal_printf` is something like:

```
void terminal_printf(int, int, const char*, ...);

```
> 3 votes

---
Tags: c++
---


# Question
Title: Geometry Shader not generating geometry for some Vertices
I am playing with a geometry shader and I am wondering why it doesn't generate geometry for each vertex in all meshes?

* I don't think this is a Cull problem because the same vertices generate geometry as you rotate around and setting `Cull Off` changes nothing.
* Another problem could be a multiply by zero somewhere but I tried to eliminate as many variables as possible and still have the issue.
* A third unlikely issue could be limiting the output amount somewhere. I didn't set anything explicitly to hinder that.

I notice the problem on a Cube(5/8) and Quad(2/4) but seems to generate all the geometry fine on a plane, cylinder, etc. The following are some results from using the bare-bones geometry shader.

Cube *(closest: Unity default, further back: Cinema 4D exported `.fbx` cube)*:

Quad:

It seems to work fine on a plane (update: It is actually missing a whole row on each axis)

## Unity Shader Code *`GeometryShaderTest1.shader`*:

Note: If you are testing out the shader and nothing is displaying; Rotate your camera around so the normals are facing the right direction to show up.

```
Shader "Custom/GeometryShaderTest1" {
    Properties {
        _Color ("Color", Color) = (1,1,1,1)
        _Amount ("Height Adjustment", Float) = 0.0
    }
    SubShader {
        Pass {
            Tags { "RenderType"="Opaque" }
            LOD 200

            CGPROGRAM
            #pragma target 5.0
            //#pragma addshadow
            #pragma vertex vert
            #pragma geometry GS_Main
            #pragma fragment frag
            #include "UnityCG.cginc"

            // Vert to geo
            struct v2g
            {
                float4 pos: POSITION;
            };

            // geo to frag
            struct g2f
            {
                float4 pos: POSITION;
            };

            // Vars
            fixed4 _Color;
            float _Amount;

            // Vertex modifier function
            v2g vert(appdata_base v) {

                v2g output = (v2g)0;
                output.pos = mul(_Object2World, v.vertex);
                // Just testing whether all vertices affected
                output.pos.y -= _Amount;

                return output;
            }

            // GS_Main(point v2g p[1], inout TriangleStream<g2f> triStream)
            // GS_Main(line v2g p[2], inout TriangleStream<g2f> triStream)
            // GS_Main(triangle v2g p[3], inout TriangleStream<g2f> triStream)
            [maxvertexcount(4)]
            void GS_Main(point v2g p[1], inout TriangleStream<g2f> triStream)
            {
                float4 v[4];

                float3 asdfUp = float3(0, 1, 0);
                float3 asdfRight = float3(0, 0, 1);
                v[0] = float4(p[0].pos + 0.25 * asdfRight - 0.25 * asdfUp, 1.0f);
                v[1] = float4(p[0].pos + 0.25 * asdfRight + 0.25 * asdfUp, 1.0f);
                v[2] = float4(p[0].pos - 0.25 * asdfRight - 0.25 * asdfUp, 1.0f);
                v[3] = float4(p[0].pos - 0.25 * asdfRight + 0.25 * asdfUp, 1.0f);

                float4x4 vp = mul(UNITY_MATRIX_MVP, _World2Object);
                g2f pIn;
                pIn.pos = mul(vp, v[0]);
                triStream.Append(pIn);

                pIn.pos = mul(vp, v[1]);
                triStream.Append(pIn);

                pIn.pos = mul(vp, v[2]);
                triStream.Append(pIn);

                pIn.pos = mul(vp, v[3]);
                triStream.Append(pIn);
            }

            fixed4 frag(g2f input) : COLOR {
                return float4(1.0, 0.0, 0.0, 1.0);
            }

            ENDCG
        }

    }

    FallBack "Diffuse"
}

```

---

Geometry shader resources:

# Answer
> 3 votes
From the OpenGL wiki:

> The input\_primitive type *must* match the primitive type used with the drawing command that renders with this shader program.

Given, Unity is probably using DirectX on Windows, but the same thing should hold true. Because your shader is asking for a point, it is only taking the first point from each primitive and ignoring the rest.

Assuming Unity draws with triangles, you need to change the first parameter to receive that, set `maxvertexcount` to 12, and generate three quads instead of one. Quick example:

```
[maxvertexcount(12)]
void GS_Main(triangle v2g p[3], inout TriangleStream<g2f> triStream)
{
    for(int i = 0; i < 3; i++)
    {
        // generate a quad with p[i]

        triStream.RestartStrip();
    }
}

```

# Answer
> 7 votes
The input primitive, aka. the mesh fed into the shader, has a `MeshTopology` setting which can be adjusted in code. The accepted answer works because the default input primitive for a mesh(including imported meshes) is `triangle`/`MeshTopology.Triangles`.

But if you use `MeshTopology.Triangles`, you will be creating more geometry than you need for the shader. Because a single vertex may be part of multiple triangles, you will have billboards on top of other billboards. You won't notice it visually, because they overlap perfectly, but it will cost you performance. The fragment shader will be working on duplicate geometry for no reason.

Instead, you should use `point`/`MeshTopology.Points` as your input primitive, as your original shader already does, and then tell Unity to draw with points rather than triangles.

You can use `Mesh.SetIndices` to adjust the mesh's topology and then your original shader will work just fine.

```
using UnityEngine;

public class UsePointTopologyMeshMode : MonoBehaviour {

    [ContextMenu("ConvertToPointTopology")]
    void ConvertToPointTopology() {
        Mesh mesh = GetComponent<MeshFilter>().mesh;
        int[] indices = new int[mesh.vertices.Length];
        for (int i = 0; i < indices.Length; i++) {
            indices[i] = i;
        }
        mesh.SetIndices(indices, MeshTopology.Points, 0);
    }

    // Use this for initialization
    void Start () {
        ConvertToPointTopology();
    }
}

```

---
Tags: unity, shaders, vertex, geometry-shader
---


# Question
Title: UNET start game with friend by finding their name, Android
There is a game at the google play store called Fun Run 2- Multiplayer Race. I loved its feature to find friends by writing their names, and then to play with them. Is it possible to achieve that with UNET? How?

Another one is called Virtual Table Tennis. There I have a lobby full of people from whom I can choose. Can I achieve that with UNET? How?

# Answer
> 1 votes
I implemented a lobby of sorts by using a middle-man machine that hosts would register sessions with, allowing connecting-clients to scan the well-known middle-man for sessions and connect without needing to know the IP and port of the respective host.

Options then include: 1) An online, well-known server that performs the middle-man role. This would be used to implement a fully networked lobby as you would see in many games 2) A middle-man on the same local network as the clients that either discovers hosts by being well-known (and therefore hosts register sessions with this middle-man) or by discovering them using the low-level API (have a Google - there's a forum post regarding the discovery of hosts using Unity Multiplayer's LLAPI) http://docs.unity3d.com/Manual/class-NetworkDiscovery.html

The middle man could always be running on a host itself, so you don't necessarily need a third wheel

---
Tags: unity, android, unity-networking
---