# Question
Title: Algorithms for calculating vertex normals in 2D polygon
I have the points of a 2D polygon in the order in which they are connected, and I need to calculate the vertex normals and move them along it. An example is shown.

I would like to know how to calculate them efficiently and which structures I could use. I don't know if I have to find the orientation of the polygon, and what to do in general. As I said the only thing I have to start with is the list of points in the order in which they are connected. Say 5 vertices, I have a list that goes: x1, y1, x2, y2, x3, y3, x4, y4, x5, y5.

Where should I start?

It doesn't matter if the polygon becomes complex or self crossing, nothing matters just that to calculate the normals at the vertices and move them along these normals in the correct direction, all outwards or all inwards the polygon.

# Answer
If I understand the question correctly we have the following:

* Given a list of numbers (I'm going to presume we're working with doubles or decimals) we need to transform this into a sequence of 2D vectors which describe a path along the perimeter of a polygon either clockwise or anticlockwise (which we can know ahead of time)
* Next we calculate the vector between each pair of points, including the first and last. We're only interested in the direction of this vector rather than the size, so we may as well make these unit vectors by dividing them by their magnitude.
* So now we have two same-length sequences of vectors, one describing nodes, the other the direction along each edge. If we take these tangential vectors we can rotate them by a quarter-turn in order to get vectors in the normal direction to each edge (whether you go clockwise or anticlockwise depends on which way around the shape your points go), and the sum + normalise each pair, again including the first and last.
* What we have now is a sequence of unit vectors at a normal to each vertex, which we can add or subtract in order to grow or shrink our shape.

Looking at the operations we need to perform leads us towards a data-structure. I would propose that we will obviously want something to represent a 2d vector, and it makes sense for this to be immutable for reasons I'll describe later. I would be tempted to create another data structure for our shape, constructed with a doubly-linked-list of vectors, (doubly-linked for reasons which should become clear later) which exposes a same-length sequence of pairs of vectors to represent a point and its normal. These are standard enough data-structures that I'm not going to provide pseudo-code to implement them.

This constructor can then hold a dictionary/hashmap of vector pair to vector - this is constructed from our rotated unit tangential vectors keyed by the two vertices which form the described edge. Having vectors immutable allows for good behaviour using their references/pointers as keys allowing for efficient lookup later.

We can then for each point in our input create a pair of this point, and the sum of the dictionary entries keyed by this and its two neighbours (which is why doubly-linked), which is a vector along the normal, which we then divide by its magnitude to make this a unit vector too.

I have made some assumptions here, including that you're using an OO language, but similar patterns can be employed just as effectively in other paradigms. The other assumptions I made:

* The points given follow either clockwise or anticlockwise - if they are not in some order this is rather insoluble as you can't know what shape is being described,
* That you know whether it's clockwise or anticlockwise up front - if not this can be deduced by summing the angles to the left and right as you go round (not forgetting to join the first and last). If the angles to the right are greater, you are traveling anticlockwise, if it's left, clockwise.

## Code example of the above waffle:

```
"""
For the purposes of pseudo-code I'm using python for its clarity and I have
gone for a functional style for its brevity.

I'm assuming you have a `Vector2D` class which supports vector addition +
scalar division and has a property `normalised` which returns the result of
dividing the vector by its magnitude.

I'm also assuming you're using an implementation of a doubly linked list that
is something like https://dbader.org/blog/python-linked-list

`normal_of` will be some matrix multiplication of a vector, to perform the
quarter rotation, but which direction this is depends on the input.
"""

@dataclass
class VertexInfo:
    vertex: Vector2D
    normal: Vector2D

def unit_direction_between(from_vertex: Vector2D, to_vertex: Vector2D) -> Vector2D:
    return (to_vertex - from_vertex).normalised

def unit_average_vectors(vec1: Vector2D, vec2: Vector2D) -> Vector2D:
    return (vec1 + vec2).normalised

def iterate_pairs_from(vertices: DoublyLinkedList[Vector2D]) -> Iterator[Tuple[Vector2D, Vector2D]]:
    """ This covers the fact that we need to associate the first and last """
    node = first = vertices.head
    while node:
        following = node.next
        yield node.value, (following or first).value
        node = following

def shape_from_vertices(vertices: DoublyLinkedList[Vector2D]) -> Iterator[VertexInfo]:
    edges = {
        (node, following): normal_of(unit_direction_between(node, next))
        for (node, following) in iterate_pairs_from(vertices)
    }

    # A bit of a dance to get the last entry in the list, this would be unnecessary with
    # a standard python list (which is actually a dynamic array) or tuple as you can
    # simply index to collection[-1] - this could be implemented on your doubly
    # linked list if you track the last node on your list object.
    node = first = vertices.head
    while node:
        node, last = node.next, node

    # This is the actual business logic
    node = first
    while node:
        previous = (node.previous or last).value
        current = node.value
        following = (node.next or first).value

        edge_normal_behind = edges[previous, current]
        edge_normal_ahead = edges[current, following]
        vertex_normal = unit_average_vectors(edge_normal_behind, edge_normal_ahead)

        yield VertexInfo(current, vertex_normal)

        node = node.next

```

There are some parts of this which could be simplified - you don't really need a dictionary or a doubly-linked-list but they make the code a lot more obvious without any significant performance penalties, and relying on well-known data structures makes it easier to test your implementation.
> 2 votes

# Answer
First, obtain the normals for each edge of the polygon. The normal for an edge is given by the normalized cross product of the edge vector (`p2 - p1`) with the 2D plane normal (a unit vector pointing in the direction of the Z-axis). The cross product of a 2D vector with the positive Z-axis is given by `(-y, x)`. This will give you outward pointing normals for vertices in the counter-clockwise winding order, and inward pointing normals for a clockwise vertex winding order. Let the normals be stored in a list of `n` (number of vertices) elements, where the normal of the edge formed by vertices `i` and `(i + 1) % n` is stored at the index `i`.

For each vertex `i`, its neighboring edge normals have the indices `i` and `(i - 1) % n`. The simplest way to combine these edge normals into a vertex normal would be a normalized sum (`(normals[i] + normals[(i - 1) % n]).normalized`).

In pseudocode:

```
normals = [(0, 0)] * n

for i in 0..n {
    j = (i + 1) % n
    edge_vec = vertices[j] - vertices[i]
    normals[i] = (-edge_vec.y, edge_vec.x).normalized
}

vertex_normals = [(0, 0)] * n

for i in 0..n {
    j = (n + i - 1) % n
    vertex_normals[i] = (normals[i] + normals[j]).normalized
}

```

For the vertex normal calculation algorithm, more "intuitive" vertex normals may be calculated using a weighted edge normal sum instead, where each edge normal is weighted by the edge length (`normals[i] * edges[i].length + normals[j] * edges[j].length`). Since edge length is equal to the magnitude of the edge vector which is the same as the magnitude of the un-normalized edge normal from our cross product, we can skip normalization of the normals altogether, resulting in a (theoretically) faster algorithm.

```
weighted_normals = [(0, 0)] * n

for i in 0..n {
    j = (i + 1) % n
    edge_vec = vertices[j] - vertices[i]
    weighted_normals[i] = (-edge_vec.y, edge_vec.x) // == normals[i] * edge_vec.length
}

vertex_normals = [(0, 0)] * n

for i in 0..n {
    j = (n + i - 1) % n
    vertex_normals[i] = (weighted_normals[i] + weighted_normals[j]).normalized
}

```

Your animated example seems to be using a weighted sum too, as the vertex normal of the bottom-most concave angled vertex stays the same even though the edge normal to its left changes in direction while the edge normal to the right stays almost the same.
> 2 votes

# Answer
First compute the edge normals as follows. Treat each edge *e* as a vector from one endpoint to the other (subtracting one endpoint from another). Then rotate edge *e* 90 degrees by multiplying by the rotation matrix. $$ R = \left( \begin{array}{rr} \cos \theta & -\sin \theta \\ \sin \theta & \cos \theta \end{array} \right) = \left( \begin{array}{rr} 0 & 1 \\ -1 & 0 \end{array} \right) $$ Now normalize this edge normal to have unit length.

Then, as @DMGregory suggested, average two edge normals *a* and *b* by forming *a + b* and normalizing to unit length.
> 1 votes

# Answer
What you call the vertex normals are not normals. They are the bissectors of the normals of the two adjoining sides.

To find their direction, normalize the normals to unit length and take the vector sum. You can normalize once again. Make sure to take the normals on the same side of the edges.
> 1 votes

---
Tags: 2d, vertex, normals
---


title: Simple 3D OBB-Collision (DirectX9, C++)

text:
# Question
Title: Simple 3D OBB-Collision (DirectX9, C++)
I'm trying to implement a simple OBB vs. OBB collision detection! I **don't** need to know where the collision occures, I only want to know whether a collision occures.

The problem is, that after lot of research in the internet I only found comments like "It's very simple, just use SAT in 3D" or some complex math. No examples anywhere!

In the best case, the algorithm should use the max/min Vectors of the boxes.

I know, that similar questions where asked before, but (I think) none of them had examples.

Apologise my bad english, I'm German and still in school! Also a reason why I want simple mathes. I hope you can help me and maybe supply me with some code.

# Answer
> 2 votes
Unfortunately the correct answer *IS* to use a complex algorithm. The two common approaches are the Separating Axis Test (SAT) or Gilbert–Johnson–Keerthi Algorithm (GJK). I would favour SAT in this case. The OBB v. OBB test is arguably the most complicated of the basic primitive collision detectors as it is a specialization of general n-face convex hull detector. Trying to cut and paste the answer onto stack exchange would be too much code. So the previous answer OBB vs OBB Collision Detection has good information and explanations.

As for working implementations, there are two that I know of:

1. The canonical implementation in the ODE library http://www.ode.org/ in their box collider you could try adapting to your needs. It is somewhat difficult to follow but it is one of the first implementations I ever saw.
2. Randy Gaul has a physics simulator sample that is ONLY oriented bounding boxes here https://github.com/RandyGaul/qu3e it looks modern and complete so it could be a good source.

I am sure there are others, but maybe those would work for you.

# Answer
> 2 votes
A C++ code implementation of the separating axis theorem for simple collision detection between two 3D OBB would be this:

