# Question
Title: Camera warps back to where player entered the car when they get out
I am currently working on a 2D game that gives the player the ability to drive cars and get in and out of them.

I wrote a script that basically gets the job done; the only issue is every time my character gets out of the car, the camera jumps from where the car originally was to where I drove it to.

While I'm driving the car, the camera follows the car just fine.

The preferred reaction would be for the camera to just still be where the car is and immediately start following the player when they get out of the car.

Here is my entire driving script:

```
public class Driving : MonoBehaviour {

    public int movementSpeed = 2;
    public int rotationSpeed = 50;
    public float angle = 0;
    public int levelToLoad;
    public CameraController camCon;
    public PlayerController playCon;
    public int powerMod;

    public GameObject camera1;
    public GameObject player;
    public GameObject tractor1;
    bool isInVehicle;
    bool isInCollider;
    bool gotOut;
    Vector3 tractorPosition;
    public float power = 3;
    public float maxspeed = 10;
    public float turnpower = 2;
    public float friction = 3;
    public Vector2 curspeed;
    Rigidbody2D rbody2d;
    public bool gas;

    void Start()
    {
        rbody2d = GetComponent<Rigidbody2D>();
        isInCollider = false;
        isInVehicle = false;
        Quaternion origRotation = camCon.transform.rotation;
        transform.rotation = Quaternion.identity ;
    }

    void Update()
    {
        if (gotOut)
        {
            isInCollider = false;
            isInVehicle = false;
        }

        if (isInVehicle)
        {
            isInCollider = true;

            curspeed = new Vector2(rbody2d.velocity.x, rbody2d.velocity.y);

            if (curspeed.magnitude > maxspeed)
            {
                curspeed = curspeed.normalized;
                curspeed *= maxspeed;
            }

            camCon.targetSpeed = maxspeed -5;

            if (Input.GetKey(KeyCode.W))
            {
                //transform.Translate(Vector3.up * movementSpeed * Time.deltaTime);
                rbody2d.AddForce(transform.up * power);
                rbody2d.drag = friction;
                gas = true;
            }
            if (Input.GetKey(KeyCode.S))
            {
                // transform.Translate(Vector3.down * movementSpeed * Time.deltaTime);
                rbody2d.AddForce(-(transform.up) * (power/2));
                rbody2d.drag = friction;
                gas = true;
            }
            if (Input.GetKey(KeyCode.A))
            {
                //angle = angle + rotationSpeed * Time.deltaTime;
                transform.Rotate(Vector3.forward * turnpower);
            }   //noGas();
            if (Input.GetKey(KeyCode.D))
            {
                //angle = angle - rotationSpeed * Time.deltaTime;
                transform.Rotate(Vector3.forward * -turnpower);
                //noGas();
            }
            //transform.rotation = Quaternion.Euler(new Vector3(0f, 0f, angle));
            noGas();

        }
        if (Input.GetKeyDown(KeyCode.Escape))
        {
            //Application.LoadLevel(0);
            SceneManager.LoadScene(levelToLoad);
            //transform.rotation = Quaternion.Euler(new Vector3(0f, 0f, angle));
            Transform thistrans1 = transform;
            ResetRot(thistrans1);
        }
        if (Input.GetKeyDown(KeyCode.E))
        {

            if (gotOut)
            {
                gotOut = false;
                //transform.rotation = Quaternion.identity;
            }

            if (isInCollider)
            //if (!isInVehicle)
            {
                Debug.Log("Key pressed...");
                //camera1 = GameObject.FindWithTag("MainCamera");
                //player = GameObject.FindWithTag("player");
                //tractor1 = GameObject.FindWithTag("tractor1");
                tractorPosition = transform.position;
                if (!isInVehicle)
                {
                    Debug.Log("Entered vehicle..");
                    //camera1.transform.parent = tractor1.transform;
                    player.GetComponent<Renderer>().enabled = false;
                    isInVehicle = true;
                    camCon.cameraTarget = tractor1;
                    playCon.moveSpeed = 0;
                    camCon.targetSpeed = 10;

                }
                else
                {
                    Debug.Log("In vehicle....");
                    if (isInVehicle)
                    {
                        //Transform thistrans1 = transform;
                        //ResetRot(thistrans1);
                        Debug.Log("Exited vehicle....");
                        //camera1.transform.parent = player.transform;
                        player.GetComponent<Renderer>().enabled = true;
                        player.transform.position = tractorPosition;
                        isInVehicle = false;
                        isInCollider = false;
                        gotOut = true;
                        camCon.cameraTarget = player;
                        playCon.moveSpeed = 3f;
                        //camCon.transform.rotation = (player.transform.rotation);
                        camCon.transform.position = new Vector3(player.transform.position.x, camCon.transform.position.y, player.transform.position.z);
                        camCon.targetSpeed = playCon.moveSpeed;
                    }
                }
                camera1.transform.position = new Vector3(0f, 0f, -10f);
                camera1.transform.rotation = player.transform.rotation;
            }

        }
    }

    public virtual void ResetRot(Transform trans)
    {
        if (isInVehicle)
        {
            trans.rotation = Quaternion.identity;
        }

    }

    void OnTriggerStay2D(Collider2D col)
    {
        if(col.name == "Player")
        {
            Debug.Log("Trigger entered....");
            isInCollider = true;
        }

    }

    private void OnTriggerExit2D(Collider2D collision)
    {
        isInCollider = false;
        //isInVehicle = false;
    }

    void noGas()
    {
        //bool gas;
        if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.S))
        {
            gas = true;
            turnpower = (1 * powerMod);
        }
        else
        {
            gas = false;
            turnpower = 0;
        }

        if (!gas)
        {
            rbody2d.drag = friction * 2;

        }
    }
}

```

# Answer
You're explicitly setting the camera position back to \<0,0,-10\> when the player exits the vehicle

```
camera1.transform.position = new Vector3(0f, 0f, -10f);

```

But since the target of the camera is still the player (from when the player initially entered the vehicle) the camera controller is moving the camera back to the current location of the player.

I'd suggest try removing that line altogether and retesting; but if you still don't get the correct behavior, try changing it to

```
camera1.transform.position = player.transform.position;

```
> 1 votes

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


title: Board like strategy map

text:
# Question
Title: Board like strategy map
I want to make a strategy game like Risk. I want to use C# for the mechanics and Unity for the graphics.

My problem is that I don't know how to create the map itself and integrate it with C#. I don't want a tile map but instead I want to create a customized world map, with different provinces defined by me.

The map would be something like Imperial Glory, where you see it top down and then move your generals like chess pieces. I'm not implementing any real time battles at this point, it's just something really simple, like a board game. Could anyone please help me?

I'll try to explain it a bit better: I need to create a map of the Mediterranean basin that would cover all the land occupied by the Romans at the height of their empire.

Next, I'll divide the map into 20 provinces (Italy, Gaul, Germania, etc), each one producing a set ammount of resources and population. I also want them to have their own wheather and buildings (for example, you can only train soldiers in provinces that have a barracks). I guess I'll need a text box popup that appears when you click on a province to display it's information.

I'll also need some buttons to open dropdown menus or perhaps whole windows, for other purposes such as diplomacy, statistics, tech trees, etc.

I wanted the map to be in 3d because I think it would be much more interesting to look at it in perspective instead of flatten 2d.

I'm fairly new into Unity so I really admit that I have no idea where to start. Please, have patience with my ignorance. Thank you very much for all your help. If there are any doubts about my question, please let me know and I'll try to explain it better.

PS: I think I'll make it a turn based game since I think this would make it simpler to code and faster to run.

# Answer
Unity is a game development platform that uses languages, such as C# and JavaScript, to create scripts that provide behaviours for elements within your game. If you're creating a 2D top-down game, you could use tools such as GIMP, Paint.NET or Photoshop to create graphics that you would import into Unity as assets.

For your map, you could create a world comprised of continents and provinces. Reddit's Worldbuilding subreddit (filtered to Maps) has some great examples, tips and tricks on creating worlds.

**Example Map:**

I moved these apart in Photoshop, making it easier to create a texture atlas, disabled the background, saved it as a `.png` file, and imported it into Unity as a `Sprite` with `Sprite Mode` set to `Multiple`. Finally, I created an empty `GameObject` called World, containing each of the continents, and a cube object behind them which fills the camera's view, acting as a surrogate ocean.

**2D / 3D view of the result:**

As you can see in the 3D perspective, the map is separated by four continents. My experience with Unity is limited, but this could be a good place to start, or give you an idea of what to do. I also suggest checking out Unity's official tutorials, their online forum and their answers site, if you want to learn more about the platform and how to use it.
> 4 votes

# Answer
Just as it has been said in the comments, it is not clear if you are asking both how to design/create the assets that will represent the provinces, or just how to connect the assets representing provinces within your C# code. My guess is that you are looking for the later.

So, first of all, you don't need to have one rectangle for the map and then subdivide it into the countries and then provinces. You could have a separate GameObject asset for each province. Then, a simple approach would be to give a proper name for each asset of each province, then to create in C# a custom class with a Dictionary that holds data for each province (the same can be achieved with a List if you prefer it over Dictionaries).

Then, each entry in such Dictionary would be a province with the Key being province name, and when you reference any given one (e.g. using the name of the province object that was hit by a mouse click), you could access its other info stored at that Dictionary entry. For example, for each enter in the Dictionary you could have a field for the number of units garrisoned there, another for the resources, another for weather, another with the color name of the owner, or even a sub-list within the Dictionary, containing the names of the neighbor-provinces of that province.
> 2 votes

# Answer
I was working on a very similar (but more complicated) project. The basic idea is to create a colormap and a 2D sprite and perform a per-province palette-swap in the sprite's fragment shader based on the province's RGB value.

Conceptually, you'd keep two textures, a colormap texture, and a lookup texture. The colormap could be whatever size you want, but the lookup texture has to be of size 4096\*4096. The details are contained in the accepted answer to my earlier question on the topic.

This is a very graphically cheap way to do this, though it can be pretty computationally expensive to repeatedly update a large texture.

This also allows you the option of easily projecting your texture over a 3D terrain if you ever want to go that route (for example, if you ever want a map like the one in Risk 2, Europa Universalis, or Crusader Kings 2).

