# Question
Title: Should the bullet trajectory calculated by server or by client?
In a FPS game like Battlefield or Arma, when playing online, should the bullet trajectory be calculated by the server or by the client?

# Answer
> 4 votes
Note that most of us cannot answers specific questions about either of the games you mentioned. We aren't the authors of that code and can't reasonably know exactly how it was built.

Generally speaking, there are multiple approaches.

One approach is that the server is authoritative on *everything*. When a client wants to fire a weapon a round-trip to the server is required. The server tells the client which trajectory to use. This approach adds significant latency to firing. Games that use this approach might hide the latency by animation or a smoke particle effect of the like so that the player doesn't realize that the client is waiting on the server (on well-behaved networks).

Another more complicated approach does firing as part of client-side prediction. The client fires the weapon. It tells the server that it fired the weapon along with information about the specific time of the fire request. The server is then able to simulate the same firing trajectory (or very close to). The server's fire message, when received by the client, is used to adjust the projectile (if necessary). Note that the server should still be in charge of determining what the projectile hits and what the results are. The weakness of this approach is that, in some situations, the client can see a firing effect that is wildly different than what actually happens. However, in most cases the client should see something close to what happens, and the firing will feel instant, which makes this approach "feel" good on low-latency connections.

These are not the only two approaches, nor did I describe the most advanced approaches. Networking games is *really hard*. There's a good reason that network programmers are some of the best paid engineers in the game industry.

# Answer
> 20 votes
# Always assume the client is a lying, cheating, bastard.

The client is responsible for:

* Receiving input from the player (and sending *commands* to the server, which validates)
* Rendering the known gamestate

The client is *in no way allowed to calculate the gamestate* except as client-side interpolation for smooth animations.

# Answer
> 3 votes
More than likely, it works like this (major speculations):

1. Client sends Shoot command to server, along with parameters such as position, direction, velocity, type, etc...
2. Server accepts command and broadcasts to all players on next frame.
3. Clients render the shot.
4. If shot hits a player, server broadcasts kill.

Can't tell for sure though, as I don't have access to the source code.

# Answer
> 2 votes
One thing a lot of people say here and is pretty fangerous is to have the player send information about his state when he shoots. The server is a machine, he can't decide who cheats and who doesn't. "Yes, I really did stand in front of him for 30 seconds without he noticing it, then I shot him in his eye while he was running around in a thight place, looking down...while crouching...on a ledge." You need to store information about the playsrs server side.

## What a client should do

* Draw the scene
* Talk with the server, sending him his current position, and receiving the positions of other players
* Handle keyboard and mouse control.

## What a server should do

* Have a nice, clean command window.
* Manage collision detection
* Speak with the client

Servers tend to have a better CPU, than clients, so they can manage more complex things, like collision detection, or player movement without having a hard time.

---
Tags: physics, client-server, bullet-physics, first-person-shooter
---


# Question
Title: Should a transform class store a matrix or seperate position/rotation/scale values?
I'm creating a transform class to make storing the transform of individual objects in a scene easier, but I'm unsure on how to do it.

I could create one like this:

```
class Transform
{
public:
    //...

private:
    Matrix4f matrix;
};

```
* Easy to concatenate
* Easy to perform operations on (since the matrix functions already exist)
* Can store certain information such as the camera projection
* Difficult to get the individual values such as the position of the object
* Performing operations in the wrong order can lead to unexpected results (rotate/translate/rotate results in a very different transform than rotate/rotate/translate)
* Lots of memory usage (64 bytes of data for a single-precision transform)

Or like this:

```
class Transform
{
public:
    //...

private:
    Vector3f position;
    Quaternionf rotation;
    Vector3f scale;
};

```
* Very easy to extract individual values
* Very easy to change individual values
* Because the position, rotation, and scale are independent from one-another, there is no "correct" order for rotate/translate/scale
* Smaller, being only 40 bytes for single-precision
* Cannot store anything beyond position/rotation/scale
* Performing operations which require information stores in more than one value (such as strafing, which changes the position but depends on the rotation) are much more difficult to implement

I'm not entirely sure how most game engines deal with this. Which implementation should I go with?

# Answer
Store the components and compute the matrix on-demand when you need it.

Storing the matrix itself is inferior if you're ever going to be manipulating the transformation in any interesting or useful way, because floating point error can creep into the matrix after repeated successive mutations (such as rotations). This can result in a matrix that doesn't do what it logically should, such as a matrix that is the result of nothing but rotation operations applying a non-uniform scale because of the accumulation error.

Many of your other "pros" for the matrix approach aren't really that big of a deal, or sort of come out in the wash (it's pretty trivial to do operations on vectors and quaternions as well, for example).
> 6 votes

---
Tags: physics, graphics, transformation, scene-graph
---


# Question
Title: Using a smaller off-screen buffer for rendering
I am seeing this in most of the game codes I read and tutorial videos I watch. When using double buffering in rendering, they use a smaller sized off-screen buffer, then just scale it up when drawing onto the screen. Why is this so? Is there any advantages and/or disadvantages when using this technique?

# Answer
> 1 votes
This technique is called ***MRT***'S or Multiple Render Targets, and employs the use of additional ***Framebuffers***.

---

## Why is this used?

Because when wanting to achieve certain screen space effects, whether it is screen space lighting or ambient occlusion, it is quite efficient to store certain scene parameters ***as textures***. Imagine a scene with hundreds of lights and thousands of objects. It is quite possible that many lights won't affect the final color of some of those objects, and yet they would be processed anyways within the lighting calculations for those objects. Instead, in the case of deferred shading the scene is encoded into a series of textures limited to what is actually visible in the viewport, then decoded and processed in a separate pass, reducing the rendering time quite significantly by just performing lighting calculations on each pixel of the viewport.

This isn't just useful for deferred shading, it is also a key choice for a wide range of other rendering techniques, such as shadow calculations.

## Why vary the size?

Certain effects, such as screen space ambient occlusion or bloom also apply visual effects to the screen from the camera's perspective. However, these effects may undergo a series of blurring passes like box blurring or gaussian blurring. These blurring passes will take **longer** based on the **size** of the screen.

Since the end goal of some of these techniques is a blurred texture (blurring out high frequency information), a smaller texture would not only aid in losing some of that information, but would also allow the blurring pass to finish much more quickly.

---
Tags: rendering, double-buffering
---


# Question
Title: How to adapt UV code to use a tilesheet that is "uneven"?
The tutorial has code that takes a tilesheet and builds a UV mapping:

```
 const float tileSize = 0.25f;

 public virtual Vector2[] FaceUVs(Direction direction)
 {
     Vector2[] UVs = new Vector2[4];
     Tile tilePos = TexturePosition(direction);

     UVs[0] = new Vector2(tileSize * tilePos.x + tileSize,
         tileSize * tilePos.y);
     UVs[1] = new Vector2(tileSize * tilePos.x + tileSize,
         tileSize * tilePos.y + tileSize);
     UVs[2] = new Vector2(tileSize * tilePos.x,
         tileSize * tilePos.y + tileSize);
     UVs[3] = new Vector2(tileSize * tilePos.x,
         tileSize * tilePos.y);

     return UVs;
 }

```

He explains why he uses `tileSize = 0.25f`:

> The variable tileSize is equal to 1 divided by the number of tiles per side, in the case of our example texture 1/4 (0.25). The function creates an array of vector2 and gets the tile position with the direction and populates the array based on the tile position. Every UV coordinate corresponds to a vertex and the triangle made of those vertices uses the corresponding texture coordinates.

This is the tilesheet he is using, which is a 4x4:

I have a tilesheet which is not a 4x4:

I have tried `tileSize = 0.0667f` (1/15 if I assume the tilesheet is 15x15), but this is not correct. For example, a grass block is (5, 14) for the side, and (5, 8) for the top. But the game renders really weird textures.

**What should the** `tileSize` **be since this tilesheet is not a perfect square** (it looks like 6x15 tiles, but it also has a lot of empty space which might cause problems)?

---

Reference:

Tutorial: `http://alexstv.com/index.php/posts/unity-voxel-block-tutorial-pt-2`

Source tilesheet (CC0 license): `http://kenney.nl/assets/voxel-pack`

# Answer
You may have had an issue with your tile-sheet. The question now displays a properly framed one.

It looks like at 6\*15 tile sheet. So...

Instead of using a `float tileSize`, which has the same value for the x and the y axis, I would suggest you use a vector2 instead:

```
// Keep in mind that my c# is not good so you may need to adjust the syntax of the code, but
// it gives you an idea.
const Vector2 tileSize(1/6, 1/15); // This is to be used with the current texture

public virtual Vector2[] FaceUVs(Direction direction)
{
  Vector2[] UVs = new Vector2[4];
  Tile tilePos = TexturePosition(direction);

  UVs[0] = new Vector2(tileSize.x * tilePos.x + tileSize.x, tileSize.y * tilePos.y);
  UVs[1] = new Vector2(tileSize.x * tilePos.x + tileSize.x, tileSize.y * tilePos.y + tileSize.y);
  UVs[2] = new Vector2(tileSize.x * tilePos.x, tileSize.y * tilePos.y + tileSize.y);
  UVs[3] = new Vector2(tileSize.x * tilePos.x, tileSize.y * tilePos.y);

  return UVs;
}

```
> 0 votes

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


# Question
Title: Scale smaller resolution to full resolution libGDX
Short question about the scaling in libGDX. At the moment i have a application with the resolution 480x320. I define this in the main method of the desktop launcher. My whole application is now calculating with this resolution. For example is the player 50x50 pixels. How can i now scale my application to, for example, 1920x1080 on android so my player is now not only 50x50? I use a orthographic camera and give the width and height of 480x320 in the constructor.

# Answer
Take a look as using a different type of ViewPort (this page shows the different types).

Based on what you have described I would recommend using a StretchViewport, which would upscale (or downscale) your 480x320 camera to whatever resolution you needed it to be.

Note that if you changed the aspect ratio you might get some ugly stretching artefacts.
> 1 votes

# Answer
On the resize event method in your `ApplicationListener` (the main game class) change public static width and height integers like so:

```
WIDTH = Gdx.graphics.getWidth();
HEIGHT = Gdx.graphics.getHeight();
float scale = (float)prefferedWidth / (float)WIDTH;
WIDTH = (int) (WIDTH  * scale);
HEIGHT = (int) (HEIGHT  * scale);

```