```
#include <iostream>

// define the operations to be used in our 3D vertices
struct vec3
{
    float x, y, z;
    vec3 operator- (const vec3 & rhs) const { return{ x - rhs.x, y - rhs.y, z - rhs.z }; }
    float operator* (const vec3 & rhs) const { return{ x * rhs.x + y * rhs.y + z * rhs.z }; } // DOT PRODUCT
    vec3 operator^ (const vec3 & rhs) const { return{ y * rhs.z - z * rhs.y, z * rhs.x - x * rhs.z, x * rhs.y - y * rhs.x }; } // CROSS PRODUCT
    vec3 operator* (const float& rhs)const { return vec3{ x * rhs, y * rhs, z * rhs }; }
};

// set the relevant elements of our oriented bounding box
struct OBB
{
    vec3 Pos, AxisX, AxisY, AxisZ, Half_size;
};

// check if there's a separating plane in between the selected axes
bool getSeparatingPlane(const vec3& RPos, const vec3& Plane, const OBB& box1, const OBB&box2)
{
    return (fabs(RPos*Plane) >
        (fabs((box1.AxisX*box1.Half_size.x)*Plane) +
        fabs((box1.AxisY*box1.Half_size.y)*Plane) +
        fabs((box1.AxisZ*box1.Half_size.z)*Plane) +
        fabs((box2.AxisX*box2.Half_size.x)*Plane) +
        fabs((box2.AxisY*box2.Half_size.y)*Plane) +
        fabs((box2.AxisZ*box2.Half_size.z)*Plane)));
}

// test for separating planes in all 15 axes
bool getCollision(const OBB& box1, const OBB&box2)
{
    static vec3 RPos;
    RPos = box2.Pos - box1.Pos;

    return !(getSeparatingPlane(RPos, box1.AxisX, box1, box2) ||
        getSeparatingPlane(RPos, box1.AxisY, box1, box2) ||
        getSeparatingPlane(RPos, box1.AxisZ, box1, box2) ||
        getSeparatingPlane(RPos, box2.AxisX, box1, box2) ||
        getSeparatingPlane(RPos, box2.AxisY, box1, box2) ||
        getSeparatingPlane(RPos, box2.AxisZ, box1, box2) ||
        getSeparatingPlane(RPos, box1.AxisX^box2.AxisX, box1, box2) ||
        getSeparatingPlane(RPos, box1.AxisX^box2.AxisY, box1, box2) ||
        getSeparatingPlane(RPos, box1.AxisX^box2.AxisZ, box1, box2) ||
        getSeparatingPlane(RPos, box1.AxisY^box2.AxisX, box1, box2) ||
        getSeparatingPlane(RPos, box1.AxisY^box2.AxisY, box1, box2) ||
        getSeparatingPlane(RPos, box1.AxisY^box2.AxisZ, box1, box2) ||
        getSeparatingPlane(RPos, box1.AxisZ^box2.AxisX, box1, box2) ||
        getSeparatingPlane(RPos, box1.AxisZ^box2.AxisY, box1, box2) ||
        getSeparatingPlane(RPos, box1.AxisZ^box2.AxisZ, box1, box2));
}

// a quick test to see the code working
int _tmain(int argc, _TCHAR* argv[])
{
    // create two obbs
    OBB A, B;

    // set the first obb's properties
    A.Pos = { 0.f, 0.f, 0.f }; // set its center position

    // set the half size
    A.Half_size.x = 10.f;
    A.Half_size.y = 1.f;
    A.Half_size.z = 1.f;

    // set the axes orientation
    A.AxisX = { 1.f, 0.f, 0.f };
    A.AxisY = { 0.f, 1.f, 0.f };
    A.AxisZ = { 0.f, 0.f, 1.f };

    // set the second obb's properties
    B.Pos = { 20.f, 0.f, 0.f }; // set its center position

    // set the half size
    B.Half_size.x = 10.f;
    B.Half_size.y = 1.f;
    B.Half_size.z = 1.f;

    // set the axes orientation
    B.AxisX = { 1.f, 0.f, 0.f };
    B.AxisY = { 0.f, 1.f, 0.f };
    B.AxisZ = { 0.f, 0.f, 1.f };

    // run the code and get the result as a message
    if (getCollision(A, B)) std::cout << "Collision!!!" << std::endl;
    else std::cout << "No collision." << std::endl;

    // pause and quit
    std::cout << std::endl;
    system("pause");
    return 0;
}

```

---
Tags: c++, collision-detection, directx9
---


# Question
Title: How to sleep for the desired duration between game loop iterations?
My game loop below doesn't sleep as log as it should. The `delta` value always ends up less than 1, when it's supposed to be 16.6666 or close to 16.6666

```
double targetTime = 1000.0 / 60.0;//1000 millisecunts / 60 fps
long startTime;
long endTime = System.currentTimeMillis();
long delta;

long timer = System.currentTimeMillis();
int frameCount = 0;
while(running){
    startTime = System.currentTimeMillis();
    delta = startTime - endTime;
    endTime = startTime;

    tick(delta);
    render();
    frameCount +=1;
    try{Thread.sleep(targetTime - delta);}catch(InterruptedException e){}

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

```

# Answer
> 2 votes
There's several layers of issues in the code above.

1) The pattern you're using to just sleep the remainder of the frame has an issue: each sleep is not simply the remaining delta: you've already called "render" in the current loop, taking X milliseconds, and then you "sleep to the beignning of the next frame", which takes (16 - X) milliseconds, and then you render and "sleep to the beginning of the 3rd frame", which takes (16 - (16 - X)) milliseconds, etc. This means you are effectively rendering **twice** per frame. This also means that for a fast render, **X alternates between \<1 milliseconds and about 16 milliseconds**.

2) To fix the time delta accounting bouncing around, you can make a small adjustment and avoid calculating the sleep relative to the previous frame's time: instead of `sleep(targetTime - delta)`, which is a measure of "how close the current frame follows the previous frame", you could use `sleep(startTime + targetTime - System.currentTimeMillis())` which is a measure of "how long until the desired next frame from the current frame."

3) There's still a few issues with running your game logic (`tick`) at a variable frame rate based on the rendering speed, including drift over time due to the imprecision of Thread.sleep, and unstable behavior due to variable time steps, things can feel "higher friction" or glitch through/blow up when frame rate is too high or too low. You'll probably want to switch to a fixed-timestep loop (there are many resources on the internet, one popular one is at https://gafferongames.com/post/fix\_your\_timestep/) to get more stable simulation behavior.

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


title: VBO interleaving dillema

text:
# Question
Title: VBO interleaving dillema
I'm trying to write a map editor for a unity game using openGL. In order to do that, I need to unpack it's resource files to get meshes, textures and other good stuff.

In doing so, I've discovered that unity mesh asset stores vertices, normals, texture data, and any other per-vertex type data in one interleaved array.

I have two choices here. First is to leave the data as is and push it into a single VBO and then use attrib pointer to adjust strides and whatnots to make it work. When I read data from file into memory, I can just read whole array with a single `ifstream::read` method call.

Second choice is to unravel all data into it's separate channels and have a separate VBO for each data type. I personally prefer it this way, but this means that I need to deinterleave that array. I'm unsure how to do this efficiently. The most obvious way (and very inefficient) is to read it char by char and store each char in appropriate array, depending on channel structure. I could maybe mess with it a bit and set it up to read it channel per channel (meaning 2-4 chars at once) instead of char by char. This still seems very slow to me.

Maybe I could load the whole array into memory and then deinterleave it there, but I'm still unsure of method that would be fast.

The priority is for the program to be fast while drawing, and deinterleaved multiple VBO setup is said to be faster due to lesser amount of cache misses.

To give you a sense of numbers, the game I'm looking at contains about 2630 different mesh assets, with each containing an estimated average of 500 vertices.

How do I deal with this? I will be loading all this data just once on program startup anyway, so it doesn't have to be super fast, but I don't want to force the user to wait for too long even then. Maybe number of vertices altogether is small enough for it to be very fast regardless, but I don't want to commit to either way before I have some idea of what I'm doing.

Bottom line is, should I just leave it interleaved, or is there some efficient way to deinterleave it? Am I jumping the train here, being scared of leaving it interlaved? I know I should probably benchmark both cases, but both cases are drastically different in my case and would require huge code changes, not to mention I'm nowhere close to actually drawing the scene I need to.

# Answer
> 3 votes
> not to mention I'm nowhere close to actually drawing the scene I need to -

So then do you really want to spend extra time on data transformations, when you could be working on getting the scene drawing?

Make it work first. Then you'll know if performance is impacted heavily enough to be worth budgeting time to change the VBO format. Otherwise you might be sinking extra time into data transformation code for no tangible benefit at all.

You already have one data point suggesting the format is OK as-is: your Unity app appears to use it this way with acceptable performance.

---
Tags: unity, opengl, c++, vbo
---


# Question
Title: Why are clicks not corresponding correctly to XY positions?
I'm trying to make custom buttons in LibGDX (I really only wanted to use it for the Android/Desktop portability, not for any of its features, like Scene2D)

The issue I'm having is that the clickable area and the texture don't have a 100% overlap. I can click some places in the texture that don't respond to my isClicked method, and there are places outside the texture that do. I just don't understand what's happening.

Here's my button class.

```
public class btn
{
private Texture btnTexture;

private int x;
private int y;

private int width;
private int height;

public btn(String btnTexturePathSet, int xSet , int ySet)
{
    btnTexture = new Texture(btnTexturePathSet);
    x = xSet;
    y = ySet;
    width = btnTexture.getWidth();
    height = btnTexture.getHeight();

}

public void render(SpriteBatch sb)
{
    sb.begin();
    sb.draw(btnTexture, x, y);
    sb.end();
}

public boolean isClicked()
{
    if (Gdx.input.justTouched())
    {
        if (Gdx.input.getY() >= y && Gdx.input.getY() <= y + height && Gdx.input.getX() >= x && Gdx.input.getX() <= x + width)
        {
            return true;
        }

    }
    return false;
}
}

```

# Answer
> 2 votes
I solved it. First, make sure your orthographic camera is set to false for yDown

then, make sure to use camera.unproject() after gathering the input x,y's, but before applying them;

```
        mouse.set(Gdx.input.getX(), Gdx.input.getY(), 0);
        cam.unproject(mouse);

        if (mouse.y <= y + height  && mouse.y >= y && mouse.x >= x && mouse.x <= x + width)
        {
            return true;
        }

```

---
Tags: java, libgdx
---


# Question
Title: How to remove gameobjects that have the same transform position as each other?
If I have 4 copies of the same gameobject in my scene and they all have the exact same transform position as each other, how can I remove the 3 duplicates so that only one unique gameobject remains? This is what I tried so far...

```
private void Update()
{
    if (Input.GetKeyDown(KeyCode.Space))
    {
        RemoveDuplicate(GameObject.FindGameObjectsWithTag("Path"));
    }
}

private void RemoveDuplicate(GameObject[] other)
{
    for (int i = 0; i < GameObject.FindGameObjectsWithTag("Path").Length; i++)
    {
        if (GameObject.FindGameObjectsWithTag("Path")[i] == other[i]) continue;
        if (GameObject.FindGameObjectsWithTag("Path")[i].transform.position == other[i].transform.position)
        {
            Destroy(other[i]);
        }
    }
}

```

But it doesn't work at all. Any ideas?

# Answer
Assuming `GameObject[] other` is the object you want to check against I would do something like this

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

public class RemoveDupes : MonoBehaviour
{

    void Update ()
    {

        //I don't know where you get the object you want to test against from
        //so I have done it in the quickest simplest way possible
        if (Input.GetKeyDown(KeyCode.Space))
        {
            //find the first object with the tag "Path" I'm using this as the position to compare against note 'FindGameObject' not Objects
            GameObject objectToTest = GameObject.FindGameObjectWithTag("Path");
            RemoveDuplicates(objectToTest);
        }
    }

    private void RemoveDuplicates(GameObject objectToTest)
    {
        //cache the array instead of calling it each time
        GameObject[] gameObjects = GameObject.FindGameObjectsWithTag("Path");

        //loop over each object in the array
        foreach (var obj in gameObjects)
        {
            //if the current objects position is the same as the object we are testing against
            if (obj.transform.position == objectToTest.transform.position)
            {
                //we should also make sure that the function doesn't compare the object against itself or you would have no cubes left
                if (obj != objectToTest)
                {
                    Destroy(obj);
                }
            }
        }

      }
}

```
> 1 votes

---
Tags: unity
---


# Question
Title: How can I insert random numbers in specific place in text of UI Text?
I have a Canvas with Text and a Panel. I want that it will show random numbers between 3 and 10 between the almost and hours:

> Hello my friend, It's about time to wakeup. You were sleeping for almost...hours. My name is NAVI and i'm your navigation helper in the game.

Sometimes when running the game I was sleeping for almost 5 hours and sometimes when running the game I was sleeping for almost 3 hours.

For example:

> Hello my friend, It's about time to wakeup. You were sleeping for almost 5 hours. My name is NAVI and i'm your navigation helper in the game.

Instead the 3 dots to add a random number.

# Answer
Along with what else is stated in other answers, you may want to write out the number (eg. “three hours”) which you can do with a simple array of options:

```
private static readonly string[] _numberNames = new string[]{"two","three","four","five","six"};

void Start() {
  string numberName = _numberNames[Random.Range(0, _numberNames.Length)];
  textbox.text = string.Format("Hello my friend, It's about time to wakeup. You were sleeping for almost {0} hours. My name is NAVI and i'm your navigation helper in the game.", numberName);
}

```
> 2 votes

# Answer
Simply use string interpolation in your code.

See here: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated

Or simply do something like

`"Sometimes when running the game I was sleeping for almost 5 hours and sometimes when running the game I was sleeping for almost" + myVar + "hours."`

Then simply set the string to your text component.

To get a random number:

`int myVar = Random.Range(0, 24);`
> 1 votes

# Answer
You can create a script that can access the Text component and alter it's text based on input, attach the below script the the same GameObject that contains the Text UI Component

```
using UnityEngine;
using UnityEngine.UI;

public class CustomText : MonoBehaviour
{
    //I'm using a vector2Int to store the hour range but you could use two seperate Ints if you like.
    public Vector2Int hourRange;

    private int randomHours;
    private Text textField;

    // Use this for initialization
    void Start ()
    {
        //get a reference to the Text Component, for example this script is on the same object
        //as the Text component
        textField = GetComponent<Text>();

        //set the hours to pick between
        SetHourRange(hourRange.x, hourRange.y);

        //access the Text Components text property and concatenate the randomly chosen hour value to the sentence.
        SetText("Hello my friend, It's about time to wakeup. You were sleeping for almost " + randomHours + " hours. My name is NAVI and i'm your navigation helper in the game");

    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            SetHourRange(hourRange.x, hourRange.y);
            SetText("Hello my friend, It's about time to wakeup. You were sleeping for almost " + randomHours + " hours. My name is NAVI and i'm your navigation helper in the game");
        }
    }

    //You can use this function in other scripts to set the hour range
    public void SetHourRange(int minHours, int maxHours)
    {
        randomHours = Random.Range(minHours, maxHours);
    }

    //You can use this function in other scripts to set the text field
    public void SetText(string _text)
    {
        if (textField)
        {
            textField.text = _text;
        }
    }
}