Another way to do it is to read through a colormap like the one in my linked question, and create 1 2D sprite per province. This approach was taken by the (now-defunct) Of Bears and Eagles project (which is coded in Java), but it is worth noting that a heavily-mutated private fork of the project is being run by Reddit user Kalelovil, and is pseudo-regularly updated here (the project on Reddit hasn't been very active, most of us who contribute do so over the project's Slack group). The project was recoded in C# once Kalelovil took over (in order to work with Unity), so if you want further details on how to write the map parser, I'd suggest seeking out Kalelovil on Reddit (he is active on Slack, so I imagine he is also active on Reddit, but I haven't checked).

I'd share my own code, but I use several classes and several files to generate my (now-obsolete) 2D maps, and honestly it would be extremely cumbersome to paste and format all that code (several hundred lines). This is pretty memory intensive, and it can be graphically intensive depending on the number of provinces you want to display, but it would be perfect for a game with only 20 or so provinces. You can use shaders to decrease granularity.

A third option would be to fork this Github project and use it to generate a 2D mesh for each province from a vector graphics file from path's. The linked file only handles the MoveTo and LineTo commands, but it can be easily modified to support Horizontal and Vertical commands. Other, more complex commands (Bezier curves and arcs) are going to be harder to implement, but are still within the realm of possibility.

Finally, as a last resort, if you don't mind paying large sums of money, the Unity Asset developer, Kronnect, has an entire string of (admittedly expensive, but extremely well-maintained and well-supported) assets that would definitely cover any and all map needs you might have. I personally own a copy of their World Political Map 2D Edition and their World Map Strategy Kit, and they both run like a charm. All the bottlenecks I have encountered (aside from the occasional bug which is usually fixed in a Beta within hours to a day of my report) have been in my code.
> 2 votes

---
Tags: unity, c#, maps, strategy
---


# Question
Title: Why does a translation matrix need extra row?
Following recommendation of this answer I've recently read the series of articles of Wolfire about linear algebra. I'm somewhat familiar with matrices and I came to a conclusion that vector and a matrix multiplication is in fact multiplication of 2x2 and 2x1 matrices:

\begin{equation\*} \begin{bmatrix} a & c \\ b & d \end{bmatrix} \qquad \begin{bmatrix} x \\ y \end{bmatrix} \end{equation\*}

In the article the author reveals that to accomplish translation in addition to rotation we need to add a row and a column to the translation matrix:

> If we want to translate by a vector (e,f), we can just tack it onto our change-of-basis matrix like this: \begin{bmatrix} a & c & e\\ b & d & f\\ 0 & 0 & 1 \end{bmatrix} And then we add an extra  to the end of each position vector like this: \begin{bmatrix} x\\ y\\ 1 \end{bmatrix}

*P.S. I edited the direction of the vector to make it comply with matrix multiplication conditions.*

The 1 at the third row of the vector is totally understandable: to multiply 2x3 matrix we need a 3-row matrix.

What I didn't get here is why we need extra row for translation matrix? I can't see any difference in multiplication (except for the useless 1):

\begin{equation\*} \begin{bmatrix} a & c & e\\ b & d & f\\ 0 & 0 & 1 \end{bmatrix} * \begin{bmatrix} x\\ y\\ 1 \end{bmatrix} = \begin{bmatrix} ax + cy + e\\ bx + dy + f\\ 0 + 0 + 1 \end{bmatrix} \end{equation\*}

\begin{equation\*} \begin{bmatrix} a & c & e\\ b & d & f\\ \end{bmatrix} * \begin{bmatrix} x\\ y\\ 1 \end{bmatrix} = \begin{bmatrix} ax + cy + e\\ bx + dy + f\\ \end{bmatrix} \end{equation\*}

So the same question for 3D matrices, just it's easier to convey with a 2D case

# Answer
> 2 votes
If you're doing all your transformation with a single matrix, and you don't need to do any other computation with that matrix or the output vectors, then you're right, you don't need the extra row.

But if you want to transform a vector in stages, then the extra row helps. Imagine this:

```
v2 = MatrixA * v1
v3 = MatrixB * v2

```

If `MatrixA` & `MatrixB` are 2x3 matrices, then even if `v1` is a 3-vector, the multiplication by `MatrixA` squashes the result `v2` down to a 2-vector. Now it doesn't have enough entries to multiply by `MatrixB` for the second step of the computation.

The same thing happens if we want to concatenate matrices:

```
MatrixC = MatrixB * MatrixA
v3 = MatrixC * v1

```

Here `MatrixA` isn't the right shape to multiply with `MatrixB`, so we can't express their combination as a third matrix.

And we run into similar problems if we need the inverse of a matrix at any point, to un-transform a vector. The inverse is only strictly defined for square matrices.

So, adding this extra row helps us preserve the extra translation dimension through multiple chained operations, and lets our math proceed in a more uniform way, whether we're working backwards or forwards, through one matrix or several.

Now, just because the third row is there mathematically doesn't necessarily mean we need to store it and compute it literally. Some game & graphics math libraries will still just store the preceding rows, and structure their multiplication methods "as though" an extra row (0, 0, ..., 1) were present, without explicitly storing or multiplying by all those zeroes & the final one.

---
Tags: matrix, transformation
---


# Question
Title: How do I make gameobject flip and change position when player is facing left?
I attached a a gameobject labeled "Gun" to my player's back and when the player is facing left I want the Gun to continue to look like it's still attached to his back. Right now when I play the game and the player is facing left, the gun stays in the same position it was in regardless of what direction the player is facing. How do I make the gun look like it's still on the players back if facing left? (sorry if it sounds like idk what i'm doing... I'm sorta new to game dev.)

# Answer
make the weapon child of player and set weapon `order in layer = 1`

then you can do `Scale X` or `Rotate Y` to achieving flip effect.

```
void Flip(){
    Vector2 scale = transform.localScale;
    scale.x *= -1;
    transform.localScale = scale;
}

/* another method
    void Flip(){
        Vector2 currentRotation = transform.eulerAngles;
        currentRotation.y += 180;
        transform.localEulerAngles = currentRotation;
    }
*/

```

If you want to know player is facing left or right you can do this:

```
 private bool facingRight;

 float h = Input.GetAxisRaw("Horizontal");
 if(h > 0 && facingRight){
 Flip();
 }else if(h < 0 && !facingRight){
 Flip();
 }

void Flip(){
    facingRight = !facingRight;
    Vector2 scale = transform.localScale;
    scale.x *= -1;
    transform.localScale = scale;
}

```
> 1 votes

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


# Question
Title: Why does my gameobject fly of into the air when the screen is touched?
I am encountering a peculiar problem when updating a piece of code that translates my gameobject left and right based on mobile touch input.

To provide context, the platform upon which the gameobject, which is a sphere in my case, translates, is this:

The platform is 10 units wide, with the sphere in the center.

In its original form, the code looks like this:

```
void FixedUpdate () {
    if(Input.touchCount == 1) {
        float touchXComponent = Input.GetTouch(0).deltaPosition.x;
        transform.Translate(Vector3.right * Time.smoothDeltaTime * touchXComponent * 0.5f);
    }
}

```

It provides the desired left and right movement, but it has a tendency to allow the ball to leave the platform, and then start moving up and down in the air with each further touch.

To combat that, I tried editing the code as follows:

```
void FixedUpdate(){
    if (Input.touchCount == 1){
        float touchXComponent = Input.GetTouch(0).deltaPosition.x;
        transform.Translate((Vector3.right * Time.smoothDeltaTime * touchXComponent * 0.5f).x, transform.position.y, transform.position.z);
    }
}

```

This, however, causes the ball to fly of the screen the second it is touched, leaving me with this error in the console:

```
Assertion failed: Invalid worldAABB. Object is too large or too far away from the origin.

```

I would have thought that the update I made to the code would keep the ball stationary on the y and z-axes, while allowing it to translate freely on the x-axis. Why is that not the case?

Thank you.

# Answer
> 0 votes
As this doc says :

> If relativeTo is left out or set to Space.Self the movement is applied relative to the transform's local axes.

Which means you're actually translating your object by it's own position every update. To avoid that just change your call to :

```
transform.Translate((Vector3.right * Time.smoothDeltaTime * touchXComponent * 0.5f).x, 0, 0);

```

# Answer
> 0 votes
From what I understand, you want the ball to move on the X axis only, relative to world coordinates. The current method you're using will do it in the local coordinates (relative to the object).

Since Transform.Translate method already gives you this functionality, you can just change your line from

```
transform.Translate((Vector3.right * Time.smoothDeltaTime * touchXComponent * 0.5f).x, transform.position.y, transform.position.z);

```

to

```
transform.Translate((Vector3.right * Time.smoothDeltaTime * touchXComponent * 0.5f).x, transform.position.y, transform.position.z, Space.World);

```

