# Question
Title: Would it be better to use XML/JSON/Text or a database to store game content?
I'm considering how to implement a component-based game, as that seems to be the hot thing and I like the idea of such a flexible design. One of the features of such a design is that adding new things to the game can be done through data, often presented as loading content through text files such as XML. This has the advantage of being human readable and easily editable in any text editor. On the downside, text can be slower to deal with, and you have to manage a large collection of data files. Similar text-based formats like JSON or config files would have similar benefits.

On the other side, there are small, portable databases like SQLite or Tokyo Cabinet. While not directly human readable, these files are easy to interface with, and I'd imagine some kind of editing tool would be preferable for game content design anyway. Using a DB allows for a consistent storage of config information and easy retrieval. You could serialize data into a DB for save games as well.

Performance wise, I think generally XML is faster for small files but a database scales better to large amounts of data. I'd imagine any real game is going to have a whole lot of game objects.

So the question: Which is the preferable approach? I'm leaning towards the DB, but I want to know if there are hidden pitfalls or real strong advantages to text files. Or if there are other alternatives besides these (serialize to binary format I guess?)

# Answer
It might not come up so much for a small personal game, but one hard problem when it comes to game data is multi-user editing/versioning. We use a lot of small text files that get baked down to a small number of binary blobs by a build process. This makes life easier for designers since they have a lot of flexibility in their workflow. CCP, as a counter example, uses a central editing database that all designers connect to. This makes the build step unneeded (or at least a lot simpler) but it means you need to implement all the versioning and workflow features yourself, so they are bound to be simpler than other tools out there. You can deal with performance in either case, so the real question is what do you want for a designer workflow and how can you get there?
> 18 votes

# Answer
Im late to the party here but I spent A-LOT of time researching this.

First why I don't use the following:

**XML:** Excessively verbose. Tons of redundancy. Repeating field names? GROSS

**JSON:** I think JSON is great for a UI layout but for a database, hell no. It will have the same problems as XML, redundancy, and deep nesting. GROSS.

**SQL**: This is a great option, if you manage the headaches of setting it up. I've made mobile games where we store the game data online in an SQL database. The table format is nice. The issue was we had to fetch the database from online and setting that up can be a hassle. But SQL is a decent solution. Unity doesn't support this natively, and the plugins I tried had major issues (esp when trying to get it to work with version control).

Finally, here is the solution I opted to use (and I love it).

**CSV**: Simple. Lets me use table format, and I have one easy point of reference when I need to update it. I can have a table for all my weapons, columns for all the attributes, and rows for each type of weapon.

You can use Microsoft Excel but it spits out these stupid warnings every time you need to save. You can use macros to override it but I say save yourself the trouble and get LibreOffice. Its free, supports CSV editing, and when you open the file it loads the column width to match the name (Excel doesnt do this and it drove me nuts).

Then you just need to parse the CSV files into your game. I use Unity so all I had to do was use this nifty C# CSV parser I found:

CSV parser example

You convert the CSV files into your in game data objects and you are good to go. With Unity you can turn these into ScriptableObjects. So my workflow is: Update CSV -\> Parse CSV into Scriptable Objects -\> Use data from ScriptableObjects for my game
> 10 votes

# Answer
JSON is very lightweight and easy to understand. I think it's better suited for a game. cJSON is really nice. it will also incorporate into your source in the same manner as SQLlite does.

XML files are harder for users to edit than you may think. if you go that route you may want to make an editor for folks to use to help them avoid common pitfalls.
> 7 votes

# Answer
The answer to this depends on the what language you are using for the game.

If you are using C++, you would be well advised to use one of the existing XML libraries (such as TinyXml or eXpat).

On the other hand, if you were using PHP, you could very easily use a database server such as MySQL or SQLite. (Keep in mind that if you go this route, you will need more resources because the database server will be running as a separate process and larger database applications like MySQL can consume a lot of RAM when running.)

JSON is gaining a lot of momentum and is certainly the best choice if your application is written using more than one language.

In short, it depends on what is easily usable in your language.
> 6 votes

# Answer
If you wanted to stay in the XML realm of things you can use **Binary XML** to help increase load performance.

For example **Fast Infoset** is an implementation of binary xml

> One can think of Fast Infoset as gzip for XML, though FI aims to optimize both document size and processing performance, whereas gzip optimizes only the size. While the original formatting is lost, no information is lost in the conversion from XML to FI and back to XML.
> 2 votes

# Answer
I've been designing databases and played around with many game ideas for years now. My personal favorite at the moment, is some kinda textbased, human-readable format for configurations, but then parsing these "slow scripts" into something more runable. Much like JAVA and .NET is compiled into Run-time bytecode.

Same idea goes here. I have a "source" version of components and then a pre-compiler/parser runs through these. If they take up too much memory, you can put them in a fast SQL-datbase of some kinda or save them as binary files. But my point is, use the memory or SQL-database as your workspace/cache so that you dont have to parse the scripts over and over again. You could make the compiler, move the parsed files into a "source-lib" and this way let the precompiler do the versioning too (keeping the previous files for rollback purpose).

If its about "unlimited harddrive space", then sign up to something like Dropbox or Amazon S3 and sync with them.

**So the plan for me is currently:**

1. Config/scripts/xml (some human readable format) as textfiles (just like sourcecode)
2. Parser/validator that runs through new scripts and checkes they are following rules
3. Compiler that makes binary or SQL-row out of the original files, so that these are fast to retreive + fast to run.

Regarding stability, I'm currently building the database to be "co-location hosted" and autosync between multiple locations too, so that if there is a network/hardware failure one location, the other sites should be able to handle the same traffic/gamestates.
> 1 votes

# Answer
If you use couchdb you will essentially be saving everything as a JSON structure. Couchdb will take care of replicating your (multiple) user's data more or less painlessly.
> 1 votes

# Answer
You can find a procedure in Unity Wiki with PHP, MySQL and C#/JavaScript, and it works fine for its purpose.

It consists of three steps

1. Create a blank MySQL Database and a table.
2. Create a PHP server side script (This will connect to the MySQL table, receive data from a Unity script (step 3), and query the database (the examples given are either inserting data or selecting))
3. Create the Unity Controller Script (This will connect to the PHP script created in step 2)
> 0 votes

---
Tags: component-based, databases, xml, data, configuration
---


# Question
Title: Spawn Array of GameObjects to Array of Transforms
I have a question regarding spawning an array of GameObjects in Unity. What I want to happen is that when a big enemy dies, it will spawn enemies into their respective Transform positions (i.e., Enemy 1 will spawn in Position 1, Enemy 2 in position 2, and so on).

I suppose I could go on with something like:

```
// C#

public GameObject[] Enemies;
public Transform[] SpawnPoints;

void KillEnemy()
{
    GameObject enemy1 = Instantiate(Enemies[0], SpawnPoints[0].position, SpawnPoints[0].rotation;
    GameObject enemy2 = Instantiate(Enemies[1], SpawnPoints[1].position, SpawnPoints[1].rotation;
    GameObject enemy3 = Instantiate(Enemies[2], SpawnPoints[2].position, SpawnPoints[2].rotation;

    Destroy(gameObject)
}

```

But the problems are:
1. I'm aware that the code is expensive to run, especially since I'm doing a 2D game; and
2. It provides no flexibility, meaning if I want a different enemy to use the same code, then I won't be able to do stuff like adding more enemies to spawn (after the first one dies, of course).

So yeah, I hope I get some help with this. Thanks!

# Answer
Would simple for loop work?

```
public GameObject[] Enemies;
public Transform[] SpawnPoints;

void KillEnemy()
{
    for(var i; i < Enemies.Length; i++) {
        var spawnPoint = SpawnPoints.Length> i ? SpawnPoints[i] : SpawnPoints[SpawnPoints.Length- 1];
        Instantiate(Enemies[i], spawnPoint.position, spawnPoint.rotation)
    }

    Destroy(gameObject)
}

```

And if you need the reference to the created enemy just do var enemy = Instantiate... etc.
> 2 votes

---
Tags: unity, gameobject, spawning
---


# Question
Title: Animate a 3D boss with some parts that become independant
I would like to create a boss but first, I want the player to fight the head. Then the head flies to the body and becomes attached to it.

Later, the boss will throw an arm to the player and the arm will chase the player, becoming independent with its own AI.

Do I have to render 3 models separatly? (The head + one arm + the body)
If I do this, how am I supposed to animate the complete body when everything is attached together?

Do I have to render the 3 models (The head + one arm + the body) + 1 model without the arm (Head + body) + 1 model with everything attached?
If so, how do I handle animations with these 5 models?

# Answer
Remember, just because two things look the same or logically are the same in your game's fiction, does not mean they need to be the same entity in your game's implementation.

Here you can have one model that is your boss as a whole, that you can animate as one complete being. Using submeshes or vertex colours, you can split parts of it to render only selectively: replacing the material for one submesh with a transparent pixel, or `clip`ing it out of existence in your shader based on a uniform variable.

This lets you have one animated body, with pieces you can hide on demand. (Just be sure the torso's neck/shoulder are capped, so you don't see inside the hollow model when the head/arm are hidden)

You can similarly disable the colliders for these body parts, or shunt them to a non-colliding layer when the body parts are absent.

In the same frame that you hide the head part of the main mesh, you spawn (or reveal/enable) a standalone head object at the same place, which can then separate and start doing its own thing.

Then when you want to re-attach it, you can have it fly back to the position of the head bone, then hide itself / re-enable the full body's hidden head in the same frame. A brief flash of particle effects can help hide the transition if you have trouble getting it completely seamless.
> 5 votes

---
Tags: unity, animation, blender
---


# Question
Title: When an animation involves movement, where is the movement better to implement?
For context, I am using Blender and Unity. Regarding the question, as an example, in some games, when you get hit, your character tucks a bit and gets knocked back a few distance. The tucking animation I want to implement in Blender but how about the knockback distance? Do you move your model in Blender (tuck and knockback), or do you do the tuck animation only (tuck in place) and then handle the knockback in Unity (basically triggering the tuck animation and then moving the model backwards a bit).

My question basically is, what's commonly done and if there's any specific reason, why?

# Answer
> 1 votes
Both options have pros and cons; in practice I'd advocate for using a mix of techniques, as appropriate for the situation.

When the animation drives the object's world position, the animator has significantly increased control over the artistic look and feel of the animation and how realistic (or stylistic) they'd like it to be. But the game has significantly less control over the object, leading to more work and/or potentially very ugly looking stopgap techniques to (for example) prevent objects from being forced inside other objects due to the animation (if collision is off). Or if collision is on, preventing the animation-driven displacement from being countered by collision, destroying all the animator's hard work as the object "slides" against some surface while animating. IME it's better to let the animation drive the object for complex interactions like clambering over obstacles.