```

You could also control this script from elsewhere by getting a reference to it and calling the set hours and/or set Text functions or combine them into one.
> 1 votes

---
Tags: unity
---


# Question
Title: Camera with zoom that follows the player in javascript
I'm passing the time programming a little game in javascript, I've done what I'm trying this in several in game engine. And what I'm trying to do is generate the world while the player walks around the map. Using engines like unity and godot, I have always had the facilities to deal with the camera and the scene. Now with pure javascript I'm kind of not knowing where to go.

Come on, what I have so far:

A world generated by 2D noise and my character in it can move with the keys of the keyboard. What I want to do now is that when walking he generate the world and also the camera accompany him. And that with the scroll of the mouse I can take the camera to a bigger zoom so that I can better visualize the generated world.

So there are 3 questions I have:

1 - How to create a camera that will follow the player, already thinking about the best way to make the world be generated when walking the player.

2 - How to generate the world while he walks (This I believe I can do.)

3 - How to zoom in with the mouse scroll?

# Answer
> 2 votes
Making the camera follow the player is relatively simple. If you're using canvas, then simply use the rendering context's translate function to translate the current origin to the player's position, then use the scale function to create the zoom effect and lastly translate the camera in the other direction by half of the canvas size to center the player. It's important to not mix these up, because that would make the scaling origin messed up.

In code this would look something like this

```
ctx.resetTransform(); // You need to make sure to include this
// Keep in mind though, resetTransform doesn't exist in some browsers, you may want to use setTransform instead
ctx.translate(playerPositionX, playerPositionY);
ctx.scale(currentZoom);
ctx.translate(-canvas.width / 2, -canvas.height / 2);

```

To learn how to modify the zoom using the scroll wheel, read this, but basically, listen to the wheel event and use the deltaY value it gives you.

If you aren't using canvas (e. g. divs, svg-s), then this is much harder. Make sure everything has a position. when the player moves, move everything the same amount in the other direction. When the user zooms in, get the distance vector pointing from the player to the div, multiply it by the amount the scene zooms in (e.g. a value of 2 makes everything twice as big) and add it to the player's position to get the new position of the object. Also make sure the change the size of the divs too.

---
Tags: 2d, javascript, camera
---


# Question
Title: Reducing texture bindings in LibGDX when drawing text
I'm making custom menus and buttons (I don't want to use scene2D) and I have everything in atlases, but when I draw a button, if it has text, the texture binding is always x2 because of the switching back and forth between the texture in the atlas and the bitmapfont.

(example of drawing order)

```
public void draw(SpriteBatch b){
   if(texture != null)
      texture.draw(b);

   if(text != null && !text.isEmpty())
      font.draw(b, "TEXT", x, y);
}

```

So as you see, if I have 3 buttons, each button will increase the texture binding x2. When using several buttons, texture draw/bind is maybe around the number 24. This hasn't cause noticeable performance issues yet (FPS stay at 60~61) but I want to know how I can reduce the number of bindings when drawing textures and fonts at the same time.

# Answer
> 4 votes
Make *two batches*, one for the buttons (texture) and one for the labels (bitmap font).

That is also why you normally batch draw-calls. Group the things using the same resources to reduce draw calls and expensive unbinding/binding of textures and shader-programs.

---
Tags: libgdx, rendering, ui-design, batching
---


# Question
Title: Unity - UI - Raw Image with Texture becomes Smaller after Build
I am a beginner in the game development world, I have just one quick problem with the UI, as you can see during the Unity Player, the UI (Raw Image w/ Texture) is normal in size but when I build my game to APK or EXE and run it, the UI is small. Why is this happening and how to fix it?

# Answer
> 2 votes
From the information you provide it is most likely to assume that the elements that are getting wildly resized are all UI-Elements.

When placing UI-Elements, by default, Unity puts them into pixel-fixed positions rather than relative-positions. To fix that set the `Ui Scale Mode` on the `Canvas` holding all your UI-Elements to `Scale With Screen Size`, as detailed in this answer on Unity Answers.

Screenshot from the linked Unity Answer in case it will ever go down.

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


# Question
Title: How to store 3d transformation in a game?
I am curious what is the best strategy to save 3d transformation of a model.

Here are the few choices I think about:

* 4x4 matrix
* 4x3 matrix(skip the bottom row of a 4\*4 matrix)
* Dual quaternions with a 3d scaling vector
* 3x3 matrix with a 3d translation vector

# Answer
> 0 votes
There are two considerations here:

1. What format do you need to export to your GPU for rendering (or to your physics engine for simulating)?

This will usually be a matrix. You can decide whether it's worth keeping the last row/column separate or implicit, or if it's more convenient to store a full 4x4 explicitly.
2. What format do you need for manipulating your objects each frame?

Here, it's important to ensure you can handle many iterated transformation changes without distorting your values.

If scale and rotation are both baked into a matrix, then you can't easily distinguish between deliberate scale changes and rounding errors accumulated through repeated rotations.

So at minimum you'll want to separate your rotation and scale source values, so you can work with them independently (eg. as a quaternion and a vector, or a matrix and a vector) and combine them to the exported format (1) on demand without degradation.

Translation could be combined into the rotation matrix without ambiguity, though you might find it simplest to keep all three parts independent and combine them only for the final result.

---
Tags: mathematics, models, transformation, gameobject
---


# Question
Title: I am struggling with a combo system for a game of mine
I am currently trying to make a game with a friend but at the moment I am having a few problems with finding a combo system. Until we progressed I copied this code from a video where I use our first combo hit as a source of damage. My code for this is below:

```
public Animator anim;
private bool attack1 = false;
private float attackTimer = 0;
private float attackCd = 0.3f;
public Collider2D attackTrigger;
public KeyCode Stance1;
public KeyCode Attack1;

// Use this for initialization
void Awake ()
{
    anim = gameObject.GetComponent<Animator>();
    attackTrigger.enabled = false;
}

public void CreateHitbox (int createhitbox)
{
    attackTrigger.enabled = true;
}

public void DestroyHitbox (int destroyhitbox)
{
    attackTrigger.enabled = false;
}

// Update is called once per frame
public void Update ()
{
    if (Input.GetKeyDown(Stance1))
        anim.SetTrigger("Stance");

    if (Input.GetKeyUp(Stance1))
        anim.SetTrigger("Stance");

    if (Input.GetKey(Stance1))
    {
        //Melee attack
        if (Input.GetKeyDown(Attack1) && !attack1)
        {
            attack1 = true;
            attackTimer = attackCd;
        }

        if (attack1)
        {
            if (attackTimer > 0)
                attackTimer -= Time.deltaTime;
            else
                attack1 = false;
        }

        anim.SetBool("attack1", attack1);
    }
}