and it should work in theory (I don't have access to Unity right now).

---
Tags: unity, movement, input, transformation, touch
---


# Question
Title: Registering a C++ callback with Lua API without additional libraries
Basically, I'm trying to register a callback into a Lua state like this:

```
class MyClass
{
    public:
        int myLuaFunction(lua_State* L)
        {
            //do something
        }

};

```

I want to be able to call MyClass::myLuaFunction of a given instance (which could register itself).

I've spent a couple hours trying to do tricks with templates and lambdas in an attempt to get it to work, but I haven't got anything successful (mainly the fact that I couldn't pass a lamba function that uses parent scope variables to Lua's API).

Without having to download any other libraries (just Lua's standard interpreter implementation), how could I do this?

# Answer
While a non-capturing lambda function can be converted into a free function pointer, a capturing one can not, which you've discovered.

The generic approach to using member functions as callbacks is a common problem and is typically resolved via thunking or trampolines.

In short, you make a static/free function which compatible with the mandated interface, and hide a pointer to the object you want to call it on in user-specified data. The function body would extract this object and make a call to the actual member function, forwarding the parameters and return values.

You can fiddle around with templates and member function pointers to get a single thunk function template that can dispatch to functions with a particular arity, but then you've reinvented most of luabind or similiar libraries.

An example in a fictional interface:

```
typedef int (*Fn)(State*);
void RegisterFn(Fn fn, void* userData);
void* GetUserData(State* state);

struct S {
    int f(State*);
};

int SfThunk(State* state) {
    void* userData = GetUserData(state);
    S* obj = (S*)userData;
    return obj->f(state);
}

S s;
RegisterFn(&SfThunk, &s);

```
> 1 votes

# Answer
Push `this` as a light uservalue when pushing the callback as a closure and make it an upvalue:

```
class MyClass
{
    public:
        int myLuaFunction(lua_State* L)
        {
            //do something
        }

        static int myLuaFunctionCallback(lua_State* L){
            lua_getupvalue(L, lua_upvalueindex(1)); //pushes the light userdata
            MyClass* obj = static_cast<MyClass*>(lua_touserdata(L, -1)); //gets the value of the user data
            lua_pop(L); //pop userdata
            obj->myLuaFunction(L); //call actual function
        }
};

```

and to register the callback you do:

```
lua_pushlightuserdata(L, obj);
lua_pushcclosure(L, MyClass::myLuaFunctionCallback, 1);

```
> 0 votes

---
Tags: c, lua, c++
---


# Question
Title: Why is OpenGL displaying this specific color as white?
I have a sprite class that is supposed to make a 2D rectangle based on the location, colour and size of the rectangle. I have created a renderer class that uses this sprite class to create buffers and finally render things on the screen.

Currently, I have 2 sprites.

```
/**
 * RSprite sprite(x coordinate of the lower left corner of the rectangle,
 *                y coordinate of the lower left corner of the rectangle,
 *                horizontal length of the rectangle,
 *                vertical length of the rectangle,
 *                Vector 4D consisting of 4 floats representing a colour(RGBA)) for the rectangle
 */
RSprite sprite1(0, 0, 4, 4, Vector4D(0.75f, 0.047f, 0.9f, 1.0f)
                         /* ^Normalised form of (193, 12, 232, 255)rgba */);

RSprite sprite2(0.5, 0.5, 0.5, 0.5, Vector4D(0.6f, 0.0f, 1.0f, 1.0f));
                                 /* ^Normalised form of (153, 0, 255, 255)rgba */);

```

Now I add these sprites to a group, which is just a structure maintaining a vector array of these sprites.

```
Group * g = new Group();
g->addRenderable(&sprite2).addRenderable(&sprite1);

```

Finally, I add this group to a layer object I had made earlier.

```
layer0.addGroup("group1", *g);

```

Now my problem is the colour specified for `sprite1` i.e. (193, 12, 232, 255)rgba is appearing completely white(which is not what I intended it to be). However, the other `sprite2` has the colours appearing just fine.

Concludingly, the problem is boiled down to, why is OpenGL not displaying 193, 12, 232, 255rgba incorrectly but at the same time it is correctly displaying 153, 0, 255, 255rgba?

EDIT: Adding code samples. Implementation of the layer class I am using:

```
RStaticLayer::RStaticLayer(RShaderComponent& shader)
        : m_Renderer(new RGuerrillaRendererComponent()), m_Shader(shader)
    {
        m_Shader.enableShader();
        m_Shader.setUniformMat4("proj_matrix", (const RML::Matrix4) RML::Matrix4::orthographic(0.0f, 16.0f, 0.0f, 9.0f, -1.0f, 1.0f));
        m_Shader.disableShader();
    }

    RStaticLayer::~RStaticLayer()
    {
        delete m_Renderer;
    }

    RLayer & RStaticLayer::addGroup(std::string name, Group & group)
    {
        m_Groups[name] = &group;

        return *this;
    }

    void RStaticLayer::draw()
    {
        m_Shader.enableShader();

        m_Renderer->begin();
        for(auto group = m_Groups.begin(); group != m_Groups.end(); group++)
        {
            for(auto renderable = group->second->renderables.begin(); renderable != group->second->renderables.end(); ++renderable)
            {
                m_Renderer->submit(*renderable);
            }
        }
        m_Renderer->end();
        m_Renderer->flush();

        m_Shader.disableShader();
    }

    void RStaticLayer::removeGroup(std::string name)
    {
        m_Groups.erase(name);
    }

```

What the m\_Renderer.submit(), begin(), end() and flush() do:

```
void RGuerrillaRendererComponent::begin()
    {
        GLCall(glBindBuffer(GL_ARRAY_BUFFER, m_VBO));
        GLCall(m_Buffer = (VertexData *) glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY));
        m_IndexCount = 0;
    }

    void RGuerrillaRendererComponent::submit(const RRenderableObject * renderable)
    {
        const RML::Vector3D & position = renderable->getPosition();
        const RML::Vector2D & size = renderable->getSize();
        const RML::Vector4D & color = renderable->getColor();

        m_Buffer->vertex = position;
        m_Buffer->color = color;
        m_Buffer++;

        m_Buffer->vertex = RML::Vector3D(position.x, position.y + size.y, position.z);
        m_Buffer->color = color;
        m_Buffer++;

        m_Buffer->vertex = RML::Vector3D(position.x + size.x, position.y + size.y, position.z);
        m_Buffer->color = color;
        m_Buffer++;

        m_Buffer->vertex = RML::Vector3D(position.x + size.x, position.y, position.z);
        m_Buffer->color = color;
        m_Buffer++;

        m_IndexCount += 6;
    }

    void RGuerrillaRendererComponent::end()
    {
        GLCall(glUnmapBuffer(GL_ARRAY_BUFFER));
        GLCall(glBindBuffer(GL_ARRAY_BUFFER, m_VBO));
    }

    void RGuerrillaRendererComponent::flush()
    {
        GLCall(glBindVertexArray(m_VAO));
        m_IBO->bindIndexBuffer();

        GLCall(glDrawElements(GL_TRIANGLES, m_IndexCount, GL_UNSIGNED_SHORT, NULL));

        m_IBO->unbindIndexBuffer();
        GLCall(glBindVertexArray(0));

        m_IndexCount = 0;
    }

```

What my shader enable/disable functions look like:

```
void RShaderComponent::enableShader() const
    {
        GLCall(glUseProgram(m_ShaderID)); // m_ShaderID is acquired successfuly. It has been used in another project too.
    }

    void RShaderComponent::disableShader() const
    {
        GLCall(glUseProgram(0));
    }

```

Pardon the GLCall() macro. It's just a pre-v4 error checking macro.

# Answer
> 1 votes
I'm not sure the code samples you've shown have a logic error, but I have a couple observations:

1) it's possible you meant to use `Vector4f` instead of `Vector4D` based on the comment `// Vector 4D consisting of 4 floats representing a colour(RGBA)`, and you're actually passing in 2 doubles instead of 4 floats as the parameters. This wouldn't result in a white output though.

2) Is some part of your code passing in the 0-255 byte values instead of floats? I noticed that in your screenshot even the "just fine" (0.6, 0, 1.0) color looks to be completely cyan (0, 1.0, 1.0).

3) related to the above, what is the pixel format for your framebuffer? It looks like some of your channels are mixed up, and possibly a mismatch in the format and bit depth could be causing your issues.

# Answer
> 0 votes
Are you using the correct blending function? For simple 2D games, it's usually the normal blending function:

```
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

```

# Answer
> 0 votes
The frame buffer format is not matching the attribute pointer format that the renderer is setting. I had this in my code:

```
glVertexAttribPointer(SHADER_COLOR_LOCATION, 4, GL_UNSIGNED_INT, GL_FALSE, VERTEX_SIZE, (const GLvoid *) (offsetof(VertexData, VertexData::color)));

```

Notice the GL\_UNSIGNED\_INT that I was passing in. Mistook it to be an index buffer for a second I guess. However, I fixed it by replacing it with the correct data type that I was using for my colour buffer i.e. float.

```
glVertexAttribPointer(SHADER_COLOR_LOCATION, 4, GL_FLOAT, GL_FALSE, VERTEX_SIZE, (const GLvoid *) (offsetof(VertexData, VertexData::color))));

```

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


# Question
Title: Toggle action for gamepad triggers, whilst being held down
I'm doing a small fighting game project, as up now every button command in my map code is occupied with their designated functions. All except the triggers; as up now they only have their basic "press n hold" actions assigned; "sidestep" for the \[LT\] and "jump/fly" for the \[RT\].

However there are still two more actions that I would like to implement to the triggers "if possible"; they being, "Block" for the \[LT\] and "Fly up" for the \[RT\].

That being said, is it possible to somehow, add a "tap toggle action" to the triggers while they're still being held? If yes please let me know.

---

**For Tom Tsagk:** Yes, I'm trying to cause an event while holding down a button "this case a trigger", but 'not' by pressing another button for the execution, "since every other button is occupied doing something else".

What I'm trying to attempt is: when holding a trigger down, to be able to give small "taps" to the trigger without the need let go.

# Answer
You should consider doing the opposite of what you're suggesting: using your triggers to enter quasimode and your buttons to produce actions.

If you did that, it would considerably expand your available action vocabulary. You could have a Defense mode (LT) which would transform your actions, for instance Attack would become Block and Jump would become Dodge. Similarly, RT could enter the Flying mode and transform your actions into aerial versions.

Note that you would gain a new quasimode for free! Maintaining LT + RT would give access to aerial defense moves. If you feel you want to expand your design, of course, otherwise, the last quasimode selected would cancel the previous one.

Using this approach, you could add a lot of depth and skill to a combat system, maybe having combos that require quick quasimode switching, while keeping the responsiveness of face buttons that are less "squishy" than triggers.
> 1 votes

---
Tags: game-design, input
---


# Question
Title: FixedUpdate is Being Called Less and Less Over Time...Why?
My game is still in the very early stages, but basically I have an enemy that follows the player if it can see them and will continue to follow the player for a few seconds after the player leaves its sight. This works fine, except that the enemy moves slower and slower the more it moves.

I put a Debug.Log within FixedUpdate that logs the enemies movement and the more the enemy moves, the less often the Debug.Log is logged in the console, until eventually the enemy is pretty much at a stand-still. Sooo basically I think this means that FixedUpdate is being called more and more slowly over time.

Anyone have any ideas why this is happening? It's driving me crazy! Is there a problem with the way I'm applying force to move the enemy? Most of this code is from a tutorial that I followed.

Here's my code (I'm using A\* Pathfinding btw):