The `prefferedWidth` is the in-game-world width that you want to cover. This keeps the aspect ratio from being gross and stretchy on different phones. Then you just use this `WIDTH` and `HEIGHT` to set up your camera:

```
//gsm.game is how I obtain the instance of the main game class
cam = new OrthographicCamera(GdxGame.WIDTH,GdxGame.HEIGHT);

```

It keeps the window nice and pretty without skewing. If you make a portrait game do the scaling based on your `prefferedHeight / HEIGHT`
> 0 votes

---
Tags: java, libgdx
---


title: SceneKit – White layer covering my tube

text:
# Question
Title: SceneKit – White layer covering my tube
I have a simple tube node in my scene that isn't displaying properly.

When I rotate it to face the camera, more than half of it is covered by some invisible sheet. When I rotate the tube enough, it gets completely covered by the sheet. Here is a screenshot showing my problem:

As you can see, the red tube is covered on its top-end. If I were to rotate it far enough, it would disappear.

There is nothing complex in my code, it's all very simple. In fact, here is is:

```
// Create tube geometry.
    let tubeGeometry = SCNTube(innerRadius: 5.0, outerRadius: 6.0, height: 200.0)
    tubeGeometry.firstMaterial!.diffuse.contents = UIColor.redColor()/*UIImage(named: "GreenTube")*/

    // Create tube node.
    let tube = SCNNode(geometry: tubeGeometry)
    tube.position = SCNVector3Make(0.0, -11.0, 0.0)
    tube.rotation = SCNVector4Make(1.0, 0.0, 0.0, Float(M_PI_2))
    self.rootNode.addChildNode(tube)

```

# Answer
> 0 votes
I fixed it! It turns out my Field of Vision was set too low. I went into my custom camera's `xFov` and `yFov` and set them to be a bit bigger than the length of my tube. My tube was merely going out of view too soon :)

---
Tags: swift, scenekit
---


# Question
Title: Why does compiling Unreal Engine fail in Xcode on OS X?
I'm following Ben Tristem's latest course on using Unreal Engine and coding in C++. I have issues getting into Unreal however: when I create a project, it does its stuff, i.e. generates code, compiles it etc. but then I get this message:

I tried to open it with Xcode but I don't know what to do next… could someone help me out?

# Answer
The answer at https://answers.unrealengine.com/questions/274013/fresh-install-new-c-third-person-project-doesnt-co.html suggests that you are using a version of OSX or XCode that is not currently supported by Unreal Engine. I don't know the version you are using, but you should check the UE documentation and make sure you have the correct versions.

Otherwise you could just try to edit the method declaration in the error to `override`. See http://en.cppreference.com/w/cpp/language/override for reference.
> 2 votes

---
Tags: unreal, unreal-4, xcode
---


# Question
Title: How does collisions caculates when developing game in Build an HTML5 Game book
I don't understand author's logic when calculating collisions between two circles (bubbles). Here is the Calculating collisions section.

Author writes:

> The bubble being fired follows a set of coordinates defined by the equations:
>
> px = ex + tdx py = ey + tdy
>
> where px and py are points on the trajectory of the bubble’s center point. The calculation of px and py happens in jQuery’s animate method and is the standard equation for moving a point along a line. Next, we’ll calculate t at the closest point on this line to the center of the bubble that we’re checking against:
>
> var t = dx * distToBubble.x + dy * distToBubble.y;

I don't understand what `t` is and why it calculates by the following formula:

`var t = dx * distToBubble.x + dy * distToBubble.y;`?

# Answer
They are describing how to get the nearest point on the moving circle trayectory to the "checking" circle center, without using vector math. Or better , using it but without telling that.

```
var t = dx * distToBubble.x + dy * distToBubble.y;

```

is simply the dot product of the moving vector (velocity vector) and the direction vector from moving circle. Hope this image can help :

t is the "projection length" of red vector on black vector. With t you can calculate the green vector and so the position of red point(the closest point). If closest point is inside checking circle then there will be a collision..
> 1 votes

# Answer
I *think* that the author is describing how to calculate a bounding sphere in a (rather poor, IMHO) roundabout way. I skimmed over the text you linked to and it doesn't make any sense to me, either.

The basic concept of a bounding sphere is that the distance between the center of the object and any point on the sphere is always the same. So all you need to do to calculate collision is check whether or not the point you're testing against is closer to the center point of the object than the radius of the sphere.

I imagine that the point the author wants to test against is a point on the trajectory of the bubble and they're using vector math to find it, or trying to find a common point between the vector of the bubble's path and a vector from whatever it's colliding against.

What I would do instead is using the distance formula to find the distance between the center points of both bubbles (or whatever) and if that distance is smaller than the radius of the bubble, you have a collision. My gut feeling is that is what the author is trying to explain but not doing it very clearly.

Finding the distance between two points
> 0 votes

---
Tags: collision-detection, mathematics, linear-algebra
---


# Question
Title: Libgdx: more efficient way of using Vector 3?
I currently use

```
if(cam.frustum.pointInFrustum(new Vector3((float)posX, (float)posY, 0)))

```

To check if my sprite is in the camera's view. I have to make a new Vector3 every frame wich is very inefficient.

Is there a better way to do this?

# Answer
If it's the allocation of the `Vector3` you're worried about you might consider keeping an instance as a private member of the class and re-use that;

```
private final Vector3 v3 = new Vector3();

public void yourMethod() {
  if(cam.frustum.pointInFrustum(v3.set((float)posX, (float)posY, 0))) {
  }
}

```

Another way, if you have many of these instances you could apply pooling;

```
private final Pool<Vector3> pool = new Pool();

public void yourMethod() {
  Vector3 v3 = pool.obtain();
  if(cam.frustum.pointInFrustum(v3.set((float)posX, (float)posY, 0))) {
  }
  pool.free(v3);
}

```
> 1 votes

---
Tags: java, libgdx, game-design, optimization
---


title: Efficient use of pathfinding

text:
# Question
Title: Efficient use of pathfinding
I'm doing a post-mortem on my game project, and this problem kept bugging me as my team couldn't solve it throughout.

So my game is a pure 2D top-down shooter built with Unity3D, with enemies constantly spawning and pathing to the player. The top-down shooter has narrow passages making it somewhat maze-like, and for now I can have anywhere from 1 to 20 enemies in-game at any point in time. I use a 2D pathfinding package which I assume to be sufficiently optimized.

Currently it performs terribly thanks to the pathfinding algorithm being called too many times.

What tricks can I use to reduce the number of calls?

PS. I know I could use NavMesh and all that built-in awesomeness. But the way we had set the game up denied us the use of those features :/

# Answer
Instead of pathing from each new enemy to the player as they spawn of the player moves significantly. Do a floodfill from the player to fill the entire map with how far the player is from each tile and which way he is. Then for pathing you just follow the arrows.

The floodfill Will only need to update the neighbours of the tiles whose value changed after the player moved. And you can limit how many tiles get updated per frame.

As another point you may need to double check your heuristic that you gave the package. A\* is only as good as its heuristic.
> 2 votes

# Answer
You probably run the pathfinding algorithm every frame. It should only happen once, when the enemy spawns. If your area is destroyable, then you will need to do it every time an obstacle is destroyed.
> 0 votes

---
Tags: unity, path-finding
---


# Question
Title: Slick2D: Animation not being parsed from spritesheet correctly
I have a 960x960 spritesheet with each tile being 192x192. I initialized my spritesheet and animation like so:

```
spritesheet = new SpriteSheet("resources/spritesheets/player.png", 192, 192);
walkingLeft = new Animation(spritesheet, 3, 0, 0, 1, true, 20, true);

```

When I attempt to render the animation, I get a `java.lang.ArrayIndexOutOfBoundsException: -1` error. This error doesn't occur when I'm creating an animation from images in the same row. Therefore, I'm assuming that the error is being caused because of the way Slick is handling horizontal scanning (going to the next row after reaching the end).

# Answer
> 0 votes
I think you need to provide a little bit more information as you may be initialising walking left locally and then in your render method using an uninitialised variable hence the -1 response.

# Answer
> 0 votes
Judging from the documentation on the Animation class in slick, it looks like some of your parameters are incorrect.

> frames - The sprite sheet containing the frames
> x1 - The x coordinate of the first sprite from the sheet to appear in the animation
> y1 - The y coordinate of the first sprite from the sheet to appear in the animation
> x2 - The x coordinate of the last sprite from the sheet to appear in the animation
> y2 - The y coordinate of the last sprite from the sheet to appear in the animation
> horizontalScan - True if the sprites are arranged in hoizontal scan lines. Otherwise vertical is assumed
> duration - The duration each frame should be displayed for
> autoUpdate - True if this animation should automatically update based on the render times

As you can see, your first sprite co-ordinate is (3,0) and your last sprite co-ordinate is (0,1). If you fix this, it should stop the out of bounds error.

---
Tags: java, animation, slick, spritesheet
---


# Question
Title: Is Angry Birds Made Purely Using Bitmaps/Raster graphics?
Being a beginner game developer I would like to start creating my own engine and graphics so I am concerned about how successful games accomplish the graphics portion. My question is, are all the graphics (background, birds, slingshot etc) in Angry Birds made with raster images only and using something like a sprite sheet for character animations?

# Answer
Yes.

You were able to see the sprites when Angry Birds Chrome was available to play and they looked like this:
> 1 votes

---
Tags: java, android, opengl-es
---


# Question
Title: What is the difference between compiler and IDE?
What is the difference between compiler and IDE? Please explain me. because i am new to this terms.

# Answer
> 0 votes
An IDE is an "Integrated Development Environment." It happens to contain a minimum of three things:

* A Text Editor (albeit more complicated than Notepad, but you *can* use Notepad if you're feeling sadistic)
* Code Completion (this is the most powerful thing about using an IDE over Notepad: it can suggest auto-completions or jump you to definitions of classes, methods, or properties)
* A compiler

Often it will have more than this, such as Christer comments below, but this is pretty much the bare minimum: "the ability to modify the code and the ability to run it contained within the same application."

A compiler, then is this:

* A program that takes as input raw code and outputs an executable program file, dll, or other similar binary.

---
Tags: terminology
---


# Question
Title: 2D BoundingBox Collision Detection Problem
I implemented collision detection into my game (using Bounding Boxes) The character is floating above the blocks instead of standing on them. I know what is happening, but I can't figure out how to calculate how high that space is, so I can change the position.

Here is a picture:

# Answer
> 0 votes
If you know the boundingbox size (you should), the character position would be:

```
character.y=floorBoundingBox.y - characterBoundingBox.height

```

You don't actually directly calculate the *difference* between the floor and the character, you calculate the position of colliding objects by pushing them their height or width outside the floor.

---
Tags: java, libgdx
---


title: Modern OpenGL c++ obj loader

text:
# Question
Title: Modern OpenGL c++ obj loader
So i made a obj loader in c++.I used blender to export my files. I tried to draw 2 squares(one perpendicular to the other) and when im looking at them from above some weird black triangles apear, although i have `glEnable(DL_DEPTH_TEST)`

I uploaded a video so you can see the problem https://www.youtube.com/watch?v=1NStm1mFkX0&feature=youtu.be

Vertex shader:

```
#version 330 core

layout (location = 0) in vec3 position;
layout (location = 1) in vec3 normal;
layout (location = 2) in vec2 texCoord;

out vec2 TexCoord;

uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;

void main()
{
    gl_Position = projection * view * model * vec4(position, 1.0f);
    TexCoord=texCoord;
}

```

Fragment Shader

```
#version 330 core

in vec2 TexCoord;

out vec4 color;

uniform sampler2D Texture;

void main()
{
    color = texture(Texture, TexCoord);
}

```

Here is my class

```
#ifndef MESH_H
#define MESH_H

#include "Includes.h"
#include "Shader.h"

struct Vertex
{
    glm::vec3 position;
    glm::vec3 normal;
    glm::vec2 texCoord;
    Vertex(){};
    Vertex(glm::vec3 p,glm::vec3 n,glm::vec2 t)
    {
        position=p;
        normal=n;
        texCoord=t;
    }
};

struct Material{
    char name[100];
    float ns,alpha,illum;
    float amb[3],dif[3],spec[3];
    unsigned int ID;
    string path;
    sf::Image image;
};

class Mesh
{
    public:
        void draw(Shader &shader);
        void loadMesh(const char* fileName);
    private:
        GLuint VAO,VBO,EBO;
        vector<Material>material;
        vector<Vertex> vertex;
        vector<GLuint> indices;
        void loadMaterial(Material &M,string imgPath);
        void setupMesh();
};

#endif // MESH_H

```

And the cpp:

```
void Mesh::loadMaterial(Material &M,string imgPath)
{
    M.path=imgPath;
    M.image.loadFromFile(imgPath);

    M.image.flipVertically();
    glGenTextures(1,&M.ID);
    glBindTexture(GL_TEXTURE_2D,M.ID);

    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_REPEAT);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, M.image.getSize().x, M.image.getSize().y, 0, GL_RGBA, GL_UNSIGNED_BYTE, M.image.getPixelsPtr());
}

void Mesh::loadMesh(const char* fileName)
{
    int i,j,number1,number2,number3,indNormal1,indNormal2,indNormal3,indTC1,indTC2,indTC3,nrFace=0,nrInd=-1;
    char text[256],matName[256],path[256];

    vector<string>tmp;
    vector<string>line;
    vector<glm::vec3>position;
    vector<glm::vec3>normal;
    vector<glm::vec2>texCoord;
    vector<glm::vec3>vertexNormal;
    vector<glm::vec2>texCoordCopy;
    ifstream fin;
    string imageName;
    glm::vec3 v;
    glm::vec2 t;

    fin.open(fileName);
    while(!fin.eof())
    {
        fin.getline(text,256);
        line.push_back(text);
    }
    fin.close();

    string matFileName;
    matFileName=fileName;
    matFileName.resize(matFileName.size()-3);
    matFileName+="mtl";

    fin.open(matFileName.c_str());
    while(!fin.eof())
    {
        fin.getline(text,200);
        tmp.push_back(text);
    }
    fin.close();

    for(i=0;i<tmp.size();i++)///READ MATERIALS
    {
        Material M;
        if(tmp[i][0]=='\n')
            continue;
        if(tmp[i][0]=='n'&&tmp[i][1]=='e'&&tmp[i][2]=='w')
        {
            sscanf(tmp[i++].c_str(),"newmtl %s",&M.name);
            if(tmp[i][0]=='N'&&tmp[i][1]=='s')
                sscanf(tmp[i++].c_str(),"Ns %f",&M.ns);
            if(tmp[i][0]=='K'&&tmp[i][1]=='a')
                sscanf(tmp[i++].c_str(),"Ka %f %f %f",&M.amb[0],&M.amb[1],&M.amb[2]);
            if(tmp[i][0]=='K'&&tmp[i][1]=='d')
                sscanf(tmp[i++].c_str(),"Kd %f %f %f",&M.dif[0],&M.dif[1],&M.dif[2]);
            if(tmp[i][0]=='K'&&tmp[i][1]=='s')
                sscanf(tmp[i++].c_str(),"Ks %f %f %f",&M.spec[0],&M.spec[1],&M.spec[2]);
            if(tmp[i][0]=='K'&&tmp[i][1]=='e')
                i++;
            if(tmp[i][0]=='N'&&tmp[i][1]=='i')
                i++;
            if(tmp[i][0]=='d'&&tmp[i][1]==' ')
                sscanf(tmp[i++].c_str(),"d %f",&M.alpha);
            if(tmp[i][0]=='i'&&tmp[i][1]=='l')
                sscanf(tmp[i++].c_str(),"illum %f",&M.illum);
            if(tmp[i][0]=='m'&&tmp[i][1]=='a')
            {
                tmp[i].erase(tmp[i].begin(),tmp[i].begin()+7);
                i++;
            }
            imageName=fileName;
            for(j=imageName.size()-1;j>=0;j--)
                if(imageName[j]=='/')
                    break;
            imageName.erase(imageName.begin()+j+1,imageName.end());
            imageName+=tmp[i-1];
            loadMaterial(M,imageName);
            material.push_back(M);
        }
    }
    //vector<int>face;

    for(i=3;i<line.size();i++)///READ THE MESHES
    {
       if(line[i][0]=='v'&&line[i][1]==' ')
        {
            sscanf(line[i].c_str(),"v %f %f %f",&v.x,&v.y,&v.z);
            position.push_back(v);
        }
        else if(line[i][0]=='v'&&line[i][1]=='t')
        {
            sscanf(line[i].c_str(),"vt %f %f",&t.x,&t.y);
            texCoord.push_back(t);
        }
        else if(line[i][0]=='v'&&line[i][1]=='n')
        {
            sscanf(line[i].c_str(),"vn %f %f %f",&v.x,&v.y,&v.z);
            normal.push_back(v);
        }
        else if(line[i][0]=='s'&&line[i][1]==' ')
            continue;
        else if(line[i][0]=='u'&&line[i][1]=='s'&&line[i][2]=='e')
        {
            sscanf(line[i].c_str(),"usemtl %s",&matName);
            //face.push_back(nrFace);
        }
        else if(line[i][0]=='f'&&line[i][1]==' ')
        {
            nrFace++;
            sscanf(line[i].c_str(),"f %d/%d/%d %d/%d/%d %d/%d/%d",&number1,&indTC1,&indNormal1,
                                                                  &number2,&indTC2,&indNormal2,
                                                                  &number3,&indTC3,&indNormal3);
            indices.push_back(number1-1);
            indices.push_back(number3-1);
            indices.push_back(number2-1);

            if(position.size()>vertexNormal.size())
                vertexNormal.resize(position.size());
            if(position.size()>texCoordCopy.size())
                texCoordCopy.resize(position.size());
            vertexNormal[number1-1]=normal[indNormal1-1];
            vertexNormal[number2-1]=normal[indNormal2-1];
            vertexNormal[number3-1]=normal[indNormal3-1];
            texCoordCopy[number1-1]=texCoord[indTC1-1];
            texCoordCopy[number2-1]=texCoord[indTC2-1];
            texCoordCopy[number3-1]=texCoord[indTC3-1];
        }
    }
    //face.push_back(nrFace+1);

    for(i=0;i<position.size();i++)
        vertex.push_back(Vertex(position[i],vertexNormal[i],texCoordCopy[i]));
    setupMesh();
    fin.close();
}

void Mesh::setupMesh()
{
    int i;

    glGenVertexArrays(1, & VAO);
    glGenBuffers(1, & VBO);
    glGenBuffers(1, & EBO);
    glBindVertexArray( VAO);
    glBindBuffer(GL_ARRAY_BUFFER,  VBO);

    glBufferData(GL_ARRAY_BUFFER,  vertex.size() * sizeof(Vertex),
                 & vertex[0], GL_STATIC_DRAW);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,  EBO);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER,  indices.size() * sizeof(GLuint),
                 & indices[0], GL_STATIC_DRAW);
    // Vertex Positions
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex),
                         (GLvoid*)0);
    // Vertex Normals
    glEnableVertexAttribArray(1);
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex),
                         (GLvoid*)offsetof(Vertex, normal));
    // Vertex Texture Coords
    glEnableVertexAttribArray(2);
    glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex),
                         (GLvoid*)offsetof(Vertex, texCoord));
    glBindVertexArray(0);
}

void Mesh::draw(Shader &shader)
{
    int i,j,ind;

    //glEnable(GL_DEPTH_TEST);
    shader.Use();

    glBindTexture(GL_TEXTURE_2D, material[0].ID);
    glBindVertexArray(VAO);
    glDrawElements(GL_TRIANGLES, indices.size(), GL_UNSIGNED_INT, 0);
    glBindVertexArray(0);
}

```

The `loadMesh()` fuction gets a fileName(the exemple.obj file) and reads the content from it.Also it reads the exemple.mtl file content.Then it starts building the data from that file.The first file is the mtl file.It reads all the parameters and saves them into the vectormaterial .Then the function builds data from the obj file.

Then the setupMesh function uses the opengl functions. I know that my code is incomplete since my program doesnt know which texture to bind for each face,it just binds the first one.But i have a model which has only one texture so i figured it should work.

# Answer
Try using `glCullFace( GL_BACK );`
> -1 votes

---
Tags: opengl, c++, blender, obj
---


title: unable to render to multiple textures

text:
# Question
Title: unable to render to multiple textures
I'm trying to make an example of deferred rendering. I'm trying to render to three separate textures the position, the normal and the color. Here is the setup :

```
void setup()
{
    //generate and bind fbo
    glGenFramebuffers(1, &fboHandle);
    glBindFramebuffer(GL_FRAMEBUFFER, fboHandle);

    //generate the depth buffer
    glGenRenderbuffers(1, &depthBuf);
    glBindRenderbuffer(GL_RENDERBUFFER, depthBuf);
    glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, WindowSize, WindowSize);
    glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depthBuf);

    //Create positin, normal and color buffers
    createBufTex(GL_TEXTURE0, GL_RGB32F, posTex);
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, posTex, 0);
    createBufTex(GL_TEXTURE1, GL_RGB32F, normTex);
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, normTex, 0);
    createBufTex(GL_TEXTURE2, GL_RGB8, colorTex);
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2, GL_TEXTURE_2D, colorTex, 0);

    //Attach the texture to fbo

    GLenum drawbuf[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2 };

    glDrawBuffers(3, drawbuf);

    if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
        std::cout << "Frame buffer not created. \n" << glCheckFramebufferStatus(GL_FRAMEBUFFER);

    //unbind the frame buffer
    glBindFramebuffer(GL_FRAMEBUFFER, 0);

    createGeometry();

    glm::mat4 view = glm::lookAt(glm::vec3(0.0f, 0.0f, 3.0f), glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f));

    glm::mat4 proj = glm::perspective(45.0f, 800.0f / 800.0f, 0.1f, 100.0f);

    PV = proj * view;

    LightPos = glGetUniformLocation(renderProgram, "pointLight.position");
    LightIntensity = glGetUniformLocation(renderProgram, "pointLight.Intensity");

    defaultlight.intensity = glm::vec3(0.7f);

    renderPlane.initBuffer();
}

```

Here is the render call:

```
glm::mat4 MVP;

// Clear the color buffer and the depth buffer
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

// Clear the screen to white
glClearColor(1.0, 1.0, 1.0, 1.0);

// Tell OpenGL to use the shader program you've created.
glUseProgram(program);

glBindFramebuffer(GL_FRAMEBUFFER, fboHandle);
glViewport(0, 0, 800, 800);
{
    //Sphere1
    // Set the uniform matrix in our shader to our MVP matrix for the first object.
    MVP = PV * glm::translate(glm::mat4(1), sphere1.origin);
    glUniformMatrix4fv(uniMVP, 1, GL_FALSE, glm::value_ptr(MVP));
    // Draw the Gameobjects
    glBindVertexArray(sphere1.base.vao);
    glDrawArrays(GL_TRIANGLES, 0, sphere1.base.numberOfVertices);

    //Sphere2
    // Set the uniform matrix in our shader to our MVP matrix for the first object.
    MVP = PV * glm::translate(glm::mat4(1), sphere2.origin);
    glUniformMatrix4fv(uniMVP, 1, GL_FALSE, glm::value_ptr(MVP));
    // Draw the Gameobjects
    glBindVertexArray(sphere2.base.vao);
    glDrawArrays(GL_TRIANGLES, 0, sphere2.base.numberOfVertices);
}

glUseProgram(renderProgram);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glViewport(0, 0, 800, 800);
{
    glBindVertexArray(renderPlane.vao);

    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, posTex);

    glActiveTexture(GL_TEXTURE1);
    glBindTexture(GL_TEXTURE_2D, normTex);

    glActiveTexture(GL_TEXTURE2);
    glBindTexture(GL_TEXTURE_2D, colorTex);

    glDrawArrays(GL_TRIANGLES, 0, renderPlane.numberOfVertices);
}

```

The vertex Shader :

```
#version 430 core // Identifies the version of the shader, this line must be on a separate line from the rest of the shader code

layout(location = 0) in vec3 in_position;    // Get in a vec3 for position
layout(location = 1) in vec3 in_normal;
layout(location = 2) in vec4 in_color;        // Get in a vec4 for color

out vec3 out_pos;
out vec3 out_normal;
out vec4 out_color; // Our vec4 color variable containing r, g, b, a

uniform mat4 MVP; // Our uniform MVP matrix to modify our position values

void main(void)
{
    out_color = in_color;    // Pass the color through
    gl_Position = MVP * vec4(in_position, 1.0); //w is 1.0, also notice cast to a vec4
}

```

and the Fragment Shader:

```
#version 430 core // Identifies the version of the shader, this line must be on a separate line from the rest of the shader code

layout(location = 0) out vec3 texPos;
layout(location = 1) out vec3 texNormal;
layout(location = 2) out vec3 texColor;

in vec3 out_pos;
in vec3 out_normal;
in vec4 out_color;    // Take in a vec4 for color

void main(void)
{
    texPos = out_pos;
    texColor = vec3(1.0f, 0.0f, 1.0f);
    texNormal = out_normal;
}

```

I'm using Nvidia's Nsight to view the pipeline. I figured out that the textures are properly being bound to the FBO. The Texture's color values are not altered at all, even though the depth buffer clearly shows two spheres being rendered. Any suggestions would be helpful.

# Answer
I figured out the cause of the problem. I had to clear the depth buffer before rendering the screen filling quad, even though I switch the frame buffer. Apparently the quad culls the objects behind it, causing the textures not to appear

I did `glClear(GL_DEPTH_BUFFER_BIT)` before I unbound the FBO.

This fixed the issue for me.
> 1 votes

---
Tags: opengl, deferred-rendering, multiple-render-targets, fbo
---


title: Displaying Trajectory Path

text:
# Question
Title: Displaying Trajectory Path
How can I display trajectory path **exactly** as in this image?

I have used `void OnDrawGizmos`, but that only displays trajectory in the editor and without any arrows like shown below.

Trajectory with `void OnDrawGizmos`

Script:

```
public Transform someObject; //object that moves along parabola.
float objectT = 0; //timer for that object

public Transform Ta, Tb; //transforms that mark the start and end
public float h; //desired parabola height

Vector3 a, b; //Vector positions for start and end

void Update () {
    if ( Ta &&  Tb ) {
        a = Ta.position; //Get vectors from the transforms
        b = Tb.position;

        if ( someObject ) {
            //Shows how to animate something following a parabola
            objectT = Time.time % 1; //completes the parabola trip in one second
            someObject.position = SampleParabola( a, b, h, objectT );
        }
    }
}

void OnDrawGizmos () {

    //Draw the parabola by sample a few times
    Gizmos.color = Color.red;
    Gizmos.DrawLine( a, b );
    float count = 20;
    Vector3 lastP = a;
    for ( float i = 0; i < count + 1; i++ ) {
        Vector3 p = SampleParabola( a, b, h, i / count );
        Gizmos.color = i % 2 == 0 ? Color.blue : Color.green;
        Gizmos.DrawLine( lastP, p );
        lastP = p;
    }
}

#region Parabola sampling function
/// <summary>
/// Get position from a parabola defined by start and end, height, and time
/// </summary>
/// <param name='start'>
/// The start point of the parabola
/// </param>
/// <param name='end'>
/// The end point of the parabola
/// </param>
/// <param name='height'>
/// The height of the parabola at its maximum
/// </param>
/// <param name='t'>
/// Normalized time (0->1)
/// </param>S
Vector3 SampleParabola ( Vector3 start, Vector3 end, float height, float t ) {
    float parabolicT = t * 2 - 1;
    if ( Mathf.Abs( start.y - end.y ) < 0.1f ) {
        //start and end are roughly level, pretend they are - simpler solution with less steps
        Vector3 travelDirection = end - start;
        Vector3 result = start + t * travelDirection;
        result.y += ( -parabolicT * parabolicT + 1 ) * height;
        return result;
    } else {
        //start and end are not level, gets more complicated
        Vector3 travelDirection = end - start;
        Vector3 levelDirecteion = end - new Vector3( start.x, end.y, start.z );
        Vector3 right = Vector3.Cross( travelDirection, levelDirecteion );
        Vector3 up = Vector3.Cross( right, travelDirection );
        if ( end.y > start.y ) up = -up;
        Vector3 result = start + t * travelDirection;
        result += ( ( -parabolicT * parabolicT + 1 ) * height ) * up.normalized;
        return result;
    }
}

```

# Answer
As your desired image reflects that you want it in 2D, so I have modified your current script which would draw a path from your given Game Object, decided start position, mouse or finger position would be the end position. Other than that you can specify number of elements should be drawn on the path.

Well, have a look and give it a try. Comments will also help you a little bit.

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

public class Test5 : MonoBehaviour
{
    public Transform _moveableObject; // Objet to move on path
    public GameObject _trajectoryElement; // GO to draw in path of trajectory. GO having signle white arrow attached on it
    public Transform _startPosition; // Start position from where trajectory should start and mouse of finger position is the destination
    public float _height; //desired parabola height
    public int _numberOfElements = 10; // Number of elements should draw in path of parabola

    Vector3 a, b; //Vector positions for start and end
    List<GameObject> _trajectoryElementsContainer = new List<GameObject> ();

    void Start ()
    {
        // For now I have instantiated all the objects will be drawn on the path of parabola. Then did handle them later.
        // Please modify it according to your needs
        for (int i = 0; i < _numberOfElements; i++)
            _trajectoryElementsContainer.Add (Instantiate (_trajectoryElement) as GameObject);
    }

    void Update ()
    {
        if (Input.GetMouseButton (0) && _startPosition) {
            a = _startPosition.position; //Get vectors from the transforms
            a = new Vector3 (a.x, a.y, 0);
            b = Camera.main.ScreenToWorldPoint (Input.mousePosition);
            b = new Vector3 (b.x, b.y, 0);

            float distributionTime = 0;
            for (float i = 1; i <= _numberOfElements; i++) {
                distributionTime++;
                Vector3 currentPosition = SampleParabola (a, b, _height, i / (float)_numberOfElements);
                _trajectoryElementsContainer [(int)i - 1].transform.position = new Vector3 (currentPosition.x, currentPosition.y, 0);

                Vector3 nextPosition = SampleParabola (a, b, _height, (i + 1) / (float)_numberOfElements);
                float angleInR = Mathf.Atan2 ((nextPosition.y - currentPosition.y), (nextPosition.x - currentPosition.x));
                _trajectoryElementsContainer [(int)i - 1].transform.eulerAngles = new Vector3 (0, 0, (Mathf.Rad2Deg * angleInR) - 90);
            }

            if (_moveableObject) {
                //Shows how to animate something following a parabola
                _moveableObject.position = SampleParabola (a, b, _height, Time.time % 1);
            }
        }
    }

    void OnDrawGizmos ()
    {

        //Draw the parabola by sample a few times
        Gizmos.color = Color.red;
        Gizmos.DrawLine (a, b);
        float count = 20;
        Vector3 lastP = a;
        for (float i = 0; i < count + 1; i++) {
            Vector3 p = SampleParabola (a, b, _height, i / count);
            Gizmos.color = i % 2 == 0 ? Color.blue : Color.green;
            Gizmos.DrawLine (lastP, p);
            lastP = p;
        }
    }

    #region Parabola sampling function
    /// <summary>
    /// Get position from a parabola defined by start and end, height, and time
    /// </summary>
    /// <param name='start'>
    /// The start point of the parabola
    /// </param>
    /// <param name='end'>
    /// The end point of the parabola
    /// </param>
    /// <param name='height'>
    /// The height of the parabola at its maximum
    /// </param>
    /// <param name='t'>
    /// Normalized time (0->1)
    /// </param>S
    Vector3 SampleParabola (Vector3 start, Vector3 end, float height, float t)
    {
        float parabolicT = t * 2 - 1;
        if (Mathf.Abs (start.y - end.y) < 0.1f) {
            //start and end are roughly level, pretend they are - simpler solution with less steps
            Vector3 travelDirection = end - start;
            Vector3 result = start + t * travelDirection;
            result.y += (-parabolicT * parabolicT + 1) * height;
            return result;
        } else {
            //start and end are not level, gets more complicated
            Vector3 travelDirection = end - start;
            Vector3 levelDirecteion = end - new Vector3 (start.x, end.y, start.z);
            Vector3 right = Vector3.Cross (travelDirection, levelDirecteion);
            Vector3 up = Vector3.Cross (right, travelDirection);
            if (end.y > start.y)
                up = -up;
            Vector3 result = start + t * travelDirection;
            result += ((-parabolicT * parabolicT + 1) * height) * up.normalized;
            return result;
        }
    }
    #endregion
}

```

**NOTE:** This script is not in proper way and un-optimized. Please make it better for performance sake. (if needed)

**Edit:** The "- 90" factor is here (in last line of update)due to my arrow image is originally vertical (pointing upward/sky) that is why it is balancing the angle. This script is also expecting from you that if you give white arrow like you have shown in question, then try to rotate it from outside the Unity as it should point to the sky otherwise you'd have to play with that "- 90" factor :)
> 2 votes

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


# Question
Title: How to dynamically create an UI text Object in Unity 5?
I have been searching for something that should be simple, but Unity 5's documentation on that is fairly outdated. What I want to achieve is to be able to create UI Text totally from script, i.e. fully dynamically - in my real case application, I will do that in a loop of not pre defined number of iterations.

A search using Google will find quite many examples on how to do that, but all I saw either use methods that are already deprecated (are from before Unity version 5) or are simply wrong (no surprise here...). I already know that I should first add a Canvas to my project, then I should include `using UnityEngine.UI` in my C# code, and also that I could declare a UI Text like `Text _guitext`.

However, the code below does not work. I mean, it's not that it crashes, but rather that nothing is shown:

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

public class MyClass: MonoBehaviour {

Text _guitext;

// Use this for initialization
void Start () {
    _guitext.text = "testing";
}

// Update is called once per frame
void Update () {
}
}

```

Worse than that, it seems that while game is played, no new object appears in the object hierarchy list.

Could you please point me out in the right direction here? Thanks.

# Answer
> 9 votes
I think what you are looking for is something like following:

```
GameObject CreateText(Transform canvas_transform, float x, float y, string text_to_print, int font_size, Color text_color)
{
    GameObject UItextGO = new GameObject("Text2");
    UItextGO.transform.SetParent(canvas_transform);

    RectTransform trans = UItextGO.AddComponent<RectTransform>();
    trans.anchoredPosition = new Vector2(x, y);

    Text text = UItextGO.AddComponent<Text>();
    text.text = text_to_print;
    text.fontSize = font_size;
    text.color = text_color;

    return UItextGO;
}

```

It means, you first create an Empty GameObject. Then you add a Text component, with the specific local and/or anchored parameters, set the desired text and its color, then you make this object a child of the empty game object.

You want to retrieve the UI Text information from or set variable of that object you've created via script, you can then just use `yourGOname.GetComponent<Text>().text`, `yourGOname.GetComponent<Text>().font`, etc.

And of course, for that to work you need to be `using UnityEngine.UI`.

# Answer
> 4 votes
If you are looking for a quick&dirty solution for debugging, you can still use the old Unity 4 solution. Implement the `OnGUI` event of any MonoBehavior you have always active to call the GUI class to add some UI element to the current rendering frame.

```
void OnGUI() {
    GUI.Label(new Rect(10, 10, 100, 20), "Hello World!");
}

```

If you want to use the canvas, you need to add a script to the canvas which:

1. creates a new `GUIText` game object
2. sets the text on that object
3. appends it as a child to the `transform` of the canvas

# Answer
> 3 votes
1. Do you mean you want *change* the **uitext dynamically**?
If you want to change it, first you have to attach your script to GameObject. Then bind your variables. Tutorials could be found here

```
transform.gameObject.GetComponent<Text>().text = "123";

```
2. If you want to create **uitext** which is **not** in *Hierarchy* beforehand.
You could use GUI. GUI Label
Put the created instances in OnGUI. It is like the update which is called every frame.
3. Actually 2nd answer *does not* create uitext object.
But it will achieve the same results.
If you really want the uitext object instead of the effects; you may do it in a **prefab**, and initiate it in runtime. However, the uitext should be child of canvas.

---
Tags: unity, gui, text
---


title: Find Minion with shortest path

text:
# Question
Title: Find Minion with shortest path
I'm working on a game like Settlers III/IV. There are buildings which produce goods which have to be gathered by carrier units.

I have to find the carrier with the shortest path to collect the goods. So far, not a big deal. I simple do a expanding circle, starting from the production building, and choose the first carrier found due it has the shortest direct way.

If this carrier can't reach the building (e.g. is on another island or so), the search goes on.

But now take a look at my awesome paintskills. The black line is an obstacle which my minions can't get over. Red lines are direct paths, blue is absolute path.

The first carrier is A, but it's direct way is blocked. Second is B, direct way blocked as well and third, C, has the longest path of all.

As you easily can guess, I want to sent B due it has the shortest absolute path.

What's the lowest affort do determinate if a carrier with blocked direct way has a shorter way then a carrier with a longer direct way?

I'd love to have some lecture about that, but I only was able to find (a lot) of pathfinding where the unit itself searches the path, not the target searches the unit with shortest path.

Edit: Simply trying out until the minion with shortest path is found is no solution. I don't want to make it stuttering on a i7 or so. Settler 3 is a 17 years old game and somehow they have implemented such a functionality without needing over 9000 gigahertz. If you have any idea which involves routing tables or whatever, I'm happy. Goal is simply to find the minion which could arrive as fastest, in the shortest time possible. Not a big deal if therefore 200mb of routing table have to be generated or whatever.

# Answer
> 4 votes
You could use Breadth First Search or Dijkstra's Algorithm to find the paths from the building to all carriers. I have a demo here of a related problem. Once you find a carrier, stop; that's the closest one to the building (taking into account walls etc.).

Breadth First Search can be quite fast. Dijkstra's Algorithm is a little bit slower but it can handle varying movement costs. It's very much like your expanding circle idea; run the animations on my page to see how it expands in all directions, but can also go around walls.

# Answer
> 2 votes
You have almost answered your question in your post. You say that you

> simple do a expanding circle, starting from the production building, and choose the first carrier found due it has the shortest direct way.

So this should be your initial point, the production building. You do not need to cycle through all of your idle minions to get the nearest one, instead you can start searching for the idle minions around your building and stop whenever you find one.

Having no idea how your map and pathing models are setup, I would assume that you have some kind of two-dimensional array as a map, with XY orientation and elements meaning what type of object you have on the map. Buildings, trees, roads etc. Minions and other "moveable" objects go in separate array with just XY coordinates for their position.

If this is your case - you can just send a wave from your production building and see which idle minion it arrives first. It would be your nearest idle minion.

If you don't have this, and you have XY coordinates system, with the list of the objects on the map and their XY coordinates, widths, lengths, shapes, etc. then it's going to be painful.

If your map is huge and sending a wave will lead to significant calculations and slows down the system, if your map and objects on it are 'indestructible', 'immovable' etc. you can build up hashtable with the shortest paths or just lengths of the shortest paths from any-to-any points on the map. There would always be no more than n\*(n-1)/2 elements in your hashtable, where n is total number of the 'map-squares'.

If your map and objects are changeable, you still can build up such hashtable and update only the part, where your changed points belong to. Consider you build new building on the tile (x=10, y=15), meaning that you need to update only paths for the pairs of points, which shortest paths lead through this point.

Having such a table, you can easily get all the paths starting from the point where your production building stands, sort them by lengths, join with the points where your minions stand and get the one with the shortest path.

I know, it all sounds like you need to build some path-finding engine from a scratch, but when you do it you know it's got to work perfectly.

# Answer
> 0 votes
I don't known if you've solved the issue since the question was posted, but how do you expect to know which is the carrier that is closer to the building at a given time, if you don't know their shortest path? It does not make sense. You need to calculate some sort of path-finding between building and carriers. And just after that, select the closest carrier. There is no logical way of selecting the closest before knowing how much close they are.

> I'd love to have some lecture about that, but I only was able to find (a lot) of pathfinding where the unit itself searches the path, not the target searches the unit with shortest path

You see, there is the confusion. The two things are the same: path-finding. The only difference is that, you are right, there might optimizations for the case when you have to run it for multiple agents (e.g. carriers) but the target is the same for all of them (e.g. the currently selected building). It is still the same path-finding, but just optimized.

I will get into that shortly, but first let me just comment as a disclaimer that you are assuming just too fast thatthe a game from the 1990s was not using path-finding for doing the job you want just because of older computers. It is actually quite likely that it did use it. You over-estimate the CPU cost of path-finding and under-estimate its use in the past. Even older games employed path-finding fora bunch of objects.

That said, here is one way of *optimizing* the path-finding for the situation when the target is the same for multiple agents:

1) it can be simply called the "early exit approach". Sure, if you are testing path-finding for 10 carriers in relation to a given building, one of the end points of the path will be always the same: the building's position. And you are right: there is something you could do with that particularity of your problem that will help you immensely.