```

Our attack animations take a bit to initiate so we work with a hitbox as an attack trigger and activate the trigger through an animation event so that enemies are hit when they are supposed to. Furthermore in our game you have to go in a stance where you draw your sword to attack so I wrote it so that you can only attack when you are in the stance.

The problem is that I want to have a 3 hit combo in the end but I have a problem finding a solution that works. In addition I would like the different combo attacks to deal different damage so giving each attack different values would be great. My friend and I are beginners when it comes to C# as well so thinking of something ourselves was not possible.

# Answer
you can solve a few different ways depending on how you setup the combos. a simple solution may be to be able to combo within the attack itself.

```
if (attack1)
    {
        if (attackTimer > 0)
        {

            attackTimer -= Time.deltaTime;
            if(Input.GetKeyDown(Attack1)&& attackTimer >0)
            {
               TransitionToAttack1Combo();
            }
        }
        else
        {
            attack1 = false;

        }
    }
void TransitionToAttack1Combo()
{
    //DoComboStuff
}

```

another solution could be to setup a Sequence array and issue a timespan to be able to initiate the combo.
> 2 votes

# Answer
I think you should allow input while the attack is happening as this feels natural. I think you may build a set of N N-nary trees for how you represent your combo; where 'N' is the number of 'Attack buttons' that you can use to combo; which happens to be the same "branching factor" each node in the N-nary tree would have at maximum.

This would allow you to build your attack trees from a file or an initialization step; rather than dozens of functions.

Each tree would have at its root the first button in an attack, then if another button is pressed; you check to see if that child exists on this node.

Some incomplete code below can give you an idea of what I mean:

```
class AttackNode
{
    enum ATTACK_TYPES
    {
        X,
        Y,
        B,
        A
    };

    int AttackDuration;
    // other attributes like animation frames, etc.

    var children = new AttackNode[ATTACK_TYPES];

}

class AttackManager
{
    var baseAttacks = new AttackNode[ATTACK_TYPES];
    AttackNode currentAttack;
    AttackNode nextAttack;

    AttackButtonPress(int button)
    {
        if(currentAttack != null && currentAttack.AttackTimer < currentAttack.AttackDuration)
        {
            if(currentAttack.children[button] != null)
            {
               NextAttack = currentAttack.children[button];
            }
        }
        else
        {
            currentAttack = baseAttacks[button];
        }
    }
}

```

This means that your combos aren't directly stored, but rather implicit in the datastructure you build for your attacks. Rather than *ever* searching for moves or writing more than one piece of code to do this, you can instead simply build your N-nary tree to solve it for you.

What's more, this is extendable to any depth of combo; so if you desire to add another move, it's as simple as defining it in your JSON (or whatever file type you use) file and having your program read it in.

*Note: The above is obviously incomplete code and requires initialization and various Properties/methods you need.*
> 2 votes

---
Tags: unity, c#, game-mechanics, combat
---


title: Why is clip-space 3 dimensional?

text:
# Question
Title: Why is clip-space 3 dimensional?
A vertex shader is basically a transformation function that converts a vertex in your world space to a space that can be rendered on screen.

Since the screen is a 2 dimensional surface whats the purpose of the intermediate clip space? Why not have the vertex shader directly transform a 3d vertex to a 2d point on the raster surface?

# Answer
There are a few reasons it's valuable to retain a third dimension of information.

1. Depth Buffering

To get near content to show up in front of far content, we need to retain some information about what pixels are "near" or "far." Without this information, we'd only be able to layer objects in the order that we draw them, reducing our ability to batch content and breaking the illusion of 3D content in cases that can't be solved by sorting (like two interpenetrating triangles).
2. Z Clipping

Our depth buffer only has so much precision, and a perspective projection has a singularity at the camera's location, so to keep the projection and sorting well-behaved we need to clamp the depth range of geometry we draw, and exclude content too close to the camera or too far away. This is done in clip space.
> 5 votes

---
Tags: shaders, glsl
---


# Question
Title: Execute script in edit mode when scripts finish compiling, without an object in the scene
I need to inspect some method information before game starts to implement something in Unity.

I can run the script by \[ExecuteInEditMode\] attribute, however it only works if at least one object in the scene has the script as component.

What I want is to run the script in edit mode as soon as Unity finishes each recompilation, without a scene object, so other developers can use my library/framework without creating objects manually.

How do I run the script in edit mode after the scripts recompile, without creating an object in the current scene?

# Answer
> 1 votes
I solved this by using "InitializeOnLoad" attribute. Using this attribute without MonoBehaviour, you can run the code what you want.

# Answer
> 0 votes
Try removing the "monobehaviour" attribute from your script. This will seperate the script from any visual objects.

---
Tags: unity, editors
---


# Question
Title: Indexing a point outside of a 3D signed distance field
I have a 3D signed distance field that is voxelized into a grid, surrounding an object. However, I would like to query the signed distance field to determine the shortest possible distance between points outside of the signed distance field grid, and the mesh itself. Is there any way to determine this distance without increasing the size of the signed distance field? Thank you!

# Answer
You can form an upper bound by finding the closest sample in your grid to your query point, and summing the distance in that grid cell plus the distance of that grid cell from your query point.

By the triangle inequality, this will be greater than or equal to the actual shortest distance to the level set (since there might be an elbow in the resulting path, between the first and second leg of the trip).

If you can afford some extra storage, you can store in each cell not just the shortest distance to the level set, but also the closest point on the level set. Then you can improve your earlier bent-line distance to a straight-line distance, by computing the distance from the query point to the stored closest point.

This can still overestimate the distance (the closest point to the closest grid cell might not be the closest point to your query, though it usually won't be far off)
> 1 votes

---
Tags: signed-distance-field
---


# Question
Title: Do textures that are inside a shader resource need to be explicitly released too? (DirectX 11)
I have a ID3D11Texture2D (that I've created manually) inside a ID3D11ShaderResourceView. When I want to `Release()` the resource view, do I need to `Release()` the texture that it is inside too? Or is it not necessary to do so?

Msdn doc and Google couldn't help me on this one. :/

# Answer
> 4 votes
Yes. Any reference you have to a D3D object needs a `Release()` call when you're done with it. It doesn't matter whether another object might also have a reference to it. The object will not be deleted until all references to it are gone, so it's safe to `Release()` the texture as soon as you don't need the pointer to it anymore. If it's also referenced by an SRV, that reference will keep it alive until the SRV is also deleted.

# Answer
> 1 votes
I would add to the prior answer a discussion about bound Shader Resource Views and a distinction between D3D10 and D3D11. Microsoft changed the behavior when binding resources such that the D3D11 runtime holds a reference to the resource until you bind something else to whatever slot it is on.

D3D10 *did not* do this and various swapchain operations that require you to release all resources will fail if you do not clear all SRV bindings first in D3D11 (but not D3D10). You may have implicit references floating around even if you have released every resource you ever created.

---
Tags: c++, directx11
---


# Question
Title: unity UI limitation for tutorial purpose
i want to add a tutorial part to my game that i make by unity.i have some panels that for tutorial purpose i want to limit user to just click a button.most of games make a dark panel over all places except learning UI.

i know there is lots of ways for making that but is there any standard way for that?

# Answer
> 1 votes
You can achieve this with Maskable UI. See Unity documents for Sprite Masking here or this tutorial here.

Also, you can use this paid Unity Asset.

---
Tags: unity, gui, ui-design, ngui
---


# Question
Title: Time based events separate from the game loop
How can set up time elapsed based events separate from the game loop?

I want the character to heal over real time rather than per cycle of the game loop. How might i do that?

# Answer
> 3 votes
This is a very wide question, and difficult to answer specifically, so I will be general instead:

Any "over time" effects will still be based on your game loop, but have their own "tick" of time they are bound to. Diablo 3 does this for damage and healing over time effects. The tool tips list the amounts as "per second" but it is actually applied "per tick", which is more than a frame (max 16ms), but less than a second.

An example could be:

```
//Base effect class
class OverTimeEffect
{
public:
    virtual void apply(Character& c, float dt)=0;
    void setTickSize(float tick);
    void setDuration(float seconds);
    float getRemaining();
protected:
    float m_tick_s;
    float m_duration;
    float m_accum;
    float m_remaining;
};

class HealOverTime:
    public OverTimeEffect
{
public:
    virtual void apply(Character& c, float dt)
    {
        if(m_accum + dt >= m_tick_s)
        {
            c.addHealth(1);
            m_accum = 0.0f;
            m_remaining-=dt;
        }
        else {
            m_accum += dt;
            m_remaining-=dt;
        }
    }
};

// This is your game character base class
class Character
{
public:
    void addHealth(int hp);
    void addOTE(OverTimeEffect& ote)
    {
        m_ote.push_back(ote);
        //then min sort by remaining time in effect
        //so shortest duration is always at the front of the queue
    }
    void update(float dt)
    {
         for (auto& effect: m_ote)
         {
             effect.apply(*this,dt);
             if(effect.getRemaining() <= 0.0f)
             {
                 m_ote.pop_front();
             }
         }

    }
private:
    deque<OverTimeEffect> m_ote;
    float m_hp;
};

```

This is but one of the many, many ways you could implement such effects. I recommend further reading up on game engine architecture books and articles, as this is a very common feature of games, and so there is likely to be a solution that will suit your game.

# Answer
> 3 votes
Time elapsed events are not separate from the game loop but are controlled from the game loop.

The easiest way to achieve the effect is to have a floating-point value that represents the number of seconds the event should be active.

From the game loop you call an update function that takes the number of seconds since the last frame: `Update(float deltaSeconds);` and in that you increment an internal value based on that elapsed time. If it's greater or equal to your pre-determined length of time you stop:

Example Pseudo-code:

```
class Player {
    //Other stuff...
    public:
    void Update(float deltaSeconds);
    void DoHealOverTime(float deltaSeconds);

    float maxTimeToHeal = 5.0f;
    float currentTimeToHeal = 0.0f;
    float health = 0.0f;
    float healthPerSecond = 1.0f;
    float maxHealth = 100.0f;
    bool isHealing = false;
};

void Player::Update(float deltaSeconds) {
    DoHealOverTime(deltaSeconds);
}
void Player::DoHealOverTime(float deltaSeconds) {
    if(!isHealing || maxHealth < health) {
        return;
    }
    timeToHeal += deltaSeconds;
    health += healthPerSecond * deltaSeconds;
    if(maxTimeToHeal < timeToHeal) {
        isHealing = false;
        timeToHeal = 0.0f;
    }
    //std::clamp is a better use here, but need c++17 compiler.
    //Parenthesis around function names are intentional to avoid name-collisions with preexisting macros.
    health = (std::max)(0.0f, (std::min)(health, maxHealth));
}