```
using UnityEngine;
using System.Collections;
using Pathfinding;

[RequireComponent(typeof(Rigidbody2D))]
[RequireComponent(typeof(Seeker))]

public class EnemyMovement : MonoBehaviour {

 // What to chase
 public Transform target;

 // How many times each second we will update our path
 public float updateRate = 2f;

 // Caching
 private Seeker seeker;
 private Rigidbody2D rb;

 // The calculated path
 public Path path;

 // The AI's speed per second
 public float speed = 300f;
 public ForceMode2D fMode;

 [HideInInspector]
 public bool pathIsEnded = false;

 // The max distance from the AI to a waypoint for it to continue to the next waypoint
 public float nextWaypointDistance = 1f;

 // The waypoint we are currently moving towards
 private int currentWaypoint = 0;

 private bool searchingForPlayer = false;

 public bool stillSearching = false;

 public bool facingRight = true;

 float horizontalVelocity;

 float timer = 0f;

 public float continueSearchingTime = 15f;

 Vector3 enemyLocation;

 Player player;
 EnemySenses enemySenses;

 public static EnemyMovement instance;

 void Awake()
 {
     if (instance == null)
     {
         instance = this;
     }
 }

 void Start()
 {
     player = Player.instance;
     enemySenses = EnemySenses.instance;

     enemyLocation = transform.localScale;

     seeker = GetComponent<Seeker>();
     rb = GetComponent<Rigidbody2D>();

     if (target == null)
     {
         if (!searchingForPlayer)
         {
             searchingForPlayer = true;
             StartCoroutine(SearchForPlayer());
         }
         return;
     }

     // Start a new path to the target position, return the result to the OnPathComplete method
     seeker.StartPath(transform.position, target.position, OnPathComplete);

     StartCoroutine(UpdatePath());
 }

 void FixedUpdate()
 {
     if (target != null && player.isDead == true || target != null && enemySenses.CanPlayerBeSeen() == false && stillSearching == false)
     {
         searchingForPlayer = false;
         return;
     }
     else if ((target != null && stillSearching == true && enemySenses.CanPlayerBeSeen() == false) || (target != null && stillSearching == false && enemySenses.CanPlayerBeSeen() == true))
     {
         if (!searchingForPlayer)
         {
             searchingForPlayer = true;
             StartCoroutine(UpdatePath());
         }
     }
     else if (target == null)
     {
         if (!searchingForPlayer)
         {
             searchingForPlayer = true;
             StartCoroutine(SearchForPlayer());
         }
         return;
     }

     if (path == null)
         return;

     if (currentWaypoint >= path.vectorPath.Count)
     {
         if (pathIsEnded)
             return;

         // Debug.Log("End of path reached.");
         pathIsEnded = true;
         return;
     }
     pathIsEnded = false;

     // Direction to the next waypoint
     Vector2 dir = (path.vectorPath[currentWaypoint] - transform.position).normalized;
     dir *= speed * Time.fixedDeltaTime;

     // Move the AI
     rb.AddForce(dir, fMode);

     // Debug.Log("Dir: " + dir);

     float dist = Vector3.Distance(transform.position, path.vectorPath[currentWaypoint]);
     if (dist < nextWaypointDistance)
     {
         currentWaypoint++;
         return;
     }
 }

 void LateUpdate()
 {
     Flip();
 }

 void Flip()
 {
     horizontalVelocity = rb.velocity.x;

     if (facingRight == true && horizontalVelocity < -.10) // Facing right and moving left
     {
         enemyLocation.x *= -1;
         transform.localScale = enemyLocation;
         facingRight = false;
     }
     else if (facingRight == false && horizontalVelocity > .10) // Facing left and moving right
     {
         enemyLocation.x *= -1;
         transform.localScale = enemyLocation;
         facingRight = true;
     }
 }

 IEnumerator SearchForPlayer()
 {
     GameObject searchResult = GameObject.FindGameObjectWithTag("Player");
     if (searchResult == null)
     {
         yield return new WaitForSeconds(0.5f);
         StartCoroutine(SearchForPlayer());
     }
     else if (player.isDead == false)
     {
         target = searchResult.transform;
         searchingForPlayer = false;
         StartCoroutine(UpdatePath());
         yield return false;
     }
 }

 IEnumerator UpdatePath()
 {
     if (target == null)
     {
         if (!searchingForPlayer)
         {
             searchingForPlayer = true;
             StartCoroutine(SearchForPlayer());
         }
         yield return false;
     }

     // Start a new path to the target position, return the result to the OnPathComplete method
     seeker.StartPath(transform.position, target.position, OnPathComplete);

     yield return new WaitForSeconds(1f / updateRate);
     StartCoroutine(UpdatePath());
 }

 public void OnPathComplete (Path p)
 {
     // Debug.Log("We got a path. Did it have an error? " + p.error);
     if (!p.error)
     {
         path = p;
         currentWaypoint = 0;
     }
 }

 IEnumerator OnTriggerExit2D()
 {
     stillSearching = true;

     while (timer < continueSearchingTime)
     {
         yield return new WaitForSeconds(1f);
         timer++;
         // Debug.Log("Timer: " + timer);
     }

     if (timer >= continueSearchingTime)
     {
         stillSearching = false;
     }
 }

 void OnTriggerEnter2D()
 {
     timer = 0.0f;
     stillSearching = false;
 }
 }

```

# Answer
> 1 votes
My first guess is your coroutine. Having a coroutine in any update sequence could result in this type of behavior if it's getting inside somehow.

I would suggest taking a peak at your profiler and see what script is bogging the game, you should be able to spot the problem with your scripts in there.

Edit:

I took another look. You're calling a the same coroutine inside the coroutine which would cause a memory leak over time if not careful.

If you want to loop over your game searching for the character use a while look and start a single coroutine at the start function. It's not a great idea to do it this way, but that would probably solve your delay issues. You've done something similar with your OnTriggerExit2D.

Also your OnTriggerExit2D should not be a coroutine, do this instead

```
void OnTriggerEnter2D(Collider2D other){

     if(other.name == "Player")
         playerInZone = true;
 }

```

---
Tags: unity, 2d, movement, ai, path-finding
---


# Question
Title: What are the differences between random encounters and permanent mobile enemies?
**Random Encounter:**

A player has a 10% chance to encounter an enemy. while moving through a 5x5 grid.

**Permanent Mobile Enemies:**

There is one enemy that constantly moves through the 5x5 grid and only encounters the player when they land on the same grid. Also, both the enemy and the player cannot see each other until they meet.

Obviously, the random encounter will give better performance, but are there any benefits through implementing the second option?

# Answer
The probability distribution is slightly different because your previous moves influence the probability of finding the invisible enemy - the difference probably isn't that noticeable for 5x5 areas, but is very pronounced in a small narrow 1x5 area -- you will always encounter the invisible enemy once since there's no way to bypass it, but for the "random chance in every move" strategy, you'd sometimes not encounter any enemy, or sometimes encounter more than one enemy.
> 2 votes

# Answer
The second option gives you a deterministic number of opponents the player will face (within a range); as in 0-1 in your case. In the case of Random Encounters, one player may hit as many as 5 if you don't cap it; while they would likely have a smaller chance of hitting 0.

The main benefits I can see is it allows you to:

* Have cool items that maybe temporarily reveal where the thing *was* or *is*, giving depth of gameplay
* It can be used on particularly tough opponents, encouraging the player to find those items, but they don't have to. This allows the player to make a meaningful decision: "Should I search for items X or Y or should I gear up for a massive fight?"
* Having it "hunt" the player a bit, maybe the player "makes noise" when they move or similar, allowing further depth of gameplay where moving slower, skirting the edge, etc. allows you to dodge it with better; possibly with a "throwing rocks" mechanic that Far Cry and similar games had

I can't think of anything outside of these types of mind-games and decisions that it allow. Remember that Games are a 'Series of Interesting Decisions', so when implementing a thing; see if it affects the gameplay in a way that affects decision making. If not, you can consider removing it; simplifying it; or adding decision making to make it more interesting.

The above Lures, Monster-Finders, etc.. may all be single use things; allowing you to skip one of a number of fights; making which ones you do meaningful. Additionally, being "hunted" and having things assist you with that adds a lot of atmosphere, where random encounters are just there for grinding and simplification of development.
> 1 votes

# Answer
Supplementing Jimmy's answers which I agree with.

Benefits of random encounters:

* Better control of the number of encounter per time unit.
* Invisible process, so it may be tweaked dynamically without the player noticing (e.g. you may put a cap on the number of encounters per area or automatically trigger an encounter after a certain amount of time if none had occurred).
* It can also be tweaked to reflect the difficulty of the game or an area with only one parameter.

Drawbacks of random encounters:

* It feels... random ;) If your game is not about grinding, it may feel like random encounter interrupt the flow of gameplay or the player's plans.
* If you don't supervise the randomness as suggested above, can create very unbalanced experiences (too few or too many encounters).

Benefits of mobile enemies:

* Encounters can be anticipated and even avoided if the terrain lets the player move around them. It's a great way to give the player a sense of control, even if they find an enemy in a corridor (they have the time to craft items, review the characters, save, etc.).
* You can have a visual representation of difficulty: an area crawling with encounters, a lone enemy that can be avoided but looks XP/loot-worthy, etc.
* You can add gameplay to the map level. Maybe the different enemies have different speeds, movement behaviors (chasing, defending a place, flocking, etc.), movement capacities (flying, crossing water, etc.). Maybe the player can affect the enemies' behaviors on the map: dropping an object that lures them or using a capacity that repels them; creating barriers (fire, magic); summoning or dispelling enemies; etc.

Drawbacks of mobile enemies:

* It's a lot of work, both in terms of assets and programming. Make sure that it's worth your efforts for the player.
* It'll be harder to scale difficulty and forced encounters can feel like railroading.
> 0 votes

---
Tags: game-design, performance, game-mechanics, random
---


# Question
Title: ds_map_find_value returning number instead of array
Currently messing around on how to make a text engine in GameMaker and figured I would hold all my conversations in JSON format stored in a *.txt* file, which I'll convert into a *ds\_map* and draw the text using the screen to the map.

Here's the JSON:

`{"Neku": ["Hey Shiki.","Just trying to make this text engine thingy.","I really hope it works!"],"Shiki": ["Hey Neku! Long time no see!","What's up?","Wow thats cool!","I believe in you Neku!"]}`

And here is the code I added into the create section of an empty object in a room:

```
str = ""
file = file_text_open_read("convo.txt")
str = file_text_read_string(file)
file_text_close(file)
map = json_decode(str)
if(ds_map_exists(map,"Shiki")) show_debug_message("A map exists") else show_debug_message("No map exists")
lst = ds_map_find_value(map,"Neku")
show_debug_message("What is lst?: " + string(typeof(lst)))

```