When the game drives the object's world position, the game logic has much more precise control over the object; since it's usually game logic that translates player input into displacement of player-controlled objects, this can result in much tighter-feeling control. But it can also result in less than ideal visuals because the animators typically cannot know for sure when the game will blend between two animations, and some blending techniques can result in obviously-video-gamey transitions in scenarios where, for example, you stop a character short in their walk cycle. IME it's better to let the game drive the position for locomotion related actions in particular, and also as a default choice.

There's a variety of ways to combine animation techniques in a mix-and-match approach that let you hide or minimize some of the cons of either approach (motion matching, for example, is a Relatively Hot New Thing recently).

What I recommend you specifically do is look at what is most efficient for you: is it easier for you to work in Blender and have all your displacements authored there? Or is it easier for you to do displacements programmatically (for the majority of cases). Either way you'll likely need to put work in to smooth over artifacts, so you'll be paying that cost. So look at which option will let you personally pay the cheapest cost for your project's needs.

# Answer
> 2 votes
In my opinion this is best handled inside the game and **NOT** inside the animation. In your case that would be inside Unity and not Blender.

So the idea is the animation is only showing what your character looks like when they get hit, and through Unity you can configure how long away you want the character to move.

Here are the benefits:

* You can use the same animation for multiple characters and multiple occasions. Characters that are small (so thrown further away) or big (not really moving), or creating a big explosion or just a small bullet.
* Usually from within the game, all objects are in the "center" of themselves. So if you place a box at coordinates `(0, 0, 0)`, you assume that it will be in the center of the world. If you animate a character, and at the end of the animation they now have an offset, that might make it awkward to place it correctly in the world and make it look smooth.
* You can combine multiple animations easier, as its animation can assume the character is at the center, and not offset because of the previous animation.

---
Tags: unity, blender
---


# Question
Title: How to generate a random tunnel consists of series of two line paths
I have a 2D path that follows series of lines thru points p1 p2 p3 p4.

Like this: `___/\__/\___`

I want to make a tunnel out of this path, so I need to split this path in two sideways and make a hole inside of it. Like this:

```
     ________
____/        \_____
     _______
____/       \_____

```

How do I do that?

I actually want to just generate a random tunnel it doesn't have to follow a path.

# Answer
A simple approach would be to take the 2D path, create a copy of it, so you now have two identical paths on top of one another, then offset the Y-values of one path so they form an upper and lower bound, creating a "tunnel".

example using the path you supplied:

```
intial path: ___/\__/\___

                        ___/\__/\___
duplicated and offset:
                        ___/\__/\___

```

There are many methods that would generate a 2D "tunnel", but given that you already have a 2D path this seems the simplest.
> 1 votes

---
Tags: javascript
---


title: Unity Content Size Fitter to large

text:
# Question
Title: Unity Content Size Fitter to large
I have a content size fitter on the content within the scroll view. However the content size fitter is over double the height needed and when scolling there is a large blank space at the bottom on the content that keeps scrolling.

I have tried to change all the settings but nothing has made it shrink and fit the content.

# Answer
> 1 votes
Although I don't have enough information to determine whether this is the problem you're facing, I'll just add it as an answer for you (and other people with similar problems) to check if this actually causes it.

Unlike what you might expect, the Content size fitter does not set its own size to the size of its child components. it sets its size to its layout properties. These layout properties are set by layout components such as layout groups (which might set layout properties based on childs values) or LayoutElement. You can see these properties in the same place where the preview window is displayed for Materials etc.

As shown in the image, check what is modifying this preferred size of 'Content', make sure it is the GridLayoutGroup, if something else is, then that's the problem. Also check if these values are what you expect them to be. (In your example with 28 items, size of 195 and given padding of 10 I expect it to be either 1375 or 1960)

Also note that the 'H Delta' display in the inspector only updates properly in playmode. Outside of playmode it often shows incorrect values when driven by a content size fitter, which might hide the actual problem for us.

Also note when debugging that h delta is not the height in pixels, to get it to display height in pixels, set the anchor min Y to 1 aswell. (just make sure Y min and max are equal, the actual value doesn't matter for this)

---
Tags: unity
---


# Question
Title: Directx11 batching verticies to draw later
I have several draw functions in my renderer to draw primitives e.g.:

Drawing a Quad:

```
void Renderer::DrawQuad2D(float left, float bottom, float right, float top, const Rgba& color /*= Rgba::WHITE*/, const Vector4& texCoords /*= Vector4::ZW_AXIS*/) noexcept {
    Vector3 v_lb = Vector3(left, bottom, 0.0f);
    Vector3 v_rt = Vector3(right, top, 0.0f);
    Vector3 v_lt = Vector3(left, top, 0.0f);
    Vector3 v_rb = Vector3(right, bottom, 0.0f);
    Vector2 uv_lt = Vector2(texCoords.x, texCoords.y);
    Vector2 uv_lb = Vector2(texCoords.x, texCoords.w);
    Vector2 uv_rt = Vector2(texCoords.z, texCoords.y);
    Vector2 uv_rb = Vector2(texCoords.z, texCoords.w);
    std::vector<Vertex3D> vbo = {
        Vertex3D(v_lb, color, uv_lb)
        ,Vertex3D(v_lt, color, uv_lt)
        ,Vertex3D(v_rt, color, uv_rt)
        ,Vertex3D(v_rb, color, uv_rb)
    };
    std::vector<unsigned int> ibo = {
        0, 1, 2
        , 0, 2, 3
    };
    DrawIndexed(PrimitiveType::Triangles, vbo, ibo);

}

```

Sending the verts and indexes to the GPU

```
void Renderer::DrawIndexed(const PrimitiveType& topology, const std::vector<Vertex3D>& vbo, const std::vector<unsigned int>& ibo) noexcept {
    UpdateVbo(vbo);
    UpdateIbo(ibo);
    DrawIndexed(topology, _temp_vbo.get(), _temp_ibo.get(), ibo.size());
}

```

Setup and call DrawIndex on immediate context.

```
void Renderer::DrawIndexed(const PrimitiveType& topology, VertexBuffer* vbo, IndexBuffer* ibo, std::size_t index_count, std::size_t startVertex /*= 0*/, std::size_t baseVertexLocation /*= 0*/) noexcept {
    GUARANTEE_OR_DIE(_current_material, "Attempting to call Draw function without a material set!\n");
    D3D11_PRIMITIVE_TOPOLOGY d3d_prim = PrimitiveTypeToD3dTopology(topology);
    _rhi_context->GetDxContext()->IASetPrimitiveTopology(d3d_prim);
    unsigned int stride = sizeof(VertexBuffer::arraybuffer_t);
    unsigned int offsets = 0;
    ID3D11Buffer* dx_vbo_buffer = vbo->GetDxBuffer();
    ID3D11Buffer* dx_ibo_buffer = ibo->GetDxBuffer();
    _rhi_context->GetDxContext()->IASetVertexBuffers(0, 1, &dx_vbo_buffer, &stride, &offsets);
    _rhi_context->GetDxContext()->IASetIndexBuffer(dx_ibo_buffer, DXGI_FORMAT_R32_UINT, offsets);
    _rhi_context->DrawIndexed(index_count, startVertex, baseVertexLocation);
}

```

The most noticeable problem is each function issues a draw call. Doing this enough per frame (about 100) causes massive lag. How would I implement a batching such that each of these functions, instead of emitting a draw call immediately, collects all the verts/indexes and doesn't draw until the end of the frame?

# Answer
> 0 votes
A few things come to mind when I look at your code.

1. Setting up your draw context should be done once at the start before you start executing draw calls.
2. Consider using Instancing to reduce your call count down (does require more set up).
3. Small vertex sets in a draw call will mean that the GPU Wavefront will not be filled completely. If you draw say 6 vertices and the GPU can handle on its wave front say 64 vertices per wave front then you leave a lot of waste. Having said that, it shouldn't be an issue here for say 100 draw call.
4. If you have a slow CPU but it has multiple cores, look up deferred contexts and multi threading. This method in DX 11 allows the GPU graphics driver to order the draw calls more readily.
5. If you have lots of different vertex buffers, pack them into 1 Vertex buffer, and call the drawindexed with the offsets of each vertex group. (say object 1 starts at Vertex 0, object 2 starts at 300, if you want to draw object 2, you make the draw call with the vertex offset at 300).

In general, try not switch the state of the GPU everytime, because this causes microstalls because it has to flush the entire pipeline on occassion to switch state. Now this isn't a problem on later GPUs, they can localise flushing of state in the pipeline. But you should try in general to reduce this.

If you need examples for say for packing multiple models into one vertex buffer, I will add them as a follow up. But in general, batching can be achieved through instancing (in regards to your original question) or through using a deferred context if you want to continue using discreet calls per object.

---
Tags: c++, batching
---


# Question
Title: Element's texture is null - Monogame/XNA, C#
I have a ArgumentNullException everytime I try to call the Draw() method of my Projectile class in the Game1.Draw() method.

***In Game1.cs Initialize() method:***

```
//PROJECTILES INITIALIZATION
        lesProjectiles = new List<Projectile>(20);
        for (int i = 0; i < lesProjectiles.Capacity; i++)
        {
            lesProjectiles.Add(new Projectile(projectileSprite,
                new Vector2(playerPosition.X - 15.5f, playerPosition.Y - 20)));
        }

```

***This is the Projectile class constructor:***

```
public Projectile(Texture2D texture, Vector2 startPos)
    {
            this.projectileSprite = texture;
            this.projectilePosition = startPos;
    }

```

The -15.5f and -20 values are for placing the projectile at the middle of my spaceship. (Not optimized logic ikr.)

Apart from my whole game logic, let's say I wanna draw the first element of my array. I'm doing that:

***In Game1.cs Draw(GameTime gameTime) method:***

```
        spriteBatch.Begin();
        lesProjectiles[0].Draw(gameTime, spriteBatch);
        spriteBatch.End();

```

***And there is the Draw() method from my Projectile class :***

```
public void Draw(GameTime gameTime, SpriteBatch spriteBatch)
    {
        spriteBatch.Draw(this.projectileSprite, this.projectilePosition,
            Color.White);
    }

```

The returned error: System.ArgumentNullException: Value cannot be null. Parameter name: texture

I don't understand why the projectileSprite values of my array elements are null, considering it's done in the initialization method whenever the constructor is called.

Thanks for further help, sorry if my explanations are bad

# Answer
> 0 votes
***Ok I found a fix after multiple tries.***

It seems like, even if I use the Content.Load in my LoadContent() method and loads a sprite into variable, I can't use it in both Update() and Draw() method. The texture isn't found.

My fix is not perfect (I guess), but it works. Instead of actually loading my sprite.png in the LoadContent() method, I did it in my Initialize() method, just before my For structure. Here it is:

***In Game1.cs Initialize() method:***

```
        //PROJECTILES INITIALIZATION
        projectileSprite = Content.Load<Texture2D>("rocket");

        lesProjectiles = new List<Projectile>(20);
        for (int i = 0; i < lesProjectiles.Capacity; i++)
        {
            lesProjectiles.Add(new Projectile(projectileSprite,
                new Vector2(playerPosition.X - 15.5f, playerPosition.Y - 20)));
        }

```

Now I can Draw the sprites from my array without any issue. Thanks to Felsir, he got me on the way.

# Answer
> 0 votes
Be sure you have something like this in your code:

```
Game(1)
{
Content.RootDirectory = "Content";
sContent = Content;
}

```

In the book "Learn 2D Game Development with C#" on page 43 they left that out.

---
Tags: c#, xna, textures, sprites, monogame
---


title: Problems With Opening Room Gamemaker

text:
# Question
Title: Problems With Opening Room Gamemaker
In Gamemaker, I have a main menu room, and hitting start takes you to the gameplay room. When testing it, it did not take me to the gameplay room. I made it load into the problem room first, and all it loaded was a black screen. I also noticed when I looked in the console it was said:

> RequestStats - failed: 2

What's causing this and how do I fix it?

Here is my game: https://drive.google.com/open?id=1xWota0WfzcwvYGHY4zFVwS0vXDwNQfDp

# Answer
> 0 votes
I have not found out what caused the problem, but I deleted the room, then created it again and readded all the objects, and it fixed the issue. The error in the console has not gone away, but the room loads properly.

---
Tags: game-maker
---


# Question
Title: Why is there a gameObject inside a GameObject
In order to manipulate a game object via script in Unity I need to access the `gameObject` inside the *main* `GameObject`.

Why is it structured this way? What is the *main* `GameObject` representing compared to the `gameObject`?

```
public class Sun : MonoBehaviour
{
    private GameObject[] _satelliteGameObjects;
    private Rigidbody[] _satelliteRigidBodies;
    public GameObject[] Satellites;

    private void Start()
    {
        if (Satellites == null)
        {
            Debug.LogError($"You haven't added a {nameof(Satellites)}.'");
            throw new InvalidOperationException($"{nameof(Satellites)} should not be null");
        }

        _satelliteRigidBodies = new Rigidbody[Satellites.Length];
        _satelliteGameObjects = new GameObject[Satellites.Length];

        for (var i = 0; i < Satellites.Length; i++)
        {
            var satellite = Satellites[i];
            _satelliteRigidBodies[i] = Satellites[i].gameObject.GetComponent<Rigidbody>();
            _satelliteGameObjects[i] = Satellites[i].gameObject;
            _satelliteRigidBodies[i].AddForce(Vector3.up * 100);
        }
    }
}

```

In the example above, I'm passing a `GameObject` into this class. However, in order to call members on the *actual* game object, I need to go through the `gameObject` property.

# Answer
> 1 votes
GameObject is a unity class. These are things in your scene. Most unity scripts you write are *components* that are attached to these game objects. These are scripts that are subclasses of the MonoBehaviour class not GameObject.

BUT... Since MonoBehaviours are always attached to a GameObject, the MonoBehaviour class gives you an easy way to get a reference to that GameObject through the gameObject field. This is the main way you access other components on the object including the Transform and Rigidbody component etc.

In summary:

capital GameObject is a class.

Lowercase gameObject is a field in MonoBehaviour scripts that lets you access the GameObject the MonoBehakviour is attached to.

# Answer
> 0 votes
you have nested gameObjects or Prefabs for more flexiblity and function. if an object is Parented by another, it derives many behaviors from parent object like movement and rotation etc...

if you want to access a child of object or parent of object you should use transform like this:

```
 void Awake()
    {
        GameObject parent = transform.parent.gameObject;
        GameObject firstChild = transform.GetChild(0).gameObject;
    }

```

---
Tags: unity, gameobject
---


# Question
Title: How can I stop this fixed update from executing
so I want this FixedUpdate() Method to stop executing when the Method OnMouseDown() is executed. A bool doesn't work a if() statement also doesn't work Please use my whole code Please help :) Thanks,