```

---
Tags: c++, game-loop, rpg, timer
---


title: Ienumerator is not working as expected

text:
# Question
Title: Ienumerator is not working as expected
So I'm trying to get my miner drone to mine from the resource by using an Ienumerator but the miner either leaves with more than the capacity or it leaves and it has taken more than the amount of resources available.

So in short, the miner is to head to the resource, when its within the trigger, it needs to take the minerAmount over the miningSpeed amount of time.

Please help.

```
private void OnTriggerStay(Collider other)
{
    MinableResource mr;
    if (other.CompareTag("Resource"))
    {
        Debug.Log("Within Range of Resource");
        mr = other.GetComponent<MinableResource>();

        if (minerCurrentCapacity < minerMaxCapacity)
        {
            StartCoroutine(MineResource(other));
        }
        else if (minerCurrentCapacity >= minerMaxCapacity)
        {
            minerFull = true;
            Move(storagePos);
        }
    }
}

IEnumerator MineResource(Collider _other)
{
    if (minerFull)
        yield break;

    yield return new WaitForSeconds(miningSpeed);
    Mining(_other);
}

private void Mining(Collider _other)
{
    Debug.Log("Mining");

    MinableResource mr;
    mr = _other.GetComponent<MinableResource>();

    minerCurrentCapacity += miningAmount;
    mr.resources -= miningAmount;

}

```

# Answer
This is the kind of problem we can debug by stepping through the code to see what it does at each moment. Let's look at the first frame your object stays inside range of a mineble resource:

**Frame 1**

`OnTriggerStay`: `minerCurrentCapacity < minerMaxCapacity`, so we start a new `MineResource` coroutine. (#1)

`MineResource` (#1): `minerFull` is false, so we wait for the defined `miningSpeed` delay. For simplicity let's say that's 3 frames.

**Frame 2**

`OnTriggerStay`: `minerCurrentCapacity < minerMaxCapacity`, so we start *another* `MineResource` coroutine (#2).

`MineResource` (#1): still waiting.

`MineResource` (#2): `minerFull` is false, so we wait for the defined `miningSpeed` delay.

**Frame 3**

`OnTriggerStay`: `minerCurrentCapacity < minerMaxCapacity`, so we start *another* `MineResource` coroutine (#3).

`MineResource` (#1): still waiting.

`MineResource` (#2): still waiting.

`MineResource` (#3): `minerFull` is false, so we wait for the defined `miningSpeed` delay.

**Frame 4**

`OnTriggerStay`: `minerCurrentCapacity < minerMaxCapacity`, so we start *another* `MineResource` coroutine (#4).

`MineResource` (#1): finishes waiting, and calls `Mining` to harvest resources from `other`. To speed up this example, let's say that's the last of the resources we need to hit our max capacity, and to empty the resources available at this site.

`MineResource` (#2): still waiting.

`MineResource` (#3): still waiting.

`MineResource` (#4): `minerFull` is false (even though we're full now - it's only set in `OnTriggerStay` which runs earlier in the frame, so we won't know we're full until next frame!), so we wait for the defined `miningSpeed` delay.

**Frame 5**

`OnTriggerStay`: `minerCurrentCapacity >= minerMaxCapacity`, so we set `minerFull = true` and start moving back to the storage hopper.

`MineResource` (#2): finishes waiting, and calls `Mining` to harvest resources from `other`. Even though the miner is full and the resource source is empty, there's no logic here to check for that, so we harvest resources that aren't there and put them in capacity we don't have.

`MineResource` (#3): still waiting.

`MineResource` (#4): still waiting.

**Frame 6**

`MineResource` (#3): finishes waiting, and calls `Mining` to harvest even more excess resources from `other`.

`MineResource` (#4): still waiting.

**Frame 7**

`MineResource` (#4): finishes waiting, and calls `Mining` to harvest even more excess resources from `other`.

---

So, there are a whole pile of problems here: `OnTriggerStay` runs every physics step that we remain in range. We start a new coroutine every time, without cancelling or waiting on the previous one. We check if we're full only when we start waiting, not when we actually do the mining. We never check whether the resource patch is empty.

I'd recommend something a bit more like this:

```
// OnTriggerEnter fires just once, when a new trigger is touched, not every frame.
void OnTriggerEnter(Collider other) {

    // I like to use a state enum to keep track of what we're doing.
    if(state == MinerState.Mining || state == MinerState.Return)
        return; // Ignore new triggers if we're busy or returning with stuff.

    var resource = other.GetComponent<MinableResource>();

    // If there are resources there to grab, start mining.
    if(resource != null && resource.resources > 0) {
        StartCoroutine(MineResource(resource));
    }
}

IEnumerator MineResource(MinableResource resource) {
    // Mark that we're busy mining, so we don't try to start another coroutine.
    state = MinerState.Mining;

    // Rather than fire a new coroutine each frame, we'll just loop till we're done.
    while(resource.resources > 0 && resourcesHeld < capacity) {
        yield return new WaitForSeconds(miningDelay);

        // Never take more than what's there, or what we can hold.
        var increment = Mathf.Min(
            miningAmount,
            resource.resources,
            capacity - resourcesHeld
        );
        resourcesHeld += increment;
        resource.resources -= increment;
    }

    if(resourcesHeld == capacity)
        DropOff(); // Transition to our delivery state.
    else
        SearchForNearbyResources(); // Look for a new target.
}

```
> 1 votes

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


# Question
Title: Class for each specific item in an RPG, or use a factory?
I had a question regarding the best way to have items in my RPG game.

Currently I have a class structure in which everything inherits from GameObject. Item inherits GameObject. Armour Inherits Item. Helmet inherits Armour. Etc.

I am wondering whether I should have a class for each specific piece of armour, weapon, item, etc. in the game, or whether I should have generic "Helmet", "Shield" etc. classes and then use a factory instead to fill in the constructor arguments. I am unsure of whether the number of classes will become too much and if this is bad.

Classes:

```
Item* firstHelmet = new LeatherHelmet();
Item* otherHelmet = new SteelHelmet();

```

Factory:

```
Item* firstHelmet = Armour::Create(ArmourType.Helmet, Tier.Leather);
Item* secondHelmet = Armour::Create(ArmourType.Helmet, Tier.Steel);

```

The first example will result in a large number of classes. However, the second example is going to result in a lot of if statements or switch cases to query the type and tier of armour being created and then setting the appropriate variables.

Which is best, or is there another better solution I am missing?

# Answer
> 5 votes
The rule of thumb about whether to subclass or to create multiple instances of the same class is: **Do these objects need different program logic or just different values**?

When the steel helmet and leather helmet use the exact same programming and only differ by the values of attributes like `name`, `defense`, `price` and `sprite`, they should all be instances of the class `Helmet`.

When all types of armor use the same programming and differ only by which equipment slot they occupy, then they should all be instances of the class `Armor` with an attribute `slot`.

But if any armors have unique game mechanics, then it might make sense to implement these as individual sub-classes. When all helmets have values for hearing-impairment and vision-impairment but all other types of armor have not, then a class `Helmet` inheriting from `Armor` which has these additional attributes might make sense. When you have an unique helmet with a very gimmicky game mechanic, like a helmet which turns the character into a chicken if equipped on a Thursday, it might make sense to create an unique class just for this helmet which overrides the `equip` method. On the other hand, if you have many items with unique mechanics, it might be worth it to add a scripting engine to your game and allow items to contain scripts.

> the second example is going to result in a lot of if statements or switch cases to query the type and tier of armour being created and then setting the appropriate variables.

Instead of hardcoding your item creation you might want to consider to move your items and all of their values to an external file. You will still have a `switch` to convert strings from the file to the correct enumerations, but all the numeric values should come directly from the input file.

This keeps your item initialization code clearer and also gives you the advantage that your can change your item values without having to recompile the game.

# Answer
> 2 votes
There is probably not the one ultimate solution. In our game we are basically using your second approach:

All our items inherit from a base Item-Class that sums up all properties that they have in common. Like if they can be sold, and if then their sell value or if they are magic or not.

The items themself are divided by their purpose. So we have classes for wearables (which have a property on what slot they can be equipped \[chest, feet ...\]) weapons, consumeables (food, potions...) and materials (mainly for crafting or misc. stuff like Wood or an old can) Last but not least we have a seperate class for quest items since those may have unique use-effects or properties.

By now we store all our items in an XML file and parse the items from there into the game. Since there is not such a massive amount of items like in current MMOs we tend not to use a seperate database or something.

By now we are quite satisfied with this system. But Keep in mind that you may need to adapt your structure during you dev progression and on how many different items you plan to implement.

# Answer
> 0 votes
If you think about it logically, in terms of behaviour:

Armour protects are part of the body(slot). In an rpg it will negate a certain *amount* of damage, which depends on it's class (cloth/leather/mail/plate whathaveyou). This is not a change in behaviour, this is simply a change in values.

Likewise:

A weapon deals damage. How fast it deals it, and how much it deals, is down to it's weapon class. Again, no change in behaviour, just numbers.

Here's where it gets confusing: How do I deal with Bows/guns etc? Well, you introduce a "attack range" value. This value is the max distance the character can be from an enemy before this weapon can be used. Ranged weapons have this number set to a far larger value than the melee weapons.

The only behaviour that may differ is special effects, or "magic" armour and weapons, such as defensive effects that are passive, or trigger when hit, and weapon effects that trigger when they hit something.

Diablo 3 uses a very simple method to do all this:

It generates a weapon within a specific level range. This dictates the outside range of min/max damage it can deal. A quality level is randomly generated, which upgrades the damage numbers again, and dictates how many "prefixes" and "suffixes" the item can have.

For each such affix, additional damage/defence values may be added to the base, or other numbers may be added, such as resistances, triggered effects, elemental modifiers etc.

So, rather than seeing a bad/decent/good/excellent weapon as different classes, we say that any weapon *can* have excellent values, but will likely not. Just as legendary weapons *can* have on hit effects (represented by, perhaps, plugin callback classes), but other weapons do not.

The behaviour of the items itself does not change, only the values of the item. Remember that what you *see*, animated on the screen, is not necessarily what is going on in behind the scenes.

But this is just how the Diablo series does it (And how I would do it, if so inclined). You may find that a polymorphic approach works for you.

---
Tags: c++, architecture, rpg
---


# Question
Title: Why am I getting an access violation when assigning to a 2D array member?
c++ Beginner here, coming from Java background, and I'm getting the feeling this is a c++ specific error I'm running into. I am trying to procedurally generate a 2D map, which is of type Tile\[y\]\[x\]. As seen in code below I loop through all the indeces in the 2D array and I generate a colorvalue, which lets it decide what color the tile is, and a position, which defines the position the tile should be drawn to. However, I get a read access violation when I try to add Tiles to the 2D array. What am I doing wrong here?

Also whenever I have an array that is a bit bigger than this one, I get a stack overflow error. Now I read that arrays are kept in stack memory, and the stack is only very small, so what would be a solution to this? Thanks in advance

Map.cpp:

```
    #include "Map.h"
    #include <memory>

    Map::Map(int size)
    {
        this->size = 10;
        noiseGenerator.SetNoiseType(FastNoise::NoiseType::Perlin);
        std::cout << "Setting noise" << std::endl;
        for (int x = 0; x < size; x++) {
            for (int y = 0; y < size; y++) {
                tileMap[x][y] = Tile{ sf::Vector2f{x * 8.0f, y * 8.0f }, noiseGenerator.GetValue(x, y) //This is where the read access violation happens
            };
            }
        }
    }