Now when I look at my console I see that a map does exist and the type of `lst` is shown to be a number and not an array as I had hoped. If I remove the `[]` in the JSON and just have one key-value pair the text shows up. If anyone could point me in the proper direction here I'd be grateful, apologies if this is a redundant stupid question.

# Answer
Of course `lst` is not an array, because it is a *ds\_list* data structure. From the documentation about JSON decode:

> If the JSON to be decoded requires a hierarchy of lists and maps \[...\] these are decoded too \[...\] using the following rules \[...\]:
>
> * Json is a single value - returns a *ds\_map* with a single entry "default" that is the value
> * Json is an array of objects or values - returns a *ds\_map* with a single entry "default" that is a *ds\_list* of the objects or values
> * Json is an object - returns a *ds\_map* that has the object entries in it

Since your JSON keys have arrays as corresponding value (second case above), they cannot be decoded directly into an array, instead they are stored as a *ds\_list* \- I guess because it is way more versatile to return as result rather than a simple array.

I'm not sure why the result of `typeof(lst)` is "number", though GameMaker always warns us that dealing with dynamic data structure is our own concern when it comes to writing/reading values and freeing memory, so I'm not surprised I can't be told whether a variable is a data structure or not.

This said, after you call `lst = ds_map_find_value(map,"Neku")` you have a full-working *ds\_list* where values are stored exactly as you defined in the JSON string. After assigning `lst`, if you call:

```
show_debug_message(ds_list_find_index(lst, 0));

```

the result will be:

> Hey Shiki.

which is the first value in the array referenced by the label "Neku". Values order is always preserved. You can iterate through the *ds\_list* to read the values, or just go full `ds_list_*()` functions, so you don't have to hardcode strings and can even use text files dynamically.

At the bottom of the JSON decode doc page there's a nice code snippet showing how to read data from a JSON string with multiple arrays saved internally.
> 0 votes

---
Tags: game-maker, text, json
---


# Question
Title: How can I start the game with a random formation?
```
public class SquadFormation : MonoBehaviour
{
    enum Formation
    {
        Square, Circle, Triangle
    }

    [Header("Main Settings")]
    public Transform squadMemeberPrefab;
    public int columns = 4;
    [Range(4, 100)]
    public int numberOfSquadMembers = 20;
    public float yOffset = 0;
    [Range(1, 20)]
    public int numberOfSquads = 1;
    [Space(5)]
    [Header("Formations")]
    public int squareSpace = 10;
    public int circleSpace = 40;
    [Range(3,50)]
    public float moveSpeed = 3;
    public bool randomSpeed = false;
    [Range(3, 50)]
    public float rotateSpeed = 1;
    public float threshold = 0.1f;
    public bool destroySquad = false;
    public string currentFormation;
    public bool startRandomFormation = false;

    private Formation formation;
    private List<Quaternion> quaternions = new List<Quaternion>();
    private List<Vector3> newpositions = new List<Vector3>();
    private bool move = false;
    private bool squareFormation = false;
    private List<GameObject> squadMembers = new List<GameObject>();
    private float[] step;
    private int[] randomSpeeds;
    private int index = 0;
    private int numofobjects = 0;

    // Use this for initialization
    void Start()
    {
        numofobjects = numberOfSquadMembers;
        if (startRandomFormation)
        {
            formation = UnityEngine.Random.Range(1, 3);
        }

```

In this case I have 3 formations. But it might later more or less formations. Making this line is has no sense:

```
formation = UnityEngine.Random.Range(1, 3);

```

The idea is to start randomly with one of the 3 formations.

How can I get the number of formations ? The count in the enum ? And how can I select randomly one formation ?

# Answer
This question essentially boils down to "how do I get the number of elements in an enum in C#", which is already answered on stackoverflow:

```
Enum.GetNames(typeof(Formation)).Length;

```

But I would recommend a different approach than an enum for this situation.

Your formations are certainly more than just an integer. A formation is actually a list of positions, and maybe even some information about how members of the formation behave at runtime. That means it might make sense to create a `class Formation` which contains all data and code specific to each formation. You can then have a `Formation[] possibleFormations` in your `SquadFormation` class.

You could even go one step further and make `SquadFormation` a `ScriptableObject`. That way you can create new squad formations as assets, edit them in a custom-made editor and assign them to your `SquadFormation` game objects using the inspector.
> 2 votes

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


# Question
Title: libgdx ashley how to detect clickEvent on Entity
How can I detect a click event on an Entity?
I use libgdx with Ashley.
Must I implement it by my self e.g. in touch down method of InputProcessor test if any entity is on this click position.
Or exist already a listener for Entity like the ClickListener for Actor in libgdx?

Thanks for your advice

# Answer
As far as I know Ashley does not have any pre-built systems that would handle click events and map them to entities.

A simple clickable system could easily be created using a clickable component and clickable system.

# An example with an OrthographicCamera:

The clickable component with the rectangle bounds

```
public class ClickableComponent implements Component{
    public Rectangle bounds = new Rectangle(0,0,10,10);
}

```

A Transform component to store location

```
public class TransformComponent implements Component{
    public final Vector3 position = new Vector3();
}

```

With a Clickable System

```
public class ClickableSystem extends IteratingSystem{

    private ComponentMapper<ClickableComponent> cc;
    private ComponentMapper<TransformComponent> tc;
    private OrthographicCamera camera;

    @SuppressWarnings("unchecked")
    public ClickableSystem(OrthographicCamera cam) {
        super(Family.all(ClickableComponent.class,TransformComponent.class).get());
        cc = ComponentMapper.getFor(ClickableComponent.class);
        tc = ComponentMapper.getFor(TransformComponent.class);
        camera = cam;
    }

    @Override
    protected void processEntity(Entity entity, float deltaTime) {
        ClickableComponent click = cc.get(entity);
        TransformComponent transform = tc.get(entity);

        //update click bounds
        click.bounds.x = transform.position.x;
        click.bounds.y = transform.position.y;

        if(Gdx.input.isButtonPressed(Buttons.LEFT)){
            // touching
            Vector3 clickPosition = camera.unproject(new Vector3(Gdx.input.getX(), Gdx.input.getY(),0));
            System.out.println(clickPosition+":"+click.bounds.toString());
            if(click.bounds.contains(clickPosition.x, clickPosition.y)){
                //object clicked
                //do your thing
                System.out.println("Touched"+entity.toString());
            }
        }
    }
}

```
> 3 votes

---
Tags: libgdx, input, ashley
---


# Question
Title: How to implement Lua thread for Sleep function
I am running into a problem in my game engine right now. I want to be able to call Sleep(number\_of\_seconds) from .lua file (1 only) and halt the execution of the lua file, WHILE the game is running and rendering / updating. When the sleep is done, the .lua file will return execution. Is this possible? All the best, Aldo

p.s. I guess this can be implemented with C++ `<thread>`but I couldn't find a solution for now:/

# Answer
Make the lua script a coroutine and have sleep yield

```
if(now()-timestamp > sleepDuration){ // overflow-proof timeout check
    int oldtop = lua_gettop(L);
    int yielded = lua_resume(L, NULL, 0);
    if(yielded == LUA_YIELD){
        lua_pop(L, lua_gettop(L) - oldtop - 1); //only keep timeout value
        sleepDuration = luaL_checkinteger(L, -1);
        timestamp = now();
        lua_pop(L, 1); //pop timeout
    }
}

```

You can have `sleep()` yield multiple values so other wakeup reasons are possible. You can also pass that wakeup reason as a parameter to resume in so the script knows what woke it up.
> 1 votes

---
Tags: c++, lua
---


# Question
Title: Unity: Moving on global X and Z axes with respect to local Y rotation
I'm having a bit of trouble with the math on this.

I'm trying to move an object forward based on it's local yaw. Ordinarily, I'd just move it forward on the Z axis locally:

```
body.velocity = transform.TransformDirection (new Vector3 (0f, 0f, forward_velocity));

```

However, I need it to ignore the object's pitch and roll. I don't want the Y coordinates to change. It needs to move forward flatly across the X/Z plane based on its Y rotation only, even if its X and Z rotations are non-zero.

I tried doing this the way I would do it in 2D (by calculating how far it would need to move on X and Z separately), but the results are completely wrong. The object moves on the x/z plane, but only along a single path, regardless of it's yaw.

```
Vector3 rotation = transform.rotation.eulerAngles;
float global_x_speed = forward_speed * Mathf.Cos (rotation.y);
float global_z_speed = forward_speed * Mathf.Sin (rotation.y);
body.velocity = new Vector3 (global_x_speed, forward_velocity, global_z_speed);

```

I tweaked some of these values, thinking I'd made a small mistake (swapping sine and cosine, using body.transform instead of transform), but I only got different weird results.

The last thought I had was that I could move it forward on the local Z and then reposition the Y coordinate to what it was before the translation, but I think that would result in both strange movement speed and strange clipping.

# Answer
One simple solution is to get the forward vector of the transform, set the y-component to zero, then normalize that vector:

```
Vector3 forward = transform.forward;
forward.y = 0;
body.velocity = forward.normalized * forward_velocity;

```

This assumes that the object is never pointing straight up or down, in which case it would not work, since the vector would end up having zero magnitude.
> 2 votes

# Answer
If you don't want Y to change, then the solution is really simple.

1. Record Y coordinates in some variable
2. Move locally
3. Reset Y to the values previously recorded.
> 0 votes

---
Tags: unity, physics, movement
---


title: Aim/Scope Oscillation Algorithm