```
 private void FixedUpdate()
    {
            int random = Random.Range(1, 4);
            if (random == 1)
            {
                m_SpriteRenderer = GetComponent<SpriteRenderer>();
                m_SpriteRenderer.color = Color.green;
            }
            if (random == 2)
            {
                m_SpriteRenderer = GetComponent<SpriteRenderer>();
                m_SpriteRenderer.color = Color.blue;
            }
            if (random == 3)
            {
                m_SpriteRenderer = GetComponent<SpriteRenderer>();
                m_SpriteRenderer.color = Color.yellow;
            }

    }
    private void OnMouseDown()
    {
        shouldexecute = false;
    }

```

# Answer
From unity documentation: "FixedUpdate functions will not be called when timeScale is set to zero.".

So setting timescale to 0 would prevent execution of fixedUpdate, but it will also pause the entire physics simulation across your entire game, which I don't think is the desired behavior if I am interpreting your question correctly. I think this is a bit of an xy problem.

If you have code that you want to only execute if certain conditions are met you should use an if-statement. You mentioned in your question that an if-statement hadn't worked before, but this is its exact use case, and it should work if implemented properly. In this case you want to evaluate the "shouldExecute" boolean and then execute or not depending on the boolean value.

I would also recommend taking the code inside of fixed update and extracting it into another method to improve maintainability and modularity of the code.

Here is an example of how to implement the if-statement:

```
bool shouldExecute = false;

 private void function setRandomColor(){
    //.....Do stuff in here
    console.log("setting random color");
  }

 private void FixedUpdate(){
   if(shouldExecute == true){
       setRandomColor();
     }
  }

 private void OnMouseDown(){
        // Mouse event has been changed to toggle the boolean rather than
        // only turn it off
        shouldExecute = !shouldExecute;
  }

```
> 2 votes

# Answer
you just can put this before your code in **FixedUpdate**

```
if(Input.GetMouseButtonDown(0)) return;

```
> 0 votes

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


title: Stop checking for the same collision

text:
# Question
Title: Stop checking for the same collision
I am creating a JavaScript game that is currently implemented as follows:

* Run a game loop
* Check for arrow keys pressed
* When arrow is pressed, calculate the new player coordinates
* if new player coordinates result in a collision, do not move the player, but instead append a status message to the onscreen status box

My issue is that if I am holding down the arrow key and collide with an object, that onscreen status box gets hundreds of messages appended to it.

I originally thought that a way to get around this would be to check the last line in the status box and if it is the same as the new line then not to append the new line. However, this will cause a problem if the user walks away and comes back to the same object again, in this case the user SHOULD see a second message appended to the box.

What is a proper way to deal with this situation?

# Answer
Have the character keep track of which objects it is currently "touching". Whenever collision happens with a new object, add it to the list, and trigger a collision event (The message in your case).