void Map::draw(sf::RenderWindow *window)
{
    for (int x = 0; x < size; x++) {
        for (int y = 0; y < size; y++) {
            window->draw(tileMap[x][y]);
        }
    }
}

```

Map.h: Tile is inheriting from base class sf::RectangleShape

```
#pragma once
#include <iostream>
#include <string>
#include "FastNoise.h"
#include <SFML\Graphics.hpp>
#include "Drawable.h"
#include <memory>
#include "Tile.h"

class Map : public Drawable
{
public:
    Map();
    Map(int size);
    ~Map();
    void draw(sf::RenderWindow *window);

public:
    int size;
    sf::RectangleShape tileMap[5][5];
    FastNoise noiseGenerator;
};

```

Game.cpp with the main function:

```
std::list<Drawable*> drawableList;
    int main()
    {

        sf::RenderWindow window(sf::VideoMode(800, 800), "Zieke game");

        Map map{100};
        drawableList.push_front(&map);

        sf::Clock clock;

        while (window.isOpen())
        {
            deltaTime = clock.restart().asSeconds();
            sf::Event event;
            while (window.pollEvent(event))
            {
                if (event.type == sf::Event::Closed)
                    window.close();
            }

            for (auto x : updateableList) {
                x->update(deltaTime);
            }

            window.clear();

            for (auto x : drawableList) {
                x->draw(&window);
            }
            window.display();
        }

        return 0;
    }

```

# Answer
> 1 votes
> I get a read access violation when I try to add Tiles to the 2D array. What am I doing wrong here?

You declare `tileMap` like so:

```
sf::RectangleShape tileMap[5][5];

```

You access it with `tileMap[x][y]` in a nested loop inside `Map::Map`. Both of the loops (over `x` and over `y`) have an upper bound of `size`, which you set to 10 in the first line of the map constructor. That means when `x` is 0 and `y` is 5, which it eventually will be, you will begin invoking undefined behavior by accessing the array outside of its bounds. This will generally cause a crash.

In your comments you claimed the tile map is declared as `tileMap[100][100]`. Perhaps that is what you intended to do instead? Either way, the `size` variable and the actual declared size of your array are not in sync, and that's causing you trouble. If you make them agree, you should be fine.

I'd suggest you might want to consider looking in to using `std::vector` to manage your tilemap storage, as well. `std::vector` is C++'s dynamic array type -- you should probably also use it in place of the `std::list` you are using for your drawables, which is a linked list.

---

It is also worth noting that by declaring your array as one of `sf::RectangleShape`, that is *all* you can store in the array. When you attempt to assign a `Tile` to an array element, you *slice* that `Tile`, removing all the stuff that makes it a `Tile`. You probably want your array to be declared as `Tile tileMap[whatever][size];`.

> Also whenever I have an array that is a bit bigger than this one, I get a stack overflow error. Now I read that arrays are kept in stack memory, and the stack is only very small, so what would be a solution to this?

The stack size is generally configurable, but yes, it's usually small-ish by default. The issue is that you are statically declaring your array, which means the entire memory for the array is inline inside an instance of the `Map` class. You then declare the map instance on the stack (in `main`), which means the stack must be used to allocate the array memory.

The solution to this is to store the array on the heap, using `new`. Even better is to use `std::vector`, which manages the rigmarole of a heap-allocated dynamic array yourself (and is perfectly fine to use for heap-allocated *fixed size* array as well).

You can make a "2D" vector by doing `std::vector<std::vector<Tile>>`, but I'd rather recommend you simply flatten the map into a `std::vector<Tile>` that is `width * height` elements large; you can access any individual (`x`, `y`) element of that linear array as if it were 2D with the calculation `y * width + x`), like so:

```
tileMap[y * width + x] = /* ... */;

```

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


# Question
Title: Execute cloud build from script in Unity
Want to make cloud build functionality in Unity.
How can I do it in Unity from script(in EditorWindow)?
Update: Found Pre- and post-export methods, but still can't find the way to execute cloud build...

# Answer
One way to execute a cloud build programmatically is to use Unity's Cloud Build API.

The API documentation is available here, and the build command itself is here

Their example for making the call via curl is

```
curl
  -X POST
  -d '{"clean": true, "delay": 30}'
  -H "Content-Type: application/json"
  -H "Authorization: Basic [YOUR API KEY]"
  https://build-api.cloud.unity3d.com/api/v1/orgs/{orgid}/projects/{projectid}/buildtargets/{buildtargetid}/builds

```

Making web service calls from Unity is probably a separate question, but has ample documentation online.

`BuildPipeline` doesn't seem to offer cloud functionality, yet.

`CloudProjectSettings` may streamline your efforts a bit, if you're trying to kick off a build for the currently open project.
> 1 votes

---
Tags: unity, c#, build-process
---


# Question
Title: How can I display the visible number of health?
I'm trying to create health that is just numbers, I know how to do the bar but I just want it to show.

Here is the gml you need to see

```
plvl = 1;

mphlth = 75 + (plvl * 25);

phlth = 100
if (phlth >= mphlth) {
    phlth = mphlth
}
draw_text(10,10,string(phlth));

```

I also tried with the following:

```
draw_text(10,30,"health: "+string(player1.phlth));

```

Is there anyway to display the health number?

# Answer
sorry I found it out on my own all I had to do was make it a global variable then type draw\_text(32,32,phlth); numbers are changeable
> 0 votes

---
Tags: game-maker
---


# Question
Title: How would joints work in an impulse-based physics engine?
I want to learn about physics engines, especially impulse-based ones. So I've followed along this tutorial to create some simple rigid-body physics: http://gamedevelopment.tutsplus.com/tutorials/how-to-create-a-custom-2d-physics-engine-the-basics-and-impulse-resolution--gamedev-6331

I've got this working and it seems pretty solid to me. So I wanted to add revolute (fixed) joints. I've started off with a simple structure:

```
struct Joint
{
    RigidBody* A;       // One body
    Vec2 AnchorPointA;  // A's anchor point's offset (0,0 if center)
    RigidBody* B;       // The other body
    Vec2 AnchorPointB;  // B's anchor point's offset (0,0 if center)
};

```

I'm guessing this would do the job. Now... I'm not too good with physics (hence I started to code this) so I started out what I thought would work:

```
RigidBody* A = joint->A;
RigidBody* B = joint->B;

// Rotate the anchor points based on the body's rotation
Vec2 ancha = A->BodyShape->Transform * joint->AnchorPointA;
Vec2 anchb = B->BodyShape->Transform * joint->AnchorPointB;

// The relative positions of the 2 points
Vec2 relativeVel = (B->Position + B->Velocity + anchb) - (A->Position + A->Velocity + ancha);

// Apply a force towards eachother, pulling at the anchor points
B->ApplyImpulse(-relativeVel, anchb);
A->ApplyImpulse(relativeVel, ancha);

```

This approach simply pulls the bodies together. And it works... Kind of. After the bodies slide together as the joints are set up, it looks ok, but when the bodies fall they tend to spin away from eachother or start to freak out (keep rotating). After messing around with the code (which was getting worse and worse as I was changing it) I've tried to look up solutions on the internet or at least some hints. I've found this: How can I implement revolute (hinge) joints in a 2d physics system?

But this approach does not apply impulses, it fixes position. Wouldn't be an impulse-based system better? How can I fix it? I don't even know how big forces should I apply (I guess it should be based of the distance or something like that and also for the masses of the bodies). Thanks for any help!

# Answer
> 0 votes
I'm facing a similar issue, and here is what I've come up with so far:

1. joint must fix position between two body but it can still rotating.
2. joint can transfer force or impulse in x,y axis
3. rotating object apply centripetal force to joint

This is just my hypothesis, and I'm still working to find out a solution.

---
Tags: physics, physics-engine, rigid-body-dynamics, joints
---


title: How to combine steering forces?

text:
# Question
Title: How to combine steering forces?
I am trying to understand how to implement and combine steering vectors for autonomous agents as described by Craig Reynolds.

My understanding is that each steering force should be calculated separately and then all of the steering forces should be added together and then applied.

I understand that each steering force is equal to the desired velocity for a particular behavior, minus the agent's current velocity.

I am trying to combine two basic behaviors: Seek and Flee. Below are two diagrams to illustrate my issue.

I have an agent that is Seeking a target directly ahead of it, and fleeing from a target below it. When the target is at rest (current velocity = 0), the steering forces for each behavior are equal to their respective desired velocities:

vSteer = vDesired - currentVelocity = vDesired - 0 = vDesired

And the combined steering force points up and to the right, in blue. This is roughly what I would expect.

However, if the agent is moving, we get a completely different result. For the sake of simplicity, say the agent is already moving at top speed in the direction of the target. So the agent's current velocity is equal to its desired seek velocity.

When the agent's current velocity is equal to the desired seek velocity, then the seek steering force is 0 (vSteer = current - desired = desired - desired = 0). The flee steering force then is equal to the desired flee velocity minus the current velocity, which produces a vector that points BACKWARD! And since the seek steering force is zero, the total steering force equals the flee steering force.

I noticed this issue while trying to implement a separation force, which is essentially the situation illustrated in the diagrams but with the red X representing a neighboring agent. The net effect is that agents maintain separation, but move at about half speed, with a seek steering force pointing forward, a flee steering force pointing backward and away from the neighbor, that largely end up cancelling each other out.

It really doesn't seem like any component of the flee force should be pointing backwards here. What am I misunderstanding?

# Answer
> 1 votes
I would solve this on two levels:

On top level, the Flee / Seek urges battle it out to determine where the agent should go to. This stage determines a location. Depending on what is urgent at the moment, it could be more influenced by threat or by target.

Below that, at the lower level, I would take the resulting target location, and actual current location to derive the steering force by use of a PID Controller.

# Answer
> 1 votes
In 'vSteer = current - desired', you may want to only use the *component*, i.e. projection, of the current velocity on the desired velocity, instead of *current*. That way, each controller only modifies the steering force along the direction of its desired velocity; the steering force would only point upwards in ex. 2.

The component of a on b is the magnitude of b times the cosine of the angle between a and b.

# Answer
> 1 votes
You are subtracting the current velocity multiple times, once for each behavior (in this case 2 times), when you should be subtracting it only once at the end, when you have summed all of the behaviors together.

# Answer
> 1 votes
The way I usually handle this is to add the forces—which should be independent of the current velocity—then check whether the result has a greater magnitude than the maximum force I want to be applying, and normalize it to that magnitude if so. This preserves the relative “strengths” of the forces without allowing their combined result to blow up the system. Pseudocode:

```
combinedForce = seekForce + fleeForce
combinedForceMagnitude = length(combinedForce)
if combinedForceMagnitude > maximumForceMagnitude:
    combinedForce *= (maximumForceMagnitude / combinedForceMagnitude)