text:
# Question
Title: Aim/Scope Oscillation Algorithm
I have been struggling to find an algorithm to implement something that will make a direction oscillate within a cone constraint, in a helix-shaped fashion as in photo (it will always go back to the centre after traveling toward the boundaries of the constraint, it doesn't have to hit the max amplitude everytime). Do you know any algorithm that does this?

EDIT: My mind is telling me that this is somehow similar to a gravity pull but I don't know how to ensure that it always goes back to the centre.

# Answer
Using polar coordinates would do the trick. Here’s a graph of the function `r=sin(2.3θ)`, with `θ` going from 0 to 2π:

Given `r` and `θ`, you can convert back to Cartesian (`x`/`y`) coordinates with `x = r cos θ` and `y = r sin θ`. Increase `θ` steadily over time, add the resulting `x` and `y` offsets to your aim direction, and you should have the effect you’re after.
> 2 votes

---
Tags: 3d, geometry, interpolation, trigonometry
---


# Question
Title: Waiting for object's Awake() after loading a new scene synchronously
I have a `GameScene` with an initially active `GameObject` in it, which has a singleton component:

```
public static ObjectiveManager Instance;

public void Awake()
{
    if (Instance != null && Instance != this)
    {
        Log.Info(this.GetType(), "Instance of this class already exists! CRITICAL");
    }

    ObjectiveManager.Instance = this;
}

```

Now, when I call:

```
private void StartGameScene(){
    SceneManager.LoadScene("GameScene");
    ObjectiveManager.Instance.SomeFunction(); // << singleton not initialized
}

```

I get an error, because `ObjectiveManager` is not set to an instance of an object.

As `LoadScene` is a synchronous operation so my guess was that `Awake()` is called immediately, synchronously. As I can see now, it's not.

Is there any way to determine that all of the objects on the scene have their `Awake()` already called, without checking each of them with some custom `IsReady`?

# Answer
From Unity’s docs:

> When using SceneManager.LoadScene, the loading does not happen immediately, it completes in the next frame. This semi-asynchronous behavior \[...\] can be confusing because load does not complete immediately.

So there’s no way to do it synchronously. A coroutine running on an object marked as `DontDestroyOnLoad` would be a simple alternative, although in that case, you may as well use `LoadLevelAsync`:

```
private void StartGameScene(){
    DontDestroyOnLoad(this);
    StartCoroutine(StartGameSceneAsync());
}
private IEnumerator StartGameSceneAsync() {
    yield return SceneManager.LoadSceneAsync("GameScene");
    ObjectiveManager.Instance.SomeFunction(); // << singleton should be initialized now.
    Destroy(gameObject); //Since it would normally be destroyed during level load, I assume you didn’t need this around any more.
}

```
> 1 votes

---
Tags: unity, scenemanager, monobehaviour
---


# Question
Title: How could I give a lifespan to my MMO characters?
A problem I've encountered in some MMO games, is that players congregate around the endgame content, meaning that when a new player joins they are basically playing a solo game until they reach a high enough level to join the other players.

To combat that, I'm considering giving the player characters a finite lifespan. For example making it so that after X hours of gameplay, or once they reach level X, they start losing power instead of gaining it. Then they are encouraged to reincarnate, starting again from level 1 and only carrying over some small subset of their abilities.

My hope is that this will make the early game content (probably randomly generated, to keep it interesting) more useful, and more busy.

My questions is:

How could I implement this to make it appealing to the players?

# Answer
I am a big proponent of some form of character **permadeath** in MMOs so I have some ideas.

MMO's are about progression, reaching ever greater heights but that does not necessarily have to do with your character being an immortal.

## World permanence and group progression.

In most MMOs the world is static while your character is permanent but if you had the real ability to change the world effectively and leave your mark on the world you wouldn't be as dependent on character permanence. Thinks along the lines of Minecraft or EQ: Landmark shaping the world through blocks as well as complex social structures and political factions ala EVE.

Furthermore I propose players to be relegated as citizens of a town/city and be tied as part of that local community. Instead of individual character progress you can have a shared group progress by developing that town like in a RTS game with base construction. Crafting and gear can be tied to the level of development of that town and the facilities present where everyone in the group can pinch in resources to construct new buildings.

Develop a Cathedral and players in that community can unlock more advanced classes like Cardinals and Bishops with powerful abilities.

Ashes of Creation has a similar idea with nodes that develop a region but I don't know how that will turn out.

All players should have an allegiance to one of those towns even if you can migrate there should be limits with some encouragement given to developing new towns in uncharted lands. You would also have a form of reputation and status with that city that would be gone if you migrate.

This is to create a sense of community and belonging.

Your reputation and status hower is not affect by your character's death. Characters are expendable and could be thinked of as units in a RTS. Your are meant to represent multiple lives and generations.

More nefarious players would have bandit or pirate groups with their camps but the same sense of being part of a group.

To me the spirit of community and development of it is much more real permanece in the world then an immortal character the same as the rest of the other immortal characters.

---

## Class Unlocks

I mentioned things like unlocking advanced classes through building things in the city. But class unlocks have potential even beyond that.

Class unlocks can be permanent progress on your account and when you die you can start as that class.

In Warframe crafting a new weapon or warframe can be a whole journey that takes you from place to place.

Unlocking classes can be similarly be a journey that can make you experience many things the game has to offer through it's requirements and achievements as well as having plenty of secrets left to explore.

Reincarnating and advancing as a new class can be a hard reset so that we could get players acclimated that something like death is a normal part of the game.

To advance to a higher potential you need to rest your progress.

---

## Permadeath with lives

Permadeath in a MMO can be tricky, we don't need the purity of Roguelikes where you only have one chance. We can implement a lives system like in the old Mario games.

Every class has a limited number of lives that cannot increase in any way and once they are gone that character permadies.

What is interesting about this is different classes can have different amount of lives with base classes having more than advanced classes. This could have interesting consequences with some class unlocks requirements needing to achieve its goals with one character so it could be a tradeoff between the power and abilities of an advanced class versus the safety net the lives represent for a base class.

Furthermore this system solves the networking and DC issues that a permadeath system represents. One monthly renewed character life can be given for networking issues and other problems that can be contested with a GM and reinstated if the GM finds the issue legitimate through the logs.

---

## Soft Permadeath

This comes from Mordheim:City of the Damned. In that game when a character is knocked out they will get a number of permanent wounds until that character becomes so wondend he becomes useless.

A similar idea could be implemented. On death characters will get a wound that might or might not be healed. Healing could require special resources or other ways of taking care of it. Like having a cyborg arm that has to be crafted.

Ultimately that character will eventually be too expensive or useless to maintain so you roll a new character.

I think this system has its own kind of charm and it would be funny to see pirate like characters with wooden legs, eyepatches and a hook for a hand.

And the demand for "alternative" gear would be interesting in a crafting economy.
> 5 votes

# Answer
---

## What to keep between incarnations

Keeping in mind that the person playing is the same, and we cannot make the real person playing forget how to beat the game... there is little motivation to erase what the character knows.

That is, something you can keep from an incarnation to another is knowledge. For example, learned spells, intrigue, etc. For instance, you may not have the level or energy to cast a spell but you may not have to learn it again, or you could skip the sub plot of figuring out what you need to do and just go do it, and dialog trees that depend on the character having done something already could stay open.

---

## What to lose between incarnations

Evidently, level, iventory, etc... would be lost.

Interestingly, the world is the same. A way to keep stuff could be to have a vault in a bank that is tied to a password, with instructions to give to whoever knows the password, and with some limited space for storage. Using it you could give a few items to your next incarnation.

If the character after reincarnation is different. This means that NPCs does not have to recognize you. If your game have relationships, diplomacy, or similar mechanics, that could be wiped out.

What happens to the character from the old incarnation? You can have a hall of fame in game, a leader board of sorts.

*Consider the mechanic of rewinding time in The Legend of Zelda: Majora's Mask.*

---

## Aging the characters

You need to be careful about how you affect the character. On one hand you risk it feeling unfair, and on the other some people may like the extra challenge for playing the handicaps of old age.

You see, it is natural that difficulty goes up. You do it too much, and it is unfair, you do it too little and the game is boring. You do it just right and it is engaging. So, do you really want to increase difficulty to motivate people to reincarnate?

If you do, plot wise, characters could have a disease (a curse?), that will give them an unusually short life span. An interesting variant is that this is an unholy dimension that corrupts the characters, or drains their sanity.

---

I did also consider something else... but it looks more on the engaging side: Going back to the idea of diplomacy and similar systems, you could implement something like the Nemesis System from Middle-earth: Shadow of Mordor. Just like people remember you, enemies might be aware of you and be more aggresive or come better prepared... however that goes away when you reincarnate.

---

## On progression systems

You also have the risk of the playing felling they are being held back in early content. You need to build a healthy progression system, one that does not require the player to waste time learning what they already know, and that does not rely on heavily on grind and random loot.

In fact, does your game *need* progression? To challenge the assumptions of the question, consider that a game would not suffer from heavy content abandonment if it didn't have a heavy progression system. Getting rid of the progression system would - probably - make people label your game as "casual"... but ther is nothing wrong with that, many "casual" games have high engagement from their players.

So, make the game fun first. If you will have a progression system, make it integral to the game, but not rely on psychological traps... because, the game should be fun first. Done correctly, and players should be able to enjoy staying in the early levels, even if they have already beated the whole game.

**Addendum**: There is also the issue of balance. If the higher level player leaves nothing to the lower player to do, that is bad. Avoiding the progression system would fix that. Reincarnation - if there is motivation to do it - could fix it too.

**See also**: My alswer to "Level playing field: Punish the better player or enhance the worse player?".

---

## Motivationt to reincarnate

People can be willing to replay a game on their own, but often they do not what to lose what took them effort to get. Owning a virtual item feels like owning a real item... so, we need a bit of extra encouragement.

Aside from using random generation, and having score and ranking systems...

You could have titles that can only be acquired on the first try, and then use this to tweak the experience. For example NPCs could have different interactions if you have different titles. Futhermore, having some title could prevent you from getting another... now it can interesting to reincarnate to - try to - explore what happens when you get a different set of titles.

Ideas:

* A title for being undefeated.
* A title for finding a pacifist solution to a conflict.
* A title for killing large quantities of enemies.

Alternatively, there could be some meta gaming. Perhaps between reincarnations you go to an afterlife/astral plane where you create your new avatar, and may have the chance to give you special quirks (perhaps some form of blessing or genetic manipulation, perhaps there are secrets/passwords that you can discover in the game and use here). With that, there are thing that you can only get by reincarnation.

**Notes**:

* It does not have to be an afterlife. Perhaps, it is all in virtual reality, or you are remote controlling avatars, or you could be reliving the memories of an ancestor, or it is time travel... you get the idea.
* If anybody can input these secrets/passwords, there would be no motivation to replay. However, I think the game is more interesting if you do not have to get them from the source, but another player can give them to you. One option could be to have a way to share them in game... another would be to have them change them randomly and periodically, so people have to rediscover them.

*Consider the reincarnation mechanic of - if you know what it is - Cookie Clicker.*

**See also**: My answer to "Should I worry about Youtube Let's Plays when I'm creating a story-heavy game?", as it has a similar concern: keeping the gameplay interesting even when people already know the plot of the game.

---

If it applies, I would suggest to ask worldbuilding for implications of people reincarnating. The economy and politic of (your particular brand of) reincarnation could guide your setting. And for your consideration: Is there people in universe that know that reincarnation is a thing?
> 4 votes

---
Tags: game-design, mmo
---


# Question
Title: How can I duplicate a GameObject with the correct number of copies?
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FormationsManager : MonoBehaviour
{
    public GameObject squadMemeberPrefab;
    public int numberOfSquadMembers = 20;
    public int numberOfSquads = 1;
    public int columns = 4;
    public int gaps = 10;
    public Formations formations;

    private int numofmembers;
    private int numofsquads;
    private GameObject squadToClone;
    private List<GameObject> SquadMembers = new List<GameObject>();

    // Use this for initialization
    void Start()
    {
        squadToClone = GameObject.Find("Squad");
        numofmembers = numberOfSquadMembers;
        numofsquads = numberOfSquads;
        formations.Init(numberOfSquadMembers, columns, gaps);
        GenerateSquad();
    }

    // Update is called once per frame
    void Update()
    {
        if (numofmembers != numberOfSquadMembers)
        {
            numofmembers = numberOfSquadMembers;
            formations.Init(numberOfSquadMembers, columns, gaps);
            GenerateSquad();
        }

        if (numofsquads != numberOfSquads)
        {
            numofsquads = numberOfSquads;
            for (int i = 0; i < numberOfSquads; i++)
            {
                Instantiate(squadToClone);
            }
        }
    }

    private void GenerateSquad()
    {
        GameObject go = squadMemeberPrefab;
        List<GameObject> newSquadMembers = new List<GameObject>();

        int i = 0;
        for (; i < formations.newpositions.Count; i++)
        {
            if (i < SquadMembers.Count)
                go = SquadMembers[i];
            else
                go = Instantiate(squadMemeberPrefab);
            go.transform.position = formations.newpositions[i];
            go.tag = "Squad Member";
            go.transform.parent = gameObject.transform;
            newSquadMembers.Add(go);
        }

        for (; i < SquadMembers.Count; i++)
            Destroy(SquadMembers[i]);

        SquadMembers = newSquadMembers;
    }
}

```

In the Update I duplicate the squad:

```
if (numofsquads != numberOfSquads)
            {
                numofsquads = numberOfSquads;
                for (int i = 0; i < numberOfSquads; i++)
                {
                    Instantiate(squadToClone);
                }
            }

```

The problem is that if for example when running the game there is 1 squad and then I'm changing the value of numberOfSquads to 3 then instead duplicating more 2 squads it will duplicate more 3. And then if I will change the value of numberOfSquads from 3 to 4 it will add more 4 squads instead only 1.

And I also want to make that if I change the value of numberOfSquads to be lower then destroy the last squad/s.

# Answer
> 1 votes
In your loop you create a new squad for every numOfSquads. So if you want a total of 3 then you instantiate an extra 3.

Instead set the loop to start at 1(or current squad count) instead of 0 so it skips the amount you already have.

```
if (numofsquads != numberOfSquads)
        {

            for (int i = numofsquads; i < numberOfSquads; i++)
            {
                Instantiate(squadToClone);
            }
            numofsquads = numberOfSquads;
        }

```

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


# Question
Title: Editor-Assignable function pointer in UE4 C++?
So I have a TriggerBox that I'm using as a pressure pad, and I want to be able to attach objects to it that, when the TriggerBox is activated, will have specific functions called. Similar to unity's UI buttons, where you can assign a function to be called when the button is clicked.

I am working as the sole programmer, and the rest of my team are designers. They need to be able to assign the object's function to the TriggerBox from within the editor.

I have attempted to use C++'s function pointers, but I have not been able to find a way to make them assignable in the editor.

Is there a solution to this? If not, any suggestions on better ways to do this?

# Answer
> 1 votes
You need to make the function callable in Blueprint. To do this, in the line above the function put in as follows:

UFUNCTION(BlueprintCallable, Category="YourCategoryName")

This will tell Unreal that you want your function to be used inside the editor using the usual Blueprint chain with inputs and outputs.

A full list of things you can do with this is available here: https://wiki.unrealengine.com/Blueprints,\_Creating\_C%2B%2B\_Functions\_as\_new\_Blueprint\_Nodes

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


title: How MMOs store IDs for game entities

text:
# Question
Title: How MMOs store IDs for game entities
Wondering in general how IDs are stored in a large massively multiplayer online game.

From what I can imagine, it seems that each "game entity" would have a globally unique ID (GUID). Say there are 10 people connected to the game. The game *server* then spawns any new game entity, and sends the GUID (along with the entity data) to the clients. The *clients* never create entities directly. Actually no, the client maybe can also create game entities that are unique to the view of that specific client. So if player 1 is viewing a screen, then they might see game entity x, in addition to game entities a, b, c, etc. Then player 2 sees game entities a, b, c, and y, but not x. Not sure if these "dynamic" game entities are created on the client or server, so that is the first part of the question.

Then given these GUIDs, say there is *tracking* (analytics) that goes on. Say the game company wants to track when a player defeats a game entity. So it saves to the backend/server database "player 1 defeats game entity 123asdf....GUID". But if game entities are constantly spawned and then destroyed/cleared (by hiding or maybe they have a temporary/ephemeral existence), then the database would have GUIDs for a lot of non-existent game entities. So I'm wondering if this is how it's done, or if these ephemeral game entities have metadata permanently stored to the database beyond their GUID, or if they are never saved to the DB, etc.

Then there is the problem of having lots of game entities (particles) on the screen. If each particle of say 1 million particles has a GUID, and you shoot (if it's like asteroids game) one of them, then the DB saves "player 1 destroyed GUID x at timestamp y". But the GUIDs have to be unique across the game server. So if 10,000 people are playing asteroids, and each asteroid has a GUID, the problem is how to guarantee the GUID is unique, and also secure (if that's a concern).

Then there is the issue of offline playing. Say you play offline, but then sync your data occasionally. Then GUIDs need to be generated on the *client*, and could be tampered with (and be insecure). Ideally the GUIDs would be generated on the server so we know how they are constructed and that they are secure.

Basically, I am wondering how GUIDs work in a MMO.

* If *all* game entities have a unique GUID.
    + If *ephemeral* game entities have unique GUIDs.
    + If there are non-ephemeral (persistent) game entities that have GUIDs.
* If tracking/analytics tracks both ephemeral and persistent game entities.
* How GUIDs are guaranteed to be unique.
* How GUIDs work if the player is playing offline.

# Answer
How important is it really that you track individual entities or that all of them are unique?

Per player you only care about which type of monster killed and what loot he got.

Then when the respawn timer runs out you can spawn the monster again and make it indistinguishable from the previous monster.

You can still use timestamps to differentiate between the monsters if you need to.

Also when you allow offline play *everything* the client says he did when reconnecting is suspect GUIDs are the least of your worries then.
> 2 votes

---
Tags: entity-system, mmo, databases
---


# Question
Title: How to calculate object speed so it accelerates exponentially?
Think a rocket or a missile. Completely don't know how to make it start slow and then get progressively faster in an non-linear fashion, given max speed and base acceleration. Curve like this would look best.

```
 ^                       .
S|                       .
 |                      .
 |                    ..
 |                ....
 |         .......
 | ........
 +------------------------>
                         T

```

# Answer
> 1 votes
considering time step `dt`, position `x`, speed `s`, acceleration rate `a(s)` :

```
s += a(s) * dt;
x += s * dt;

```

Acceleration rate `a(s)` can be a constant, then you will have quadratic acceleration.

For exponential :

```
a(s) = s * factor

```

if `factor` is positive, the more the speed, the more the acceleration.

You can give a few tries for the `a(s)` function until you come to what looks nice to you...

# Answer
> 0 votes
Generally, for this "progressively getting faster" behavior to work, you need to have `acceleration` constant and variable `speed`. Update `speed` and objects `position` each tick (with `dt`, delta time between this and previous tick) like so:

```
acceleration := 1; // some constant value
speed := speed + acceleration * dt;
position := position + speed * dt;

```

To make behavior even more progressive, you can make `acceleration` to grow over time too:

```
acceleration_grow := 1; // some constant value
acceleration := acceleration + acceleration_grow * dt;
speed := speed + acceleration * dt;
position := position + speed * dt;

```

Note that if you have varying `dt`, then the behavior will vary as well, since every previous step affects next one. E.g. one `dt=0.5` update will produce significantly different result than five updates with `dt=0.1`, despite having the same `dt` sum.

---
Tags: mathematics
---


# Question
Title: How should I arrange collision primitives around characters for a top-down, oblique game?
I'm planning to develop a top-down oblique mobile game (like the one in the screenshot below), but I'd like to understand something before I start:

When I'm working on collisions, where should the fixture for collision be? Should it be at the character's feet, or elsewhere?

# Answer
> 1 votes
When you have a 2d game with an oblique perspective, then a collider should represent the floor space which is occupied by an object. The collider size should be independent from how tall the object is. If you use the pixel height and width of the sprite to generate a collision rectangle (as you would do in a straight top-down or side-view perspective), then you will get the weird result that tall objects occupy more vertical space than short objects but not more horizontal space. You should instead choose a radius for a collision shape which represents the thickness of the object at the thickest height.

Imagining all collider primitives on the floor level is usually a good mental model. You could of course also imagine the colliders on chest level or head level. But in the end the collider height really just exists in your imagination. When you have pure 2d game mechanics, then all colliders (moving objects and environment) need to be on the same height anyway. So using a different height than zero just means you add a constant value to all y-values in your collision detection code. This won't have any game-mechanical consequences. So there is no value in doing that.

The green ellipse around the feet of the one character on the screenshot could be a visualization of its collision circle.

Another mental model you can use is to imagine your collision shapes as infinitely high vertical columns in 3d space.

I am looking forward to playing your game.

# Answer
> 0 votes
This entirely depends how you would like your game to behave.

Can other humans/creatures walk behind your hero in such a way that your hero's head hide their fit? Then the collision should be focused on the legs. There is not "should be" or anything like that. When you are making the game, you are in control of what is happening. It only changes how the game behaves, which in this case, there is no wrong/correct choice, only which one you like most.

---
Tags: collision-detection
---


title: Rotating Weapon Towards mouse.position

text:
# Question
Title: Rotating Weapon Towards mouse.position
OK guys i have tried lots of things and researched but cannot find a solution please someone give me hope.. So on my phone when i am playing i want to shoot with a screen button in the canvas that is the entire screen size, and when i click it i can shoot towards where my finger is clicked "This works"... now my problem is whilst i am shooting when i also use my up and down button to move my player at the same time my gun stops moving towards my finger and instead moves towards my up and down buttons.. What can i do to fix this?

public void ShootButton() {

```
    timer = 0;
    Face = true;
    //if finger is press on Shootbutton
    //then activate this
    Vector3 difference = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position; // subtracting the position of the player from the mouse position.
    difference.Normalize(); //normalizing the vector meaning all the sum of the vector will be = to 1.

    float rotZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;//find the angle in degree.
    WeaponTrans.transform.rotation = Quaternion.Euler(0f, 0f, rotZ + rotationOffset);
    if (reloading == false)
    {
        if (fireRate == 0)
        {
            {
                Shoot();
            }
        }
        else
        {
            if (Time.time > timeToFire)
            {
                timeToFire = Time.time + 1 / fireRate;
                Shoot();
            }
        }
    }
}

