title: Malformed/Pixelated Vertex Normals

text:
# Question
Title: Malformed/Pixelated Vertex Normals
I am trying to generate vertex normals for a given triangles/vertices list with the following code:

```
**BASE METHOD:**

private void CalculateNormals()
{
    for (Int32 i = 0; i < m_Meshes.Count; ++i)
    {
        Mesh mesh = m_Meshes[i];

        List<Point3D> vertices = mesh.GetVertices();
        List<Triangle> triangles = mesh.GetTriangles();

        List<Point3D> normals = new List<Point3D>(vertices.Count);

        for (Int32 y = 0; y < vertices.Count; ++y)
            normals.Add(new Point3D(0.0f, 0.0f, 0.0f));

        for (Int32 y = 0; y < triangles.Count; ++y)
        {
            Triangle triangle = triangles[y];
            UInt16 index1 = triangle.Index1;
            UInt16 index2 = triangle.Index2;
            UInt16 index3 = triangle.Index3;

            Point3D vertex1 = vertices[index1];
            Point3D vertex2 = vertices[index2];
            Point3D vertex3 = vertices[index3];

            Point3D a = vertex2 - vertex1;
            Point3D b = vertex3 - vertex1;
            Point3D normal = a % b;

            normals[index1] += normal;
            normals[index2] += normal;
            normals[index3] += normal;
        }

        for (Int32 y = 0; y < normals.Count; ++y)
            normals[y] = normals[y].Normalize();

        mesh.AddNormals(normals);
    }
}

**POINT3D METHODS & OPERATORS:**

public static Point3D operator +(Point3D left, Point3D right)
{
    Single x = left.X + right.X;
    Single y = left.Y + right.Y;
    Single z = left.Z + right.Z;

    return (new Point3D(x, y, z));
}

public static Point3D operator -(Point3D left, Point3D right)
{
    Single x = left.X - right.X;
    Single y = left.Y - right.Y;
    Single z = left.Z - right.Z;

    return (new Point3D(x, y, z));
}

public static Point3D operator /(Point3D point, Single value)
{
    Single x = point.X / value;
    Single y = point.Y / value;
    Single z = point.Z / value;

    return (new Point3D(x, y, z));
}

// Crossed Product
public static Point3D operator %(Point3D left, Point3D right)
{
    Single x = (left.Y * right.Z) - (left.Z * right.Y);
    Single y = (left.Z * right.X) - (left.X * right.Z);
    Single z = (left.X * right.Y) - (left.Y * right.X);

    return (new Point3D(x, y, z));
}

public Point3D Normalize()
{
    Single magnitude = (Single)Math.Sqrt((m_X * m_X) + (m_Y * m_Y) + (m_Z * m_Z));

    if (magnitude == 0.0f)
        return (new Point3D(0.0f, 0.0f, 0.0f));

    return (this / magnitude);
}

```

This is what I get:

What am I doing wrong? Can someone help me please?

**EDIT:**

I tried to do this process with a single mesh containing a single triangle to have a better control over what's going on in my algorithm. Here are the triangle vertices values:

Here are the values I get:

And here are the correct values automatically calculated by a plugin tool:

# Answer
There is nothing inherently wrong with your original code when it comes to normalization. The only problem can be with meshes that do not properly share vertices, meaning your normalization code will always normalize the vertices that belong to a single Triangle.

If you wish to fix such a mesh, you should either:

1. Weld all vertices during import stage
2. Apply normals to all vertices that share coordinates

A brute force O(N^2) method to apply your normal to all vertices that share coordinates is pretty easy to create. Keep in mind that Vertex operator == compares the X/Y/Z values, not the references:

```
public class Mesh
{
    int numVertices; // number of vertices
    int numIndices;  // number of indices

    Vertex[] vertices; // [numVertices]
    int[]    indices;  // [numIndices]

    public void CalcVertexNormals()
    {
        // reset all normals (if you are recalculating them)
        for (int i = 0; i < numVertices; ++i)
            vertices[i].normal = Vector3.ZERO;

        // calculate all face normals
        // assuming faces are provided in sets of 3 vertex indices
        // like in most 3D formats and models
        for (int i = 0; i < numIndices; i += 3)
        {
            // get vertices for this triangle:
            Vertex v0 = vertices[indices[i]];
            Vertex v1 = vertices[indices[i + 1]];
            Vertex v2 = vertices[indices[i + 2]];

            // calculate Face normal:
            Vector3 ba = v1.pos - v0.pos;
            Vector3 ca = v2.pos - v0.pos;
            Vector3 normal = ba.cross(ca);

            // if large triangles dominate normal calculation
            // adding this will favor the side with most triangles
            normal.normalize();

            // add normals to any vertex that shares v0/v1/v2 coordinates
            for (int j = 0; j < numVertices; ++j)
            {
                Vertex v = vertices[j];
                if (v == v0 || v == v1 || v == v2)
                {
                    v.normal += normal;
                }
            }
        }

        // normalize all vertex normals
        for (int i = 0; i < numVertices; ++i)
            vertices[i].normal.normalize();
    }
}

```
> 3 votes

# Answer
The problem is that you need to actually average the normals. I see that you are accumulating a sum of each face normal that a vertice is apart of but I don't see where you actually divide it by the number of normals that you summed. What you would probably need to do is have another int array of the same size as your normal array and increment them after you add the normal to the normal array like this:

```
List<int> count_of_normals = new List<int>(vertices.Count);

for (Int32 y = 0; y < triangles.Count; ++y)
{
    count_of_normals[index1]++;
    count_of_normals[index2]++;
    count_of_normals[index3]++;
}

for(Int32 n = 0; n< vertices.Count; n++ )
{
    normal[n]/=count_of_normals[n];
}

```

Hope that helps
> 1 votes

---
Tags: c#, vector, vertex, .net, normals
---


# Question
Title: Convert large range of numbers to a smaller scale
What is a good formula to use in order to relate two different scale distances to each other? For example, I have a camera that can have a minimum size of 2 and a maximum of 10. I would like the camera to zoom proportionally with the mouse distance from an object.

The problem is the distance is returned in terms of pixels (e.g. 500px) and I'd like to transform that into a relative value between 2 and 10. What's the best way to do this?

Thanks

# Answer
**Normalization**

The best option would probably be to normalize the data. This can easily be done using the formula:

```
x = a + (X - A) * (b - a) / (B - A)

```

where `a` and `b` are the minimum and maximum values for your desired range, respectively; `A` and `B` are the minimum and maximum values for your original range, respectively; `X` is the input value (in your case, the distance returned in pixels); and `x` is the normalized version of `X`.

For your use, `a` would be 2, `b` would be 10, `A` would be the smallest number of pixels possible, `B` would be the largest number of pixels possible, and `X` would be 500 (as in your example distance).

You can then use `x` (the relative value) as you please.
> 4 votes

---
Tags: c#, unity, mathematics, camera, scale
---


title: How to add a texture in jmonkey

text:
# Question
Title: How to add a texture in jmonkey
Hello I have a pretty simple question, I'm new to jmonkey and I want to add a .jpg file to the /assets/textures folder and dragging and dropping the file doesn't appear to work for me.

# Answer
> 2 votes
Moving the jpg file into the textures folder in finder works. For some reason it won't allow me to do it using the sdk.

# Answer
> 0 votes
You can also copy it from Finder and then paste it into the SDK.

---
Tags: jmonkeyengine
---


# Question
Title: Should frame update and network packet sending synchronous or asynchronous?
I am making a game server that has 60 Update-Per-Second (assume I can most of the time achieve it). In the current model, my main loop does the following tasks in sequence:

* Update game logic (position, etc...)
* Serialize the data to JSON string
* Broadcast the data (through `WebSocket`) to the clients. Currently the broadcast method is `async`, that means my server does not stop and wait for the broadcast to finish.

I have 3 questions:

* Is it good to send the packages at this frequency?
* Should I cap the UPS to 30 instead?
* Should I separate the broadcast into another thread, so no matter the UPS of my server, the broadcast will do asynchronous time and depend on the update?

Here is my current code:

```
public MusicGame(GameRoom room)
{
    this.Room = room;
    this.ConnectedSessions = new List<GameBehavior>();

    this.timer = new Stopwatch();
    this.timer.Start();

    new Thread(() =>
    {
        while (!this.Disposed)
        {
            float delta = (float)this.timer.Elapsed.TotalSeconds;
            if (this.timer.Elapsed.TotalSeconds < MusicGame.FpsLimit)
            {
                Thread.Sleep((int)((MusicGame.FpsLimit - delta) * 1000));
                continue;
            }
            this.timer.Restart();

            delta = Math.Min(DeltaTimeLimit, delta);
            this.Act(delta);
        }
    }).Start();

    this.CurrentScreen = new WaitingScreen(this);
}

public void Act(float delta)
{
    if (this.CurrentScreen != null)
    {
        this.CurrentScreen.Act(delta);
        this.CurrentScreen.SerializeData();

        var data = this.CurrentScreen.SerializedData;
        this.BroadcastGameAsync(data);
    }
}

```

I am using C# Console Application and WebSocketSharp if it matters.

# Answer
As for the update frequency it depends from the type of game. For an action type of game 30 updates per seconds should be perfectly smooth, but for an mmorpg (where you have thousands of players) better use something like 10 per second, to save server time.

I doubt there will be any reason to have 60 updates per second, that will just use a lot of server time and I don't think anything in the game will change that fast.
If you do want to send an update right after that happens, you can just call the SendUpdate() function.

*Since question was edited I'll remove this part:*

> Generally you should separate the frame update from the networking updates, as those 2 are not depending on each other.
> Also you should use vsync to limit the frame rate.
> 2 votes

---
Tags: c#, networking, server, client-server, websocket
---


title: 2D Camera sizing and movement

text:
# Question
Title: 2D Camera sizing and movement
Apologies if this is a basic question, or been asked a 1,000 times in the past...

I'm new to Unity, and having problems understanding some of the basics to do with 2D cameras (orthographic), and while I've read a lot nothing has made me have that 'ah-ah!' moment yet.

What I'm trying to create is the following (camera position depicted by the box with the pink dashed line) - where the yellow filled boxes are made up of a whole bunch of sprites.

Overtime, the camera need to move left to right, and then bottom to top...

What my issue seems to be is understanding how I can get the camera to display all of the sprites - in other words, resize the camera *view* to fit the background sprite's height, and know *when* to stop the camera in order to start moving it up.

What I'd like to understand is how and why to solve this problem - it's the only way I'll learn!

Thanks

Kieron

# Answer
I wrote a camera script that auto-zooms based on a transform's position and scale.