When collision happens with an object it is already touching, do position collisions (so the character doesn't clip through), but don't trigger the event. If the character moves away from the object it was touching, remove it from the list.

This will work with both 2D or 3D graphics.
> 1 votes

# Answer
What is this message box used for? Is it just for debugging or is it part of a gameplay feature?

You would need to add booleans to your code and conditions, which check, whether you should print the message or not. What kind of condition you add would depend on what you want. You need to ask yourself what needs to happen in order to UNLOCK the status box (i.e. enable printing messages again). Do you want to make it dependable on time? For example, the status box prints a message upon collision and with continious collision you print every x seconds. Or whether you want to only catch "first collisions". In that case you would need to re-enable the status box once the player stopped moving into the object.

I don't know what your code structure looks like in detail. Would help, if you could post the collision detection of the player object with other objects and the code for the status box.
> 0 votes

# Answer
What about simply checking if the message box exists. When it doesn't you can make one and if it does then don't make one. This assumes it gets removed. If it doesn't get removed you could make a boolean which is set to false when the player doesn't collide. but true when they do. If they collide you check the value of the bool, if its false you add the message and set it to true. Otherwise you don't add the message.
> 0 votes

---
Tags: collision-detection
---


# Question
Title: Add single color background to texture using shader
I want to add a single color background to my texture. In my case, in Unity UI, I can simply create two Image components, one on top of another, and use the one on the bottom as a single color background. However, I would like to do it in a single draw call, using a shader. This is the shader that I use:

```
   Shader "UI/Background Tinted"
   {
    Properties
    {
        [PerRendererData]_MainTex ("Sprite Texture", 2D) = "white" {}
        _BgClip ("Offset Mask", Range(0,0.1)) = 0.025

        _StencilComp ("Stencil Comparison", Float) = 8
        _Stencil ("Stencil ID", Float) = 0
        _StencilOp ("Stencil Operation", Float) = 0
        _StencilWriteMask ("Stencil Write Mask", Float) = 255
        _StencilReadMask ("Stencil Read Mask", Float) = 255

        _ColorMask ("Color Mask", Float) = 15

        [Toggle(UNITY_UI_ALPHACLIP)] _UseUIAlphaClip ("Use Alpha Clip", Float) = 0
    }

    SubShader
    {
        Tags
        {
            "Queue"="Transparent"
            "IgnoreProjector"="True"
            "RenderType"="Transparent"
            "PreviewType"="Plane"
            "CanUseSpriteAtlas"="True"
        }

        Stencil
        {
            Ref [_Stencil]
            Comp [_StencilComp]
            Pass [_StencilOp]
            ReadMask [_StencilReadMask]
            WriteMask [_StencilWriteMask]
        }

        Cull Off
        Lighting Off
        ZWrite Off
        ZTest [unity_GUIZTestMode]
        Blend SrcAlpha OneMinusSrcAlpha
        ColorMask [_ColorMask]

        Pass
        {
            Name "Default"
        CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #pragma target 2.0

            #include "UnityCG.cginc"
            #include "UnityUI.cginc"

            #pragma multi_compile __ UNITY_UI_CLIP_RECT
            #pragma multi_compile __ UNITY_UI_ALPHACLIP

            struct appdata_t
            {
                float4 vertex   : POSITION;
                float4 color    : COLOR;
                float2 texcoord : TEXCOORD0;
                UNITY_VERTEX_INPUT_INSTANCE_ID
            };

            struct v2f
            {
                float4 vertex   : SV_POSITION;
                fixed4 color    : COLOR;
                float2 texcoord  : TEXCOORD0;
                float4 worldPosition : TEXCOORD1;
                UNITY_VERTEX_OUTPUT_STEREO
            };

            fixed4 _TextureSampleAdd;
            float4 _ClipRect;
            float _BgClip;

            v2f vert(appdata_t v)
            {
                v2f OUT;
                UNITY_SETUP_INSTANCE_ID(v);
                UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(OUT);
                OUT.worldPosition = v.vertex;
                OUT.vertex = UnityObjectToClipPos(OUT.worldPosition);

                OUT.texcoord = v.texcoord;

                OUT.color = v.color;
                return OUT;
            }

            sampler2D _MainTex;

            fixed4 frag(v2f IN) : SV_Target
            {
                half4 main = tex2D(_MainTex, IN.texcoord);

                float mask = 1.0 - main.a;

                half4 bg = IN.color;
                bg.a = mask;

                half4 color = main + (bg * mask);

                return color;
            }
        ENDCG
        }
    }
}

```

With two Images component everything is fine. However, with single shader approach I encounter sharp edges near image alpha boundaries.

Using 2 images, looking fine:

Using single shader, jagged edges:

How do i fix that, using a single shader approach?

# Answer
I figured it out using the following code in pixel shader:

```
            float mask = 1.0 - main.a;

            half4 bg = IN.color;
            bg.a = mask;

            half4 color = half4((main.rgb * main.a + bg.rgb * bg.a), main.a + bg.a);

            return color;

```
> 0 votes

---
Tags: unity, shaders, fragment-shader
---


# Question
Title: Load large quantities of data in Unity3D
I'm building an Android app using Unity3D where users can visualize data immersively.

The data is immutable and stored using a MySQL database hosted on cPanel.

When the user clicks a button in the environment, it starts the creation of a chart. First, contacts a .php file present in the server responsible to query the database, fetching the data and make it available to the Unity controller which then adds the points to the chart. This works fine for small quantities of data.

To increase performance, thought of exporting from MySQL as CSV and transform to one JSON, instead of querying a database or try to make MySQL transform to JSON, but I'm afraid this won't be enough.

Could also extract as CSV and use a 3rd party for reading it.

How would you load the data in such case to have the best performance?

# Answer
> 2 votes
**TL;DR**

Use metrics to find what's a performance problem, don't just guess what it is.

**TL**

As you're accessing it via a web interface, the datastore at the back end is irrelevant. The performance considerations for you concern the transport of the data to your client and then the parsing of the data into workable data structures (i.e. C# classes).

If you have control of the format you receive the data in, and it's tabular, then CSV will smaller than JSON. If not, then you have to work with what you're given.

You said you can parse from CSV into JSON, which means you already have a working CSV parser and so have no need for the JSON.

The performance hits now are to do with processing power (to read the CSV) and memory (is it big enough to hold the dataset you want to work with?

If those are fine then you need to consider the number crunching and searching. To find the data (in memory) that you're interested in you need to use a nicely indexed data structure. You might find that the `System.Data.DataTable` is best, it's old and can cause allot of GC collections but it may be good enough for your MVP. If that doesn't work then you need to write a bespoke structure.

You may also was to calculate some aggregations and store those so that they're not calculated on the fly (you might even have these delivered to you by the call to your PHP file, the server & DB are far more capable of doing this that a mobile device), as well as store aggregations the user has requested ready for when they ask for them again.

Long answer, but you question isn't a simple one to answer. Whatever you decide to do, you **must** gather metrics in order to find out what is *really* the performance problem rather than what you *think* is the performance problem.

---
Tags: unity, android, data-oriented
---


title: How to upgrade a project in Unity Hub

text:
# Question
Title: How to upgrade a project in Unity Hub
Before Unity Hub, it used to be the case that if you opened up a project that was from an older version, you would be prompted to upgrade the project.

I am now on the latest Unity Hub 2.0.0 and I am trying to open a project that was last saved with `2018.2.1f1` but I am unable to. From installs, I am able to download and install the closest available version, `2018.2.21f1`, but anytime I try to open my project I get the message

> Missing editor version 2018.2.1f1 on this machine. Select another version from the list or install the missing one.

How can I upgrade this project like we did in older versions?

# Answer
> 46 votes
The entry in the Unity Version column is a drop-down menu. Click on it and you can select one of your installed versions to which to upgrade your project. Remember to save a backup elsewhere first!

In older versions of the Unity Hub, this drop-down menu would only work if you had at least two versions of Unity installed (whether or not either of them matched the project version). But as of the last time I checked in 2020, this now works even if you have only a single version installed.

# Answer
> 5 votes
I can verify PixelCake's issue, and elaborate on Mario's reply. You don't specifically need **the** older version to be installed - literally any other version present on the system will allow you to upgrade.

With only one Unity version installed, you will get no dropdown under the Unity Version column, and the version number appears as simple text. Clicking the text does nothing. Clicking the project name fails to open the project, and displays the error as PixelCake reported.

To reproduce this effect, install Unity 2019.2.6f1 from the download page, and create and save an empty project with that version. Uninstall **all** Unity versions, then install any higher version (as of this writing, 2019.2.8f1 is the highest). Make sure this is the only version installed. Then, try to open your project. The "Unity Version" column will be text, not a dropdown, showing the only installed Unity version. Opening the project through Unity Hub will be impossible, giving the error reported in the original post:

However! Now install *any other Unity version*. In this example (just to illustrate the point) I installed a very old Unity version, 2017.1.5f1. With two+ versions available, the dropdown is now present, and the project can be opened in 2019.2.8f1:

Note that the little orange caution sign is gone. You can now select the higher version, upgrade the project, then delete the dummy install that forced the dropdown to appear.

Assertion: **I should be able to upgrade my project to a newer version of Unity, even if that's the only version installed.**

---
Tags: unity
---


title: understanding the basics of raytracing

text:
# Question
Title: understanding the basics of raytracing
I have got a sphere in my world space. I don't understand how can i find my sphere using my X and Y on my screen, because i don't understand what the value Z of my ray assuming the fact that we use world coordinate system.

# Answer
> 0 votes
Raytracing is an algorithm, that is a recipe, or series of steps to achieve a result, like so:

```
For each pixel in final image, loop
    1. Convert pixel direction (x0, y0, 1) to world space direction (x1,y1,z1) using inverse view transform
    2. using the new ray direction, perform collision detection
    3. sort the list of hits in ascending order, and choose the lowest distance.
    4. get information (colour etc) from the hit data.

    5. If (lighting) do lighting calculations #optional

    6. while (reflectionsEnabled AND rayCount < maxRays) loop #optional
        6a. compute reflected ray
        6b. repeat steps 2-5 and add to result
        6c. Increment rayCount.
    end while loop

    7. while (refractionsEnabled) loop #optional
        7a. Compute refracted ray.
        7b. repeat steps 2-6 and add to result
    end while loop

    assign result to image at coordinates (x0,y0)
end for loop

```

Ignore steps 5-7 until you are ready for them, but remember that a good raytracer should be able to do them.

This algorithm requires a change of coordinate system (view space to world space). To do this, you need to know a little matrix mathematics, in particular, homogeneous coordinate systems and affine transformations. A little vector mathematics wouldn't hurt either.

You will have to generate a view space transform, then compute the inverse of it (fortunately only once for a frame), and use that to transform your (x * y) parallel ray directions into world space.

You will then need a starting point in world space for each of your rays.

You then compute a ray of \[max ray distance\] length, and use it to compute ray vs sphere collision detection. In your case, a single sphere, once you have worked out if you have a hit or not, you can do the colouring of the pixel.

If you want to do fancier stuff, you will need the collision normal vector, distance from the origin point, light direction etc, in order to perform realistic lighting, but don't worry about that for now.

You don't "find" the sphere, as you are not looking for it. If a ray hits it, then you update the pixel with it's colour. If not, leave the pixel black.

---
Tags: opengl, raytracing
---


# Question
Title: How to draw a smoother solid-fill circle?
I'm experimenting with drawing circles and have brute-forced a very simple one:

Pseduocode:

```
r=7
d=r*2

for y = 0 to d
  for x = 0 to d
    if (x-r)^2 + (y-r)^2 <= (r)^2
      plot(x+r, y+r, c)
    endif
  next
next

```

The principal is simple. Step through every point in a square and plot every point which lies within the area of the circle.

I end up with something like this:

I don't want the single-pixels that appear on on each side so I adjusted this line from:

```
if (x-r)^2 + (y-r)^2 <= (r)^2

```

to:

```
if (x-r)^2 + (y-r)^2 < (r)^2

```

I end up with a circle like this:

While this IS a circle, it's not quite the circle that I want. The edges are too sharp and don't slope in a convincing way. Instead, I want to draw something little smoother like this:

But I'm not sure how to "relax" the the pixels to achieve this.

The code I posted is meant to illustrate how I'm drawing the circle-- I'm not looking for optimizations. I'm only interested in tweaking it to manipulate the smoothness of the circle being drawn.

This is more than an adjustment for the last pixel along each side. I want something that scales with the size of the circle.

---

**UPDATE**

I experimented with the code provided by @user1118321 an found that I could manipulate which pixels were drawn along the edge by considering the distance of the point being plotted from the center of the circle.

This allows me to apply a threshold on the points at the very edge of the circle and to decide which ones I want to skip over.

The results vary depending on a few different factors and would benefit from fine-tuning with a table for an optimal threshold for very small circles to taste.

Here is one solution which provided me with the circle I was looking for:

```
for y = 0 to r*2
  for x = 0 to r*2
    deltaX = r - x
    deltaY = r - y
    distance = sqr(deltaX^2 + deltaY^2)

    // Point lies outside of the circle
    if distance-radius > 1
      continue
    endif

    // Edge threshold
    if radius/distance < 0.9
      continue
    endif

    plot(x, y)
  next
next

```

Here are some examples of various circles I was able to create:

# Answer
The midpoint circle algorithm calculates a raster path by selecting pixels which are as close as possible to solutions of \\$x^2 + y^2 = r^2\\$. At each step, the path is extended by choosing the adjacent pixel which satisfies \\$x^2 + y^2 \leq r^2\\$, but maximizes \\$x^2 + y^2\\$.

The algorithm takes advantage of the fact that a circle is symmetric. That is to say, if you can correctly draw any 45° section of the circle, all the remaining sections can be found by mirroring the pixels that you've already solved for. Thus, it draws all eight octants simultaneously, starting from each cardinal direction (0°, 90°, 180°, 270°) and extends both ways to reach the nearest multiple of 45°. This means it can stop when `x == y`, as that indicates it has traveled 45°.

Consider the following image:

Starting at 90°, note that as we follow the curve to the right, we need to decide when to take a step in the y direction. The algorithm essentially does this by tracking the accumulated error (similar to how Bresenham's line algorithm works). Also note that the image show calculations going from the middle of the center pixel to the middle of the edge pixels.

In terms of code, here's an implementation based on the (Java) code at RosettaCode.org:

```
public void drawCircle(int centerX, int centerY, int radius) {
    int d = (5 - r * 4)/4;
    int x = 0;
    int y = radius;

    do {
        plot(centerX + x, centerY + y);
        plot(centerX + x, centerY - y);
        plot(centerX - x, centerY + y);
        plot(centerX - x, centerY - y);
        plot(centerX + y, centerY + x);
        plot(centerX + y, centerY - x);
        plot(centerX - y, centerY + xr);
        plot(centerX - y, centerY - x);
        if (d < 0) {
            d += 2*x + 1;
        } else {
            d += 2*(x - y) + 1;
            y--;
        }
        x++;
    } while (x <= y);
}

```

The `d` variable is basically responsible for accumulating the drift between the ideal perfect circle & the raster location. When it accumulates enough, the code takes a step in the y direction. The block of plotting code is responsible for mirroring the `x,y` locations across all octants of the circle.

The code above will plot the outline. For my own purposes, I didn't just need the outline, I essentially needed a fill. To that end, I modified the code to give me an array holding the length of each row (the index for the array being the height) for a quarter section of the circle. Also, as a matter of personal preference, I converted the `do` loop into a `while` loop:

```
public int[] quarterCircleScanLineWidth(int radius){
    int[] result = new int[radius+1];
    int x = 0;
    int y = radius;
    int p = 1 - radius;

    quarterCircleScanLineWidthHelper(result, x, y);

    while(x < y){
        x++;
        if(p < 0){
            p += 2*x + 1;
        }
        else{
            y--;
            p += 2*(x-y) + 1;
        }
        quarterCircleScanLineWidthHelper(result, x, y);
    }
    quarterCircleScanLineWidthHelper(result, x, y);
    return result;
}

private void quarterCircleScanLineWidthHelper(int[] data, int x, int y){
    if(data[y] < x){
        data[y] = x;
    }
    if(data[x] < y){
        data[x] = y;
    }
}

```
> 3 votes

# Answer
If you think of the circle as a cone passing through the screen, with the point being in the center of the circle, you can reformulate it in a way that's pretty easy to code. The distance from the center will be between 0 and radius. But you want it to be 0 at the radius. So if you reverse it, you get something like this:

```
for (float y = 0; y < 2.0 * r; y++)
{
    for (float x = 0; x < 2 * r; x++)
    {
        float deltaX = r - x;
        float deltaY = r - y;
        float distance = sqrt(deltaX * deltaX + deltaY * deltaY);
        color = clamp (r - distance, 0, 1);
        plot(x, y, color);
    }
}

```

That produces output like this:
> 1 votes

# Answer
The simplest thing to do is to exclude radii which don't agree with your idea of an ideal circle.

The way to do this is to use really any of the algorithms desired, but filter the input value `r` for certain ranges which produce unacceptable outputs: do not use the exact `r`, but rather *snap* to an acceptable nearby (higher or lower) value of `r` if within those ranges, using similar logic to `Math.Round` found in most languages.

When `r` has a small fractional part, something like values of `1.01`, `2.01`, `3.01`, etc. (or `1.51`, `2.51` depending on how your circle is drawn) , I believe that is when you will find these annoying edge pixels.

If you disallow those input values, you will avoid the issue entirely for all possible radii, though as the radius get larger and large, the problem will be less pronounced because you will no longer just see a single pixel at the edge, but rather more of them, and at that point it becomes a non-issue.
> 0 votes

---
Tags: 2d, graphics-programming, rasterization
---


# Question
Title: How to "aim ahead of" an object moving in a circle?
Let's say I have a GameObject `A` that's moving in a circular path in orbit around a central point, and I have a second GameObject `B` that is capable of independent movement, and can move at a higher velocity than `A`. `B` may be located at an arbitrary point, either inside or outside of `A`'s orbit. I want to calculate the fastest route that will cause object `B` to intercept object `A`. (The problem is not *exactly* "I want a spaceship to arrive at a planet", but close enough for the purposes of this question.)

The obvious idea is to compute a bunch of concentric circles around `B` and use some sort of divide-and-conquer guesswork to narrow in on a circle that ends up touching `A`'s orbit at exactly the point where `A` would be if `B` moved to that point at its maximum speed. But that feels a bit clunky, not to mention computationally expensive for something that I'd want to do fairly frequently, potentially multiple times per frame. Is there a better way to calculate this?

For simplicity's sake, assume that all calculations are occurring in a 2D plane.

# Answer
> 0 votes
This approach uses approximation, since I'm not sure how this would be solved for a definitive answer, but this solution will probably work for your purposes, as long as you aren't Nasa.

First, you need to find how long it takes object A to make 1 full rotation (also known as the period of object A). Call this P. Then, find the distance from object A to the center of its rotation (or the radius of object A's rotation). Call that R. These are constant variables, and should be determined ahead of time.

Then, at runtime, find the distance from object A to object B, and divide that distance by B's velocity to find the time it will take B to reach A if A remained stationary. Call that time T2. To get the distance around circle, create a `new Vector2 (Mathf.Cos(T2/P), Mathf.Sin(T2/P))`and multiply it by R. Add the orbit's position to that vector to give you the point that A will be at when B would reach A. Call this position A'.

Finally, all you have to do is tell B to aim straight towards A'. A' is recalculated every frame, so B will travel in a more or less straight line and hit A.

Now, you will notice that A' isn't where A actually will be when B hits A. If you want more accuracy ahead of time, you can repeat this process multiple times, each time finding the distance between the projected point A' and B instead of A and B. You could do this, say, 30 times right before you launch B, and that might give you a close enough estimate that you don't need to calculate it once per frame. Or you could do this 3 times per frame, adding a little lag to give a better estimate. It really just depends on how much accuracy you need, how much performance you're willing to sacrifice for it, and whether you prefer lag spikes or slower frames.

---
Tags: unity, geometry
---


# Question
Title: How to make an animation play when a button is pressed once?
I have added an idle and jump animation to a character in unity. I can make the animation happen when the button is pressed. If the button is up middle at the animation the character goes to the idle position. But I want the whole animation happen in one press to the button and then go back to the idle position. My current script and Animator views are:

```
if (Input.GetKeyDown(KeyCode.Space))
    {
        Anim.SetBool("is_jumping", true);
        ApplyInput(moveAxis, turnAxis);
    }
    else if (Input.GetKeyUp(KeyCode.Space))
    {
        Anim.SetBool("is_jumping", false);
    }

```

# Answer
> 0 votes
Use a Trigger instead of a Boolean for this.

A trigger is like a boolean, except that it automatically resets itself to false after one frame if you set it to true.

```
if (Input.GetKeyDown(KeyCode.Space))
    {
        Anim.SetTrigger("is_jumping");
        ApplyInput(moveAxis, turnAxis);
    }

```

Note that you will need to replace "is\_jumping" with a trigger in the animator.

---
Tags: unity, c#, animation, animator
---


# Question
Title: Why can't a blueprints project edit BPs derived from c++ classes?
I am working in a relatively small team.

Now, because our IT guy is incredibly unhelpful, we don't yet have VS on all the machines (as I know this would solve the error). However, I'm still curious as to the answer to this question.

Computer A:

* C++ project
* Creates C++ classes
* Creates BP derived from said C++ classes.
* Sends project to Computer B.

Computer B:

* Gets project
* Tries to edit BP classes
* Can't open them
* Reason: 'They derive from parent C++ classes'

---

So my base question is really why is this?

I understand that this can be solved easily, but I'm interested as to why Unreal imposes these limitations.

# Answer
> 1 votes
One of the requirements to develop with Unreal is to have Visual Studio installed. Because you are specifically working with a C++ project any attempt to open the project will also try to open Visual Studio. Since it isn't installed it errors out.

As for "why unreal imposes this limitation" is "because". It's a requirement of the engine and editor to work.

Communicating this requirement to your IT guy effectively might help them understand they need to hurry up and get it on all machines:

https://docs.unrealengine.com/en-US/GettingStarted/RecommendedSpecifications/index.html

> # Minimum Software Requirements
>
> Minimum requirements for running the engine or editor are listed below.
>
> ## Running the Engine
>
> Operating System: Windows 7
>
> DirectX Runtime: DirectX End-User Runtimes (June 2010)
>
> ---
>
> The requirements for programmers developing with the engine are listed below.
>
> **Developing with the Engine**
>
> All 'Running the Engine' requirements (automatically installed)
>
> Visual Studio Version
>
> * Visual Studio 2017 v15.6 or later (recommended)
> * Visual Studio 2019

Note:

> Visual Studio 2015 is no longer supported in the current release of UE4. If you are developing with the current release of UE4, you need to use either VS 2017 or VS 2019.

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


title: Unity RTS Multiple Selection Approacah

text:
# Question
Title: Unity RTS Multiple Selection Approacah
I've recently solved the single selection problem but now I want to do multiple selections. I know I need to find two points with the mouse position to draw a box but it just won't work for me.

```
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            bool dragging = true;
            Debug.Log("Multiselect active");
            MultiSelect(dragging);
        }
    }
    private void MultiSelect(bool dragging)
    {

        mouseDownPoint = Input.mousePosition;
        if (Input.GetMouseButtonUp(0) && dragging)
        {
            mouseUpPoint = Input.mousePosition;
        }
        Debug.Log("First pos: " + mouseDownPoint + " Second pos: " + mouseUpPoint);
        dragging = false;

    }

```

What is a better way to achieve what I'm trying? If someone can tell me a way that can also detect any units inside the area that'd be nice too.

# Answer
You get the start point and end point but you also want to calculate the height and width.

```
public class CameraSelections : MonoBehaviour
{
public static Rect selection = new Rect(0, 0, 0, 0);
private Vector3 startClick = -Vector3.one;
public Texture2D selectionHighLight = null;

private void LateUpdate()
{
    StartDrag();
}
private void StartDrag()
{
    if (Input.GetMouseButtonDown(0))
        startClick = Input.mousePosition;
    else if (Input.GetMouseButtonUp(0))
        startClick = -Vector3.one;

    HandleSelectionArea();
}
void HandleSelectionArea()
{
    if (Input.GetMouseButton(0))
    {
        selection = new Rect(startClick.x, Screen.height - startClick.y, Input.mousePosition.x - startClick.x, (Screen.height - Input.mousePosition.y) - (Screen.height - startClick.y));
        if (selection.width < 0)
        {
            selection.x += selection.width;
            selection.width = -selection.width;
        }
        if (selection.height < 0)
        {
            selection.y += selection.height;
            selection.height = -selection.height;
        }
    }
}
private void OnGUI()
{
    if (startClick != -Vector3.one)
        GUI.DrawTexture(selection, selectionHighLight);
}

}

```

then in your player or selectable you can set the Selected bool to true if the selectable is inside the Rect

```
public class Player : MonoBehaviour
{
public bool Selected=false;
void Update()
{
    if (Input.GetMouseButton(0))
    {
        Vector3 camPos = Camera.main.WorldToScreenPoint(transform.position);
        camPos.y = Screen.height -camPos.y;

        //if inside the cameras drag selection area then mark player as selected
        Selected = CameraSelections.selection.Contains(camPos);
    }
}
}

```
> 1 votes

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


# Question
Title: Unity - Scripting Runtime Version Option Missing
I have been trying to open and run my couple-months old project in Unity3D, and I'm getting about 500 errors. So idecided to reinstall Unity. On the tutorial for the project, it tells us to make sure the "Scripting Runtime Version" is set to 4.x equivalent. Only problem for me is I cannot see such an option in Unity5.5.4p4. How can I set .NET 4.x in Unity for good?

# Answer
Starting from Unity 2019.2, this option is no longer available in the project settings. To solve this, I had to install the 2018.4 (LTS) version.
> 1 votes

# Answer
That option was not available on Unity 5 if I remember correctly. Try upgrading to the latest version.
> 0 votes

---
Tags: unity, .net
---


title: Simple 2d Movement (Non platformer)

text:
# Question
Title: Simple 2d Movement (Non platformer)
This seems so simple but my searching as failed to find a good result.

The idea is that you can move in 360 degrees but you aren't faster when you move in a diagonal direction. I know how to do this with trig. The problem is I I want some physics so that if you are traveling north and start traveling south you first need to slow down to zero to go south. (And if going 270 deg to 30 deg it would be a more complicated.) The character has acceleration and a max speed.

I know that vectors are the solution but I can't find how to apply them the current speed to get smooth movement.

I'm doing this in GameMaker Studio 2, but pseudocode should suffice. Here's what I have.

```
var h,v;
h = key_to_axis(vk_right,vk_left);
v = key_to_axis(vk_down,vk_up);

var dir = point_direction(0,0,h,v)
spd = approach(spd,max_spd,accel);
x+= lengthdir_x(max_spd,dir);
y+= lengthdir_y(max_spd,dir);

```

Note that this movement is shared by characters that can move in the full 360 degrees.

# Answer
> 0 votes
Figured it out. The trick is to make another acceleration vector (or two variables) with the magnitude of acceleration rate and the direction that you want to go. Then to add it to your current velocity (both x speed and y speed). Check the magnitude of the the velocity to ensure its not greater than the top speed. Then apply it to x and y.

I added a friction vector that constantly goes against your velocity. It also can't be larger than your current speed and is stronger if you aren't moving. This mimics reality because when you slow down you get the benefit of friction but when accelerating it works against you.

```
///Player Movement
not_moving = !mouse_check_button(mb_left) || point_distance(x,y,mouse_x,mouse_y)<30;
goal_dir = point_direction(x,y,mouse_x,mouse_y)
//Friction
var move_fric = not_moving ? fric+accel : fric; //if not moving then you accel to a stop

var spd = sqrt(sqr(vx)+sqr(vy));
var dir = (point_direction(0,0,vx,vy)+180)%360;
var ax,ay;
if(spd<fric){
    move_fric = spd;
}
ax = lengthdir_x(move_fric,dir);
ay = lengthdir_y(move_fric,dir);
vx += ax;
vy += ay;

//Go
if(!not_moving){
    var dir = goal_dir;
    var ax,ay;
    ax = lengthdir_x(accel,dir);
    ay = lengthdir_y(accel,dir);
    vx += ax;
    vy += ay;
    spd = sqrt(sqr(vx)+sqr(vy));
    if(spd>max_spd){
        vx = lengthdir_x(max_spd,dir);
        vy = lengthdir_y(max_spd,dir);
    }
}

```

---
Tags: 2d, movement, game-maker
---


# Question
Title: How to make a collider the follows all the animations of a prefab?
I have attached a capsule collider with my player(prefab) and made a script so that when Space key is down it does the jump animation in Unity. But because of the collider not jumping with the player, the player gets stopped by obstacles though he visually passed it. How can I make a collider that moves with my animations attached to a prefab?

# Answer
> 1 votes
You can move the collider's `transform` but not with animation. To animate the `collider`, you can make a child object and assign collider component to that child object, then you can make an animation that moves the collider child object with aniamtion.

Otherwise you can disable `APPLY ROOT MOTION` from your animator component and let **physics** move it by `AddForce()`

---
Tags: unity, collider
---


# Question
Title: How can I clip my sprite as it passes through a portal in a 2D scenario, using OpenGL?
This is a very simple question, but after a brief search and reading through the "similar questions" I could not yet find an answer.

I'm creating a 2D game using OpenGL and came across a problem: Let's say I wanted to create portals. An Entity can move into a portal A and come out of the corresponding portal B. Transforming the coordinates and velocity of the entity is easy, but this would create "hard" texture-teleportation. Which means: while half of the entity is in the A-portal, it won't be rendered on the corresponding B side. How would I create a smooth transition?

My first Idea was: I define "exit"- and "entry"-zones containing the transformation function (Matrix). Now when an Entity enteres the exit-zone the entity is also drawn at the entry zone using the transformation-matrix relative the the entry/exit-zones. But drawing it twice would still give me the difficulty, that I need to clip the entity on the portals "backside". (The entity shall vanish behind portal A when entering).

So my second thought was, that there should be a solution using (vertex?) shader? But how would such a shader look like? (Example code would be nice, but not neccessary. I'd rather want to have a "what the shader would do" answer). Would I define Uniforms (exit- and entry zones) which the shader would clip/transform ("move") the vertexes from?

How does a typical solution for this clipping look like? Or where could I read some information about these kind of problems? I only found some to 3D versions, where the view of portal B should be rendered in portal A. But this does not solve the object-moving-through-it problem...I think In my opinion changing the draw-order, or rendering something above the backside of the portals is not the right way to go, since this could create strange behavior in certain situations. (Portal B is just behind portal A for example. One of both would be overdrawn I think.)

# Answer
> 0 votes
The answer for me myself is "simply" using the so called stencil-buffer, which is a feature in OpenGL. By simplifying the question to "how to clip something behind a wall in 2D" I was able to find the feature and use it. By adding the region in front of the wall (or portal) into the stencil buffer and then only allowing rendering of the entity, if the value within the stencil buffer is 1 OpenGL clips away the rest of the entity, which moves into the wall/portal.

Solving the coming out of the other side of the portal part will simply be adding a clone of the entity at portal B and have it move in correlation to it's clones movement at portal A.

---
Tags: opengl, 2d, shaders
---


title: Unity Bot AI behaviour

text:
# Question
Title: Unity Bot AI behaviour
I'm working in Unity3d 2019.2.0f1 and I'm trying to make a chasing bot that follows a certain `GameObject` with the "Player" tag.

I'm not yet attempting a field of view approach.

How the Script works:

Step 1 : Overlap a sphere on the Bot AI's `transform.position` and put all the things in the sphere inside a `Collider[]`.

Step 2: Go through each `collider` in ColliderArray and look for a `GameObject` with the tag "Player".

Step 3: If found shoot a `Raycast` to said `GameObject` with tag.

Step 4: If the Gameobject hit does not have the "Player" tag, then the "Player" is being blocked by a obstacle therefor not in the line of sight, if the `GameObject` isn't blocked by an obstacle then we set the destination of the referenced `Navmeshagent`.

The problem I'm finding (with about 3000 Debug.Logs) is that the `Raycast` only shoots around 7 times and then just stops, also the "Player" needs to stand in a very specific random location (even tho the "Player" is in plane sight).

What am I doing wrong here?

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class EnemyAI : MonoBehaviour
{
    NavMeshAgent agent;

    public float LookRadius = 20; //unity units

    void Start()
    {
        agent = GetComponent<NavMeshAgent>();
    }

    // Update is called once per frame
    void Update()
    {
        Collider[] colliders = Physics.OverlapSphere(transform.position, LookRadius);

        foreach(Collider Object in colliders)
        {
            if(Object.transform.CompareTag("Player"))
            {
                RaycastHit hit;

                if(Physics.Raycast(transform.position, Object.transform.position, out hit, Vector3.Distance(transform.position, Object.transform.position)))
                {
                    //if not true the we hit a obstacle.
                    if(hit.transform.CompareTag("Player"))
                    {
                        agent.SetDestination(hit.transform.position);
                    }
                }
            }
        }
    }
}

```

# Answer
According to documentation the second parameter of `Physics.Raycast` (in the shape you're using) is a direction, not a position. So you have to compute the direction where you want to cast your ray from the agent.

You can get the direction by `(target.position - transform.position).normalized`.

Also, for optimization sake (not related to your question), it appears that the `OverlapSphere` call that you're doing is not necessary. You have probably a way to get the Players transforms in your code (via a singleton pattern or something else). Doing so you would avoid looping on every single object that contains a collider and that is around your agent. A simple call to `Vector3.Distance()` would be necessary to know if the player is close enough of your agent. Looping on every colliders of your scene for every agent would be overkill imho.
> 1 votes

---
Tags: unity, unityscript, bot
---


# Question
Title: How do I use GetComponent on multiple children?
I'm a beginner and I'm making a game in Unity where I set random colors for four enemies. I made an empty object called "enemies" for me to use it as a folder for the four enemies. I want to get the colors of the enemies and pick randomly one of them for my player.

I wrote this piece of code and I wanted it to store the colors in a list, but whenever I try to print it I find out that it only stores the color of the first child in the "enemies" hierarchy. How do I fix this?

```
enemies = GameObject.Find("enemies");

GameObject[] allenemies = new GameObject[enemies.transform.childCount];
List<Color> colors = new List<Color>();

foreach (Transform child in transform)
{
    allenemies[i] = child.gameObject;
    i++;
}

foreach (GameObject child in allenemies)
{
    thecolor = enemies.GetComponentInChildren<Renderer>().material.color;
    colors.Add(thecolor);
}

finalcolor = Random.Range(0, colors.Count);
//Debug.Log(finalcolor);

mr.material.color = colors[finalcolor];

```

# Answer
`GetComponentInChildren` returns only a single component (the first four item in a depth-first search).

The `Component` API has a similar method called `GetComponentsInChildren()` which returns an array containing all the relevant components.

You'll need to adapt your code slightly to use this, for example by calling `colors.AddRange()` to add the returned array to your color list.
> 1 votes

---
Tags: unity
---


# Question
Title: Calculate Mesh top, bottom, left and right position relative to mouse click position on the mesh
I have a mesh (suppose it can be circle, or rectangular,square or an **arc**). The geometry of the mesh can be anything. I can click on mesh at any position. From relative to the clicked position, I want to get its right, left top and bottom position of the mesh. Maybe the picture explain it better then my words

Update: I tried to apply a quick dirty solution. It is incomplete:

```
// Update is called once per frame
void Update()
{
    if (Input.GetMouseButtonDown(0))
    {
        //Ray r = Ray(Input.mousePosition);
        RaycastHit rayHit;
        Ray r = Camera.main.ScreenPointToRay(Input.mousePosition);

        if(Physics.Raycast(r,out rayHit,1000))
        {
            Debug.Log(rayHit.transform.name);
            Debug.Log(rayHit.point);
            Debug.Log(rayHit.normal);
            StartCoroutine(MoveToDirection(rayHit.point));
        }
    }

}

IEnumerator MoveToDirection(Vector3 startPosition)
{
    GameObject go = GameObject.CreatePrimitive(PrimitiveType.Cube);
    go.transform.position = startPosition;
    while (true)
    {
        go.transform.position=  go.transform.position + go.transform.up * Time.deltaTime* speed;
        yield return new WaitForEndOfFrame();
    }

}

```

On click i instantiated a gameobject and start moving in upward direction and when it leaves the mesh bounds i will get the position but it have differet problems, like: 1. It will not work with arc object or maybe with non rectangular geomerty. 2. I have to apply onTrigger and onExitEvent that can be skip when the cube move with fast pace.

# Answer
> 0 votes
Two possibilities here.

**1. Average but fast solution:** You could use the bounds of the mesh. Knowing the center and size of the bounds you could easily compare them to the position of the mouse and determine the left/right/top/bottom values that you need.

**2. Precise but slower solution:** As you know the mouse position you could project a line in left/right/top/bottom direction, then loop through every vertex of your mesh and check if your projected line intersects any line formed by two vertices. You would then have more precise values.

---

**EDIT**

The second solution requires you to get the vertices of the mesh. Even if your mesh is a circle it is composed of connected points/vertices to draw lines that are connected together to form a circle. You can get these points/vertices via `Mesh.vertices`. Once you get the array of vertices just take them two by two (`v[0]` with `v[1]`, then `v[1]` with `v[2]`... and so on) to get lines you can interesect with. Once you get a line (let say `v[0]` and `v[1]`) you can project a line from your mouse position in the direction you want (left for example). And using the functions given in the Wikipedia page above, you ca get an intersection point (or not). I you get a point (let's call it `inter_point`), it will mean that this segment of your mesh (`v[0]` and `v[1]`) is the left point you're looking for. You can now compute its distance from the mouse position by `Vector3.Distance(inter_point, mouse_position)`. Et voila.

Please not that for a very complex mesh, you may have several segment that would intersect your direction line, just take the further or closer distance according to your needs.

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


# Question
Title: What information should be stored in a database for a MOBA game?
I'm wondering what information should be stored in a database when developing a MOBA like game? For example: the current item a unit has, how much gold a player has, etc...

# Answer
> 1 votes
The information about the current state of an ongoing match is usually only required while that match is running. For performance reasons, that data should be in memory of the gameserver.

The only information you have to store in the database is information which persists between matches. Like player account information, unlocked content or statistics of previous matches which you use to rate player performance or to obtain metrics.

Speaking of metrics: Logging and storing some ingame events in a database *can* be useful to get data you can use to better balance your game. For example, you might want to find out which items players prefer to use and whether the amount of gold owned during different phases of the game is a predictor for winning the match. But that's optional. If you choose to log such metrics, that should be done *in addition* to keeping the information in memory.

# Answer
> 0 votes
The architecture of your game is up to you. But I'd suggest you to think in terms of security and gaming experience to avoid tricky situations and angry players.

In a MOBA storing informations in an external database will prevent some very annoying issues like, for example:

* player has uninstalled / reinstalled the game then lost everything
* player can hack the local database of the game and get more gold or use items he doesn't own

---
Tags: unity
---


# Question
Title: Shoot projectile same direction weapon faces
I want to be able to shoot a projectile from a weapon mounted on a vehicle. Right now I am able to do it but only in front of the vehicle. I managed to rotate the weapon to the direction the mouse is facing, but the projectile still goes straight.

I believe that the issue is that the velocity of the projectile is the problem here. Right now I have it like this:

```
if (playerShooting || NPCShooting)
{
    if ((timer >= cooldown) && hasEnergyAvailable())
    {
        timer = 0;
        GameObject intantiatedProjectileContainer = Instantiate(projectileContainer, transform.position, transform.rotation) as GameObject;
        Rigidbody instantiatedProjectile = intantiatedProjectileContainer.GetComponentInChildren<Rigidbody>();

        if (playerController)
        {
            instantiatedProjectile.velocity = transform.TransformDirection(new Vector3(0, 0, speed + transform.root.GetComponent<PlayerController>().getZSpeed()));
        }
    }
}

```

Where speed is the projectile speed and it's added to the vehicle speed.

I thought that this should shoot forward but with the parent rotation, can someone tell me what I'm missing here? Thanks!

# Answer
> 1 votes
```
Transform weapon;
Transform weaponMuzzle;

float ForceAmount = 10.0f;// or any value you want

private void Shoot()
{
    GameObject bullet = Instantiate(BulletPrefab, weaponMuzzle.position, Quaternion.Identity);
    bullet.AddForce(weapon.Forward * ForceAmount);
}

```

You need to `AddForce` to a bullet in the same direction of `weapon.Forward()` and instantiate the bullet on the location of your weapons muzzle. You'll have to make an empty gameObject and put it on the position of the weapon's head and and set it to `weaponMuzzle` in the inspector.

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


# Question
Title: changing color of sprite not every frame
So I have been trying making this game, which changes color of sprites in it. It should only happen when OnMouseDown(). but it is executing every frame and cannot go out of the couroutine. I want the color change to be slower. Please mark the colors should still change.

Please Help,

```
public class control : MonoBehaviour
{
    public bool startstop = false;
    SpriteRenderer m_SpriteRenderer;
    private void Update()
    {
        StartCoroutine("Changecolor", 3f);
    }
    IEnumerator Changecolor()
    {
        yield return new WaitForSeconds(3);
        if(startstop == true)
        {
            int random = Random.Range(1, 4);
            if (random == 1)
            {
                m_SpriteRenderer = GetComponent<SpriteRenderer>();
                m_SpriteRenderer.color = Color.blue;
            }
            else if(random == 2)
            {
                m_SpriteRenderer = GetComponent<SpriteRenderer>();
                m_SpriteRenderer.color = Color.red;
            }
            else if(random == 3)
            {
                m_SpriteRenderer = GetComponent<SpriteRenderer>();
                m_SpriteRenderer.color = Color.green;
            }
            else
            {
                m_SpriteRenderer = GetComponent<SpriteRenderer>();
                m_SpriteRenderer.color = Color.yellow;
            }
        }
    }
    private void OnMouseDown()
    {
        startstop = !startstop;
    }
}

```

# Answer
All you need to do here is move your if statement into the Update function. In your case you would be calling the co routine every frame, and there would be a lot off calls waiting for those 3 seconds to pass and then once the startstop is true, a lot of them would be called. So here, you basically only call it once the startstop is true, and then you immediately change its value to false so no more than 1 call is executed.

```
public class control : MonoBehaviour
{
    public bool startstop = false;
    SpriteRenderer m_SpriteRenderer;
    private void Update()
    {
        if(startstop){
            StartCoroutine("Changecolor", 3f);
            startstop = false;
        }
    }
    IEnumerator Changecolor()
    {
        yield return new WaitForSeconds(3);
            int random = Random.Range(1, 4);
            if (random == 1)
            {
                m_SpriteRenderer = GetComponent<SpriteRenderer>();
                m_SpriteRenderer.color = Color.blue;
            }
            else if(random == 2)
            {
                m_SpriteRenderer = GetComponent<SpriteRenderer>();
                m_SpriteRenderer.color = Color.red;
            }
            else if(random == 3)
            {
                m_SpriteRenderer = GetComponent<SpriteRenderer>();
                m_SpriteRenderer.color = Color.green;
            }
            else
            {
                m_SpriteRenderer = GetComponent<SpriteRenderer>();
                m_SpriteRenderer.color = Color.yellow;
            }
    }
    private void OnMouseDown()
    {
        startstop = !startstop;
    }

```
> 1 votes

# Answer
The other way would be looping the coroutine instead of calling it multiple times, and stopping it when needed.

```
public class Control : MonoBehaviour
{
    public bool startstop = false;
    SpriteRenderer m_SpriteRenderer;

    IEnumerator Changecolor() {
        yield return new WaitForSeconds(3);
        int random = Random.Range(1, 4);
        if (random == 1) {
            this.m_SpriteRenderer = this.GetComponent<SpriteRenderer>();
            this.m_SpriteRenderer.color = Color.blue;
        } else if (random == 2) {
            this.m_SpriteRenderer = this.GetComponent<SpriteRenderer>();
            this.m_SpriteRenderer.color = Color.red;
        } else if (random == 3) {
            this.m_SpriteRenderer = this.GetComponent<SpriteRenderer>();
            this.m_SpriteRenderer.color = Color.green;
        } else {
            this.m_SpriteRenderer = this.GetComponent<SpriteRenderer>();
            this.m_SpriteRenderer.color = Color.yellow;
        }

        this.StartCoroutine("Changecolor", 3f);
    }

    private void OnMouseDown() {
        if (this.startstop) {
            this.StartCoroutine("Changecolor", 3f);
            this.startstop = !this.startstop;
        } else {
            this.StopCoroutine("Changecolor");
            this.startstop = !this.startstop;
        }
    }
}

```

If this doesn't work you could fix it easily, as I'm at work and cant test it right now ^^
> 0 votes

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


# Question
Title: How to calculate the reachable space of the end effector in an IK chain?
I have an array of points in a 2d worldspace and I want to calculate which points are reachable by the end effector of a limb controlled with a CCDIK chain (with rotation limits applied).

* It's a limb with 2 hinges (upper arm & lower arm)
* The upper & lower arm have a fixed length
* The 2 hinges have fixed rotation limits
* This needs to be recalculated every update (continuously) as the limb is attached to a moving body
* I work in Unity using C#

Crude Illustration of the problem:

My idea sofar is to create a polygon collider along the outer edges of the reachable space, and then look if the points are within the bounds of that collider. But I have no idea if this is the smartest solution, or if so, how to achieve this.

How could I solve this issue?

# Answer
> 2 votes
Given that the arm exists in a 2D plane, the joints are hinge joints and not ball and socket joints, and the rotation arc for each joint is +/- maxangle:

Let H = the position of the end effector.

Let S = the position of the "shoulder" joint.

Let Slen = the length from the shoulder to the elbow.

Let Sdef = a normal vector representing the default orientation of S.

Let E = the position of the "elbow".

Let Elen = the length from the elbow to the hand.

Let SHMin = the minimum possible separation of the Shoulder and Hand (this can be pre-calculated).

TO FIND SHMin: Let Sdef = Vec(1, 0) (i.e. yaw set to zero)

1. Set the vector SE from S to E: SE = Vec(cos(Smaxang), sin(Smaxang)) * Slen.
2. Add SE to S to get E: E = S + SE.
3. Add Smaxang to Emaxang to get SEangle: SEangle = Smaxang + Emaxang.
4. Set the vector EH from E to H: EH = Vec(cos(SEangle), sin(SEangle)) * Elen.
5. Add EH to E to get H: H = E + EH.
6. Get the length of SH for Emaxang: SHlenemax = length(H-S).
7. Repeat 3-6 for -1 * Emaxang to get SHlenemin.
8. SHMin is the lesser of SHlenemin and SHlenemax.

TO DETERMINE IF POINT IS REACHABLE:

1. Set H equal to a position in the list.
2. Get the distance between S and H: SHlen = length(H-S).
3. Early Out: If (SHlen \> Slen + Elen), then point is beyond the reach of the arm.
4. Early Out: If (SHlen \< SHMin), then the point is too close for the arm to reach.
5. You now have the length of all three sides of a triangle. Use law of cosines to find angle between S and SH: c^2 = a^2 + b^2 − 2ab cos(C). This will be Elen^2 = Slen^2 + SHlen^2 - 2(Slen)(SHlen)cos(C) which solves to C = ACOS((Slen^2 + SHlen^2 - Elen^2) / (2(Slen)(SHlen)).
6. Create a normalized vector representing the direction of SE: VecA = (cos(C), sin(C)). SHnorm = normalize(SH). SEnorm = normalize(VecA + SHnorm).
7. Get the angle Sang between SEnorm and Sdef: Sang = ACOS(SEnorm (dot) Sdef).
8. Early Out: If (Sang \> Sangmax), then arm can't reach the point.
9. Get the position of E using SHnorm, Slen, and S: E = S + (SHnorm * Slen).
10. Get the normalized vector EHnorm from E to H: EHnorm = normalize(H-E).
11. Get the angle Eang between EHnorm and SHnorm: Eang = ACOS(EHnorm (dot) SHnorm).
12. Final Out: If (Eang \> Eangmax), then arm can't reach the point.

# Answer
> 1 votes
BONUS ANSWER: The question is only asking for, "Can the arm reach the point?" However, the next question would typically be, "What angles do I set each joint to so that the arm is touching the point?" My first answer describes the set up nicely, so using the terms of the answer, I will answer the followup question.

At this point, we know the absolute values of the angle Sang between (SE and Sdef) and the angle Eang between (SE and EH), but not the signed value.

TO FIND THE SIGNED VALUE OF THE ANGLES:

1. Expand the 2D vectors into 3D vectors by added a zero in the Z component: e.g. SE3 = Vec3(SE.x, SE.y, 0.0f), Sdef3 = Vec3(Sdef.x, Sdef.y, 0.0f).
2. Get the cross product SdefxSE of Sdef3 and SE3: SdefxSE = Sdef3 (cross) SE3.
3. The sign of SdefxSE.z will tell you whether to use +Sang or -Sang depending on whether you are using a right-hand or left-hand coordinate system. You may need to flip the sign.
4. Get the cross product SExEH of SE3 and EH3: SExEH = SE3 (cross) EH3.
5. The sign of SExEH.z will tell you whether to use +Eang or -Eang depending on whether you are using a right-hand or left-hand coordinate system. You may need to flip the sign.

# Answer
> 0 votes
Building on Gale's answer, I made the formula/math a little simpler, and I added my working C# code. I've built this in Unity, and used the same variables as Gale did.

**SHMin**

**// 1. Get the max angle that E can turn (whichever way) in Radians = maxEAng**

```
float maxEAng = Mathf.Max(Mathf.Abs(EHinge.min), Mathf.Abs(EHinge.max)) * Mathf.Deg2Rad;

```

**// 2. Use the max angle of E to calculate the vector to H from E**

```
Vector2 EHVec = new Vector2(Mathf.Cos(maxEAng), Mathf.Sin(maxEAng)) * EHlen;

```

**// 3. Add the length of SE to the x of the vector towards the end effector to find the position of H**

```
Vector2 H = new Vector2(EHVec.x + SElen, EHVec.y);

```

**// 4. The min distance from S to H is the magnitude of the position of H, given that S is at 0,0**

```
SHMin = H.magnitude;

```

**Calculate which grip is in range**

THis code loops through all the grips (points) and for each one checks if it is reachable, given the constraints of the arm.

**// Set H equal to a grip in the list**

```
for (int i = 4; i < gripArray.Length; i++)
    { Vector2 H= gripArray[i].position;

```

**// Get SHlen: SHlen = length(H - S)**

```
float SELen = (H - S).magnitude;

```

**//Early Out: If (SE \< minDistanceToE), then the point is too close for the arm to reach.**

```
if (SE < minDistanceToE) {continue;}

```

**// Early Out: If(SH \> Slen + Elen), then point is beyond the reach of the arm**

```
if (SH > Slen + Elen){continue;}

```

**// Use law of cosines to find angle between SE and SH c ^ 2 = a ^ 2 + b ^ 2 − 2ab cos(C) // This will be Elen ^ 2 = Slen ^ 2 + SHlen ^ 2 - 2(Elen)(SHlen)cos(C) // Which solves to C = ACOS((Slen ^ 2 + SHlen ^ 2 - Elen ^ 2) / (2(Slen)(SHlen))**

```
float C = Mathf.Acos(
(Mathf.Pow(Slen, 2) + Mathf.Pow(SHlen, 2) - Mathf.Pow(Elen, 2))
                / (2 * Slen * SHlen)
                );

```

**// Create a vector representing the direction of SE respective to SH // vecA = (cos(C), sin(C))**

```
Vector2 vecA = new Vector2(Mathf.Cos(C), Mathf.Sin(C));

```

**// Normalize SHnorm = normalize(SH)**

```
Vector2 SENorm = (H -S).normalized;

```

**// What are the angles for the direction of SE respective to SH + SH respective to the (0,-1) rotation limit axis**

```
var SEVecAngle = Vector2.SignedAngle(new Vector2(1, 0), vecA) ;
var SHAng= Vector2.SignedAngle(new Vector2(0, -1), SHnorm);
var combinedAngle = SEVecAngle + SHAng;

```

**// Final Out: If(combinedAngle \> maxSAngle or \< minSAngle), where the max and min angle is measured from rotation axis (0,-1) then arm can't reach the point.**

```
if (combinedAngle > maxSAngle || combinedAngle < minSAngle) {continue;}

Debug.Log(“Grip “ + [I] + “ is reachable!”

```

---
Tags: unity, c#, 2d, mathematics, inverse-kinematics
---


# Question
Title: How to make the player unable to change some of the game elements?
I am making a text turn based RPG fighting game in which you create your own spells. You also share them as JSON files with your friends. Sharing is required to win. *The game is designed so that it isn't a problem if a spell is copied and shared one billion times*

I do not want players to edit the files or the spell creator. The only reason is to not ruin others' experience. *I wouldn't mind at all if there were no multi-player elements in the game.*

**Is there a way to make some game elements unable to be modified ?**

My game is interpreted in Lua and has some bash integrated into it for file managing. It is also GNU/Linux only.

# Answer
> 2 votes
You can use cryptography. But doing that in a way that actually prevents people from creating spells requires that you do not ship the private key to users, which implies either an internet server, or pre-signing all the spells.

To get a little more concrete, you can cryptographically sign the spells, which essentially means you append a signature to the file which you can use the public key to authenticate. See https://en.wikipedia.org/wiki/Digital\_signature

As mentioned before if the private key is on the user’s machine, then it will be possible to use it to create arbitrary spells that another copy of the game would accept! So if you want the spells to be dynamic, then you need someplace to have the private key where players can’t see it which implies a server.

But, if you don’t want to do that, another option would be to create all the shareable spells ahead of time and to pre-sign them. That way, only those spells will be accepted by unmodified versions of the game. (Someone could still modify their own copy of the game to cheat, whether you use a server or not.)

Given that this is a GNU/Linux only game as you say, I can guess that you may want to open-source it at some point. Understand that if you open-source the private key then all this crypto stuff will be circumventable. You could make a different private-public key pair for an open-source version if you like, without compromising any other key pairs.

---
Tags: lua, linux, data, anti-cheat, user-generated-content
---


# Question
Title: What goes into a realistic wood material?
Aside from getting a wood texture to use for albedo, what goes into a realistic wood material? For example, in Unity, there are settings such as Metallic and Smoothness, and different shader types which have other settings such as Specular.

What are the best settings to use for wood to make it look realistic? Just by guessing I would think that wood would have a low amount of Metallic and a low amount of Smoothness, but I'm not sure what shader to use, or what values to use.

Just as an example, we can focus on one particular type of wood, such as Oak.

# Answer
> 2 votes
Google some wood pictures and try to match them. I know that sounds simple. And that's because it is simple as a concept. If you're unfamiliar with some terms, such as specular (light reflectivity), Google them as well so you have a grasp of what settings you're changing.

Natural wood is dull. However, a painted deck on a house or lacquered computer desk, may appear shinier than some metals. Wood also usually has micro-grooves in it which is what normal mapping is used for. Just like my lacquered desk example, some wood could be very smooth as well.

---
Tags: unity, materials
---


# Question
Title: Not able to change Rigidbody 2d gravity scale
I have been trying to change the gravity scale of my `Rigidbody2d` when I click on it. By default it is by 0 and when I click on it, it should change to 1, so that it falls down. I have a square with a `boxcollider2d` and a `Rigidbody2d` and a square with just a box `collider`.

```
public bool gravity = false;
public bool m_isRunning = false;
public SpriteRenderer m_spriteRenderer;
private Rigidbody2D rb;

private void Update()
{
    if (gravity)
    {
        rb.gravityScale *= -1;
    }
}

private void Start()
{
    m_spriteRenderer = this.GetComponent<SpriteRenderer>();
    rb = GetComponent<Rigidbody2D>();
}

private IEnumerator Changecolor()
{
    yield return new WaitForSeconds(1);
    int random = Random.Range(1, 4);

    if (random == 1)
    {
        m_spriteRenderer.color = Color.blue;
    }
    else if (random == 2)
    {
        m_spriteRenderer.color = Color.red;
    }
    else if (random == 3)
    {
        m_spriteRenderer.color = Color.green;
    }
    else
    {
        m_spriteRenderer.color = Color.yellow;
    }

    this.StartCoroutine("Changecolor", 3f);
}

private void OnMouseDown()
{
    gravity = true;
    m_isRunning = !m_isRunning;

    if (m_isRunning)
    {
        StartCoroutine("Changecolor", 3f);
    }
    else
    {
        StopCoroutine("Changecolor");
    }
}

```

# Answer
> 1 votes
This line, from inside your code's update method:

```
rb.gravityScale *= -1;

```

is setting gravity scale to current gravity scale times -1. Since you have set gravity scale to start as 0 this highlighted statement is evaluating to gravity scale 0 times -1. So ultimately the gravity scale is being repeatedly set to 0.

Changing that line to:

```
rb.gravityScale = 1;

```

This code will now directly set gravity scale to one and you should see the object fall.

# Answer
> 0 votes
if you have no need to toggle the gravity back off you can simply replace the line in `OnMouseDown()` `bool gravity = true;` with `rb.gravityScale = 1;` and remove the gravity bool and the `if(gravity)` check in the Update method.

```
public bool m_isRunning = false;
public SpriteRenderer m_spriteRenderer;
private Rigidbody2D rb;

private void Start()
{

    m_spriteRenderer = this.GetComponent<SpriteRenderer>();
    rb = GetComponent<Rigidbody2D>();
}

private void OnMouseDown()
{
     rb.gravityScale = 1;

    m_isRunning = !m_isRunning;

    if (m_isRunning)
    {
        StartCoroutine("Changecolor", 3f);
    }
    else
    {
        StopCoroutine("Changecolor");
    }
}

```

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