```

---
Tags: ai, steering-behaviors
---


# Question
Title: Get component that has specified method by Reflection API
Let's say that I have a component like this:

```
public class MyComponent: MonoBehaviour {
    public void MyMethod(int param1, int param2) {
        Debug.Log(param1 + " " + param2);
    }
}

```

And I have a string variable that has method name from that class.

```
string methodName = "MyMethod";

```

I need to invoke MyComponent.MyMethod with reflection api, however I don't know how to distinguish component that has "MyMethod".

```
MonoBehaviour[] scripts = target.GetComponents<MonoBehaviour>();

// Find the component that has method
for(int j = 0; j < scripts.Length; j++) {
    ... ??? ...
}

methodInfo.Invoke(target.gameObject, parameters);
hasFound = true;

```

If I just invoke with gameObject, of course it fails. So I have to get the component to use Invoke. In this case, how do I get the component that has specified method by Reflection?

# Answer
If you are looking for a certain method by a specific name, why don't you use **interfaces** instead? That way you can make any MonoBehaviour class implement that interface. Of course, this wouldn't let you make use of custom attributes (like RPC) for you to state a method to call by its name. But it would solve the problem (although not with your desired approach).

```
public interface ICustomInterface
{
    void MyMethod(int indexArg);
}

public class MonoA : MonoBehaviour, ICustomInterface
{
    public void MyMethod(int indexArg)
    {
        Debug.Log("I am doing what a MonoA ought to do with the Index: " + indexArg.ToString());
    }
}

public class MonoB : MonoBehaviour, ICustomInterface
{
    public void MyMethod(int indexArg)
    {
        Debug.Log("I am doing what a MonoB ought to do with the Index: " + indexArg.ToString());
    }
}

public class Example : MonoBehaviour
{
    public GameObject target;

    void Start()
    {
        ICustomInterface[] scripts = target.GetComponents<ICustomInterface>();

        for(int j = 0; j < scripts.Length; j++) {
            scripts[j].MyMethod(j);
        }

        hasFound = (scripts.Length > 0);
    }
}

```
> 1 votes

# Answer
Before I post any pseudo-code, I do entirely agree with what @DMGregory has posted. If your code knows enough to know the method, there's probably a cleaner way to do it. Interfaces are a nice and clean approach (as posted by @LinkWindcrafter in another answer here).

Now, if you've explored all reasonable options and there's simply no other alternative... I think you may be looking for the Type.GetMethod(String, BindingFlags) feature.

Here's some quickly hacked together pseudo-code:

```
    public struct OwnerAndMethod
    {
        public object Owner { get; private set; }

        public MethodInfo Method { get; private set; }

        public void Invoke ()
        {
            Method.Invoke (Owner, null);
        }

        public OwnerAndMethod (object owner, MethodInfo method) : this ()
        {
            Owner = owner;
            Method = method;
        }
    }

    private static List<OwnerAndMethod> GetMethodsFromComponentsViaReflection (IList<object> objects, string methodName)
    {
        List<OwnerAndMethod> ownerAndMethods = new List<OwnerAndMethod> ();
        for (int i = 0; i < objects.Count; i++)
        {
            MethodInfo method = objects[i].GetType ().GetMethod (methodName, BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance);
            if (method != null)
            {
                ownerAndMethods.Add (new OwnerAndMethod (objects[i], method));
            }
        }

        return ownerAndMethods;
    }

    private void Start ()
    {
        MonoBehaviour[] components = transform.GetComponents<MonoBehaviour> ();
        List<OwnerAndMethod> methods = GetMethodsFromComponentsViaReflection (components, "Hey");

        foreach (OwnerAndMethod method in methods)
        {
            method.Invoke ();
        }
    }     method.Invoke ();
        }
    }

```

There's obviously so many possible exceptions that can be thrown from this code, so take this as a reference and not so much an exact way of doing it.

I hope this helps. Good luck!
> 0 votes

---
Tags: unity, code-reflection
---


title: SDL/C++ Keyboard Input

text:
# Question
Title: SDL/C++ Keyboard Input
I'm having trouble with key management. Movement works fine but the shooting does stuff that I don't want to happen.

Every time I press the arrow keys to shoot it works fine but when I press a key to move the shooting stops and then continues shooting in the direction that I'm pressing.

```
void Player::HandleEvents() {

    SDL_Event event;
    const Uint8* keyboard_state_array = SDL_GetKeyboardState(NULL);

    while (SDL_PollEvent(&event)) {
        switch (event.type) {
        case SDL_KEYDOWN:

            //Shooting
            if ((keyboard_state_array[SDL_SCANCODE_UP])) {
                shootDirectionY = -1;
            }
            else if ((keyboard_state_array[SDL_SCANCODE_DOWN])) {
                shootDirectionY = 1;
            }
            else if ((keyboard_state_array[SDL_SCANCODE_LEFT])) {
                shootDirectionX = -1;
            }
            else if ((keyboard_state_array[SDL_SCANCODE_RIGHT])) {
                shootDirectionX = 1;
            }

            //Movement
            //Horizontal and Vertical

            if (keyboard_state_array[SDL_SCANCODE_W]) {
                speedSenseX = 0;
                speedSenseY = -1;
            }
            else if (keyboard_state_array[SDL_SCANCODE_S]) {
                speedSenseX = 0;
                speedSenseY = 1;
            }
            else if (keyboard_state_array[SDL_SCANCODE_A]) {
                speedSenseX = -1;
                speedSenseY = 0;
            }
            else if (keyboard_state_array[SDL_SCANCODE_D]) {
                speedSenseX = 1;
                speedSenseY = 0;
            }

            //Diagonals and AD WS cases

            if (keyboard_state_array[SDL_SCANCODE_W] && keyboard_state_array[SDL_SCANCODE_D]) {
                speedSenseX = 1;
                speedSenseY = -1;
            }
            else if (keyboard_state_array[SDL_SCANCODE_W] && keyboard_state_array[SDL_SCANCODE_A]) {
                speedSenseX = -1;
                speedSenseY = -1;
            }
            else if (keyboard_state_array[SDL_SCANCODE_S] && keyboard_state_array[SDL_SCANCODE_D]) {
                speedSenseX = 1;
                speedSenseY = 1;
            }
            else if (keyboard_state_array[SDL_SCANCODE_S] && keyboard_state_array[SDL_SCANCODE_A]) {
                speedSenseX = -1;
                speedSenseY = 1;
            }
            if (keyboard_state_array[SDL_SCANCODE_S] && keyboard_state_array[SDL_SCANCODE_W]) {
                speedSenseX = 0;
                speedSenseY = 0;
            }
            else if (keyboard_state_array[SDL_SCANCODE_A] && keyboard_state_array[SDL_SCANCODE_D]) {
                speedSenseX = 0;
                speedSenseY = 0;
            }
            break;

        case SDL_KEYUP:
            //Handeling speeds
            if (!keyboard_state_array[SDL_SCANCODE_W] && speedSenseY < 0) {
                speedSenseY = 0;
            }
            if (!keyboard_state_array[SDL_SCANCODE_S] && speedSenseY > 0) {
                speedSenseY = 0;
            }
            if (!keyboard_state_array[SDL_SCANCODE_A] && speedSenseX < 0) {
                speedSenseX = 0;
            }
            if (!keyboard_state_array[SDL_SCANCODE_D] && speedSenseX > 0) {
                speedSenseX = 0;
            }
            if (!keyboard_state_array[SDL_SCANCODE_W] && keyboard_state_array[SDL_SCANCODE_S]) {
                speedSenseY = 1;
            }
            if (keyboard_state_array[SDL_SCANCODE_W] && !keyboard_state_array[SDL_SCANCODE_S]) {
                speedSenseY = -1;
            }
            if (!keyboard_state_array[SDL_SCANCODE_A] && keyboard_state_array[SDL_SCANCODE_D]) {
                speedSenseX = 1;
            }
            if (keyboard_state_array[SDL_SCANCODE_A] && !keyboard_state_array[SDL_SCANCODE_D]) {
                speedSenseX = -1;
            }

            break;
        }
    }
}

```

# Answer
You're mixing two methods of input detection SDL provides. There is the event API which lets you get input via events, and there is the keyboard state API, which allows you to get the state of the entire keyboard with a single function and query it later. You're mixing them, and it's not working well.

In your code, you're detecting an SDL\_KEYDOWN event but then you're querying the state of the entire keyboard in an if/else chain. If you're pressing up, for example, then you'll never be able to detect left, right or down because you're ignoring the information given in the event.

I would stick to just querying the keyboard without events and fix your if/else chains. The code would look something like this. These 4 lines of code should do everything your code was doing.

```
while (SDL_PollEvent(&event)) {
    switch (event.type) {
        // Handle non-input stuff here like SDL_QUIT
        // Since you're using the other API, ignore keyboard events
    }
}

const Uint8* kb = SDL_GetKeyboardState(NULL);

shootDirectionY = -kb[SDL_SCANCODE_UP] + kb[SDL_SCANCODE_DOWN];
shootDirectionX = -kb[SDL_SCANCODE_LEFT] + kb[SDL_SCANCODE_RIGHT]

moveDirectionY = -kb[SDL_SCANCODE_W] + kb[SDL_SCANCODE_S];
moveDirectionX = -kb[SDL_SCANCODE_A] + kb[SDL_SCANCODE_D];

```
> 3 votes

# Answer
You are handling KEYDOWN for shoot direction, but you never handle KEYUP for the same keys?

I'm not sure how you are handling state for your events and I'm not real clear from your question what behaviour your are expecting versus what behaviour you are observing.

Maybe try searching for where else you modify the shoot direction states?
> 0 votes

---
Tags: c++, sdl, keyboard
---


title: Unity Tilemap one way collisions

text:
# Question
Title: Unity Tilemap one way collisions
How can we get one way collisions using Tilemaps in Unity?

There doesn't seem to be much online regarding this topic yet.

From this link: https://answers.unity.com/questions/1471156/how-to-make-one-way-platforms-using-a-tilemap.html, I got that we should use a Tilemap Collider 2D for collisions and not use a Composite Collider 2D. Finally, we need a Platform Effector 2D with One-Way enabled.

However, the resulting tiles all behave like normal tiles in that collisions occur along all edges.

Here's what the inspector looks like for the tile map in question.

The scene setup looks like this:

It looks like the tiles in the scene all have collision edges all the way around.

What needs to be done to allow for one way platforms? Thanks!

**EDIT**

Here is the setup of the character:

Here is a view of what it looks like in game: When jumping, the character unfortunately collides with the block above and is unable to pass through.

# Answer
The culprit turned out to be custom collision/physics code that OP had written separately (which I do not have access to).

We ran a few test cases. Confirmed that PlatformEffector2D does, in fact, work as expected on a TilemapCollider. No special steps needed to set it up.
> 1 votes

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


title: Wrap texels between desired values

text:
# Question
Title: Wrap texels between desired values
I'm using a basic pixel shader here

```
uniform sampler2D texture;
uniform float pixel_threshold;