```

# Answer
> 0 votes
When there are multiple simultaneous touches on the `Input.mousePosition` is the average of all touch positions. Instead use `Input.GetTouch(0).position;`

---
Tags: unity, c#, mouse, shooter, rotate
---


title: Prevent navmesh blocking

text:
# Question
Title: Prevent navmesh blocking
I'm writing a tower defense game in Unity, inspired by Desktop Tower Defense.

Creeps spawn on one side of the screen, and if they make it to the opposite side, the player takes damage. The board starts out unobstructed, and the player builds towers that shoot at creeps while also blocking their path. They can funnel creeps along a path by strategic placement of towers.

I have a terrain GameObject with a NavMesh, each creep has a NavMeshAgent, and each tower has a NavMeshObstacle. This works fine, the creeps go toward the goal and avoid the towers.

The problem is that the player is not allowed to block off all of the paths to the goal. If placing a tower would leave no routes open to the goal, it is not valid to place a tower there. I can detect this after the tower is placed, but I want to warn the player and prevent the placement from happening at all.

I also don't want to even briefly block the path to the goal by temporarily placing a NavMeshObstacle in an invalid position, because it might be exploitable by players by repeatedly attempting to place a tower there.

How can I predict whether placing a NavMeshObstacle will completely block a route between two paths, while NavMeshAgents are actively traversing the NavMesh?

# Answer
I would add something like a "temporary" wall on the place where the player want to build. Meanwhile on a other navmesh an Object is moving all the time super fast (something like a 1x1 collider). If this object didn't finish the route, that will activate a script which disable the option to build there.
> 1 votes

---
Tags: unity, path-finding, navmesh, tower-defense
---


# Question
Title: Legality of remaking a game from a defunct company
Ive been a head from a now defunct company under someone else. And I directed coded and produced a game that reached around 99% completion but was never completed. I was wondering if its legal to remake the game or clone it with a different theme. I dont have a contract with the employer but I already prototyped the game before we developed it under the now defunct studio.

Any ideas on how legal is cloning or remaking it?

Also am I able to show of prototype games or footages from the defunct company?

# Answer
> 0 votes
Disclaimer: I am not a lawyer & this is not legal advice.

The existence of clones doesn't make cloning legal. Whether or not some other IP holder choose to litigate *their* imitators has no bearing on whether or not the IP holder you might be infringing upon will choose to litigate you.

Since the question of how closely can a game legally resemble another has already been addressed, the remaining issue is whether or not having worked on the game grants you use of the IP.

Ownership of creative work depends on legal jurisdiction & any binding contracts that might be in place. under US copyright law, the designer automatically owns all rights to the work they do, with the following exceptions:

* When work is created by an employee in the course of employment, the employer owns the copyright.
* When work is created by an independent contractor and the independent contractor signs a written agreement stating that the work shall be "made for hire", the entity commissioning the work owns the copyright if the work it falls under certain categories. The categories in question include audiovisual works, which I believe would include games.
* If the creator has sold the entire copyright, the purchasing business or person becomes the copyright owner.

If you want legal advice as to which parts of this are applicable to your specific case, you should consult a lawyer versed in copyright, preferable one with experience in the games industry.

---
Tags: pre-production
---


# Question
Title: C# Fastest way to iterate over certain tiles overlapping multiple chunks?
What's the **fastest** way of iterating over certain tiles overlapping multiple chunks in C#.

Ideally without having to iterate over everything, just a specific set of coordinates? (green cubes example below)

I had some partial solutions, but i'd like to see what you guys come up with.

For example:

I would like to set every `tile.IsBuiltOn = true` for every tile beneath the building.

I could also use this to check if `tile.IsBuiltOn = true` to refuse placement of another building.

Chunks and each array of tiles of chunks start at `[0,0]`.

```
class World
{
    public Chunk[][] Chunks { get; set; }
}