Attach the script below to your Camera. Then, create a GameObject, and set its position and size. Then link this gameobject to the "Area" public property of this camera script.

The "Area" GameObject can be adjusted at runtime, and should provide you with a mechanism to at least get you started on what you are attempting to do.

I put the logic inside of Update() to simplify, however, you will most likely want to move this in a function that you would call manually when a recalc needs to be done.

```
using UnityEngine;
using System.Collections;

public class CameraZoom : MonoBehaviour
{
    public Transform Area;

    public void Update()
    {
        float height = Area.localScale.y * 100;
        float width = Area.localScale.x * 100;

        float w = Screen.width / width;
        float h = Screen.height / height;

        float ratio = w / h;

        float size = (height / 2) / 100f;

        if (w < h)
            size /= ratio;

        Camera.main.orthographicSize = size;

        Vector2 position = Area.transform.position;

        Vector3 camPosition = position;
        Vector3 point = Camera.main.WorldToViewportPoint(camPosition);
        Vector3 delta = camPosition - Camera.main.ViewportToWorldPoint(new Vector3(0.5f, 0.5f, point.z));
        Vector3 destination = transform.position + delta;

        transform.position = destination;
    }

}

```
> 5 votes

---
Tags: unity, 2d, camera
---


# Question
Title: Word in different color in middle of string XNA
Is it possible to use different font colors for the same string, for example, when buying a weapon in CoD AW Exo Zombies:

How do I do this?

Thanks.

# Answer
You can simply render the pieces of colored text individually, specifying any color you want for each piece. In order to get the positioning correct, you can use the SpriteFont.MeasureString() method.

```
string[] stringPieces = { "Hel", "lo, ", "wor", "ld!" };
Color[] colors = { Color.Blue, Color.Green, Color.Yellow, Color.Red };

Vector2 startPosition = new Vector2(100, 100);
Vector2 offset = Vector2.Zero;
SpriteFont font = Content.Load<SpriteFont>("myFont");

spriteBatch.Begin();

//Loop through each piece of the string,
//drawing each with a different color,
//and moving the offset forward by its measured length
for( int x = 0; x < stringPieces.Length; x++)
{
    spriteBatch.DrawString(font, stringPieces[x], startPosition + offset, colors[x]);
    offset.X += font.MeasureString(stringPieces[x]).X;
}

spriteBatch.End();

```

Code based on BTownTKD's GameDev.net post.

If you're going to do this often, I would recommend writing a basic parser to make using this easier.

Example syntax: "{{blue}}Hel{{green}}lo, {{yellow}}wor{{red}}ld!"

* Split on `{{` to get `["blue}}Hel"], ["green}}lo, "], ["yellow}}wor"], ["red}}ld!"]`.
* Loop through each result and split on `}}` to get a combination of color and text e.g. `["blue", "Hel"]`.
* Render string "Hel" using Color.Blue. Continue.
> 2 votes

---
Tags: xna, monogame, fonts
---


title: Short distances from reference point

text:
# Question
Title: Short distances from reference point
I would like to compute short distance from reference point in 2d grid. To expose:

* 0, 0: not penetrable
* 0, 1: not penetrable
* ...
* 1, 1: penetrable
* ...

I search an algorithm who return:

* 1, 1: 1
* 2, 1: 1
* 3, 1: 1
* 1, 2: 1
* 2, 2: 0
* 3, 2: 1
* ...
* 1, 6: 4
* 3, 6: 4

for `2, 2` reference point, `4` as maximum distance in exemple grid. What algorithm can to this (with good perf) ?

# Answer
An possible algorithm, expsed in python language:

```
def get_distances_for_points(object_position, max_distance):
    points_distances = {}
    points_to_looks = [object_position]

    for current_distance in range(max_distance):
        new_points_to_looks = []
        for looked_point in points_to_looks:
            around_points = <here return around points of looked_point>
            for around_point in around_points:
                if around_point not in points_distances and <here return True if around point is penetrable and False if blocked (wall)>:
                    points_distances[around_point] = current_distance+1
                    new_points_to_looks.append(around_point)
        points_to_looks = new_points_to_looks

    return points_distances

```

And according to comment of Ali.S and amitp: https://en.wikipedia.org/wiki/Breadth-first\_search (demo)
> 1 votes

---
Tags: 2d, algorithm
---


# Question
Title: Why the changes to the children and grand children objects not taken into account?
Currently I am working on a framework for a game utilising the SFML graphics library and in one of the classes representing a renderable object in the framework there is an sf::Sprite that is used to represent and draw the object. The issue is that the object instance of class 1 that is represented by the sf::Sprite (which is a private member variable of class 1), is in turn a private member variable of class 2 of which an instance is in turn a private member variable of class 3 from which the sprites belonging to the instances of class 1 and 2 must be retrieved to be rendered in the renderer class. In classes 1, 2 and 3 there are appropriate getter functions like so:

```
class One
{
     public:

     //Functions
     One();
    ~One();

     sf::Sprite getOne(){ return oneRep;};
    animate();

     private:
     //One variables
     sf::Texture oneTexture;
     sf::Sprite oneRep;

};

class Two
{
     public:

     //Functions
     Two();
    ~Two();
     One getCOneInst(){ return cOneInst;};

    private:

    //Class 1 private member variable
    One cOneInst;
};

class Three
{
    public:

    //Functions
    Three();
    ~Three();

    initTestSprite();
    One getCTwoInst(){ return cTwoInst;};

private:

    //Class 2 private member variable
    Two cTwoInst;
};

class Renderer
{
    public:

    //Functions
    Renderer();
    ~Renderer();

    private:
    //Class 3 private member variable
    Three cThreeInst;

    //Test Class One private member variables
    One testCOneInst;
    sf::Texture oneTexture;
    sf::vector2f position

};

```

Which are used to access the sprites representing the instances of class 1 and 2 from the instance of class 3 so that the renderer class may render them to the screen of the game. The issue is that: if an instance of class 1 (represented by the sf::Sprite) is constructed in the renderer class like so:

```
initTestSprite()
{
    testCOneInst.setTexture(oneTexture);
    testCOneInst.setTextureRect(textRect);
    testCOneInst.setColor(sf::Color(255, 255, 255, 255));
    testCOneInst.setPosition(position);
}

```

And should the getter function be called on the instance of classOne to retrieve the sprite representing the instance of classOne for rendering in the render class

```
window.draw(testCOneInst.getOne());

```

The render class through the function above will render the sprite representing the instance of class One: testCOneInst correctly. The problem and the question is: When the sprite representing the instance of class One must be retrieved from the instance of class Two in which the class One instance is a private member variable – the functions that should be able to be called on the class One sprite to manipulate the texture being applied to it, for example setting the IntRect texture to a new location in order to animate the sprite representing the instance of class One does not function correctly – the original texture is still applied to the sprite representing the instance of class One, if the sprite is accessed by the renderer class from the instance of class 2 and in turn the instance of class 3 like so:

```
cThreeInst.getCTwoInst().getCOneInst().animate();

```

Before rendering the sprite with the updated texture changes to the window like so:

```
window.draw(cThreeInst.getCTwoInst().getCOneInst().getOne());

```

The changes to the IntRect of the sf::Sprite instance representing class 1 will not be show when the sprite is rendered – and the question is why?

# Answer
Your getters (getCTwoInst, getCOneInst and getOne) return copies so you're calling the animate function on a copy of a copy of your sprite. This modified copy is then left unused.

Return references instead:

```
Two& getCTwoInst() {return cTwoInst;}

```
> 1 votes

---
Tags: c++, architecture, sfml
---


title: Looking for an easing equation

text:
# Question
Title: Looking for an easing equation
I am looking for an easing equation with the following properties:

1. It starts at a velocity of zero, and eases into a constant velocity of 1 for a duration of `t_1` seconds (cubic, exp, or quintic, doesn't matter)
2. It then has a constant velocity of 1 for `t_2` seconds.
3. Finally, it eases down to zero velocity for a period of `t_3` seconds.
4. `t_1 + t_2 + t_3 = t_max`
5. The function starts at zero and ends at 1.
6. `t_2` will be chosen by the easing function to satisfy (4) and (5), given `t_1`, `t_3`, and `t_max`.

Therefore the function has the form:

```
float EaseConstantVelocity(float current_time, float t_1, float t_3, float t_max)
{
    // ?
}

```

How do I construct such an easing function?

Edit:

What I'm looking for is conceptually similar to the `CubicInOut` function, except in the case of `CubicInOut`, `t_2` is 0.

# Answer
> 0 votes
As @DMGregory pointed out, it isn't satisfiable when the constant velocity desired is 1. As `t_1` and `t_3` grow in size, a constant velocity of 1 will not cause the linear segment to reach `t_max` in time. Therefore, a correction factor has to be applied to allow the slope to change to support this. Here's the code I used to accomplish what I wanted:

```
// Some initialization. t_1 and t_max can be varied, the other parameters are fixed.
float t_1 = 0.1;
float t_3 = t_1;
float t_max = 1.0;
float t_2 = t_max - (t_1 + t_3);

// Equations for each of the segments
// The first segment is a quadratic which levels off at velocity 1 when t = t_1.
float f1(float t)
{
  return (1.0f / (2 * t_1)) * pow(t, 2.0f);
}
// The second segment is linear with velocity 1, and begins at f(t_1).
float f2(float t)
{
  return  t + f1(t_1) - t_1;
}
// The third segment is quadratic, with initial velocity 1 and final velocity 0.
float f3(float t)
{
  return f2(t_1 + t_2) -  (1.0f / (2.0f * t_3)) * (pow(t_max - t, 2.0f)) + 0.5 * t_3;
}

// The final easing function is a piecewise combination of the others
float easing(float t)
{
  // This is a correction that forces the easing function to end at
  // t_max. The whole function is multiplied by this.
  float correction = (t_max/ (t_max- t_1));

  // Piecewise elements
  if (t < t_1)
  {
    return correction * f1(t);
  }
  else if(t < t_1 + t_2)
  {
    return correction * f2(t);
  }
  else if(t < t_max)
  {
    return correction * f3(t);
  }
  else
  {
    return t_max;
  }
}

```

And here are some plots for different values of `t_1`.

---
Tags: animation, easing
---


# Question
Title: player moving continuously from button controls
I added new buttons in my game made with unity 5.0 and the new UI feature.

The player keeps on moving when button is clicked instead of moving just once.

In the normal controls I make it move only once by changing back the x and y of movement to 0.

```
moving.x = moving.y = 0;

```

But how will I do that for button function?

I am calling each left, right, up, down , gun function separately in each button:

```
using UnityEngine;
using System.Collections;

public class UI : MonoBehaviour {

    public Vector2 moving = new Vector2();
    public int Bulletlimit = 0;
    public int MaxBulletlimit = 3;
    public bool Gun;
    private float lastShotTime ;
    public float fireDelay = 0.2f;
    public Transform BulletDirection;

    public Bullet bullet;

    // Use this for initialization
    void Start () {
        lastShotTime = Time.time;
    }

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

        moving.x = moving.y = 0;
        if (Input.GetKey ("right")) {
            right ();
        } else if (Input.GetKey ("left")) {
            left ();
        }

        if (Input.GetKey ("up")) {
            up();
        } else if (Input.GetKey ("down")) {
            down ();
        }

        if (Input.GetKey ("s")) {
            gun ();
        }

    }

    public void BulletCount()
    {
        Bulletlimit = Bulletlimit - 1;
    }

    public void left()
    {
        moving.x = -1;
    }

    public void right()
    {
        moving.x = 1;
    }

    public void up()
    {
        moving.y = 1;
    }

    public void down()
    {
        moving.y = -1;
    }

    public void gun()
    {
        if(Gun){
            if(Bulletlimit < MaxBulletlimit)
            {
                if(Time.time > lastShotTime + fireDelay)
                {
                    Bullet clone = Instantiate (bullet, BulletDirection.position, Quaternion.identity) as Bullet;
                    Bulletlimit = Bulletlimit + 1;
                    lastShotTime = Time.time;
                }
            }
        }

    }

}

```

# Answer
try using Input.GetKeyDown instead of Input.GetKey
> 1 votes

# Answer
Add EventTrigger to your UI BUttons ,particularly the `OnPointerUp` which you can use for `moving.x=moving.y=0`.Everytime the button is released your values will be reset.
> 1 votes

# Answer
You are using the proper callback; Input.GetKey is the "held down" callback (doesnt reset each frame).

I believe your problem is coming from the setting of x and y to 0 at the start of your update.

Instead you should only set them to 0 as else{} blocks for your key tests.
> 0 votes

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


# Question
Title: Fastest way to render image data from buffer
Currently I am doing my rendering by using a 3D array window\_width x window\_height x rgb as a buffer, then looping through the buffer and plotting pixels on screen using SDL2 (SDL\_RenderDrawPoint). I know this is horrible and stupidly slow but I am not well experienced in graphics techniques. What is the better way to do this?

# Answer
You can use SDL\_LockTexture and SDL\_UnlockTexture for **write only** access to a texture created with the `SDL_TEXTUREACCESS_STREAMING` flag. Lock, write, unlock, then use `SDL_RenderCopy` to blit to the screen.

Create the buffer with SDL\_CreateTexture (modify to you liking):

```
SDL_Texture* buffer = SDL_CreateTexture(renderer,
                           SDL_PIXELFORMAT_BGRA8888,
                           SDL_TEXTUREACCESS_STREAMING,
                           800,
                           600);

```

Lock with SDL\_LockTexture:

```
SDL_LockTexture(buffer,
                NULL,      // NULL means the *whole texture* here.
                &pixels,
                &pitch);

```

Where `pixels` is a `int *` and pitch is the width of a row of pixels in bytes.

Write your pixel data to `pixels`. You won't have any of the convenient SDL functions to do this. Just plonk the data in, one pixel after the other until you have done them all. Make sure you write with the correct PIXELFORMAT, otherwise the colours will come out wonky. (In `SDL_PIXELFORMAT_BGRA8888`, the first byte is blue, second is green, third is red and fourth is alpha. Leave alpha at 255 unless you want transparency)

Clean up with SDL\_UnlockTexture:

```
SDL_UnlockTexture(buffer);

```

Then you can RenderCopy this texture as normal:

```
SDL_RenderCopy(renderer, buffer, NULL, NULL);

```

This assumes the buffer is the same size as your window.

Note you will have to modify this for your own use case.
> 4 votes

---
Tags: rendering, sdl, sdl2
---


# Question
Title: Resources.Load doesn't grab values of my child class
I have a parent class `Unit`, and child classes `melee unit`/`ranged unit`. The parent class holds uninitialized fields such as `health`, `damage`, etc. the child class sets the values of these fields in an Awake function.

In another script, I have a Start method:

```
void Start(){
    gridX=5;
    gridY=5;
    for (int i = 0; i<(gridY*gridX);i++){
        allies.Add(new GameObject());
    }
    AddUnits();
    SetupGrid();

}

```

AddUnits looks like this:

```
void AddUnits(){
        allies[0] = (GameObject) Resources.Load ("Units/melee unit");
        allies[1] = (GameObject) Resources.Load ("Units/ranged unit);
        number = 2;
    }

```

The resources loaded are prefab gameobjects containing their respective melee unit or ranged unit script (both which derives from base class `Unit`)However, when I check the health value of the gameobjects `allies`, they're always 0. Can anyone help me figure out why?

# Answer
When a Resource is Loaded its not actually Instantiated and added to the Scene so Awake() is never called. Change your code to something like the following:

```
allies[0] = Instantiate(Resources.Load("Units/melee unit", typeof(GameObject))) as GameObject;

```

Resources.Load
> 4 votes

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


title: LibGDX obstacle collision

text:
# Question
Title: LibGDX obstacle collision
How can I handle collisions with obstacles in LibGDX?

Is there any automatic way to stop the character's movement when it collides with a wall or I have to constantly poll for all the possible objects it might encounter and stop the movement accordingly? Polling this way seems pretty poor performance-wise, especially if the framework already does that for me and I make no use of it.

My game is a top view roguelike, more or less like "The Binding of Isaac".

**EDIT** some beginners like me might make good use of it. Since LibGDX has no built in collision detection without Box2D, for games where physic calculation is not needed you can build your system as follows: Create 3 lists (Static, Dynamic, Controlled) where you put all your (relatively inherited) objects in the scene.

Static objects (walls, obstacles, traps) are passive and perform no checks.

Dynamic objects (projectiles) perform checks on both Static (stop if you hit a wall, destroy self) and Controlled (deal damage)

Controlled (players, enemies) objects perform checks on self (player hit AI controlled enemy) and static objects

After a collision is reported notify the relative objects. Controlled objects can be Dynamic aswell but if you have a lot of projectiles flying around you can avoid self-checking Dynamics and improve the performance. This way you should reduce a lot of useless checks aswell as limit cross-checks (both player and projectile notifying eachother) and keep your game well organized. This is just an idea that i'm testing now, I can't guarantee it's the best :P

# Answer
> 2 votes
Libgdx does not handle this itself, you need to take care about collision detection + collision response yourself.
One possible solution would be Box2D, a 2D physic engine. It takes care about forces, mass, friction and other physical things. It also detects and handles collisions for you. It is also possible to let `Box2D` just detect the collision and notify you about it, so that you can use a custom collision response.
As you allready said in the comments, `Box2D` would be overkill in your case, as you don't need physics, but only collision detection + response.

That means, that you need to implement collision detection + response yourself. Libgdx has some usefull methods inside the Intersector class. There are methods, which tell you, if two `Shape`s (for example 2 `Rectangle`s) overlap. Others return the intersection-shape, which might be interesting for the collision response.

As said in the comments you can use `Scene2D`, where you are working with so called `Actor`s which take part of a `Stage`. They have a `position` and a `size` you can use for collision detection. Unfortunately in `Scene2D` the `act` (logical-part / Model) as well as the `draw` method (visual-part / View) are in the same class (`Actor`), which makes it hard, if not impossible, to implement a MVC-Pattern. This might be ok for UI and simple games, but it could cause problems for bigger, more complex, projects.
So you might want to implement your own "game-world" and "game-objects", but thats up to you.

As you allready said, you can "poll" for every possible collision, which might work for small worlds if there are only a few objects. If there are to many objects, you can use different things to reduce the amount of complex checks:

* Use filters, if for example Player can't collide with other Players, you don't even need to check, if they are colliding or not
* Use AABB check, before starting to check for the real collision. This will allready sort out most of the objects with a verry simple check, before performing a more complicated check
* There are also things like Quadtrees, but i guess that would be overkill in your case.

I hope it helps.

---
Tags: collision-detection, libgdx, movement
---


# Question
Title: Event-/Input system with SFML: Cannot move diagonally in 2D
I am a beginner in anything with game development. I written a small prototype in which i can move a square around with the arrow keys. For that i use SFML.

At the moment i experiment around with my **Event System**: First, to keep things simple, i was polling for the arrow keys using sf::Keyboard::isKeyPressed(), which works fine for this small kind of "game"

```
// in handleUserInput():
if(Keyboard::isKeyPressed(Keyboard::Left))
{
        player_.moveLeft();
}

// in player the player class:
void moveLeft()
{
    velocity.x = -x_speed; // sf::Vector2f
}

// in my player-class update() method:
void update()
{
// Out of bounds check and so on...
shape.move(velocity);
velocity.x = 0;
velocity.y = 0;
}

```

With this i was able to move horizontally, vertically and diagonally.

Then i moved to create my "real" EventSystem based on callbacks. It wraps around sf::Window::pollEvent(). E.g. i register a callback method for the event type sf::Event::EventType::KeyPressed. So i changed my code to first register for the movement keys

```
event_system_.registerCallback(sf::Event::KeyPressed, [&] (const sf::Event& event)
    {
        switch(event.key.code)
        {
        case sf::Keyboard::Left:
            log->info() << "Moving Left";
            player_.moveLeft();
            break;
        case sf::Keyboard::Right:
            log->info() << "Moving Right";
            player_.moveRight();
            break;
        case sf::Keyboard::Up:
            log->info() << "Moving Up";
            player_.moveUp();
            break;
        case sf::Keyboard::Down:
            log->info() << "Moving Down";
            player_.moveDown();
            break;
        case sf::Keyboard::Escape:
            window_.close();
            break;
        }
    });

```

The problem i encountered was, that i **couldn't** **move** **diagonally** anymore. After adding the loggin parts i found out, that when i keep two arrow keys pressed the only event that gets fired over and over again was the key pressed latest (e.g. i try to press *Left & Down* and pressed the *Down-Key* *slightly later* the *Down-Event would be captured over and over* again and the *Left-Event only once*).

After that i changed my code not to reset the **velocity** in my player's *update*-method and also registered for sf::Event::KeyReleased so that it would reset the x/y-part of the velocity when the corresponding key was released.

```
event_system_.registerCallback(sf::Event::KeyReleased, [&] (const sf::Event& event)
    {
        switch(event.key.code)
        {
        case sf::Keyboard::Left:
        case sf::Keyboard::Right:
            log->info() << "Stopped moving horizontally";
            player_.velocity.x = 0;
            break;
        case sf::Keyboard::Up:
        case sf::Keyboard::Down:
            log->info() << "Stopped moving vertically";
            player_.velocity.y = 0;
            break;
        }
    });

```

But somehow this does not seem right to me (But it wouldn't seem right to me to poll for every single possible input manually - So i think events is the things to take). Could anyone give me a hint what i am doing wrong and how to do it better?

Kind Regards

# Answer
I would personally use the keyboard class that allows you to query the state of keys instead of waiting for an event.

The documentation is here

One of the reasons I prefer this method is that you can check the status of the key from almost anywhere in the code, and you don't have to store the state of the keys yourself.

> f::Keyboard can retrieve the state of a key at any time (you don't need to store and update a boolean on your side in order to know if a key is pressed or released), and you always get the real state of the keyboard, even if keys are pressed or released when your window is out of focus and no event is triggered.

The other obvious advantage is that you can check the state of multiple keys at the same time, hence making it easy to detect key combinations :

```
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Left) && sf::Keyboard::isKeyPressed(sf::Keyboard::Down))player_.moveDownLeft();

```
> 3 votes

---
Tags: c++, input, sfml, events
---


title: Logical Dependencie Problem

text:
# Question
Title: Logical Dependencie Problem
I am working with Unity and C#, but my Problem is a more general programming problem. I am trying to keep things easy, but still make them global access able and easy to modify.

So I have a Character\_Model\_Selection class, in which You can scroll from the right to the left with shifting for example to your desired model and then select it . An Id keeps track of which model is infront of the User on select. If He selects it, I compare that Id With an Integer and If it is equal to it, I pass it a string of the actual "hero" name . Before I used a singleton to create an default instance, modify the Name and then access it in the Main screen, but since I have multiply Players with different spawns singletons doesn't really make sense anymore.

Question: What design Pattern or technique could I use to have a Base class of a Player hero, which has some default properties, like health and pushforce. With I can create multiply instances of but make it global access able and modify the default properties on select.

# Answer
The pattern you are looking for is called Inheritance.

Stop using Singletons. Create a base class with default properties. Then create derived classes off of your base class, to create your separate entities.

https://en.wikipedia.org/wiki/Inheritance\_%28object-oriented\_programming%29

Post code samples if you want more help.
> 0 votes

---
Tags: c#, design-patterns, logic
---


title: Object scaling when parenting by script

text:
# Question
Title: Object scaling when parenting by script
How do I make it so an object doesn't scale with another object that I parented it with by script? If anyone knows how to get around this I would really appreciate it.

This is the part of the script I used for parenting:

```
arrowToObjAnchor.transform.parent = hitTransform;

```

# Answer
I'm assuming your question is about the scale change that occurs at the moment you parent one object to another with a net scale other than (1, 1, 1). This can be avoided, as described below. Any subsequent changes to the parent's scale will still cascade down to affect all children however, so if you want the object to retain its scale regardless of what happens to the parent, your options are either a script that applies a compensating scale to the child with each change, or changing your hierarchy so that the child is not parented to the scaling object (eg. using physics joints to connect their positions & rotations without scale leaking through)

You can use transform.SetParent(parent, false) to keep the object's local position, rotation, and scale unchanged when reparenting it:

```
public void SetParent(Transform parent, bool worldPositionStays);

Parameters
-------------------------------------------------------------------------------
parent              The parent Transform to use.
worldPositionStays  If true, the parent-relative position, scale and rotation
                    is modified such that the object keeps the same world space
                    position, rotation and scale as before.

```

Note that this may cause the object's resulting worldspace position & rotation to change as a consequence of the new parent's transform.

If you only want to keep the local scale, but allow the local position/rotation to be updated as normal, then you can do something like this:

```
var originalScale = myObj.transform.localScale;
myObj.transform.parent = newParent;
myObj.transform.localScale = originalScale;

```
> 4 votes

---
Tags: unity, c#, transformation, scale, hierarchy
---


title: Effecient tilemap rendering

text:
# Question
Title: Effecient tilemap rendering
I have done mostly tile based games, but never really bothered with optimization. I always just rendered all the tiles that convered the viewport. I am currently working on platformer for a mobile device, which has some performance issues, ecspecially when using multiple layers of tiles.

Most tiles are pretty static without animations. I wouldn't really have to render them each frame. The clear() -\> draw() loop is really printed into my brain, I'm having a hard time thinking how the handle rendering without clearing the screen each frame.

I'm currently doing this: \- start game, render screen once \- Once a tile changes, save this in a "tile\_changed" array \- Each frame, re-render all the changed tiles and clear the array

This works pretty fine, and there is a notable boos in performance. However, there are a view issues \- The PlayN framework offers no way to "erase" drawn items. Whenever I want to erase a single tile I have to completely clear the screen and redraw every tile. (PlayN SurfaceLayer). I'm using a scroll background, so can't just fill an empty tile with the background color. I can imagine low level libraries like opengl having this same issue, do they use some sort of workaround for this?

* I'm not sure how to recognize when new tiles come into the screen whenever the camera moves. I would normally just render the tiles in view each frame, so this never posed a problem.
* I have no idea if having such a big drawn rendertarget in memory is a good idea. The player could have walked across a huge map and have thousands of tiles drawn. Should I worry about this?

Any other optimiztions that I'm missing are appreciated.

---

The awnsers note that most engines draw all tiles every frame. But I know that on some less powerfull platforms this is not the case. I believe flashpunk is using some sort of buffer that only draws new tiles when you make changes in the grid. Unfortunately this is not possible for me because I have no way of clearing a single tile without clearing the entire buffer.

I'm looking into optimazations like this, which enable me to have a very large amount of tiles on the screen.

# Answer
> 6 votes
Basically its like Marthon said, that most engines simply redraw the whole scene on every render call and not only portions of the visible scene. What you are looking for is a way to limit the objects/tiles, that are actually rendered. If you have a 2d array of tiles, that are all same sized its pretty simple to find the start and the end index of the x and y loop. My render method for a tile layer looks something like this:

```
public void render(Graphics g, MappedTile[][] tiles, int width, int height, float offsetX, float offsetY, float screenX, float screenY)
{
    int layers = 1;
    int startX = (int) (-offsetX / tileWidth);
    int startY = (int) (-offsetY / tileHeight);
    int endX = (int) ((-offsetX + screenX) / tileWidth + 1);
    int endY = (int) ((-offsetY + screenY) / tileHeight + 1);
    if(startX < 0)
        startX = 0;
    if(startY < 0)
        startY = 0;
    if(endX > width)
        endX = width;
    if(endY > height)
        endY = height;

    for(int y = startY; y < endY; y++)
    {
        for(int x = startX; x < endX; x++)
        {
            //Put render code in here... Select tile, apply offset and render
        }
    }
}

```

The idea is that you only render those tiles, that are visible on screen and skip those that are outside of the viewport. You don't have to recognize when a new tiles comes into the screen, as you recalculate the variables on every render call. Alternatively you could only update the position, if the viewport has changed since the last render pass.

Note, if you want to add scaling functionality, you would also need to change the calculation of startX, startY, endX and endY, so the scaling is taken into account.

For other objects, for example sprites, that can be positioned freely on a map, a better data structure is needed. You could implement a quad tree and use it to distribute the objects around cells. You then simply select only the visible cells and render the objects from those cells (after you sorted them on the y axis). But thats another topic.

# Answer
> 3 votes
When designing for current PC GPUs you are not playing after the same performance rules, as, for example, a cellphone or the Amiga.

Modern GPUs are way more powerful than you can imagine and most of the time the bottleneck is not the drawing itself but actually the communication between your code running on the CPU and the GPU.

Take a look at this answer for performance suggestions on modern GPUs:
Drawing lots of tiles with OpenGL, the modern way

# Answer
> 2 votes
Not clearing the screen can actually degrade performance, because on double buffered framebuffer, a copy has to be performed when you swap buffers, which is apparently more expensive than simply clearing the current framebuffer to some default color value. (see https://stackoverflow.com/questions/2538662/how-does-glclear-improve-performance for example)

The performance hit of having to copy the tiles is probably lower than having to re-render them, but its something to consider.

---

So youre considering of doing either:

**A**

1. Copy entire screen to the current framebuffer from the previous one.
2. Render updated tiles on top

OR

**B**

1. Clear current framebuffer to default color (cheaper than copy?)
2. Render all tiles on top

And NOT

**C**

1. Render updated tiles on top

(this would only be the case if double buffering was not used at all)

If you cant go with option A and dont want option B, you can maybe go with option:

**D**

1. Clear current framebuffer to default color (cheaper than copy)
2. Render updated tiles on top of an offscreen texture
3. Copy this offscreen texture/framebuffer on top of current framebuffer

This allows you to render the scrolling background before you copy the offscreen texture with the tiles on top. Im assuming you have the ability to render on an offscreen texture/buffer with alpha support though. It would work as in:

1. Clear current framebuffer
2. Draw scrolling background to it
3. Render updated tiles to the offscreen buffer (or clear existing ones by filling with transparent color values)
4. Blend the offscreen buffer onto the current framebuffer, on top of the background

And of course profile your game with the correct tools to ensure you know exactly where the problem is, and make sure your rendering works as is conventional for the platform (using everything correctly, using the correct features optimally etc).

# Answer
> 0 votes
I am also working on a tile based game right now for mobile devices. I am working with a canvas, and the way i solved this problem is to make a rect object of the canvas, and then chech if the tile intersects the rect of the canvas using the intersect() method.

---
Tags: optimization, tilemap, efficiency, playn
---


# Question
Title: Low quality bilinear sampling in WebGL/OpenGL/DirectX
I'm seeing low quality bilinear texture sampling in WebGL, OpenGL and Directx, and was wondering if anyone knew how to make it higher quality? The picture below should help show what I mean.

The left uses the built in bilinear sampling, while on the right, i read in the 4 pixels of the texture and do linear interpolation myself, which results in a higher quality interpolation.

I've tried lots of things, including setting the precision to highp for everything, including the sampler, and also have tried using floating point textures and looking for any relevant extensions, but no luck.

Does anyone know if there's a way to get the smoother interpolation in WebGL?I have tried it on a couple different machines (all nvidia though) as well as the major browsers.

I know that I can make it higher quality by taking 4 samples and doing the bilinear interpolation myself, or by taking 2 samples where i left the hardware do the X axis, then i do the Y axis in my shader. Are there any other ways? Hopefully some solution that doesn't require more texture reads?

Here's a link to the actual WebGL page, where you can see the source: http://demofox.org/BilinearTest/bilineartest.html

Thanks for any help anyone can provide!!

**EDIT: code details**

I create a 2x2 texture with linear min and mag filters - no mips.

```
function createTexture(byteArrayWithRGBAData, width, height) {
    var texture = gl.createTexture();
    gl.bindTexture(gl.TEXTURE_2D, texture);
    gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array(byteArrayWithRGBAData));
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
    gl.bindTexture(gl.TEXTURE_2D, null);
    return texture;
}

....

var textureData = [
    128, 0, 0, 255,     50, 0, 0, 255,
     50, 0, 0, 255,    200, 0, 0, 255
];

// create the texture
theTexture = createTexture(
    textureData,
    2, 2
    );

```

I'm drawing a full screen quad, where the lower left has a texture coordinate of 0,0 and the upper right has one of (2,1). In my pixel shader, on the left side i sample along the diagonal of the image (again, using bilinear sampling), using the x texture coordinate to define where in the image 0.25 to 0.75 my u,v coordinates should be.

The left side uses bilinear sampling and you can see that it's very rough. This is the problem I'm trying to overcome, and have heard (but have not seen proof) that the texture is interpolated using 24.8 fixed point in the hardware, which makes those jaggies.

On the right side, i remap the 1.0-2.0 x axis texture coordinate to 0-1 so that it shows the same thing.

On the right side however, instead of doing hardware bilinear texture sampling, I'm getting the 4 pixels of the image and doing the bilinear interpolation in the fragment shader myself. The results are smooth like you'd expect, due to the calculations happening with floating point values.

To get the actual pixel color on both sides, i check the texture coordinate's y axis versus the pixel value interpolated. If the texture coordinate's y axis value is smaller, i make the pixel green, else make it black.

The vertex shader is uninteresting and just a pass through, but here's the fragment shader

```
<script id="shader-fs" type="x-shader/x-fragment">
precision mediump float;
uniform sampler2D uSampler;
varying vec2 vTextureCoord;

vec4 SamplePixel (vec2 pixel, bool bilinearSampling) {
    // Bilinear sampling:
    // Hardware based bilinear sampling
    if (bilinearSampling)
        return texture2D(uSampler, (pixel + vec2(0.5)) / 2.0);

    // Nearest sampling:
    // Software bilinear sampling (higher quality)
    float fracu = fract(pixel.x);
    float fracv = fract(pixel.y);

    vec2 floorPixel = floor(pixel) + vec2(0.5,0.5);

    vec4 A = texture2D(uSampler, floorPixel / 2.0);
    vec4 B = texture2D(uSampler, (floorPixel+vec2(1.0,0.0)) / 2.0);
    vec4 C = texture2D(uSampler, (floorPixel+vec2(0.0,1.0)) / 2.0);
    vec4 D = texture2D(uSampler, (floorPixel+vec2(1.0,1.0)) / 2.0);

    return mix(mix(A,B,fracu), mix(C,D,fracu), fracv);
}

void main(void) {
    vec4 colorValue;

    if (vTextureCoord.x < 0.995)
    {
        float pixel = vTextureCoord.x / 0.995;
        colorValue = SamplePixel(vec2(pixel), true);
    }
    else if (vTextureCoord.x > 1.005)
    {
        float pixel = fract(vTextureCoord.x - 0.005) / 0.995;
        colorValue = SamplePixel(vec2(pixel), false);
    }
    else
    {
        gl_FragColor = vec4(1.0);
        return;
    }

    float value = step(vTextureCoord.y, colorValue.x);
    gl_FragColor = vec4(0.0, value, 0.0, 1.0);
}
</script>

```

# Answer
As luck would have it Iñigo Quilez wrote an article about this which popped up in my Facebook feed this morning.

> Hardware texture intepolation is fast and convenient. It is bilinear (plus mipmapping), and despite it can be somehow improved, it works great for most cases. Most cases being texture mapping of surfaces with color/albedo, normal and specular textures. Generally these types of textures don't need lots of color fidelity (where "color" means pixel value/content), and therefore the hardware's texture interpolation units implement some simple interpolation based on 24.8 fixed point arithmetic. That's what all GPUs' hardware implments these days.
>
> A 24.8 precision texture interpolator means that there's a maximum of 256 intemediate values possible between two adjacent pixels of a texture. 256 values are a lot for albedo textures for sure, but often in computer graphics textures encode not only surface properties, but they serve as LookUp Tables (LUT), heighfields (for terrain rendering), or who knows what. In those cases, you can find yourself easily lacking more resolution than 256 values between pixels.

Here's an example image from the article:

**(Top) Hardware interpolation:** visually smooth, but the barcode shows the derivative is spiky. **(Bottom) Manual interpolation:** the constant colour in the derivative bar shows we're not getting step artifacts anymore.

So there's the answer. Hardware filtering is mainly intended to bridge sub-texel gaps for surface textures. So assuming our textures have enough resolution & mip maps for how close they are to the camera, we usually only have to interpolate a few steps - to deal with a texel center that's just a bit off from our rendered pixel center, or to fill a gap between two adjacent texels that are slightly more than 1 rendered pixel apart. For most cases, if we need *anywhere near* all 256 interpolation steps shown at once, it's because the player has crammed their camera right up against a wall, or we're trying to massively stretch a texture that's too low-res for the use it's being put to.

But if we're doing procedural graphics, it's often tempting to use a low-resolution texture stretched wide to give us low-frequency gradients, using the texture interpolator to give us free bilinear interpolation between samples. For colours this is often okay, since the human eye is pretty bad at spotting banding artifacts unless they're extreme. But if we care about the precise value at each sample - like for heightfields or sharp thresholds as you're doing here, then these staircase & plateau artifacts creep in.

**So what can we do about it?**

The most general-purpose solution (and what Iñigo Quilez recommends in his article) is exactly what you're doing: sample the texture four times and interpolate the results yourself in the shader, where you have full floating point precision.

If the case you've shown is representative of your real applications though, there may be more efficient methods:

* Increase the resolution of your input texture, say to 16x16. Now the texture interpolation from a single fetch only needs to cover 1/15th as much ground with its 256 intermediate values, so you have an effective range of 3840 intermediates from one edge to the other. Much better! And still with only 1 texture sample. The memory taken up by this texture is still tiny, so you needn't feel bad about being wasteful.
* If you only ever need to do bilinear filtering between the same 4 corners, you might as well do away with the texture and do it all in shader variables. This way you don't pay for even a single texture fetch. You can profile to double-check, but I'd wager this might be even be faster than using the "free" interpolation from the texture pipeline, since there's no contention or caching overhead.
> 5 votes

# Answer
I found this paper:
"Efficient GPU-Based Texture Interpolation using Uniform B-Splines" http://www.mate.tue.nl/mate/pdfs/10318.pdf

Which states:

> It should be noted that there are some precision issues associated with the hard-wired linear texture interpolation. When, e.g.,an eight-bit texture is filtered, most people would expect that first the neighboring texture knots are queried, casted to floating point, and then weighted and added. This is, however, not the case; the texture knots are first weighted and added, and then casted to floating point, which limits the precision to the least significant bit of the texture data format **\[Ruijters et al. 08\]**, as is illustrated in Figure 4. As a consequence, higher accuracies can only be obtained by using larger texture words, and thus at the cost of texture memory consumption.
>
> A further precision issue of the linear texture interpolation is caused by the fact that the accuracy of the texture coordinates is limited to a fixed-point format with eight bits of fractional value **\[NVIDIA 08\]**. This means that there are only 254 discrete coordinate positions between two texture knots, as shown in the zoomed graph in Figure 4, which is especially of interest when the knots are far apart...

The two references it has are:

**\[NVIDIA 08\]** NVIDIA Corporation. “Linear Filetering.” In NVIDIA CUDA Compute Unified Device Architecture: Programming Guide, Appendix D.2, 2008. http://www.uni-graz.at/~liebma/CUDA/NVIDIA\_CUDA\_Programming\_Guide\_2.0.pdf

and:

**\[Ruijters et al. 08\]** Daniel Ruijters, Bart M. ter Haar Romeny, and Paul Suetens. “Accuracy of GPU-based B-Spline Evaluation.” In Computer Graphics and Imaging (CGIM), pp. 117–122. Calgary, AB, Canada: ACTA Press, 2008. http://www.dannyruijters.nl/docs/GPU\_AccuracyBSpline.pdf
> 1 votes

---
Tags: opengl, directx, graphics-programming, webgl, interpolation
---


# Question
Title: Random Y Axis Movement Within Set Limits (C#)
I've searched everywhere for this answer but everything I find is in Javascript and a lot of it doesn't help/work in my situation since most of it is Vector3's and using each axis, and my game is 2D.

So I have these prefabs that get spawned off-screen and then I have a script attached to them that tells them to move left on the x axis. I need them to also pick a random direction (up or down) on the y axis, and travel that way until they get to a certain spot (range) and then to switch directions and go the opposite etc.

Here is what I have tried most recently:

```
public float itemUp = 0.1f;
public float itemMove = 0.7f;

public float x;
float y;
float z;
Vector3 pos;

void Update () {

    //transform.position = Vector2(Random.Range (1,4),Random.Range (1,4),10);

    transform.position -= Vector3.right * itemMove * Time.deltaTime;

    x = 0;
    y = Random.Range(-100, 100);
    z = 0;
    pos = new Vector3(-x, y, z);
    transform.position = pos * itemUp * Time.deltaTime;
}

```

Anyone know what I'm missing/not doing correctly? I'd really appreciate any help you can give, thank you.

# Answer
> 1 votes
Sample code to move an object up and down.

```
public float Y_Min = -100f; //Set this to the lowest Y value you want the Item to move to.
public float Y_Max = 100f; //Set this to the highest Y value you want the Item to move to.
public float VerticalSpeed = 5f; //Speed the Item will move vertically.
public float Dir = 1f; //Direction the Item is moving, either up or down.

void Start() {

    Dir = Random.value > 0.5f ? 1f : -1f; //Set Dir to start randomly either Up or Down.
    float StartY = Random.Range(Y_Min, Y_Max);//Get a random value between Min and Max to start off at.

    transform.position = new Vector3(transform.postion.x, StartY, transform.position.z);//Set item's Vertical position to a random value between Max and Min.
}

void Update () {

    //Check to see if the Item's Y position is above Max or below Min and switch direction.
    if (transform.position.y > Y_Max)
        Dir = -1f;
    else if (transform.position.y < Y_Min)
        Dir = 1f;

    //Compute new position based on VerticalSpeed and whether we are going up or down
    Vector3 NewPos = new Vector3(transform.position.x, transform.position.y + ((VerticalSpeed * Time.deltaTime) * Dir), transform.position.z);
    transform.position = NewPos;
}

```

---
Tags: c#, 2d, transformation, random
---


# Question
Title: How to import Cocos2d-x in codeblocks ide?
Is it possible to import cocos2d-x in codeblocks just as in xcode ?? How can I do that ?

I use ubuntu. It is not possible to use xcode in ubuntu. Cocos2dx is in c++. How can I use codeblocks for game development with cocos2dx??

Thanks

# Answer
I got answer for my own question.

refer to this link http://discuss.cocos2d-x.org/t/can-someone-tell-me-how-to-setup-cocos2d-x-on-code-blocks/10144/2

I follow these steps.

1) Create cbp file with the command cmake ../ -G "CodeBlocks - Unix Makefiles"

2) Open it in Codeblocks

This solved my problem.
> 1 votes

---
Tags: c++, cocos2d-x
---


# Question
Title: Does projection take place before clipping in the rendering pipeline?
At first I thought clipping happens before projection since new vertices may be added and the output of projection is in NDC which is 2D. However after a lot of googling, I found that some articles/presentations/images indicate that projection takes place before clipping which contradicting with other articles I've read and my initial thoughts.

Could anyone tell me which one is correct and why?

# Answer
> 2 votes
I don't know which platform you're working on, but on most modern platforms, all culling and clipping happens *after* vertex transformations, but *before* fragment shading.

You can do some custom pre-culling, and not issue draw commands for objects you know won't be visible, but once you ask some triangles to be drawn, it's not until you apply view and projection matrices that you know which vertices are eligible for culling and clipping.

This graph, which I don't know who drew it first, but is the first result when you google image search "Direct3D 9 pipeline" is very useful for understanding where everything fits.

---
Tags: graphics, rendering, projection, pipeline, clipping
---


# Question
Title: How to access raw texture data in DirectX 11?
I want to get access to a texture's pixel color data on the CPU. When trying to map the texture, I get E\_INVALIDARG in return from ID3D11DeviceContext::Map.

```
ID3D11ShaderResourceView* resourceView; //represents my texture, already loaded up
//...

//Getting the resources of the texture view...
ID3D11Resource* res = nullptr;
ID3D11Texture2D* tex = nullptr;
resourceView->GetResource(&res);
res->QueryInterface(&tex);
D3D11_TEXTURE2D_DESC desc;
tex->GetDesc(&desc); //Correct data gets filled out
D3D11_RESOURCE_DIMENSION dim;
res->GetType(&dim); //value gets set as Texture2D which it should

D3D11_MAPPED_SUBRESOURCE mappedResource;
HRESULT h;
h = context->Map(tex,0,D3D11_MAP_READ,0,&mappedResource); //This always fails
h = context->Map(res,0,D3D11_MAP_READ,0,&mappedResource); //This also fails

```

The idea is that I keep only shaderResourceViews for my textures, because that is all I needed until now, and get the relevant resources here.

I tried mapping as WRITE\_DISCARD also, but to no success. I am really confused, because I never had any problem with mapping constant buffers and vertex buffers. I seem to be certainly missing something?
By the way, I am using Wic Texture loader and DDS Texture loader for the DirectXTex toolkit, and tried this code for png, dds textures, with and without mip-maps.

# Answer
**It might help if you explained what you are doing with that texture exactly...** In general, there are lots of good performance reasons why you can't easily access texture data in Direct3D resources from the CPU...

You can't map `D3D11_USAGE_DEFAULT` textures as they are allowed to be placed into memory that is potentially inaccessible the CPU, and is therefore the fastest for the GPU to access.

You can't map `D3D11_USAGE_IMMUTABLE` at all, and can only initialize them with initData at creation time.

You can map `D3D11_USAGE_DYNAMIC` textures, but there's a performance penalty for both the GPU and CPU to read them. Generally you use them with only `D3D11_CPU_ACCESS_WRITE` and not try to read them from the CPU.

You can of course map `D3D11_USAGE_STAGING` since they are only accessible by the CPU, so they can't be rendered.

Both DirectXTex and DirectX Tool Kit's texture loaders have an `Ex` version that would allow you to specify a usage other than `D3D11_USAGE_DEFAULT` and to provide `D3D11_CPU_ACCESS_READ` which is required to access the pixels with `Map`

You could also create a second `D3D11_USAGE_STAGING` resource and then `CopyResource` from the original to the staging resource, and then you can `Map` the staging resource. Note that this is what DirectX Tool Kit's ScreenGrab and DirectXTex's CaptureTexture are doing.

It's also worth noting that if you really want to access the texture's pixel color data, you do not want to use `D3D11_MAP_WRITE_DISCARD` as the whole purpose of that flag is to tell the driver that you don't actually care about any existing data from the CPU side--this allows the driver to just give you back a pointer to some other memory of the same size while continuing to use any existing copy for rendering without slowing things down--this is called 'buffer renaming'.

BTW, be sure to read this post as to why there are texture functions in both DirectXTex & DirectX Tool Kit.

PS: If you get an HRESULT like `E_INVALIDARG`, if you enable the Debug Device you will get diagnostic output that tells you why...
> 6 votes

---
Tags: directx11
---


# Question
Title: How do I make so when user moves the camera it doesn't go beyond the scene borders in Unity3D?
How do i make so when i move my camera, it doesn't go beyond the border of the canvas while playing. This is the script i use to make the camera move:

```
        if (Input.touchCount > 0 && Input.GetTouch (0).phase == TouchPhase.Moved)
    {
        Vector2 touchDeltaPosition = Input.GetTouch (0).deltaPosition;
        transform.Translate (+touchDeltaPosition.x * speed, +touchDeltaPosition.y * speed, 0);
    }

```

# Answer
> 1 votes
There is a Video tutorial by 3D Buzz which does exactly this. In this method, you clamp camera positions and add some offset margin so that the camera gives some leeway to the player before moving to follow player.

# Answer
> 0 votes
an easy solution could be this:

```
if (Input.touchCount > 0 && Input.GetTouch (0).phase == TouchPhase.Moved)
{
    Vector2 touchDeltaPosition = Input.GetTouch (0).deltaPosition;

    vector3 delta = new Vector3(touchDeltaPosition.x * speed,touchDeltaPosition.y * speed , 0);

    if ((transform.position + delta )   is inside your canvas)  /*pseudo code*/
            transform.Translate (+delta.x, +delta.y , 0);
}

```

# Answer
> 0 votes
This code was built with LibGdx, but you should be able to easily adapt it to your own code:

```
    Camera c = this.getCamera();
    Vector3 camPos = c.position;
    float HW = c.viewportWidth / 2, HH = c.viewportHeight / 2;
    camPos.x = MathUtils.clamp(camPos.x, HW, mapWidth - HW);
    camPos.y = MathUtils.clamp(camPos.y, HH, mapHeight - HH);

```

What this code does is it clamps (keeps the first value between the min and max, the second and thrid value respectively) the x and y positions of the camera to the inside of the map. Because the LibGdx camera's position is at the center of its viewport you need to ensure that the middle is at least half of the width or hight of the viewport from the left and right sides or top and bottom, respectively.

This code should be run after you set the camera's new position since it is post-corrective.

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


# Question
Title: Unity: Can't access repeatDelay from StandaloneInputModule?
I have a very specific problem. I'm trying to change the `repeatDelay` variable within my `StandaloneInputModule`, but it's not coming up as a variable. All of the other variables come up when I use `GetComponent<StandaloneInputModule>()`, but not the one that I want. Is there something different about `repeatDelay` that I'm not seeing?

EDIT: I'm using the `UnityEngine.EventSystems` namespace too.

# Answer
> 1 votes
It was added in the 5.1 update. So download and upgrade your project and all should be good.

---
Tags: unity, input
---


# Question
Title: How can I render text using the new(ish) JOGL GPU curve rendering classes?
I'm fairly new to OpenGL/JOGL, working through various tutorials and books and making steady progress. Text, however, is an area where I'm stuck. I figured out one way using BufferedImage and Graphics2D to draw strings and then swizzle the pixels and copy to an OpenGL texture, but the quality is low, it is resolution dependent, and it's not efficient.

I found this: http://forum.jogamp.org/GPU-based-Resolution-Independent-Curve-Rendering-td2764277.html. Unfortunately while there are some demos in the GitHub repo I can't quite get my head around them. The code I've tried to use is below:

In the init() method:

```
    InputStream fontFile = getClass().getResourceAsStream("media/futura.ttf");
    try {
        font = FontFactory.get(fontFile, true);
    } catch (IOException e) {
        System.err.println("Couldn't open font!");
        e.printStackTrace();
    }

    RenderState renderState = RenderState.createRenderState(SVertex.factory());
    renderState.setColorStatic(1, 1, 1, 1);
    renderState.setHintMask(RenderState.BITHINT_GLOBAL_DEPTH_TEST_ENABLED);

    renderer = RegionRenderer.create(renderState, RegionRenderer.defaultBlendEnable, RegionRenderer.defaultBlendDisable);
    renderer.init(gl, Region.VBAA_RENDERING_BIT);

    util = new TextRegionUtil(Region.VBAA_RENDERING_BIT);

```

In the display() method:

```
    PMVMatrix pmv = renderer.getMatrix();
    pmv.glMatrixMode(GLMatrixFunc.GL_MODELVIEW);
    pmv.glLoadIdentity();
    pmv.glTranslatef(0, 0, -300);
    float pixelSize = font.getPixelSize(32, 96);
    util.drawString3D(gl, renderer, font, pixelSize, "Test", null, samples);

```

I've searched and searched for a tutorial on this stuff or a simple, commented code example explaining how it works but to no avail. If anyone can help me I'd be extremely grateful!

# Answer
> 3 votes
Ok so to answer my own question, it turns out I'm an idiot and overlooked something really simple. The code in my question works perfectly, but I never set the text renderer's projection matrix. To make it work, in the resize method I added the following code:

```
renderer.enable(gl, true);
renderer.reshapeOrtho(width, height, 0.1f, 1000.0f);
renderer.enable(gl, false);

```

I also added an x/y coordinate offset in screen coordinates to the pmv.glTranslatef call to move the text in.

Now I have nice, cleanly rendered text from any font at any resolution, thanks Rami Santina and Sven Goethal of the JOGL team :)

---
Tags: opengl, text, jogl
---


title: Geometry Struct and glDrawElements

text:
# Question
Title: Geometry Struct and glDrawElements
currently I re-write my codes and change them to make they are better.

I have vertex struct like this:

```
struct SVertex
{
    float X, Y, Z;
};

struct STexCoord
{
    float U, V;
};

```

And I re-wrote it like this

```
struct SVertex
{
    int Flag, BoneID;
    float Pos[3];
    float UV[2];
};

```

When it comes to the render function, I just need to change it from:

```
glVertexPointer(3, GL_FLOAT, 0, &(Mesh[i].Vertex[0]));
glTexCoordPointer(2, GL_FLOAT, 0, &(Mesh[i].TexCoord[0]));

```

to:

```
glVertexPointer(3, GL_FLOAT, sizeof (SVertex), &(Mesh[i].Vertex[0].Pos));
glTexCoordPointer(2, GL_FLOAT, sizeof (SVertex), &(Mesh[i].Vertex[0].UV));

```

The problem comes from the triangle struct. I re-wrote the Triangle from

```
struct STriangle
{
    int X, Y, Z;
};

```

to

```
struct STriangle
{
    int Flag, Group;
    int V[3], N[3];
};

```

and I changed the glDrawElements from:

```
glDrawElements(GL_TRIANGLES, Mesh[i].TriangleTotal*3, GL_UNSIGNED_INT, &(Mesh[i].Triangle[0]));

```

to

```
glDrawElements(GL_TRIANGLES, Mesh[i].TriangleTotal*3, GL_UNSIGNED_INT, &(Mesh[i].Triangle[0].V));

```

And I got messed vertex with the new triangle struct. If I use the old ones, it is correct. How to pass the new triangle struct to the glDrawElements?

# Answer
**EDIT:** There is actually no support for what you're trying to do. There is no equivalent function to glVertexPointer in OpenGL for the indexes. I earlier suggested glIndexPointer but it uses an array of colors, not indexes (a very misleading name, and my bad for posting it).

Unfortunately you will have to supply a contiguous array of indexes, or find another way to arrange your data in the structures. I searched for a while and stumbled upon this question in stackoverflow which is similar to what you are looking for, https://stackoverflow.com/questions/19057864/in-opengl-how-do-you-specify-indices-with-a-stride.

You should consider moving into modern OpenGL and start using VBOs. It's never too early to learn VBOs, it's probably best if you start learning VBOs sooner than later.

Timur's answer and Soapy's comment already have links to using VBOs and modern Open GL, do check them out.
> 1 votes

---
Tags: opengl, face, struct
---


# Question
Title: Analyzing movement data for a checkerboard
For a psychology experiment - subject has to learn that the 2D grid is a checkerboard, and collect all the 1s (rewards). How do I test if subjects are actually doing it in the most optimal way -- making least effort for moving from one square to the next by taking smaller steps (or selecting closest reward neighbour). My guess is that if I could simulate a learning algorithm and approximate how long it takes to learn the reward distribution, and then explore it optimally (optimality is defined as a unit of time and exploring closest squares first), I could compare the behaviour.

# Answer
> 1 votes
If the grid size is large, this becomes unsolvable by a computer, as this is a NP problem.

See https://en.wikipedia.org/wiki/Travelling\_salesman\_problem

If your grid is small, you can get a computer to calculate all possibilities, and plan a optimal route. However, as your grid gets larger, your calculations get exponentially larger, to the point where it takes forever for a computer to determine the optimal path required.

To calculate all routes, a solution would be to utilize an A\* pathfinding algorithm, to calculate the shortest path required to visit every single node.

You could calculate this by calculating every path possible, and taking the shortest one.

---
Tags: grid, analytics
---


# Question
Title: Would Raycast suffice for a game clock based on sun position?
I need help with some logic in my script. I created a dynamic day/night cycle that works fine in itself, but I want to add a game clock that works off the initial position of the sun (Directional Light).

I was thinking that it could be achieved by Shooting a ray from the directional light to the terrain and computing an angle which i would use to estimate the time.

1. Would ray casting be the best/ most efficient way to do this?
2. Is it even possible to achieve what I'm asking for, if not is there a method that better suits what I need?

So to go over.. I want the user to be able to place the sun anywhere along the x axis that would rotate around the terrain, when the user is satisfied with the position they chose, on startup of the game I would like my script to calculate the current position of the sun and then estimate the current time.

I can take care of the actual clock after that point but is ray casting from the sun to the terrain the way to go about something like this or should I be looking at this in totally different way?

# Answer
> 1 votes
I have come up with a solution and it seemed to be buried deep within my college memory. I achieved what I wanted through a Unit Circle! Basic calculus/geometry seemed to be the correct way for me to come up with a working solution. I took the x and y translation points of the sun and put them through the unit circle equation. See https://www.mathsisfun.com/geometry/unit-circle.html for more information. Using these calculations I could base my logic off the degrees the equation gave me, giving me a working solution! Math is fun... Ish

---
Tags: rotation, vector, terrain, raycasting, unity
---


# Question
Title: What's the difference between Destroy() and SetActive(false)?
I read about both methods in Unity and wanted to ask about which was the best in efficiency : destroying the object or deactivating it. What is the performance difference?

# Answer
Destroying the object gets rid of it completely. You cannot get it back. It is gone.

Deactivating it just disables it; everything is still there, it just does nothing.

Therefore, if you want to reuse the object, you can deactivate it, but if you will never use it again, you should destroy it (and get back its memory).
> 7 votes

# Answer
You should also mention that creating objects isn't cheap performance-wise. So you should be reusing objects that you plan to have multiple of. In general any game object that is being created and destroyed over the course of the whole game should be reused and not destroyed.

You can google object pooling for more information.

https://unity3d.com/learn/tutorials/modules/beginner/live-training-archive/object-pooling http://unitypatterns.com/resource/objectpool/
> 1 votes

---
Tags: unity, gameobject
---


# Question
Title: How to use PhotonPeer in Unreal Engine 4.8
I'm trying to implement PhotonPeer in Unreal Engine 4.8 but I'm stuck at the connect function. I need to provide an AppId, but nothing I try is accepted by UE4.

Here's my code:

DALGameInstance.h

```
// Fill out your copyright notice in the Description page of Project Settings.

#pragma once

#include "Engine/GameInstance.h"
#ifdef __clang__
#pragma clang diagnostic ignored "-Woverloaded-virtual"
#endif
#if _EG_WINDOWS_PLATFORM
#include "AllowWindowsPlatformTypes.h"
#endif
#pragma warning (disable: 4263)
#pragma warning (disable: 4264)
#include "Photon/Photon-cpp/inc/PhotonPeer.h"
#include "Photon/Photon-cpp/inc/PhotonListener.h"
#pragma warning (default: 4263)
#pragma warning (default: 4264)
#if _EG_WINDOWS_PLATFORM
#include "HideWindowsPlatformTypes.h"
#endif
#include "DALGameInstance.generated.h"

/**
 *
 */
UCLASS()
class DALGAME_API UDALGameInstance : public UGameInstance
{
    GENERATED_UCLASS_BODY()

public:
    //UDALGameInstance(const class FObjectInitializer& ObjectInitializer);
    ExitGames::Photon::PhotonPeer* peer;
    ExitGames::Photon::PhotonListener* listener;
    UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = DALGameInstancePhoton)
    FString ServerAddress = "127.0.0.1:5055";
    UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = DALGameInstancePhoton)
    FString ApplicationName = "MasterServer";
};

```

DALGameInstance.cpp

```
// Fill out your copyright notice in the Description page of Project Settings.

#include "DALGame.h"
#include "DALGameInstance.h"

UDALGameInstance::UDALGameInstance(const class FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer)
{
    peer = new ExitGames::Photon::PhotonPeer(*listener, ExitGames::Photon::ConnectionProtocol::UDP);
    UE_LOG(LogTemp, Warning, TEXT("Connecting to server"));
    if(!peer->connect(*ServerAddress, **ApplicationName**))
    {
        UE_LOG(LogTemp, Warning, TEXT("Connection failed"));
    }
    else
    {
        UE_LOG(LogTemp, Warning, TEXT("Connection established"));
    }
}

```

The **part** with ApplicationName is the problem. BuildTool complains No suitable conversion from FString to const nByte. I have tried everything to get this up and running but with no luck at all.

Does someone have the same issue or a hint at what I missed?

# Answer
> 1 votes
Found a solution with help from Exitgames.

DALGameInstance.h

```
/* ToDo: Find a way to get nByte as UPROPERTY! */
//UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = DALGameInstancePhoton)
nByte* ApplicationName = reinterpret_cast<nByte*>("MMOServer");

```

DALGameInstance.cpp

```
if(!peer->connect(*ServerAddress, ApplicationName))

```

Try to implement listener now and view.

---
Tags: c++, unreal-4
---


# Question
Title: Camera.unproject(Vector3) method is not working in libGdx
I know the touch postioning in libGdx uses OpenGL, making 0,0 the bottom left corner while the camera uses the top left corner as 0,0. I did some searching and found this SO question that specifies that I need to use the `Camera.unoroject(Vector3)` method. This is the relevant code:

```
package com.mycompany.mygame;

import com.badlogic.gdx.*;
import com.badlogic.gdx.graphics.*;
import com.badlogic.gdx.graphics.g2d.*;
import com.badlogic.gdx.math.*;

public class MyGdxGame implements ApplicationListener
{
    public float x;
    public float y;
    public float w = 50;
    public float h = 50;

    Texture texture;
    SpriteBatch batch;
    OrthographicCamera cam;

    @Override
    public void create()
    {
        texture = new Texture(Gdx.files.internal("android.jpg"));
        batch = new SpriteBatch();
        cam = new OrthographicCamera();

        //x = 50;
        //y = 50;
    }

    @Override
    public void render()
    {
        Gdx.gl.glClearColor(1, 1, 1, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        batch.begin();

        if(Gdx.input.isTouched()){
            Vector3 touchPos = new Vector3(Gdx.input.getX(), Gdx.input.getY(), 0);
            cam.unproject(touchPos);
            batch.draw(texture, touchPos.x, touchPos.y, w, h);
        }
        batch.end();
    }

    @Override
    public void dispose()
    {
    }

    @Override
    public void resize(int width, int height)
    {
    }

    @Override
    public void pause()
    {
    }

    @Override
    public void resume()
    {
    }
}

```

The problem is the game is not drawing correctly. It should draw the character at the touchPos.x and touchPos.y coordinates, but it is not. It is drawing in the bottom left corner. See the pictures below:

# Answer
Try this:

```
package com.mycompany.mygame;

import com.badlogic.gdx.*;
import com.badlogic.gdx.graphics.*;
import com.badlogic.gdx.graphics.g2d.*;
import com.badlogic.gdx.math.*;

public class MyGdxGame implements ApplicationListener
{
    public float x;
    public float y;
    public float w = 50;
    public float h = 50;

    Texture texture;
    SpriteBatch batch;
    OrthographicCamera cam;

    @Override
    public void create()
    {
        texture = new Texture(Gdx.files.internal("android.jpg"));
        batch = new SpriteBatch();
        cam = new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());

        //x = 50;
        //y = 50;
    }

    @Override
    public void render()
    {
        Gdx.gl.glClearColor(1, 1, 1, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        batch.setProjectionMatrix(cam.combined);
        batch.begin();

        if(Gdx.input.isTouched()){
            Vector3 touchPos = new Vector3(Gdx.input.getX(), Gdx.input.getY(), 0);
            cam.unproject(touchPos);
            batch.draw(texture, touchPos.x, touchPos.y, w, h);
        }
        batch.end();
    }

    @Override
    public void dispose()
    {
    }

    @Override
    public void resize(int width, int height)
    {
    }

    @Override
    public void pause()
    {
    }

    @Override
    public void resume()
    {
    }
}

```

If this doesn't work, try to print touch coordinates before and after `cam.unproject()`. That's the best way to understand bug and fix it.
> 2 votes

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


# Question
Title: What's the difference between mesh and a model?
Which one is created first? For example if a team worked on a graphical asset of a car, what would be a model and what would be a mesh of the car?

# Answer
A mesh is part of a model. The mesh defines the vertices of an object. Typically storing them in such an order as to imply their connectivity, like every 3 form a triangle.

Like a mesh of vertices to define the shape of an object.

The model can have other elements like an armature, animation and texture information. It can additionally include more than one mesh. Though, I imagine they're similar enough to be used interchangeably in many cases.
> 46 votes

# Answer
Short answer:

The mesh (as in one single mesh) is just data about the structure of a model. The model contains textures which are used to define how to render it's surfaces. It also contains several variations of the same mesh for animation, normally controlled by bones. Each animation frame could be considered a mesh on it's own.

Long answer:

A very important difference to note is that some models are not built from a mesh in the classic sense of the word. Models structured out of Non-uniform rational basis spline (NURBS) also exit. Technically you could build a model in many ways that do not involve a mesh in the classic sense of the word, such as atoms and Voxels. When people speak of a mesh they normally refer to a polygon mesh.

The mesh is a graph. A collection of vertices, edges and faces. A face is an ordered collection of vertices connected by edges that complete a loop. It is used to describe a flat surface on the mesh.

A model is a general term to describe data. In the specific case of 3d models, we mean the mesh, it's uv-mapping, texture and animations.

A model may not have any texture or animation(if it is not complete or if it's an inanimate object or does not require textures), as long as there is a mesh it will still be referred to as a model. The mesh itself is only the 'wireframe' part of the model. Meaning the collection of edges and their connecting vertices that represent the structure of a model. Unlike a texture which represent how the model is colored, how it reflects light and such things as bump mapping details or it's animation which represent the models motion.

So every mesh is a model on it's own. Not every model is only a mesh.

here are some references:

http://en.wikipedia.org/wiki/Polygon\_mesh

http://en.wikipedia.org/wiki/Wire-frame\_model
> 11 votes

# Answer
You may also hear of the term "Solid Model": This means that the underlying mesh model has had such additional information applied, e.g. construction material (and thence can be calculated the model's weight, Centre of Gravity, Centre of Inertia, etc), to the extent that the model is so 'physically' well defined, in a real world sense, that it can be referred to as 'solid'.
> 2 votes

# Answer
In simple terms, a mesh can be regarded as the outline of some shape/object. And the model gives the complete information of that object - texture, reflectivity, color, etc.
> -1 votes

---
Tags: 3d, graphics, terminology
---


title: How to create a Update function in Java

text:
# Question
Title: How to create a Update function in Java
I have recently started using Java, but have been programming in javascript, and actionscript 3 for a while.

I am used to the language giving me the ability to simply do something like:

```
private function Update(){
//stuff
}

```

or something similar to that.

I am looking for something similar in Java, and I want to make sure I am doing it correctly.

I started following a tutorial, and they said to do something like this:

```
 long lastTime = System.nanoTime();
        double amountOfTicks = 60.0;
        double ns = 1000000000;
        double delta = 0;
        long timer = System.currentTimeMillis();
        int frames = 0;
        while(running){
            long now = System.nanoTime();
            delta += (now - lastTime) / ns;
            lastTime = now;
            while(delta >= 1){
                tick();
                delta--;
            }

            if(running)
                render();
            frames++;

            if(System.currentTimeMillis() - timer > 1000){
                timer += 1000;
                System.out.println("FPS: " + frames);
                frames = 0;
            }
        }

```

This seems to be every second calling the tick() function, not the same as every frame though, and while things tend to happen in less time than a second, I would much rather use the same old frame by frame method i was using. (Unless someone can give me a reason not to, always up for an opinion)

So I am wondering, why not just do something like:

```
while(running){
Update();
}

```

I believe this would call every frame. Am I doing something completely crazy here? is there a much better method?

Thanks in advance

# Answer
> 4 votes
There is a nuance here. You asked:

> So I am wondering, why not just do something like:
>
> while(running){ Update(); }
>
> I believe this would call every frame.

This is false. If you place your *Update()* method inside a simple *while(true)* loop, it will be called **as much times as the processor can handle**. If your processor can run it 123456 times a second, it will.

The method the tutorial you follow is using is called a **fixed time-step update**. In other words, **you call your *Update()* function X times a second** (often 60) at fixed intervals (1/60 or 0.0166... seconds).

By using a simple *while(true)* loop, you can use a technique called a **delta-time update**. This technique calls the *Update()* functions as many times as it can, but passes the **time elapsed between 2 loops to the *Update()* function**, so that you can make your calculations accordingly.

There is a lot of documentation on the various advantages and disadvantages of both methods, a quick Google search or a search on this site should give plenty information. But nobody can tell you which one is the ABSOLUTE better.

**NOTE**: In your example, the *Update()* function is only running 1 time per second. You'd need to change a line in order to have the 60 updates per second you want:

```
delta += (now - lastTime) / ns / amountOfTicks;

```

# Answer
> -1 votes
Move the tick function outside the while loop and next to the render function Then you can even make a whole new function with render and tick if you want.

```
While (running)

{

Render ();

Tick ();

}

```

---
Tags: java, game-loop
---


# Question
Title: How can I increase the speed and frequency of a spawn?
I'm using the official Unity tutorial for the Space Shooter game, and I'm at the part where the ability to spawn a set amount of hazards in a wave at a certain delay is introduced.

I want to make it so that at the end of a certain level, the speed of the hazards, and the amount of hazards both increase. I'm pretty sure that can be handled in the game controller, but I don't know the commands I would be needing to use to make that happen. This is the existing code:

```
public class GameController : MonoBehaviour
{
    public GameObject hazard;
    public Vector3 spawnValues;
    public int hazardCount;
    public float spawnWait;
    public float startWait;
    public float waveWait;

    void Start ()
    {
        StartCoroutine (SpawnWaves());
    }

    IEnumerator SpawnWaves ()
    {
        yield return new WaitForSeconds (startWait);
        while (true)
        {
            for (int i = 0; i < hazardCount; i++)
            {
                Vector3 spawnPosition = new Vector3 (Random.Range (-spawnValues.x, spawnValues.x), spawnValues.y, spawnValues.z);
                Quaternion spawnRotation = Quaternion.identity;
                Instantiate (hazard, spawnPosition, spawnRotation);
                yield return new WaitForSeconds (spawnWait);
            }
            yield return new WaitForSeconds(waveWait);
        }
    }
}

```

What commands would I need to use to increase the amount of hazards that spawn at the end of each round? And likewise, how could I change the Hazard's script so that it will increase in speed by a certain factor at the end of each round? Is there a way I can reference the hazard's script in this script, by any chance?

# Answer
`hazardCount` is the number of hazards spawned each round.
`spawnWait` is the delay between spawning of each Hazard in one Wave.
`waveWait` is the length of each Wave.

You can add your own variable, `WaveCounter` that you can increase each Wave. And another variable to control how much you want the `spawnWait` to decrease each new Wave.

```
int WaveCounter = 0;
int HazardCountIncrease = 1;
float SpawnSpeedIncrease = 0.1f;

IEnumerator SpawnWaves ()
{
    yield return new WaitForSeconds (startWait);
    while (true)
    {
        hazardCount += (WaveCounter * HazardCountIncrease);
        for (int i = 0; i < hazardCount; i++)
        {
            Vector3 spawnPosition = new Vector3 (Random.Range (-spawnValues.x, spawnValues.x), spawnValues.y, spawnValues.z);
            Quaternion spawnRotation = Quaternion.identity;
            Instantiate (hazard, spawnPosition, spawnRotation);
            yield return new WaitForSeconds (spawnWait - (WaveCounter * SpawnSpeedIncrease));
        }
        yield return new WaitForSeconds(waveWait);
        WaveCounter++;
    }
}

```
> 1 votes

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


title: MVC How To Handle Animations?

text:
# Question
Title: MVC How To Handle Animations?
I am working on a turn based game that utilizes the model, view, controller design pattern to separate logic from input from rendering. I am still a little new to the pattern, but from my understanding I have laid out the following MVC system.

The model(s) comprise a set of pawns with game flow and interaction logic. Pawns/models know how to interact with each other and the model world, but only when signaled to do so via function calls. (i.e. pawn.move(startLocation, endLocation) or pawn.attack(enemyPawn))

The view(s) make up everything that is viewable by the player. This includes menus, visual representations of the pawns/models, and any user interface components like cursors and buttons. The view(s) query the model for data to draw visual representations of pawns. The view(s) also can dispatch user interface events to any observers interested in these events.

The controller(s) handle all transition and input logic. When an interesting user interface or input events occur, the controller decides what the model should do and signals the model to do it. The controller also handles swapping out of views when necessary.

I know there are many ways to implement MVC and I am open to suggestions if something seems off with this design, but the real problem I am having is how to handle animations in the view. Say the user commands a pawn to move 5 spaces North and 1 space West. I want an animation to show this over several seconds. How would I handle something like that?

# Answer
You need a class called Renderable. Each pawn (and other game entity) holds a reference to its own instance. Renderable is part of the View, so the Pawn is never allowed to read properties from it. It can only set its values, or call void methods.

Inside Renderable, there should be methods like these:

```
public void SetAnimationStateFlag(AnimModifier state)
{

}

public void ClearAnimationStateFlag(AnimModifier state)
{
}

```

When the pawn moves, it calls SetAnimationStateFlag on its renderable with a flag AnimModifer.Moving. The flags should be stored in a bit field member in the Renderable.

```
public enum AnimModifier
{

    Dying,
    Attacking,
    Moving
}

```

During Draw(), it is then up to the Renderable to select an animation that matches the flags that have been set on it.
> 0 votes

---
Tags: animation, turn-based, turn-based-strategy, mvc
---