void main()
{
    float factor = 1.0 / (pixel_threshold + 0.001);
    vec2 pos = floor(gl_TexCoord[0].xy * factor + 0.5) / factor;
    gl_FragColor = texture2D(texture, pos) * gl_Color;
}

```

It works great in my game. But on a new enemy it doesn't. This enemy is different because it uses a texture atlas- one big texture holding more frames than just the character. The sampling gets messed up because `factor`approaches `0` so does the `xy` coord therefore sampling some pixels outside of the character's sheet. Likewise when `pixel_threshold` gets small, the `xy` coord goes outside of the character's spot in the texture.

Clamping is not the solution because we want it to wrap around. I've tried many ways of wrapping but not seem to offer the desired effect of the original.

I tried using 4 uniforms: `left`,`top`,`width`,`height` and passing in the masking values used when drawing the sprite from the spritesheet.

```
vector2 size = mySprite.getSize();
float left = mySprite.getTextureRect().left / size.x;
float top  = mySprite.getTextureRect().top / size.y;
float width= mySprite.getTextureRect().width/ size.x;
float height=mySprite.getTextureRect().height/size.y;

myShader.setUniformf("left", left);
...
myShader.setUniformf("height", height);

```

How can I have the pixel blur shader stay within the texel ranges provided by the uniform? Thanks.

# Answer
I would do this by converting the texture coordinates to "sprite-normalized" coordinates, do your math on them, and then convert back to atlas coordinates. You'd do this by doing something like the following:

```
// Get the texture coordinate
vec2 texCoord = gl_TexCoord[0].xy;

// Make its lower-left be at (0,0) and it's upper right be at (1,1)
texCoord = (texCoord - origin) / size;

// Apply the factor
float factor = 1.0 / (pixel_threshold + 0.001);
texCoord = floor(texCoord * factor + 0.5) / factor;

// Apply the wrapping
texCoord = fract(texCoord);

// Convert back to texture atlas coordinates
texCoord = (texCoord * size) + origin;

```

In this case `origin` is the `(left, bottom)` you calculated in your code above and `size` is the `(width, height)` you calculated.
> 1 votes

---
Tags: shaders, glsl, fragment-shader
---


# Question
Title: unity: read from text file to instantiate objects
I'm trying to use the following code to read a text file stored in the Resources folder or in a file on my computer, and instantiate objects in a Unity 3D scene accordingly. I'm having trouble getting it to work. I've tried attaching the script to either the main camera or an empty gameobject. Neither work so far...

I either end up with an error saying the path does not exist (when I put the text file into the project folder on my desktop), or a null exception, or that the path contains invalid characters.

Where am I going wrong?

I'm trying to use a jagged array because I'll need users to eventually be able to change the text file on-the-go to create a level.

The text file contains the following data: S 0 0 0 1 0 0 1 0 2 2 0 0 2 1

My script currently reads:

```
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using UnityEngine;
using System.Linq;
using System.IO;
using UnityEngine.UI;

public class GenerateLevel : MonoBehaviour {

    public Transform player;
    public Transform ground;
   // public Transform floor_valid;
    public Transform floor_obstacle;
    //public Transform floor_checkpoint;

    //public const string sfloor_valid = "0";
    public const string sfloor_obstacle = "0";
   // public const string sfloor_checkpoint = "2";
    public const string sstart = "S";

    public string textFile = "maze";
     string textContents;

    // Use this for initialization
    void Start () {
        Instantiate(ground);

        TextAsset textAssets = (TextAsset)Resources.Load(textFile);
        textContents = textAssets.text;

        //string[] lines = System.IO.File.ReadAllLines("//maze.txt");

        //string textFile;
        //textFile = Resources.Load("assets/resources/maze").ToString();

        string[][] jagged = ReadFile(textContents);

        for (int y = 0; y < jagged.Length; y++)
        {
            for (int x = 0; x < jagged[0].Length; x++)
            {
                switch (jagged[y][x])
                {
                    case sstart:
                        //Instantiate(floor_valid, new Vector3(x, 0, -y), Quaternion.identity);
                        Instantiate(player, new Vector3(0, 0.5f, 0), Quaternion.identity);
                        break;
                    //case sfloor_valid:
                      //  Instantiate(floor_valid, new Vector3(x, 0, -y), Quaternion.identity);
                        //break;
                    case sfloor_obstacle:
                        Instantiate(floor_obstacle, new Vector3(x, 0, -y), Quaternion.identity);
                        break;
                    //case sfloor_checkpoint:
                      //  Instantiate(floor_checkpoint, new Vector3(x, 0, -y), Quaternion.identity);
                        //break;
                }
            }
        }
    }

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

    }

    string[][] ReadFile(string file)
    {
        string text = System.IO.File.ReadAllText(file);
        string[] lines = Regex.Split(text, "\r\n");
        int rows = lines.Length;

        string[][] levelBase = new string[rows][];
        for (int i = 0; i < lines.Length; i++)
        {
            string[] stringsOfLine = Regex.Split(lines[i], " ");
            levelBase[i] = stringsOfLine;
        }
        return levelBase;
    }
}

```

# Answer
In your code, you're trying to read two distinct files. Which text file contains the array? The one you're trying to read from Resources or the one you're trying to read with System.IO? Which of these steps is generating the error?

**Possible error in Resources.Load:**

Based on this line, looks like your Resources folder is called "resources":

```
//textFile = Resources.Load("assets/resources/maze").ToString();

```

If this is the case, try to change it's name to "Resources", with a capital R.

**Possible error in System.IO:**

You have already read one file from Resources and get its content when you call `System.IO.File.ReadAllText`. This method should receive a path as argument, so unless `textContents` is a valid path, `System.IO.File.ReadAllText` won't work properly. So, what is the value of `textContents` that you read from the first file?
> 1 votes

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


title: RTS pathfinding

text:
# Question
Title: RTS pathfinding
I'm doing my first RTS game (something like WarCraft 2) in own game engine using Monogame for graphics. I am wondering how can I implement pathfinding for a selected group of units. Movement is tile-based, I don't want to play with navmesh yet.

First of all my map is tiled (up to 256x256) For a single unit I could definitely go for something like simple shortest path algorithm (maybe Dijkstra or A\*). Unfortunately, the found path can be blocked by different unit or a building. So, quick maths 256x256x4 = 262k (edges). 262k * log 262k = 5\* 10^6 (no log for A\*, 20 times less) That's quite a lot. If I'd want my unit to respond to possible obstacle on the path, I'd have to run the algorithm each time it moves, let's say each second. It's definitely a lot... probably too much.

But what about few units? For each of them I have to run this algorithm once again, so for 10 units the complexity would be 5 * 10^7, quite a lot for a second. And even if I somehow reduce it, the units in the selected group would detect each other, which can totally mess up the whole pathfinding.

How can I solve this problem quicker? Maybe different algorithms or... I really have no idea.

EDIT: Well, I'm not going to have different speeds on different terrain, so basically I can go with a simple BFS (still not sure if A\* is better than BFS, both have worst case O(|E|), so is it worth to implement A\*? BFS is much quicker to write). So right now the complexity is about 200k per second for one unit.

EDIT 2: I'd like to avoid using any pathfinding libraries. I'm doing that game only for learning purposes, so I'd love to do all the stuff by myself.

# Answer
> 7 votes
With RTS pathfinding, your requirements are:

1. You have to compute paths for all selected units fast.
2. The pathfinding must take into account that a path may not be found (blocked)
3. The pathfinding must take into account, units of varying size.
4. The pathfinding must take into account that the path may become blocked by other allied units/buildings before the path has been completely walked.

So lets address each point in order, using starcraft as an example:

1. Starcraft uses subdivision of cells to reduce top level path finding, and then performs a lower level of pathfinding to trace a path from one cell to the next. This makes it very cheap and thus, fast, to perform.
2. A-Star (used by 90+% of games) is ideal for this, as the algorithm handles blocked paths fine.
3. By using the aforementioned sub-division of cells, you can have units which occupy N subcells. by updating subcell maps frequently, you can allow the algorithm to path small fast units around large slow units.
4. As with 3: You will want to periodically recompute each moving units' path, as a path that was previously open, may become blocked over time. Update the sub-cell maps and recompute, as in 1.

So, to summarise:

Use A-Star, subdivide subcells for performance and accuracy. Maintain a temporary subcell map of obstacles and units for pathing around blockages, or waiting for blocks to clear, and, as I have discovered through experience:

Do not recompute paths for every unit, every frame. Instead, do some sort of queuing system, and do a portion of it each frame, or every other frame, which leaves computational time for other game tasks.

# Answer
> 1 votes
Whole thing could be split into 3 big chunks:

1. **Pathfinding** \- where you build paths from point A to point B for each unit individually, or for a group together. Usually this is some modification of A\* or HPA\* (hierarchical variant of A\*, when path gets build over large chunks of terrain)
2. **Path following** \- where units follow the path with some slack, walking around small static obstacles (e.g. trees) and check for larger changes in passability that they can not handle (then path gets rebuilt)
3. **Collision avoidance** \- where units resolve local collision problems with other walking units.

3.1. E.g. in tile-based RTS if units path is blocked by another walking unit, it can wait some. If another unit is locked, we can sidestep around it. If unit is idle we can push it out of the way, and etc.

3.2. Alternatively you can look into Reciprocal Velocity Obstacles (RVO) algorithms, that allow units to walk freely and resolve collisions in a more natural (and error prone) ways.

3.3. There are also Flow-field algorithms.

---
Tags: path-finding, rts
---


# Question
Title: Import .fbx animation from Maya 2012 to Unity 2018
I have a grass made by PaintEffects tool (1) and "animated" by adding turbulence (2) and then baked with Maya 2012.

And in Maya everything looks perfect - animation works. Problem is, when I'm importing that .fbx animation to Unity 2018, nothing happens. I can't either see this animation in Preview, I can see only the "model" itself. I read on the internet that's maybe because I set wrong animation, or rig option in Unity, but I tried every one of them. Is there something I missed, either in Maya, or Unity? Maybe I have too old version of Maya?

Also, I was trying to save that animation into separate files, or with extensions like .ma, .mb... Nothing works either.

# Answer
> 0 votes
It seems that Unity 2018 HAS TO work only with newer versions of Maya. I installed update for it and by the option "Send to Unity" my animation suddenly works.

I think that the main issue lays upon the .fbx importer version. It should be as new as possible.

---
Tags: unity, animation, maya, fbx
---