class Chunk
{
    public Tile[][] Tiles { get; set; }
    public Dictionary<CoordinateKey, Building> Buildings { get; set; }
}

class Building
{
    public BuildingID BuildingID { get; set; }
    public CoordinateKey ChunkCoordinate { get; set; }
    public CoordinateKey TileCoordinate { get; set; }
    public int WidthInTiles { get; set; }
    public int HeightInTiles { get; set; }
}

class Tile
{
    public bool IsBuiltOn { get; set; } = false;
}

```

CoordinateKey is just a struct with int X, Y.

# Answer
Here is my solution.

First I created a Google sheets to help me map out the chunks and tiles with their coordinates, what I want and what I get from my current iteration code:

I want to iterate over the green tiles, across multiple chunks and receive the correct tile coordinates and chunk coordinates, with only the building Width, Height, start tile X,Y and chunk start X,Y.

This allowed me to finally come up with a working solution (below), which is fast.

Note: To get this solution working quickly I have a lot of code in class constructors, this is not advisable and I will refactor later when I move this solution into my main project.

I used https://csharppad.com/ to quickly test the following code, which can be pasted in the "interactive shell" panel, then click "Go":

```
class World
{
    public Chunk[][] Chunks;
    public int ChunkSizeTilesXY = 3;

    public World()
    {
        Chunks = new Chunk[3][];

        for (int x = 0; x < 3; x++)
        {
            Chunks[x] = new Chunk[3];

            for (int y = 0; y < 3; y++)
            {
                Chunks[x][y] = new Chunk()
                {
                    chunkX = x,
                    chunkY = y
                };
            }
        }

        Test();
    }

    private void Test(){

        int buildingWidthInTiles = 2;
        int buildingHeightInTiles = 3;

        int startTileX = 2;
        int startTileY = 2;
        int endTileX = startTileX + buildingWidthInTiles;
        int endTileY = startTileY + buildingHeightInTiles;

        int startChunkX = 0;
        int startChunkY = 0;

        int chunkX = startChunkX;
        int chunkY = startChunkY;
        int ctx = startTileX;
        int cty = startTileY;

        for (int tx = startTileX; tx < endTileX; tx++)
        {
            // Out of bounds of current chunk, increment chunk and ctx (chunk tile x)
            if (ctx > ChunkSizeTilesXY-1)
            {
                chunkX++;
                ctx = 0;
            }

            for (int ty = startTileY; ty < endTileY; ty++)
            {

                // Out of bounds of current chunk, increment chunk and cty (chunk tile y)
                if (cty > ChunkSizeTilesXY-1)
                {
                    chunkY++;
                    cty = 0;
                }

                Chunks[chunkX][chunkY].Tiles[ctx][cty].IsBuiltOn = true;

                Console.WriteLine("tx:" + tx + ", ty: " + ty + ", ctx:" + ctx + ", cty: " + cty + ", chunkX: " + chunkX + ", chunkY:" + chunkY);

                cty++;

            }

            ctx++;

            // Reset chunkY
            chunkY = startChunkY;

        }

        // Reset chunkX
        chunkX = startChunkX;

    }

}

class Chunk
{
    public Tile[][] Tiles;
    public int chunkX;
    public int chunkY;

    public Chunk()
    {
        Tiles = new Tile[3][];

        for (int x = 0; x < 3; x++)
        {
            Tiles[x] = new Tile[3];

            for (int y = 0; y < 3; y++)
            {
                Tiles[x][y] = new Tile()
                {
                    chunkX = chunkX,
                    chunkY = chunkY
                };
            }
        }
    }

}

class Tile
{
    public bool IsBuiltOn = false;
    public int chunkX;
    public int chunkY;

    public Tile()
    {

    }

}

var world = new World();

```

I am still interested in hearing from others on alternate or faster solutions.
> 1 votes

# Answer
Your solution is close; what you should do is divide each coordinate to find which chunk each coordinate is in.

```
enum POSITION_TYPE
{
    TOP_LEFT,
    TOP_RIGHT,
    BOTTOM_LEFT,
    BOTTOM_RIGHT
};

TILE_WIDTH = 3;
for each coordinate
    findChunk(Math.Floor(coordinate.X / TILE_WIDTH),
          Math.Floor(coordinate.y / TILE_WIDTH));
    markBuilt(coordinate.PositionType(),
              coordinate.X % TILE_WIDTH, // finds offset into local coordinates of chunk
              coordinate.Y % TILE_WIDTH, // finds offset into local coordinates of chunk

```

Each position type requires a different algorithm of filling squares, but they're all simple alterations (and it could possibly dealt away with with clever use of negatives or positives possibly.)

What this does is find which chunk you're in by realizing that:

* you're always a positive number
* Your tile-width is constant, so dividing by 3 gives you your chunk given a coordinate
* Your tile-local-grid is figured out by the modulus (the remainder of a divide) of Tile Width, for the same reasons as above

NOTE: Given that you'll only be marking up the grid when a building is created or destroyed, the divides/modulus aren't so bad. You may consider some hackery to avoid them; such as "x * .33" if you're using floats or moving to 2x2 or 4x4 super-tiles so that you can use bit-shifting to perform your divide for you (in the case of longs or ints.)
> 0 votes

---
Tags: c#, xna, monogame, tiles
---