The process is the following. Suppose you have to try 10 idle carriers. So, you run a path-finding algorithm for the 1st and then finds the shortest path from that 1st to the building and save it's length (in terms of number of tiles, not in direct straight distance). Now, you start doing the path-finding for the 2nd. Whenever a path being evaluated gets bigger than the saved one, you stop and exit its evaluation. If it ends up being shorter than the saved one, then you of course substitute the former saved one by this new. You then move on to the next carrier. So forth and so on.

Depending on how you implement that and your map is, then yes, it can give you a great performance advantage, because you can stop evaluating carrier's paths faster.

Now, keep in mind that in all and any well-implemented path-finding, you have a couple of other optimizations that you should **always** consider.

2) search less: just by filtering out the non-idle carriers, you decrease significantly the number of objects to path-find.

3) search in fewer places: spatial partitioning is a god-sent. You can (and actually almost always should) divide your map into areas (squares, irregular areas, whatever). Then, the first thing is to detect which carriers are in the same area as the building (or in same area + neighbor areas). And these are the carriers you wanna path-find, not all in the map. This technically is the very basic optimization for any path-finding. Although people frequently forgot about it, it has been around in the game industry for quite a long time actually.

As a bonus, keep in mind that nowadays open-map games usually use nav-mesh for path-finding, instead of tile-based grids:

4) nav-mesh - no matter if your building game uses square tiles, hexagonal tiles or whatever, if your game can have nav-meshes built on the fly, your path-finding for a building game like yours will probably be very, very cheap, in comparison to any tile-based solution (squared or hexagonal).

---
Tags: path-finding
---


title: What exactly is a 'set of states'?

text:
# Question
Title: What exactly is a 'set of states'?
Whilst looking into game-oriented applications of programming patterns I discovered a question on this site which suggests that a 'set of states' is superior to a 'stack of states' but does not clarify how a 'set of states' would be applied.

A stack of states is simple enough to comprehend - the state on the top is the active state.

But what exactly is a set of states? A set as I understand it is merely a collection of unique objects (i.e. there are no duplicates). Presumably all the states in the set are currently active. But sets are unordered, so how does one maintain order in an unordered collection? An ordered set could be used, but that then brings the question of why use a sorted set and not a list - what benefit does the uniqueness bring? I'm just not sure I can imagine how such a thing would be implemented or what benefits it would bring. (Presumably the former issue is causing the latter).

So **what exactly is a 'set of states'?** (In the context of game design/programming).

# Answer
> 3 votes
From user744's answer:

> e.g., .../MainMenu/Loading was different than .../Loading/MainMenu,

In the second case, when Loading completes, it will pop MainMenu and, presumably, push GamePlay to replace it. The resulting stack would, then, be Loading/GamePlay. MainMenu has disappeared and the Loading screen never goes away.

After Loading completes and GamePlay starts, the user may load again:

```
Loading/GamePlay/MainMenu/Loading

```

The second Loading actually needs to, first, cancel GamePlay, destroy the world and unload any unused resources. Without peeking, Loading doesn't know what precedes it in the stack and that is the reason he had to add the LoadingGamePlay state (Re: "ugly #1"). This would presumably re-load the world without destroying a bunch of resources just to turn around and recreate them.

It sounds like he was forced to add a large number of band-aids for many similar issues he encountered along the way and they eventually outweighed the benefits he envisioned from using a stack.

**As a set of states:**

```
if (currentState & 0x01) MainMenu;
//Not elseif because User744 allowed simultaneous MainMenu and Loading
if (currentState & 0x02) Loading;
else GamePlay;

```

The set is still serviced in a stack-like manner but, now, Loading, can be specifically disabled by any state, at any time; you don't need to know where in the stack it is or what's in-between it and the top.

```
currentState &= ~0x02; //Disable Loading (from anywhere)
currentState |= 0x01; //Show MainMenu (from anywhere)

```

The function pointers can point to sub-sets and/or sub-stacks:

```
if (currentState & 0x01) Menu;
...

```

Where Menu *privately* tracks which menu(s) are enabled/visible/active with its' own set/stack.

```
if (currentMenuState & 0x01) MainMenu;            //Only one
else if (currentMenuState & 0x02) Options;        //of these
else if (currentMenuState & 0x04) KeyBinds;       //three
if (currentMenuState & 0x08) SaveOrDiscardDialog; //and possibly this one

```

Options **or** KeyBinds can invoke SaveOrDiscardDialog.

---
Tags: software-engineering, state
---


# Question
Title: Should I use secure WebSockets for a game?
Is SSL necessary for a web game? I'm using Node.js with socket.io.

Without it, when using unsecured networks someone on the LAN could change commands being sent to the server and "take over" a player. But this could only happen on unsecured shared networks, so it doesn't sound too bad. Or is it?

And lets ignore the authentication phase for a moment and assume this part is secured, are there any other reasons why I should use SSL on the sockets?

# Answer
**Yes. You definitely should.**

Use Let's Encrypt to get a free SSL certificate (or as many as you want or need). SSL is always good to have: without it, man-in-the-middle attacks will be launched, by the NSA if no-one else.

Most multiplayer games (e.g. Minecraft) just use raw packets. There's little reason to encrypt packets after one is authenticated as only the network service provider (e.g. Verizon/Virgin/TalkTalk) can fake TCP packets.

However, if you're hosting your game on your website then the whole thing has to be in SSL (unless you want to have a sign in page over SSL and another page with no SSL, cringe).

**Advantages of SSL:**

* With Let's Encrypt, the certificates are automatic and free
* Actual security
* A sense of security for users (browser status bar shows lock icon)
* Privacy, no NSA spying
* +1 PageRank in search engines for using SSL
* Negligible performance cost

**Disadvantages:**

* If your game has such high performance requirements that WebSocket SSL is a deal-breaker, then your game is probably too intensive for browsers to begin with, SSL or not.
* I can't think of any others.
> 7 votes

# Answer
Just in addition to @Loblums answer:

AFAIK socket.io uses WebSocket as its default transport. With WebSocket being relatively new, not all intermediaries on the internet may be aware of it and handle it correctly. With an encrypted connection, chances of a WebSocket connection succeeding increase a lot, since then from the outside it's indistinguishable from an encrypted HTTP connection.
> 1 votes

---
Tags: client-server, node.js, security, websocket
---


# Question
Title: Convert transform from world to local space
I have a hierarchical node system. Given a world space transform, I need to obtain the transform for a specific node in local space.

My `Node` class has the following method.

```
public void worldToLocal(Matrix4 world, Matrix4 local) {
    if (dirty) update();
    local.set(worldInverse).mul(world);
}

```

`worldInverse` is the inverse of the node's world transformation matrix.

I'm using LibGDX, so this is equivalent to doing:

```
LOCAL = T^-1 * WORLD

```

T^-1 being the inverse of the node's world transform. However, this doesn't seem to be working correctly.

Let's say we have a node at (2, 4, 0) rotated 180 degrees along its Z axis.

```
    Node node = new Node();
    node.setPosition(2.0f, 4.0f, 0.0f);
    node.rotate(new Vector3(0.0f, 0.0f, 1.0f), 180.0f);

```

Now, the point (1, 7, 0) should be (2, 1, 0) in local space for that node.

```
    Matrix4 local = new Matrix4();
    Matrix4 world = new Matrix4();
    Vector3 pos = new Vector3();

    world.translate(1.0f, 7.0f, 0.0f);
    node.worldToLocal(world, local);
    local.getTranslation(pos);

```

However, I get (1, -3, 0).

I'm using this operation to translate from world space Bullet body transforms to local node transforms.

# Answer
It's a bit vague what you want to do and what you have. But this should help:

```
Vector3 pos = new Vector3();
Matrix4 nodeTransform = new Matrix4();
nodeTransform.setToTranslation(2,  4,  0).rotate(Vector3.Z, 180f);
nodeTransform.getTranslation(pos);
Gdx.app.log("Node pos", pos.toString());
Matrix4 modelTransform = new Matrix4();
modelTransform.setToTranslation(1, 7, 0);
Matrix4 worldTransform = new Matrix4();
worldTransform.set(modelTransform).mul(nodeTransform);
worldTransform.getTranslation(pos);
Gdx.app.log("World pos", pos.toString());
Matrix4 invModelTransform = new Matrix4().set(modelTransform).inv();
nodeTransform.set(invModelTransform).mul(worldTransform);
nodeTransform.getTranslation(pos);
Gdx.app.log("Recalculated node pos", pos.toString());

```

which prints:

```
Node pos: (2.0,4.0,0.0)
World pos: (3.0,11.0,0.0)
Recalculated node pos: (2.0,4.0,0.0)

```

The `nodeTransform` holds the transformation of the node and it is assumed that it is a root node (or it included the parent transform). The `modelTransform` holds the transformation of the model (e.g. it is `ModelInstance#transform`). `worldTransform` holds the resulting matrix (e.g. it is the resulting `Renderable#worldTransform` value and what is used in the shader). `invModelTransform` is the inverse of the `modelTransform` which can be used to recalculate the `nodeTransform` when given the `worldTransform`.
> 2 votes

---
Tags: libgdx, mathematics, matrix, linear-algebra
---


# Question
Title: How can i create a 2 player turn-based board game on a separate android device using unity?
im trying to make a 2 player turn-based board game, i have already made the connection between 2 device. I used photon. They both connect but i don't know how to sync them both to the game. can any one help me? i hope my question is right.

# Answer
Unfortunately, I haven't used Photon so I can't help on that front. If you are only making an Android game (and thus, you don't need to go cross platform game play) then you should look at the play-games-plugin-for-unity which is put out by Google.
> 0 votes

---
Tags: unity
---


# Question
Title: Replicating a worldspace sphere on screen space
I have quite some struggle with a post processing shader that I'm working on.

I use Unity, and I have a shader in which I want to, in screen space as part of post processing, render a sphere that looks like it was drawn in world space.

Now, I've tried some different approaches.

For all attempts, I've given the shader a world position of the sphere,a screen position of the sphere and a camera position named:

```
uniform float4 _SpherePositionCamera;
uniform float4 _SpherePositionCamera;
uniform float4 _SpherePositionWorld;

```

That is, the same point in respectively world-space camera-space and screen-space.

I've tried to project the fragment in screen space into camera space using the inverse projection matrix, and tested in the xy coords minus the screen space center of the sphere are of length \< 1. This gives a circle on the screen that does not really follow a world space shere very well.

the vertex program of the gc code is

```
v2f vert (appdata_img v){
                v2f o;
                o.pos = mul (UNITY_MATRIX_MVP, v.vertex);
                o.uv = MultiplyUV (UNITY_MATRIX_TEXTURE0, v.texcoord.xy);
                o.camPos = mul (inverseProjection, float4((o.uv * 2) - 1, _SpherePositionCamera.zw));
                return o;
            }

```

And the fragment program is

```
        fixed4 frag (v2f i) : COLOR
        {
            // Get the original screen color
            fixed4 screenColor = tex2D(_MainTex, i.uv);

            if ( length(_SpherePositionCamera.xy - i.camPos.xy) < 1 )
            {
                screenColor = ( screenColor + fixed4(1,0,0,1) ) / 2;
            }

            return screenColor;
        }

```

I have been working on this for quite some time, so I'm sorry if I'm somewhat failing at explaining the problem, but I hope that someone has some pointer to what I'm missing.

Thanks.

**EDIT**

I figured a better formulation. I think it might be done by casting a ray from each fragment and testing for intersection with the sphere in world space.

So all I need now is to construct a ray that originates from the near clipping plane and is directed in the "projection" orientation.

could this easily be done?

# Answer
The only point of trying to approximate this sphere is to filter which pixels to modify.

Try this from the reverse direction:

1) Render everything (no sphere) normally using FragmentShader1, transforming with ViewProjection:

```
return tex2D(_MainTex, i.uv);

```

2) Activate an Opaque BlendState so we overwrite whatever was just drawn.
3) Activate FragmentShader2:

```
return (tex2D(_MainTex, i.uv) + fixed4(1,0,0,1)) / 2;

```

2) Render a sphere (or bill-boarded circle) in its' actual 3D location using the same ViewProjection.
3) Fragments are generated to fill its' interior.
4) With culling enabled, fragments are generated for the front OR the back side, but not both.
5) So, for every pixel the sphere ends up occupying, FragmentShader2 will be invoked exactly once, and will overwrite the color previously stored there with the 'enhanced' color.

In this way, you are using actual geometry as a means to apply a specific fragment shader to a specific selection of pixels. Spheres work well for point lights, while cones are used for spot lights.

**Note:**
As proposed, every pixel the sphere occupies gets shaded twice; the first color produced gets overwritten. Bigger spheres means more wasted time. You can solve that problem by using the stencil buffer and drawing the sphere first. Once the sphere's pixels are drawn, the stencil buffer prevents the regular draw call(s) from overwriting it. As such, each shaded pixel requires only a single fragment shader invocation.

**Edit:**
Some of the tutorials are written with XNA, but should still make sense. The HLSL code should be virtually copy-and-pastable.

Zima has a limited selection of tutorials but specifically covers deferred lighting using geometric volumes:
http://www.catalinzima.com/xna/tutorials/deferred-rendering-in-xna/

Riemers.net is where I started. It is XNA-based and has many, many, tutorials. Series 3 covers lights and shadows.
http://www.riemers.net/

Rastertek.com has many tutorials for C++ DX11. The site is somewhat cluttered with unfinished series' (i.e. DX10, DX12) so I've linked directly to a few of the most relevant (DX11 C++):
http://www.rastertek.com/tutdx11.html #30 is point lights using shader math instead of volumes
http://www.rastertek.com/tutterr.html
http://www.rastertek.com/tutdx11s2ter.html
> 0 votes

---
Tags: unity, shaders, projection, perspective, post-processing
---


# Question
Title: LWJGL vs Slick2D vs OpenGL. What is the difference?
I was wondering what the difference was between LWJGL, Slick2D, and OpenGL.

If I'm not mistaken LWJGL is a library and it has the methods and such, but what are the other two for and how do they use each other.

Is Slick2d and OpenGL the same and they both use the LWJGL?

# Answer
You understood everything wrong. OpenGL was the first to come out. It is a low-level API that controls the GPU and such. You can work with it directly from C/C++. The name comes from Open Graphics Library.

LWJGL is a binding of OpenGL to Java, so you can use OpenGL without having to mess with unmanaged C code. The name comes from Light Weight Java Game Library.

Slick2D is just a library that may use OpenGL as its backend to support accelerated 2d graphics.

Edit: Against what other people said, read here: http://slick.ninjacave.com/ LWJGL does not use Slick2D, Slick2D uses LWJGL. And if I'm not mistaken, you can use other OpenGL bindings for Java on it too.

Slick2D is just a framework, it needs some way to get the graphics working, for this it uses a OpenGL Java binding. In this case, LWJGL. You can use LWJGL alone, but it's highly recommended that you use Slick2D too, because it will be much easier to deal with things, since OpenGL is just too broad, it will give you the tools and only this. Slick2D uses this tools to focus all them on accelerated 2D rendering.
> 4 votes

# Answer
LWJGL is a library. Slick2D is a library. OpenGL is a library.

All three are libraries.

Slick2D uses LWJGL (and both are frequently used at the same time), both LWJGL and Slick2D use OpenGL.
> 1 votes

# Answer
OpenGL is low level API that controls the hardware whereas the LWJGL just binds the OpenGL to java to make it easier to use.
> 0 votes

# Answer
In short, OpenGL is basically what the other two are built on. It has methods and classes that might come in handy, but I don't suggest using that.

LWJGL is extremely powerful, but it's not too good for if you just want to write simple games. You'll end up reinventing the wheel by making your own methods to support those of LWJGL. It will come in handy though, for if you want to use 3D graphics, but if your program only uses 2D graphics, I suggest Slick2D.

Slick2D is fast and powerful for 2D graphics. It's relatively easy and if you're looking to just write a simple game using 2D graphics only, I recommend Slick2D.
> 0 votes

---
Tags: opengl, lwjgl, slick
---


title: Raycast a ray to the tip of another ray

text:
# Question
Title: Raycast a ray to the tip of another ray
I'm using unity to raycast a line from the center of my camera viewport to a world position (yellow line).

I also want to cast a ray from the center of my character to this same point (blue line).

I have tried two methods to get this to work, however neither has worked.

The two methods are the following:

```
        if (Input.GetKey (KeyCode.Mouse0)) { //if left click is held down

        Ray crosshairPoint = viewCamera.ViewportPointToRay (new Vector3(0.5f, 0.5f, 0.0f));
        Vector3 crosshairEnd = (crosshairPoint.origin + crosshairPoint.direction * 15);
        Debug.DrawRay (crosshairPoint.origin, crosshairPoint.direction * 20, Color.yellow, Time.deltaTime, false);
        Vector3 intersect = crosshairPoint.GetPoint (20);
        Debug.DrawRay (Vector3.zero, intersect, Color.red, Time.deltaTime, false);

        Debug.DrawRay(_charFace.position, intersect, Color.cyan, Time.deltaTime, false);

    }

```

The red line being drawn is a line from the origin, which has no problem intersecting my camera ray line. The one from my character just refuses to point at the given point.

The second method is the same as above, but using vector math (origin + direction * distance) to get the same point.

Any ideas why the ray from my character won't point the right way, but one from the origin would? Something to do with world vs. local coordinates?

Thanks\]

# Answer
I ended up using Physics.linecast from the \_charface.transform.position to the intersect point.
> -1 votes

---
Tags: unity, raycasting
---


# Question
Title: How often should I calculate the position of a bullet?
In game's like Battlefield or Arma, how many times per second is the position of a bullet calculated?

# Answer
> 1 votes
You should use projectiles only for comparatively slow "bullets" like grenades from a grenade launcher or RPGs.

For very fast bullets like bullets fired from a gun, A ray cast (or a ray-world intersection test) is used instead. A ray is fired from the barrel of the gun (origin of the ray) in the direction the character is aiming (direction of the ray). If the ray hits something, the hit is registered to the code handling bullet hits after a delay which is proportionate to the distance of the hit point from the ray origin.

If you take the average muzzle velocity to be say 1 km/s, the time delay can be calculated using the simple `time = distance / speed` formula. In most cases, the distance will not be more than 100 meters (unless using sniper rifles). If the delay is more than say 0.1 seconds, you could check in the code handling bullet hits whether the object hit (or its bounding box) still contains the hit point. If it does, the bullet *has* hit that object.

You could do extensive research and find the muzzle velocity of each gun you have in the game and use it for each gun separately, or you could use an average figure.

---
Tags: physics, projectile-physics
---


# Question
Title: If I save some information with PlayerPrefs, they will remain saved even if the game is online?
If I make a game in unity and I use the PlayerPrefs function to save the progress and load it in another play, that information will be stored even if the game is loaded on an online platform? I mean: I save a number: 4. Then i close the web page, and enter again and hit load. That number will be saved and loaded properly for every user that plays the game?

# Answer
> 2 votes
So, I did some googling and according to another question it should work online with one exception :

> Basically there are no hard limits, with exception of WebPlayer, which is limited to a 1 MB.

And if this were to happen, it will throw a PlayerprefException.

---

Source : http://answers.unity3d.com/questions/182755/playerprefs-lmitations.html

---
Tags: unity, savegame
---


title: Using Unreal Engine 4 to model Earth

text:
# Question
Title: Using Unreal Engine 4 to model Earth
I could not find a game that has modeled Earth completely (i.e., The entire planet and full round model). Does UE4 have a limitation, such as maximum map size, that limits modeling the entire Earth?

Edit: Context: The goal is to create a flight simulator using UE4 with centimeter granularity for modeling earth.

# Answer
UE4 does not have exactly an inherent limit to what you can simulate at the engine. Nothing like a map size limit or something. However, besides the obvious memory and CPU hardware-limitations that a huge simulation might face, at least another indirect partial limitation related to software, i.e. in this case to UE4, does apply.

It is the fact that most engines like UE4 and Unity use float precision, instead of double precision, to calculate the position of vertices. That is one of the big difficulties in having large worlds. Very roughly speaking, as you move farther from the origin, the float variables that store X, Y and X loose precision. At the beginning, the result is negligible. When something (like a vertex of a mesh or an entire object) goes farther, the positional calculations get very noticeable, causing jittering.

To better understand why floats loose precision, read Why Floating-Point Numbers May Lose Precision and What Every Computer Scientist Should Know About Floating-Point Arithmetic. For a very introductory blog entry on how that affects the building of huge worlds in video games, read Size matters, and precision too. There are ways to circumvent parts of that problem. For more details on that, see my answers to questions Overcoming float limitations for planet-sized worlds in Unity and Is a custom coordinate system possible in Unity. Specially, see this academic article: Using a Floating Origin to Improve Fidelity and Performance of Large, Distributed Virtual Worlds for a quick review of both the problem and the possible ways to handle it.
> 3 votes

# Answer
Let's see how big the heightmap of the earth would be.

For simplicity reasons, we assume, that the earth is a square, and has no overhangs.

The earths surface is 510 million km². If you only have 1 pixel for 1 km² (wich is not very much), then you would have an image with 510 million pixel, so a 22000 by 22000 image. That takes up quite a lot of space.

If you convert it to a mesh, then you have 510 million vertices, each has an x, y and z position. Both of hem are floats, so they take up 96 bit, 12 bytes. I don't think I need to do the math, to understand it.
> 0 votes

# Answer
This isn't feasible on todays hardware the main reason being the sheer amount of data.

Lets say for arguments sake that you only hold heightmap data and "on the fly" load texturing information from another source like google maps (assuming thats even possible) ... based on what wolfram alpha has to say ... https://www.wolframalpha.com/input/?i=surface+area+of+earth

... earth is roughly 510 million square kilometers ...

So lets assume at any point in time you only need to render about 1 km square (extremely low distance range for a plane in the real world) from your height map at any point in time ... what is your resolution of the height map?

assuming 1 point every km2 we would be storing 510 million y values (floats) then we just map as a uniform grid ... that's a reasonable set of data, 510 million x 4 bytes = 2.2 billion bytes so you need 4 points just to get the area you plan to draw and you need to query a set of data roughly 2GB in size "realtime".

Ok I've seen some smart querying before stuff like Unlimited detail engine can do something like that, but that's only getting us the 4 corners of our map.

Now lets add some detail:

realistically for our flight sim we want at least a detail level of say 1 height point every 10 meters so that 1km height map now becomes 100 times bigger.

so ... for a very (and i mean VERY) low poly representation of earth we need about 200GB of data stored on our hard drive then a search algorithm that can pull a roughly 100 x 100 grid from that low res data in realtime to support the high speed moving of the aircraft.

DISCLAIMER: i don't what you want to build exactly but here goes an assumption ...

Taking a typical plane in to consideration air speeds will be for a boeing 747 about mach 0.8 or 920 km/h according to wikipedia ...

https://en.wikipedia.org/wiki/Boeing\_747

... so doing the math thats about 255 meters per second so you are crossing over a single 10 meter square quad in your extremely low res heightmap about every 0.025 seconds.

A typical game needs to render a frame every 0.016 seconds to achieve a frame rate of 60 fps.

So as a minimum you need to be able to do the following every 0.016 seconds to render a view of earth at a resolution of 10 square meters per point and keep up with your aircraft ...

1. flush out data no longer needed because its behind your plane
2. lookup from a subset of 200GB of height map points on a hard drive the set of points you need to populate the new edge verts of your map.
3. build the new mesh info
4. query google for new image data
5. upload the new data to your gpu
6. render the frame

....

A typical web request on a very good internet connect for a texture will come in at around 100ms so using google as a source of the texture data is not an option.

So how good you want your game to look, at resolution of 1 pixel per meter you need to store a colour value for 10X the number of points in your map, colour values are usually 3 floats so 12 bytes so 200GB x 10 x 3 is the amount of storage space you need locally to store your textures ...

so lets assume you have the 6TB needed to store your 1 pixel per meter textures to really get down to the final solution ...

using caching and read aheads to prevent bottlenecking in this whole process you're going to need to be able to build data for at least 2 edge rows of your map every frame with no latency across a dataset of 6.2TB to get the worst looking flight sim on the market up and running.

Oh dear ...

Now assuming your aircraft only ever flys at a height of say 10km up this might be considered reasonable but then for the plane to even see any ground you need to render further out to the horizon so the problem then gets worse.

How the big guys do it ....

They cheat, they only have data for key objects like central city areas or around major airports, in between all that is just "noise" or a repeated "green texture".

They also just provide maps for a small area.

So ... taking your question, how feasible do you think this is at 1cm accuracy?

EDIT:

That said, i'm trying to do similar with voxels (think minecraft) but my advantage is im using the gpu to automatically generate a portion of a random planet using noise functions, which actually is possible on todays hardware for example: http://libnoise.sourceforge.net/tutorials/tutorial8.html

Given that a typical GPU these days has a throughput of terabytes every second all is good but getting raw static data from hard drive to the screen when the static dataset is so large will most definitely require hardware way better than what is typically available today.
> 0 votes

---
Tags: graphics, unreal-4, 3d-modeling
---


# Question
Title: How to know when user has stopped dragging
How can we know when user has stopped dragging fingers over screen if user has not removed finger from screen but stopped dragging ?

# Answer
> 5 votes
Check if `Touch` `TouchPhase` is `Stationary`, which even says will be set only if:

> A finger is touching the screen but hasn't moved.

I suggest you also read up on the `Touch.phase` property, which exposes the `TouchPhase` for the specific `Touch`. The link also has examples on how to use the `phase`.

The other option is to check the `deltaPosition` of the `Touch`.
If `deltaPosition.x == 0 && deltaPosition.y == 0`, then the user has stopped dragging.

# Answer
> 1 votes
It would be great if your question was more specific, like dragging a game object or something. However you can use Interface to solve the problem. The demo code is given here. If you have questions regarding how to use it feel free to ask.

```
  using UnityEngine;
  using UnityEngine.EventSystems;
  public class AnswersManager : IBeginDragHandler,IEndDragHandler,IDragHandler
  {

      public void OnBeginDrag(PointerEventData eventData)
      {
          //When Dragging Started
      }

      public void OnDrag(PointerEventData eventData)
      {
          // When Player is dragging

      }

      public void OnEndDrag(PointerEventData eventData)
     {

          // What to do when drag is completed

      }
  }

```

---
Tags: unity, input
---


# Question
Title: Will using similar/exact name to a current Marvel superhero name for your game be a problem?
I have heard that the word 'superhero' is trademarked by marvel and DC and thus we can't use superhero as part of the name of a game we develop. But I wonder do they also have exclusibe rights to all the names of their super hero characters?

For example will people get in trouble if they name their games 'premagneto', 'superwolverine', 'exbeyonder' or 'the cyclop'?

# Answer
Usual disclaimer: I am not a lawyer and in this site questions about these issues have to be always taken as ideas, thoughts or experiences, never as technical advice.

That said, first of all, certainly words in themselves are not trademarked per se. I very much doubt that the word "superhero" or its variants could even be trademarked. And even if they were, I very much doubt that such trademarking would make any sense in any judicial dispute.

Second, however, yes, character names can be and often are trademarked. For instance, in a quick search, you can find an entry related to Marvel's Cyclops or Marvel's Magneto. And, to be honest, even if they didn't trademark their characters, they would still have a possible claim over their names - you own the rights over the things you create even without registering them.

Sure, if you take the name of a character and change it *enough*, you might be safe from issues regarding the trademark of the original name. The practical problem is how much is "enough". It is something that can't be determined a priori. Therefore, there is always risk.

Of course, some big companies only bother going after big enough contenders, i.e. they won't pay much attention until your games are successful enough to get into their radars. Others, however, are pretty strict and tend to cause trouble even for the smaller unknown developers, or even for modders and fans. Nintendo, for instance, has already took down a fan-made non-profit learning project: http://ca.ign.com/articles/2015/03/31/nintendo-takes-down-super-mario-64-hd-fan-project. It means that, again, there is risk.

Whether those risks are worth taking, is something that you and only you can decide. But those risks are, often, enough of a burden. Specially for independent developers. You have to consider that the problem of being sued is not only loosing, but even before that, wasting time and resources on the matter. Time and resources that are, of course, far more costly to you than to big companies like Marvel and DC.
> 2 votes

# Answer
To search for trademarks, use the website of the United States Patent and Trademark Office. But you can assume that the name of every major comic book character and villain is trademarked. Corporations like Marvel and DC which make vast amounts of money by licensing their intellectual property are very thorough in this regard.

Having *almost* the same name can already be an infringement when there is reason to believe someone might mistake your character for the trademarked one. I am not a lawyer, so I can not give you an estimate how likely it would be to get away with either of your examples when in court, but the chance is high that you couldn't afford to defend against a lawsuit to find out, so you should better avoid it.
> 1 votes

---
Tags: legal
---


# Question
Title: What's the difference between Mathf.Lerp and Mathf.SmoothDamp
I want to smoothly go from one value to a new one (moving a slider or changing color). I tried using both functions and they all basically give the same result. What is the difference between them and which one should I use?

How I used SmoothDamp:

```
    // Show the HUD
private IEnumerator ShowHUD() {
    var HUDCanvasGroup = GameObject.FindWithTag("HUD").GetComponent<CanvasGroup>();
    var alphaValue = 1f;
    var velocity = 0f;
    var time = 0.30f;

    yield return new WaitForSeconds(1.5f);

    // Gradually fade in the canvas
    while (!Mathf.Approximately(HUDCanvasGroup.alpha, alphaValue)) {
        HUDCanvasGroup.alpha = Mathf.SmoothDamp(HUDCanvasGroup.alpha, alphaValue, ref velocity, time);
        yield return null;
    }

    HUDCanvasGroup.alpha = 1; // Since float is not accurate, manually set the alpha to 1 after
    HUDCanvasGroup.interactable = true;

    var blur = GameObject.FindWithTag("BlurryCamera").GetComponent<BlurOptimized>();
    blur.enabled = true;
}

```

How I used Lerp:

```
public static IEnumerator Dim() {
    while (t < 1) {
        t += Time.deltaTime / 0.4f;
        dimRend.material.color = Color.Lerp(undimColor, dimColor, t);
        yield return null;
    }
}

```

# Answer
> 17 votes
The mechanical difference is that `Lerp` is linear, while `SmoothDamp` follows a sigmoid function. See How to Lerp like a pro and Smoothstep for more in-depth explanation and graphs.

In terms of which one you *should* use, that varies from product to product, situation to situation. `SmoothDamp`-style is often more pleasant to the eye, especially for slower fades in/out, or where the thing being interpolated is intended to be seen as physical. I.e. `SmoothDamp` motion generally looks more like the object is accelerating and decelerating, rather than suddenly starting and stopping.

The linear fade of `Lerp` works well for very fast fades, and is (I expect) slightly quicker to compute. So, if you're doing an enormous amount of interpolation, `Lerp` might better suit your needs. Again, however, it can look unnatural for things that are physical.

In short, read up on what they do under the hood, play around with both of them. You'll have to decide for yourself which looks and feels better for your app.

# Answer
> 0 votes
SmoothDamp suits well for situations where the value it's moving towards is dynamic, like transform values, and you want it to retain an organic sense of motion and agency. This is due to SmoothDamp factoring velocity in its algorithm.

Lerp is fine for most other cases.

---
Tags: unity, lerp
---