# Question
Title: how to move character move on a circular surface in only one direction?
Making a 2d game:

I want to move character on circular surface only in one direction?

Script attached to child object is:

```
    public GameObject ball;
    float speed=2f;

    // Start is called before the first frame update
    void Start()
    {
        GetComponent<Rigidbody2D>();
    }

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

    void Left()
    {
        if(Input.GetKey(KeyCode.LeftArrow))
        {
            ball.GetComponent<Rigidbody2D>().AddForce(Vector3.forward * speed);
            //transform.Rotate(Vector2.left);
        }
    }

```

**Note:** character will move on a circular surface in only one direction...

**Image reference:**

# Answer
you need polar coordiates. you need to find the position in polar **coordintaes(radius,teta)** to unity basic **cartesian coordinates(x,y)** you can move the object by changing the theta angle this is my example code:

```
private void FixedUpdate()
    {
        foreach (var item in PolarElements)
        {

            float x = item.radius * Mathf.Cos(item.myAngle);
            float y = item.radius * Mathf.Sin(item.myAngle);

            item.position = new Vector3(transform.position.x+  x,transform.position.y+y,transform.position.z);
            item.myAngle += item.speed;
        }
    }

```
> 1 votes

---
Tags: unity, rotation
---


title: Unity Raycast not detecting layers

text:
# Question
Title: Unity Raycast not detecting layers
I am having problems with layers detection using raycasts.

Context: I created a grid to use in a pathfinding algorithm on a 2D plane. I want to implement now different weights according to the layer each node of the grid is in e.g. a node in a normal terrain will have a "terrainPenalty" of 1 and more difficult terrains 2 or more. In order to detect the terrain type on the 2D plane, I am shooting a raycast on the node position for each node previously considered "walkable". The problem comes up now, because I observed that the paths created are neglecting such values, this is the slice of code which is giving me problems:

```
            if (walkable)
            {
                Ray ray = new Ray(worldPoint + Vector3.back * 10, Vector3.forward);//PROBLEM HERE (NOT DETECTING PENALTIES)
                RaycastHit hit;
                walkableMask = ~walkableMask;
                if (Physics.Raycast(ray, out hit, 100, walkableMask))
                {
                    walkableRegionsDictionary.TryGetValue(hit.collider.gameObject.layer, out terrainPenalty );
                }
            }

```

At first I thought that the problem was how the layers were called, because I created a LayerMask combining 2 layers using the bitwise OR operator, but then I tried to play around with all the layers (hence why there is `walkableMask = ~walkableMask;` now). The result was always a false output for `Physics.Raycast(ray, out hit, 100, walkableMask)`.

I thought that maybe I was getting the wrong coordinates for the ray, but I created some gizmos to actually check that the ray was piercing perpendicularly my plane and it did, as well as trying to change layers to see if anything worked, but the output is always false. What am I getting wrong? Here is the rest of the function, if needed I can upload the whole script as well:

```
    void CreateGrid()
{
    grid = new Node1[gridSizeX, gridSizeY];
    Vector3 worldBottomLeft = transform.position - Vector3.right * gridWorldSize.x / 2 - Vector3.up * gridWorldSize.y / 2;

    for (int x = 0; x < gridSizeX; x++)
    {
        for (int y = 0; y < gridSizeY; y++)
        {
            Vector3 worldPoint = worldBottomLeft + Vector3.right * (x * nodeDiameter + nodeRadius) + Vector3.up * (y * nodeDiameter + nodeRadius);
            bool walkable = !(Physics2D.OverlapCircle(new Vector2(worldPoint.x, worldPoint.y), nodeRadius, unwalkableMask));
            //bool walkable = !(Physics.CheckSphere(worldPoint, nodeRadius));

            int terrainPenalty = 0;

            if (walkable)
            {
                Ray ray = new Ray(worldPoint + Vector3.back * 10, Vector3.forward);//PROBLEM HERE (NOT DETECTING PENALTIES)
                RaycastHit hit;
                walkableMask = ~walkableMask;
                if (Physics.Raycast(ray, out hit, 100, walkableMask))
                {
                    walkableRegionsDictionary.TryGetValue(hit.collider.gameObject.layer, out terrainPenalty );
                }
            }

            grid[x, y] = new Node1(walkable, worldPoint, x, y, terrainPenalty);
        }
    }
}

```

**EDIT :** Here is how I create the layerMask:

```
        foreach (TerrainType region in walkableRegions)
    {
        walkableMask.value |= region.terrainMask.value; // | is the bitwise OR operation, I could have simplified by writing " --- |= ---; "
        walkableRegionsDictionary.Add((int)Mathf.Log(region.terrainMask.value, 2), region.terrainPenalty);
    }

```

Where `TerrainType` is the following class:

```
    [System.Serializable]
public class TerrainType
{
    public LayerMask terrainMask;
    public int terrainPenalty;
}

```

I basically create an array of TerrainType objects that will store their layerMask and penalty and then upon positive output from the raycast I access the dictionary to retrieve the terrain penalty. For the terrain and obstacles I am using a 2D BoxCollider and 2D PolygonCollider respectively, they do not interact with any other layer.

Thanks for any possible hints, I don't know what else to try :\ .

# Answer
> 1 votes
It looks as though you're trying to fire a ray with the 3D physics engine PhysX, represented by the `Physics` class, and expecting it to interact with a collider managed by the 2D physics engine Box2D, represented by the `Physics2D` class.

These are two completely separate universes that know nothing about and cannot interact with one another.

(As a hint, look at the fact that a 3D `RaycastHit` can only tell you about a 3D `Collider` it hit. It couldn't tell you about a `Collider2D` hit if it tried!)

To fire rays against 2D colliders, you need them to be 2D rays, ie. `Physics2D.Raycast`. But as noted in this answer and comment thread, these are rays *in the plane*, that check where they cross a collider's edge. They can't fire *through* the plane along the third dimension because there is no third dimension in 2D.

So really it looks like what you want is Physics2D.OverlapPoint, to get the 2D collider with the least Z value that overlaps this point in 2D.

It looks like your problem never had anything at all to do with layers or layer masks, so including that in your question was a red herring. Please try to do tests when preparing your question — like "what if I don't use a layermask at all, does the problem persist? What if I have only one object in my scene?" etc. — so you can eliminate distracting elements and focus on solely the details that are relevant to the root cause.

---
Tags: unity, 2d, path-finding, raycasting, layers
---


title: Get the tile in unity tile map

text:
# Question
Title: Get the tile in unity tile map
I am trying to get the sprite of a tile in unity from where a **raycast** hits. Right now it only works in some cases, and always in positive x.

This is my current code.

```
Vector3Int LocalPos = new Vector3Int((int)hit.point.x, (int)hit.point.y,0);

Sprite spr = tilemap.GetSprite(LocalPos);

```

From what I can tell it gets the correct sprite.

Edit: I removed pointless code

# Answer
I guess you should read the manual, how Unity Tilemap is structured. If you create a Tilemap in Unity Editor, first you have a Grid and then a Tilemap under it. If you move Grid, Tilemap will move along it. This same thing is true for getting tiles in code. Tiles are stored in GridLayout space not in world space. So if you happen to start "drawing" you tiles from Scene world position 0,0,0 that doesn't mean Grid origin couldn't be in other location (like -2,-2,0 for example).

So one solution is to first convert screen mouse position to ray, then Raycast with this Ray against a plane matching Tilemap plane, then convert the world hit point to Grid space cell position and try to get a Tile.

It has been quite a while since I touched Tilemap and I'm no professional coder by any means, but this is one way to get your tiles under mouse cursor. I guess there might be more cleaner and shorter ways to do this...

```
if (Input.GetMouseButtonDown(0))
{
    // mouse position in screen space
    var mpos = Input.mousePosition;

    // Create a ray from camera to world
    var ray = Camera.main.ScreenPointToRay(mpos);

    // Create a Plane object to raycast against
    // Assume Tilemap resides on plane z 0
    var plane = new Plane(Vector3.back, Vector3.zero);

    // Do a Plane Raycast with your screen to world ray
    float hitDist;
    plane.Raycast(ray, out hitDist);

    // If you aimed towards this infinite Plane, it hit
    var point = ray.GetPoint(hitDist);
    Debug.Log("Point: " + point);

    // Convert hitpoint to Tilemap / GridLayout space
    // Cell position is an integer positions in GridLayout
    var tpos = tilemap.WorldToCell(point);

    // Try to get a tile from cell position
    var tile = tilemap.GetTile(tpos);

    if (tile != null)
    {
        // A tile exists in this cell
        Debug.Log("Tile sprite: " + tilemap.GetSprite(tpos));
    }
}

```

See also:

https://docs.unity3d.com/ScriptReference/Tilemaps.Tilemap.html

https://docs.unity3d.com/ScriptReference/GridLayout.html

https://docs.unity3d.com/ScriptReference/Plane.html
> 2 votes

---
Tags: unity, tilemap
---


# Question
Title: How to make an action perform only after an animation has run?
**I have an actor who has some animations. Animations perform based on some actor states (animation blueprint of actor):**

**Conditions at the Event Tick (similar to while loop):**

The actor changes perfectly from animation to animation. What I'd like to do is for it to damage an enemy as soon as the attack animation is over.

I tried some codes...

**In this one, for example:**

**This variable (`minionAtk`) modifies the state of the actor. See the image below in the event (which is only called when the `minionAtk` is true) that I can successfully change the state of the actor (to the attacking state):**

**Animation Blueprint:**

**Transition:**

But since the change from true to false is done instantly, the attack animation is not even shown.

**To solve this, I put a delay and a condition so that the event could not be called again while the execution of cycle (attack animation =\> end attack animation) ended:**

So when the actor is in the attacking state, the attack animation usually performs. After 5 seconds the animation stops.

It turns out that in this time interval the animation does not play only once.

I imagine there is a way to do the time calculation that the animation lasts, and based on that set the delay time.

But better than that, I wondered if there was no way to know when the animation was finished and from that, change the variable to false and perform the damage action.

**Thinking about it I researched and found this:**

https://answers.unrealengine.com/questions/329698/animation-damage.html

**But I came across this error:**

> This blueprint (self) is not a BTTask\_BlueprintBase, therefore ' Target ' must have a connection.

**Error link:**

https://answers.unrealengine.com/questions/549437/error-this-blueprint-self-is-not-a-therefore-self.html

I also saw something about sphere traces, attached to an actor socket. But in my case I don't want to apply the damage just in case of contact of the actor's arm (armed or unarmed) to the target, it would be something as seen in MOBA style games.

It would be like a basic attack from Garen/Yasuo/Darius.

# Answer
I suppose you want to use AnimNotifies it is a feature of UE4, when an AnimationInstace can send an event to your AnimationBP.

You can find more info at UE4 docs:
> 1 votes

# Answer
"How do I make X happen if Y occurs" can almost always be answered with:

Event Handlers... Or in the case of Unreal / C++ Delegates / Event Handling. This is one of the most reliable and predictable methods for a great number of things. Events / Listeners can basically be stapled onto any piece of code and wired up to each other. Event happens, listener detects it, and applies whatever logic you put into the listener on whatever object the listener is attached to. (This logic can be as complex, or as simple as needed).

If you're dealing with multiple potential enemies: event's / listeners can be put as high up in the inheritance structure as needed, and simply validate to make sure logic is being applied to the appropriate object. (Event can carry required information from the attacker, listener then validates).
> 1 votes

---
Tags: animation, unreal-4, combat
---


title: How to draw stencil ref value

text:
# Question
Title: How to draw stencil ref value
hi i am currently implementing UI screen that shows Depth Complexity of scene, so that we can figure out how many time each pixels work for same pixels.

for this i need to render stencil ref value. i successed to READ stencil ref value of each pixels using staging texture. but i couldn't figure out how to pass this data to pixel shader, so that i can render 'Depth complexity'.

brief code that i have tried now.

```
//initializing Depth Stencil buffer-----------------------------------

D3D11_TEXTURE2D_DESC ds_desc;
    ds_desc.Width = SCREEN_WIDTH;
    ds_desc.Height = SCREEN_HEIGHT;
    ds_desc.MipLevels = 1;
    ds_desc.ArraySize = 1;
    ds_desc.Format = DXGI_FORMAT_R24G8_TYPELESS;
    ds_desc.SampleDesc.Count = 1;
    ds_desc.SampleDesc.Quality = 0;
    ds_desc.Usage = D3D11_USAGE_DEFAULT;
    ds_desc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
    ds_desc.CPUAccessFlags = 0;
    ds_desc.MiscFlags = 0;
    Create DepthStencil Texture ...

    D3D11_DEPTH_STENCIL_VIEW_DESC dsv_desc;
    dsv_desc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
    dsv_desc.Flags = 0;
    dsv_desc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
    dsv_desc.Texture2D.MipSlice = 0;
    Create DepthStencilView

    DX_DContext->OMSetRenderTargets(1, rtv.GetAddressOf(), dsView.Get());

// process to create SRV--------------------------------------------------------
D3D11_TEXTURE2D_DESC desc;
    desc.ArraySize = 1;
    desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
    desc.CPUAccessFlags = 0;
    desc.Format = DXGI_FORMAT_X24_TYPELESS_G8_UINT;
    desc.Width = SCREEN_WIDTH;
    desc.Height = SCREEN_HEIGHT;
    desc.MipLevels = 1;
    desc.MiscFlags = 0;
    desc.SampleDesc.Count = 1;
    desc.SampleDesc.Quality = 0;
    desc.Usage = D3D11_USAGE_DEFAULT;
    Create StagingTexture2D...

DX_DContext->CopyResource(copyTex->Get(), graphic->DepthStencilBuffer());

    D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;
    srvDesc.Format = DXGI_FORMAT_X24_TYPELESS_G8_UINT;
    srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
    srvDesc.Texture2D.MipLevels = 1;
    srvDesc.Texture2D.MostDetailedMip = 0;
    Create SRV for binding to pixel shader...

//

```

and i bind this srv into this pixel shader and just always showing BLACK

```

Texture2D<float4> uiTexture : register(t0);

float4 main(PS_INPUT input) : SV_Target
{
    int2 idx = int2(0, 0);
    return uiTexture[idx];

}

```

any advice or alternative would be really appreciated.

# Answer
> 0 votes
`Texture2D<uint2> uiTexture : register(t0);`

Texture2D should be defined like this. and then uiTexture\[idx\].y will be stencil ref value.

and probably another value(uiTexture\[idx\].x) will be depth. cheers

---
Tags: directx, fragment-shader, stencil
---


# Question
Title: graphical interface when using assembly language
I want to learn a framework to use in assembly. I know that's not possible without learning the framework in C first. So I'm thinking of learning SDL in C and then teach myself how to interpret the program and run it as assembly language code. Then I will have a window and some graphics routines to display the game while using assembly to code everything in. I need to spend some time learning SDL and then some more time learning how to code all those statements using assembly while calling C functions and knowing what registers returned calls use and what they leave etc.

My question is, is this a good way to go or is there something better to get a graphical window display using assembly language?

# Answer
> 4 votes
I would recommend starting by looking at X11, since SDL runs on top of it for Linux. My guess is that SDL will call straight to X11 for window creation and management. It's the protocol you'll be implementing in any case.

If you get a window going in assembly, your graphics routines could look like anything, so SDL would merely be inspiration at that point.

Keep in mind that my answer is more theory than experience, since I think the idea is a bit insane (I wouldn't reimplement either SDL or X11). Also I wouldn't expect any portability, but if you know assembly you probably know about that.

Godspeed, sir.

# Answer
> 2 votes
When building a GUI with assembly, you'll be working directly with the windowing system of the operating system you are compiling for. For Windows, that the Windows API. For Linux, X Window System (X11) is probably the most popular, though there are others.

> My question is, is this a good way to go...

Learning SDL won't teach you anything about those APIs, since SDL essentially does all the window creation for you already (and then some). If your goal is a GUI in assembly, then you need to learn those APIs.

> ...or is there something better to get a graphical window display using assembly language?

If you want to go about this a bit more creatively (and depending on what your goals are), you could create your GUI with C and SDL. Then you could code all your logic in assembly and compile that to a handful of libraries (.dlls). At that point, you would be able to reference those libraries from your application and have the best of both worlds. This gets you a GUI rather quickly, which you can use as your output for your assembly libraries.

# Answer
> 1 votes
The only fun way I can think of getting display in assembly is by using the 13h mode.

# Answer
> 1 votes
A good match for graphical output using assembly would be the linux framebuffer.

I would write some C code to do the opening of /dev/fb0 and set up the memory map. But once you have done that, you can pass the memory address of your framebuffer to your assembly code.

The linux framebuffer is just a big array of pixels, and you write to them directly. Maybe skip fonts for now, and use assembly to draw some geometric shapes, maybe some graphs.

There is this short guide.

But if you google, you can probably find more complete guides to the linux framebuffer.

I think you need to run a lfb app when X11 is not active. So just quit your display manager. Typically with `/etc/init.d/lightdm stop` or `/etc/init.d/gmd3 stop`

You may need some extra privileges to open /dev/fb0 though. Run as root, or give your user account access to the 'video' group.

Lastly, I want to note that there is something else than assembly and C, which sets somewhere between them, and is called intrinsics.

The nice thing about intrinsics is that you can program at a level, almost as low as assembly, but you don't have to think about registers at all. You can just use C variables, and have the compiler do the job of mapping them to registers.

Intrinsics, unlike C, will give you direct access to the CPU's SIMD operations, which means that you can process 4 (SSE), 8 (AVX) or 16 (AVX512) integer/float values in a single operation. They are the most powerful instructions on your CPU.

---
Tags: graphics-programming, sdl, linux
---


# Question
Title: Capping neighbour height difference on heightmap?
I am generating a heightmap with some basic perlin noise but I need to cap the differences between each neighbouring value. A cardinal neighbour can only be `-1, 0, +1` in difference while diagonal neighbour can range from `-2 to +2`. What is a good approach to make sure the map is generated within these rules? Does perlin or a small extension help me do this or should I make 2nd pass after the map is generated by perlin or simplex? I am currently doing the latter where I go over each tile and change it's cardinal neighbours according to it's own value but it is going over the same position/number very often.

# Answer
> 1 votes
You already mentioned the two broad solution categories. Here are some specifics about each.

**Capping the values as they are generated:**
The potential problem with this is that depending on your implementation, you need to be careful about checking values before they are assigned. For instance, the very first value generated won't have any neighbors yet. Also, if the yet to be calculated neighbors have been initialized to a default value, the code could incorrectly assume the first value generated is okay when it isn't. These are pretty standard things to check for and don't prevent you taking this route, but you'll need to account for them.

**Post-process correction:**
One way to do this without back tracking, is to process the nodes in a such a way that only prior nodes are considered. For instance, assume you process a grid of nodes as follows:

```
0 1 2
3 4 5
6 7 8

```

Let's assume you don't have any 'wrap around connectivity' (i.e. you cannot walk off the top of the grid to reach the bottom, etc). Then, for adjusting the value at the given position of `[x,y]` you only consider the following neighbors: `[x-1,y]`, `[x-1,y-1]`, `[x,y-1]`, & ignoring any positions that aren't legal neighbors. That means that position `[0,0]` will always keep its original value because `[-1,0]`, `[-1,-1]`, `[0,-1]` are not valid.

If you *do* have wrap around connectivity, then you need to the following additional logic:

* do **not** wrap any coords with `0` around. For instance, `[0,0]` will *still* keep its original value; it is *not* allowed to wrap around & look at `[max x,0]`, `[max x, max y]`, `[0,max y]`. Even though they are legal neighbors (with wrapping) they have not yet been processed.
* if you are at position `[max x, y]`, you need to consider the neighbors `[0,y]` & `[0,y-1]`.
* if you are at position `[x, max y]`, you need to consider the neighbors `[x-1,0]`, `[x,0]` & `[x+1,0]`
* if you are at `[max x, max y]`, you need to consider all neighbors

In either case though, the basic idea is the same, for any position, you adjust its height based *only* on neighbors that have already been processed. That leads to another way to implement the logic: have a companion grid of boolean values that record if a position has been processed yet. Only consider neighbors that have been flagged as processed.

# Answer
> 1 votes
Perlin and Simplex noise are both forms of gradient noise, meaning at each corner of a grid, they pseudorandomly choose a gradient vector that determines the rate of increase of the output value in the neighborhood of that point.

So you can use this to establish an upper bound on how much the output can increase over a distance of one heightmap cell, horizontally or vertically. With this upper bound in hand, we can adjust our noise scaling parameters until we can guarantee that we change by at most ±1.0 over that span.

Let's say you're sampling a single layer of Perlin noise like this:

```
float value = Noise(input * frequency) * amplitude;

```

The maximum slope this attains is (amplitude * frequency) times the maximum component of the gradient vectors used in your noise function. If you wrote your own or have access to the source code, you can check these directly, otherwise you can make an informed inference by consulting reference implementations or sampling your noise at points close to the grid points.

If you're summing multiple octaves of noise, then these slopes combine additively too (in the worst case of constructive interference — in practice you'll get destructive interference too and see more average values overall, but for our guarantees it's the extremes we care about).

So, we just need to choose our amplitudes and frequencies so that the sum of these product times our maximum gradient component is less than 1 divided by the span between heightmap cells.

For example, if there's a span of 1 unit between heightmap cells, and my noise gradient vectors have a maximum value of ±1 on any axis, I might choose octaves like this...

```
octave     amplitude    frequency   contribution
------------------------------------------------
  1           28          1/70       0.4
  2            9          1/30       0.3
  3            3          1/15       0.2
  4            1          1/10       0.1

```

So now the maximum possible increase in function value from one heightmap cell to its neighbour totals to 1.0.

The higher the amplitude of any one octave, the longer a distance I need to spread that noise octave over, to ensure it never bumps me up two steps in a single bound.

---
Tags: tilemap, terrain, perlin-noise, heightmap
---


# Question
Title: Instantiating prefabs by dragging in scene not working
So I have this problem where I try to instantiate prefabs as in this video for example. I can take instantiate one prefab to the scene, but if I try to instantiate a second one to the scene (whether it's with the same prefab or a different one), instead of creating an instance of the second prefab, it brings the first instance I had created to my mouse and I'm in position to move it by dragging it around.

The only work around I have for this so far is to drop into the hierarchy instead of the scene (which works fine), but I have to carefully avoid the scene while dragging and dropping, otherwise the above-described issue happens instantly.

Am I doing something wrong, or is this a bug of some kind?

EDIT : I managed to reproduce the error in a consistent manner. I don't know why it happens, but it does every time. It doesn't involve code and it is very simple to reproduce (at least for me, perhaps not for you if you're not doing the wrong thing that I do...).

I created a new project. I created a cube and a sphere. I turned them both into prefabs and deleted the original instances (they have the .prefab extension in my folder, so I am sure). I drag-dropped the cube in, works fine. I drag the sphere in, and it appears as a cube which I have to position (by releasing the click), and my initial prefab instance of the cube is gone.

# Answer
> 1 votes
This sounds like an issue with Unity itself. Since this is a very old post the issue is has probably been fixed, but in case anyone runs into this problem again, this is what you can do to attempt to fix it:

1. Check which version of Unity you are using and make a note of this.
2. Reinstall Unity and test if the issue is still present in a new project.
3. In case the issue is still present, either update Unity to the latest version or another "stable" version.
4. If the issue persists, contact Unity Support https://unity.com/support-services. See if the issue is already present in the issue tracker. If not, report the bug.

If the issue is solved by downgrading to a previous more stable version I also recommend reporting the bug.

Unfortunately if you get to the fourth step, solving this issue might take a while since it would have to be an issue with how your device interacts with Unity. Always make sure you don't have any other possible causes like add-ons.

If all else fails, CTRL+D duplicates any selected GameObject.

---
Tags: unity
---


# Question
Title: Prevent Animation Tab from changing the position of an object
I am quite new to Unity. I am using the latest version. When I try to make a **door open animation**, it goes well with rotation. But when I add the position property it takes it to the `Vector3(40,12.5,7.5)` instead of `(10,2.5,15)` at the first frame. I try to change the value but it reverts after I write.

# Answer
I'm not entirely sure, but this sounds like you still have your animation preview toggled on while trying to edit values.

If this is the case, you might also notice that the input field for the value you are trying to edit has a blue background. Click the preview button to toggle it.

Make sure that when you are trying to edit the values to a keyframe, the recording mode is toggled ON, and when you try to edit the values of an object while not influencing an animation, both preview and recording are toggled OFF

If this is not the issue you are currently encountering, please provide screenshots and a more detailed explanation.
> 1 votes

---
Tags: unity, animation, vector, transformation
---


# Question
Title: How to call animation event from another GameObject
I have an animation event but I want it to call a function from a script that is attached to a different GameObject that I'm not animating. Is this even possible?

# Answer
> 2 votes
> You can increase the usefulness of Animation clips by using Animation Events, which allow you to call functions in the object’s script at specified points in the timeline. https://docs.unity3d.com/Manual/animeditor-AnimationEvents.html

So you can call functions only in the object's scripts.

You can make a manager which has functions to call functions from other objects, and you can use that manager on all your animation events in your entire project. just so that you won't need to make a bunch of scripts for each of your animation events.

# Answer
> -1 votes
1. Use a **singleton** instance of the first script. Write `Method1` there.
2. Call `Method1` using singleton instance in a `Method2` in the script attached to the animating GO.
3. Use `Method2` in animation event.

Don't see any other way. At least this avoids dragging the script object reference.

---
Tags: unity
---


# Question
Title: Can I use Unity to edit a prefab created in Blender?
I've imported a character from Blender. The character is made of metaballs and so doesn't import properly. I'm trying to edit the character within Unity using the rig from the original Blender object.

The problem I'm running into is that I can only access the bones when the object is instantiated. The rig/armature object doesn't unfold in the project resource folder, and double clicking on the top-level object just opens it in Blender. So I can't seem to make edits that can later be instantiated.

Is there a way to use Unity to edit a prefab made in Blender so it can be instantiated? Any other suggestions welcome.

Screenshots for reference:

# Answer
It turns out I just had to drag the edited prefab instance from the hierarchy pane to the project pane, creating another prefab that kept my edit.

In case it's helpful for anyone, this is the resource that helped me get my head around how prefabs work. https://unity.com/prefabs
> 0 votes

# Answer
Quick Edit Unity Plugin Yes, you can. You have to write your own custom script to do this, or download one (such as the plugin linked above).

However, usually someone would want to do this to modify models at runtime. Odds are you will be better off building your models in a way that works for unity.

But yes, via scripting you can tweak any asset you want... the catch is you have to either make or find a script to do it.
> 1 votes

---
Tags: unity, blender, rigging
---


# Question
Title: How to use 3 cameras simultaneously in Unity
I'm working on a project that requires 3 panels, each rendering a game object. There will be a search box and when the player enters a string, that key word will zoom to the tagged location on the each object in the 3 panels. How can I go about accomplishing this?

# Answer
if you want multiple cameras on multiple screen you need multiple cameras and set their target Display property of camera component on different screens. like this:

```
void Start
{
      Camera.main.targetDisplay = 0;
        camera2.targetDisplay = 1;
}

```

if you want to render camera on different elements like Ui panel or... you can do like this: https://docs.unity3d.com/ScriptReference/Camera-targetTexture.html

for that you need to render camera to a **render texture** and set the result on any thing possible

i wanted to write for you whta to do but this tutorial is complete:

https://blog.theknightsofunity.com/implementing-minimap-unity/
> 0 votes

---
Tags: unity
---


# Question
Title: Easiest way to make a button in Gamemaker Studio 2
I want to make a menu for my title screen where the user can click on the option they want. The only way I can think of doing this is by making an object that checks if there is a click and then checks if the mouse is on top of it. This feels like a really round-about way to do this. Is there an easier way? I don't yet know how to use the GML so, please use DnD.

# Answer
**Use the Left Pressed event:**

This way the action will only be performed if there is a mouse click on the object (in this case the button). The click area will exactly match the size of the sprite.

**As a matter of curiosity/information:**

Since you want to know the simplest way to do this and not the most optimized/functional way, the image shows how to do what you want. This case specifically (clicking a button) is quite simple to convert to GML.
> 0 votes

---
Tags: game-maker-dnd
---


title: Handling multiple resolution

text:
# Question
Title: Handling multiple resolution
I have been trying to handle different mobile phones resolutions for my game. But the scene is not fitting accordingly in some screen its perfect but in some other screens it is shrinking. My question is how do I create a scene that will show consistent across all devices and all screen resolution. The gaming framework I am using is limejs and for building hybrid apps I have used Ionic 3. I have tried using window.devicePixelRatio and multiplying it with screen height and width but it did not work.

# Answer
> 0 votes
So after some months of trying, I came across this post-https://www.joshmorony.com/how-to-scale-a-game-for-all-device-sizes-in-phaser/ it discusses the concept of devicePixelRatio which when multiplied with window.screen.width and window.screen.height covers the entire mobile screen of all mobile devices.

the code which I used in terms of lime js when creating the director was:

```
game.director = new lime.Director(document.body, window.screen.width *
window.devicePixelRatio, window.screen.height * window.devicePixelRatio)

```

(Note that my game runs in landscape mode)

For the phaser framework, it has different scale modes which we can use to cover the entire screen of mobile devices.

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


# Question
Title: IAP consumable stuck with reason DuplicateTransaction
I've implemented Unity IAP. I have succesfully implemented it before and all went well. Now at the moment, everything goes well except for 1 consumable. When I try to purchase it, i get the `PurchaseFailureReason` with value DuplicateTransaction.

After some googling, I found out that it probably is because the transaction was cleared by Google, but the callback was never invoked inside the app. So somehow and somewhere, a flag is set indicating that this transaction is still pending or something? (The purchase on the - now not working consumable - had also indeed been made before and the callback was NOT called, so this seems to be correct.)

All other consumables work fine. They are configured exactly the same, just with another reward on the callback. (Same method, different parameter. I'm 100% sure this has nothing to do with the bug).

So now I want to try and fix this product.

* I tried reverting the purchase (even though it is a test purchase) inside Google Play.
* I tried manually adding a restore button and clicking it.

Some info:

* I am using Unity Codeless API.
* Game is only available on android as of yet.
* The bug originates from when I tried making a purchase, but (due to bad wifi) i managed to navigate to another screen before the GooglePlay popup came. This disrupted the callback somehow and probably flagged the purchase as "purchased but not completed" or something.
* I store receipts from the products in my database so I can compare/ provide support for clients when purchases go sour. The purchase in question never arrived in my database. All corresponding purchases on the same product ID now fail with reason `DuplicateTransaction`
* Consumable products are configured in Google play, online unity monetization console, in editor iap catalog. All are configured exactly the same 100%
* The game is still in Alpha, soon going to Beta (once I fix this :)).

# Answer
> 1 votes
Well after leaving the app alone for an hour I launched it up again to check the Iap screen. Somehow, without pressing anything, the purchase that was somewhere pending ended up resolving, and I saw my popup indicating that the purchase completed. The purchase finally finished.

So one of my latest actions probably triggered this, which are:

* Adding a restore button to the iap screen and clicking it.
* Adding the products to the unity monitization console online
* Reverting the purchase in Google play (does not seem likely)

Hope this helps anyone running into the same issue. Also if someone has more information on what probably caused this issue to resolve, that would be very helpful!

---
Tags: unity, android, in-app-purchase
---


# Question
Title: How to write properly shader with gradient based on vertex-color?
I took 4 squares with the outer corners painted in black, and the other ones in white. For some reason, they have a different gradient.

```
fixed4 frag (v2f i) : SV_Target
{
    fixed4 mainTex = tex2D(_MainTex, i.uv);
    fixed4 overTex = tex2D(_OverTex, i.uv3);
    fixed4 final = fixed4(lerp(mainTex.rgb, overTex.rgb, overTex.a) * i.color, 1.0);
    final = lerp(float4(0, 0, 0, 1.0), final, i.color.a); // shadows

    return final;
}

```

How can i make the same gradients as bottom-left and top-right?

In-game this is faces of blocks (like minecraft) and gradients - is smooth shadow/light. So I cannot change tris

# Answer
> 0 votes
If you can't change the vertices, there are two other approaches:

You can either give the triangles uv coordinates and do the lighting based on that (you'll need uv coordinates eventually anyways, why not add them now?)

Or you can overcompensate the colors a bit. The problem happens, because at the outer edges, the color is averaged along 1 unit, while at the inner edges it is √2 units (≈1.414). So instead of making every white vertex actually white, give the adjacent vertices to the black one a color of ~~`1/√2 * white`~~ `0.5 * white` (Thanks to DMGregory for correcting this) and the opposite vertex a color of `1 * white`. Thid way the color gets averaged out to the same gray as the others earlier. Then in the fragmenr shader multiply the colors by 2 to make them white again.

# Answer
> 0 votes
That is the intended behaviour, since the center of an edge with two different colors has to have the 50% mix of both of them. The quad is cut into 2 triangles, their shared edge goes from the top left to the bottom right.

You have 2 ways to solve this: you can simply rotate one of the quads instead of changing the vertex color or you can split it into triangles in a different way.

If instead of the current approach with 2 triangles, you use 4, where they have a shared central vertex, then it will always look like the one on the right.

Basically, instead of only cutting the quad in the top-left -\> bottom-right direction, cut them in the bottom-left -\> top-right direction too.

```
 __________
|\        /|
| \      / |
|  \    /  |
|   \  /   |
|    \/    |
|    /\    |
|   /  \   |
|  /    \  |
| /      \ |
|/________\|

```

---
Tags: unity, hlsl
---


# Question
Title: How do I convert an interface into a MonoBehavior in Unity?
In my method iTest.doStuff(), I try to convert interface testInterf \_ti into a MonoBehavior. This gives me "error CS0246: The type or namespace name 'MonoBehavior' could not be found", but in the same file, my class iTest has no trouble inheriting from MonoBehavior.

```
//testInterface.cs

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

public interface testInterf{//this is my interface
    string Name {get;}
    Sprite mySprite {get;}
    void func();
}

public class testInterfEventArgs : EventArgs {
    public testInterf i;

    public testInterfEventArgs(testInterf _i){
        i=_i;
    }
}

//iTest.cs

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

public class iTest : MonoBehaviour{
    public void doStuff(testInterf _ti){//this is the implementation
        Collider collider = (_ti as MonoBehavior).GetComponent<Collider>();//ERROR
    }
}

```

# Answer
> 1 votes
Try `(_ti as MonoBehaviour)`

MonoBehavi**ou**r is spelled the British English way - with ou.

But do not get the impression that Unity does consistently use British English spelling. Other classes like `Color` use the American English spelling.

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


# Question
Title: Draw a line along one continuous edge of a curved mesh
I have a rectangular mesh, but the mesh is curved:

I want to draw a line along one side of this curvy mesh.

Currently I can easily draw line along a side of a flat rectangular mesh by getting the mesh's min and max bounds. But what should I do to draw a curved line along the border of mesh from one of its side edges.?

# Answer
> 0 votes
Finding spatially-related parts of a mesh - like which triangle edges sit on the outer perimeter, and how they chain into a longer arc - requires adjacency information that's not usually used for game rendering. So game engines like Unity don't generate / include that information by default.

That means our first step is to extract this adjacency info, by analyzing the mesh.

```
// This structure will let us uniquely refer to a particular edge,
// identifying it by the (unordered) pair of vertices it joins.
public struct EdgeID {
    public readonly int startIndex;
    public readonly int endIndex;

    public EdgeID(int vertexA, int vertexB) {
        // Put the vertices into a canonical order to de-dupe edges,
        // no matter the direction we're traversing it.
        if(vertexA < vertexB) {
            startIndex = vertexA; endIndex = vertexB;
        } else {
            startIndex = vertexB; endIndex = vertexA;
        }
    }
}

// Here we'll count the number of times each edge occurs in the mesh.
Dictionary<EdgeID, int> _edgeUseCounts = new Dictionary<EdgeID, int>();

void IncrementEdgeUse(int vertexA, int vertexB) {
    var edge = new EdgeID(vertexA, vertexB);
    int count;
    _edgeUseCounts.TryGetValue(edge, out count);
    _edgeUseCounts[edge] = count + 1;
}

void CountEdgeUses(Mesh mesh) {
    _edgeUseCounts.Clear();

    int triangleIndices = mesh.triangles;

    for(int i = 0; i < triangleIndices.Length; i += 3) {
        IncrementEdgeUse(triangleIndices[i],   triangleIndices[i+1]);
        IncrementEdgeUse(triangleIndices[i+1], triangleIndices[i+2]);
        IncrementEdgeUse(triangleIndices[i+2], triangleIndices[i]);
    }
}

// Here, we'll extract all the edges that occur only once,
// so we know they're on the perimeter.
List<EdgeID> _perimeterEdges = new List<EdgeID>();

void GatherPerimeterEdges() {
    _perimeterEdges.Clear();

    foreach(var pair in _edgeUseCounts) {
        if(pair.Value == 1)
            _perimeterEdges.Add(pair.Key);
    }
}

// Finally, we'll gather all these perimeter edges and organize them into ordered
// loops and arcs of vertices.
public List<List<int>> GetPerimeterLoops(Mesh mesh) {

    CountEdgeUses(mesh);
    GatherPerimeterEdges();

    var loops = new List<List<int>>();

    while(_perimeterEdges.Count > 0) {
        var loop = new List<int>();

        int last = _perimeterEdges.Count - 1;
        var edge = _perimeterEdges[last];
        _perimeterEdges.RemoveAt(last--);

        int start = edge.startIndex;
        int next = edge.endIndex;

        loop.Add(start);
        loop.Add(next);

        do {
            int i = _perimeterEdges.FindIndex(e => { return e.startIndex == next || e.endIndex == next; });
            if(i < 0) break;

            edge = _perimeterEdges[i];
            _perimeterEdges[i] = _perimeterEdges[last];
            _perimeterEdges.RemoveAt(last--);

            next = edge.startIndex == next ? edge.endIndex : edge.startIndex;

            loop.Add(next);
        } while(next != start);

        loops.Add(loop);
    }

    return loops;
}

```

You can use code similar to the example above to extract all the loops of perimeter edges from the mesh. It won't behave the best if you have non-manifold geometry on the interior of your mesh (eg. 3 faces meeting along an edge), but that case can be handled at the cost of a little extra complexity, if it occurs in your meshes.

Given an edge or vertex to start from, you can search these loops to find its location on the perimeter, then walk the edge loop forward & backward to trace all the points along that perimeter. You can check the angle between consecutive edges to detect when you've hit a corner and should stop.

You can then feed those vertex positions to a LineRenderer to draw your line.

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


# Question
Title: How do I use this Perlin Noise texture to change the mesh?
Using the Unity docs page on Perlin noise, I made this script:

```
// Width and height of the texture in pixels.
public int pixWidth;
public int pixHeight;

// The origin of the sampled area in the plane.
public float xOrg;
public float yOrg;

// The number of cycles of the basic noise pattern that are repeated
// over the width and height of the texture.
public float scale = 1.0F;

private Texture2D noiseTex;
private Color[] pix;
private Renderer rend;

void Start()
{
    rend = GetComponent<Renderer>();
    scale = Random.Range(15, 20);
    xOrg = Random.Range(0, 20);
    yOrg = Random.Range(0, 20);
    // Set up the texture and a Color array to hold pixels during processing.
    noiseTex = new Texture2D(pixWidth, pixHeight);
    pix = new Color[noiseTex.width * noiseTex.height];
    rend.material.mainTexture = noiseTex;
}

void CalcNoise()
{
    // For each pixel in the texture...
    float y = 0.0F;

    while (y < noiseTex.height)
    {
        float x = 0.0F;
        while (x < noiseTex.width)
        {
            float xCoord = xOrg + x / noiseTex.width * scale;
            float yCoord = yOrg + y / noiseTex.height * scale;
            float sample = Mathf.PerlinNoise(xCoord, yCoord);
            pix[(int)y * noiseTex.width + (int)x] = new Color(sample, sample, sample);
            x++;
        }
        y++;
    }

    // Copy the pixel data to the texture and load it into the GPU.
    noiseTex.SetPixels(pix);
    noiseTex.Apply();
}

void Update()
{
    CalcNoise();
}

```

The only difference between this code and the Unity docs example is that I added some randomness to the size and origin points of the texture.

I attached the script to a plane, and now when I run the game, the plane has a random noise texture on it.

Now I want the texture to give height to the mesh, so it will look like a terrain. How do I do this?

# Answer
First, I'd recommend pulling your noise calculation into its own function:

```
float SampleNoise(Vector2 normalizedPoint) {
    Vector2 samplePoint = origin + normalizedPoint * scale;
    return Mathf.PerlinNoise(samplePoint.x, samplePoint.y);
}

```

Then you can easily re-use the same function in both your texture generation and vertex displacement, without writing it twice (with the risk of changing one copy while forgetting to change the other). Inside your texture loop it would look like this:

```
Vector2 normalized = new Vector2(x / noiseTex.width, y / noiseTex.height);
float sample = SampleNoise(normalized);

```

Then you can do a second pass to update your vertices:

```
// Do this part once, in Start, so you're not allocating new vertex arrays constantly.
var mesh = ((MeshRenderer)rend).mesh;
var vertices = mesh.vertices;

// Update your vertex heights anytime your noise changes.
for(int i = 0; i < vertices.Length; i++) {
    var vertex = vertices[i];
    // The default plane goes from -5 to +5, so remap it to 0...1:
    var normalized = (new Vector2(vertex.x, vertex.z))/10f + Vector2.one * 0.5f;
    vertex.height = heightScale * SampleNoise(normalized);
}

mesh.vertices = vertices;

```

You can also apply this displacement in the vertex shader, by reading the texture itself. But modifying the source mesh CPU-side lets you use it for things like raycasts and collisions too.
> 0 votes

---
Tags: unity, c#, procedural-generation, mesh
---


# Question
Title: Need help to make and optimize a dense forest in Unity with bird view camera
I'm currently developing a RTS game that has a bird view camera operating while playing the game. One of the core aspects of my game are trees.

So in the previous days i was playing with trees in Unity.

* First i played with Unity Tree Creator however later i realized it is broken since 2018.3, and devs said it wont be fixed because it will be a community developed package in the future
* Then i downloaded assets from the store that are said to be highly optimized trees, however they are mostly for "3rd person camera projects" thus having around 7-14k triangles.

After these experiences, i decided to export a tree prefab to fbx, then manually decrease the triangle count to around 2.5k in 3ds max, then reimport it to Unity. With this technique i was able to produce quite good results, but still not very satisfied with it.

***My camera view, and my "dense forest" 180-300fps... and only like 3-4 shadows***  For the above picture i used a Tree with 2 LOD and one billboard(BB).

After playing with this i realized i can sure do better especially with playing LOD numbers, material optimization, and with the default tree trinagle optimization.

However the problem is i can't model pine trees that satisfy my needs in 3ds max. So i started looking into SpeedTree documentation, however it seems a bit too professional for my needs(All the tutorials also make trees with like 20k poly/tri).

**So regarding this story. I would like to ask the following question + a bonus one about LOD:**

* Can you model quality trees with SpeedTree for Unity that have like around 1k-2k triangles, or SpeedTree is for high quality/high poly trees, they algorythms won't work with lower polygon count etc? (I heared they have a simplify modifier is it good? like make a 7k triangle tree then cut it to 1k-2k)
* I'm thinking about using 4-5 LOD and a BB for smooth transition. In my picture i use 2 LOD and a BB and sometimes when moving the camera fast, transitions are not as smooth as i want it to be. So i would like to rather have more lower detailed meshes before trasitioning to BB. So does having a 4-5 LOD-s a common practice or any better ides for this?

# Answer
> 2 votes
I don't know about Speedtree but this might help you:

* Create a tree in Unity 2018.3 and export it using the Unity FBX Exporter
* Try the Modular Tree addon for Blender and then export as FBX

+ Trees are also created via nodes
    + Leaf placement was problematic and I encountered a few minor bugs back when I used it
    + Might not yet be stable in the (fairly) new Blender version 2.80 but 2.79 should be fine
    + It's free & open source

Also consider using Blenders Decimate modifier to reduce triangle count of your exported mesh to create LOD's instead of doing it manually (Requires some knowledge of Blender or similar 3D modeling software):

1. Add a decimate modifier
2. Play arround with the 3 modes and their values
3. Fix uv's if the modifier messed them up (But: Automatic uv generation in Blender isn't half as good for organic meshes as it is for architecture so you might have to get your hands dirty anyway and fix uvs by hand)
    1. Apply the decimate modifier
    2. Edit Mode -\> Select faces with wrong uvs -\> Smart UV Project.
    3. Select all uv's -\> Average UV Island Scale
    4. Move new uv islands

Seperate the leafes into it's own mesh object if the decimate modifier only seems to work for either only the leafes or only the tree base (non leafs)

---
Tags: unity
---


# Question
Title: How to mirror a vector through some other vector?
I have a player's direction (`playerDirection`). I want to fire two bullets, one rotated by -30f, and one by 30f, so it looks like this:

Blue line is the `playerDirection`. I'm looking for the green and the red. I have calculated the red vector with:

```
bullet1Direction = Quaternion.Euler(0, 30f, 0) * playerDirection;

```

But this method doesn't seem to work for all cases because it produces negative angles etc.

So I've tried taking that red vector I've calculated and reflecting it with `Vector3.Reflect` but I think it's for different purposes.

How do I do that?

# edit just for reference

Turns out it works out of the box as DMGregory says. I had some issues in the algorithm.

Here's how the final version looks like, supporting shooting multiple bullets. I know that the algorithm probably could be simplified somehow.

```
for (int i = 0; i < bullets; i++)
{
    // we will calculate the angle for each bullet
    float angle = 0f;
    if (evenCount) // if the bullet count is even or not
    {
        if (i % 2 == 0) // bullet 0, 2, 4
        {
            angle = playerDirection.y + ((i + 2) * 15f); // 30f, 60f, 90f...
        }
        else // bullet 1, 3, 5
        {
            angle = playerDirection.y - ((i + 1) * 15f); // -30f, -60f, -90f...
        }
    }
    else
    {
        if (i == 0) angle = playerDirection.y; // bullet count is odd. we spawn one bullet at the player's direction
        else
        {
            if (i % 2 == 1) // bullet 1, 3, 5
            {
                angle = playerDirection.y + ((i + 1) * 15f); // 30f, 60f, 90f...
            }
            else // bullet 2, 4, 6
            {
                angle = playerDirection.y - ((i) * 15f); // -30f, -60f, -90f...
            }
        }
    }

    newDirection = Quaternion.Euler(0, angle, 0) * playerDirection;
}

```

And here's a visual result! (6 bullets and 3 bullets)

# Answer
Turns out you can rotate the direction using this formula without problems:

`newDirection = Quaternion.Euler(0, desiredAngle, 0) * playerDirection;`
> 1 votes

---
Tags: unity, vector, linear-algebra, direction
---


# Question
Title: Does a thread in a mobile game serve the same purpose as a view model in a mobile application?
I'm trying to confirm up my understanding of the coding differences and similarities between mobile *game* design and mobile *app* design for Android devices using Java/Kotlin.

~~ ~~ ~~

In mobile app design, a good design principle is "Separation of Concerns" where the app will have any number of distinct classes to handle different purposes. One design architecture separates these concerns into two classes, namely, the "View Model" and the "UI Controller" (where the UI controller is an activity or fragment).

The View Model's purpose is to have code that holds data and makes logical decisions with that data. The UI Controller's purpose is to draw that data on the device's screen, as well as, receive Input and OS events.

~~ ~~ ~~

In mobile game design, I've seen an Activity class, a GameView class (which implements SurfaceView) and a Thread subclass. The Activity will instantiate the GameView class and place the GameView class into its view hierarchy using `setContentView(GameView(this))`. This differs from how mobile app design where `setContentView(R.layout.layout_xml_file)` is used to supply views

The GameView object has a surface to have bitmaps drawn on. The GameView object manipulates that surface using surface-specific callback functions which is much like how the UI Controller manipulates lifecycle state using lifecycle-specific callback functions. The GameView object also handles User Input like the UI Controller.

Obviously, the GameView and the UI Controller have the same roles.

~~ ~~ ~~

* Does a Thread in a mobile game serve the same purpose as a View Model in a mobile application?
* If not, where are is the data and logical decisions supposed to go? Do they go in the various Bitmap classes?
* If Bitmap classes serve the same function as View Models, how do they make logical decisions (i.e. a Mario object collects a Coin object)?

# Answer
> 1 votes
A typical game loop (the main loop of the application) looks like this:

```
while(!finished) {
  collectInput();
  updateLogic();
  renderGraphics();
}

```

There are a variety of software architecture patterns that could be used to implement the above, but the fundamental structure and resulting sequence of actions generally look the same. Input is collected and stored, to be processed later when logic is updated, and the resulting game state is then drawn to the screen (including UI).

The idea of separating concerns is a software architecture idea, *not* specifically an application development idea. You can build games using MVC or MVVM patterns that are common in applications, although there is generally less of a need to do so (or perhaps less interest in doing it).

> Does a Thread in a mobile game serve the same purpose as a View Model in a mobile application?

No. A thread is a tool for concurrently performing work. It is useful for that purpose in both games and non-games.

> If not, where are is the data and logical decisions supposed to go? Do they go in the various Bitmap classes?

Those kinds of decisions go in the `updateLogic` portion of the loop above. They usually take the form of

* types representing individual game objects that implement the game logic (e.g., a `Character` class), which tends to look more like traditional OO and/or
* types that represent the category of behavior and know how to operate on bulk data that represents in-game objects (a `CharacterSystem` that manipulates `Character` components, for example, in the ECS paradigm).

Bitmap classes should be for bitmap graphics representation only, generally.

> If Bitmap classes serve the same function as View Models, how do they make logical decisions (i.e. a Mario object collects a Coin object)?

These decisions would go in the character object or component (et cetera) as described above. The specifics tend to depend on the architectural decisions you've made in your project. Usually some sort of subsystem is responsible for detecting collisions (intersections between bounding shapes) between objects and telling those objects of the collision, which causes them to run the appropriate logic.

---
Tags: android, architecture
---


# Question
Title: Examples of 3D space strategy with good XYZ controls?
I've been tinkering with an idea for a space sym, kind of like MOO2, writing it for mobile or browser as a way to learn Java. Command ships and control planets, etc. I'd love to make the game in 3d, with x, y, and z coordinates to make things more realistic, but I'm afraid that it'd be too much to implement. The engine wouldn't be any harder to code, just add another vector to the calculations, but a user interface for navigating a 3d galaxy is more difficult. I'd prefer to keep the graphics simple, without a lot of hardcore rendering for different angles.

Does anyone have any experience designing a UI for directing units in 3D? If I decide to go the 3D route, how should I have the player control the 3rd coordinate (the one that would come out of the screen)? Is there a method that would allow a player to easily tell the ship how far "back" or "forward" to travel in addition to the usual up/down, right/left?

# Answer
> 1 votes
The way you control your spacecraft depends a lot on how the camera works.

If the camera is at a fixed angle and looking at the game scene in an overhead perspective, your best solution would be having the directional-pad or control stick to move forward, backward, left and right, then have a couple separate buttons for ascent and descent. So left and right on the pad/stick would affect your X position, up/down would affect your Z position, and Y would affect your ascent/descent (however, depending on the game engine, Y and Z may be swapped).

If the camera is following behind the spacecraft, you would have the pad/stick to tilt left and right, ascend and descend. Then you'd have buttons for acceleration/braking. This is more of an space action game style (think games series like Star Fox).

As for UI, you'd have either a circle pad or directional pad for mobile, which works for both styles mentioned, and you'd have additional buttons for ascent/descent (or acceleration/deceleration).

In summary, with a fixed-angle camera, the forward and backward (coming out of the screen) would be your up and down, and the ascent and descent would be different controls. With a camera that follows behind the player, you would have buttons for acceleration and deceleration.

# Answer
> 1 votes
You should really think of good reasons why your game would benefit from a 3rd dimension other than realism. That is if realism isn't your selling point like it is for simulation games. In my opinion realism is only important if a lack of it breaks immersion in a big way. You can also try to think about why this was or wasn't used in other games.

As for how it's done you should do some investigating by analyzing how similiar games did it. The only game that I personaly played and that did this is EvE Online. While there are 3 Axis in EvE, players don't actually navigate arround space by issuing the so called 'Approach point x y z' command that often. But instead go with commands like:

* 'Approach station'
* 'Keep distance of 2km to Ship x'
* Or 'Orbit asteroid at 500m' By holding the respective hotkey and clicking on the station/ship/asteroid and using default values or select a specific one like 1,5km)

But 'Approach point x y z' is vital in some pvp scenarios where out maneuvering can easily win you the fight. In EvE this basically works with 2 mouse clicks:

The first is for selecting the distance that you want to travel on the x y plane and an axis A (which is orthogonal to the path of travel) by selecting a point on the x y plane.

Moving the mouse after the first click then rotates a line (indicating the path of travel), starting from your ship and pointing to the point where you first clicked on the x y plane, arround the axis A. So moving the mouse after the first click determines how much you travel on the z axis (+z beeing up). The command is executed after you click a second time.

I'll link/upload something to illustrate this once i have access to better internet, since my explanation sounds a bit too complicated and this actually is kind of an intuitive way of doing it.

---
Tags: strategy, user-interface
---


title: unity multiplayer components not there

text:
# Question
Title: unity multiplayer components not there
I just learned quite a bit about how to set up a multiplayer system in unity using it's built in scripts. However, when I try to add a network manager to an empty, the search comes up empty! also when i click **add component** there is no tab for **network**. What's going on?

# Answer
unity is deprecating all old multiplayer development tools and wants developers to dont use them on new projects. if still want them you need to roll back to previous versions.

new api can be found in here: https://github.com/Unity-Technologies/multiplayer
> 1 votes

---
Tags: unity, multiplayer
---


# Question
Title: Unity - Access animation clips/motion of an animator
So I have an animator on my GameObject. I need to change the animation clip/motion of different states in my animator to the one I assign in my EditorGUILayout.ObjectField. Problem is, I have no idea how to access those clips. This is purely Editor Scripting.

# Answer
> 2 votes
> This is purely Editor Scripting.

Yes, you can do it. But take note that manipulating Animator's state machine and clip inside ONLY possible in Editor. (For automation editing/scripting, etc) It is very **complicate** process but I will try to cover as much as I can.

**For side note**, *AnimationClipOverrides* in Dmitri's answer is for game runtime. It 'overrides' the original animation clip to another set of animation clips.

---

## Obtain reference to Editor's Animator

First in editor script or EditorGUI, obtain reference to UnityEditor.Animations.AnimatorController you are going to wotk with by any method, for example via field in custom EditorWindow:

```
using UnityEditor;
using UnityEditor.Animations;

AnimatorController m_CurrentAnimator;
m_CurrentAnimator = (AnimatorController)EditorGUILayout.ObjectField( "Animator", m_CurrentAnimator, typeof( AnimatorController ), false );

```

---

## Access layer and get all states inside

First is layer that you have to peel off, for simplicity, I will operate on layer 0. Then there will be AnimatorStateMachine inside it, I will use List to collect all states recursively. (also travel through nesting sub-statemachines)

```
AnimatorControllerLayer[] layers = m_CurrentAnimator.layers;
AnimatorControllerLayer workingLayer = layers[0];

List<AnimatorState> stateList = _ExpandStatesInLayer( sourceStateInfoLayer.stateMachine );

```

where

```
List<AnimatorState> _ExpandStatesInLayer( AnimatorStateMachine sm, List<AnimatorState> collector = null )
{
    if( collector == null )
        collector = new List<AnimatorState>( );

    foreach( var state in sm.states )
    {
        collector.Add( state.state );

        foreach( var subSm in sm.stateMachines ) // Jump into nested state machine
            _ExpandStatesInLayer( subSm.stateMachine, collector );
    }
    return collector;
}

```

---

## Peek into state's content (AnimationClip/BlendTree)

After long fight, now we can see contents in each state. The code is self explained. It is up to you how to modify these state.

```
foreach( var state in stateList )
{
    Motion m = state.motion;
    if( m is AnimationClip ) // It is single animation clip
        Debug.Log( "clip " + m.name );
    if( m is BlendTree ) // It is blendtree with multiple clips!
        Debug.Log( "tree " + m.name );

    state.motion = null; // TODO: Set something else to it.
}

```

---

* Dont forget a call to UnityEditor.EditorUtility.SetDirty if you actually modify it. Or better alternative UnityEditor.Undo.RecordObject. (It also set dirty state)
* If layer is SYNC layer (copy states from source layer), the workflow will be a bit different when getting state list and getting motion attached to it. It is not covered in this answer. You can lookup potential API from related class documents.

# Answer
> 0 votes
You cannot access the clip in the animator directly. Here is an example of how I used clip replacement. For more information, look into Unity's documents. https://docs.unity3d.com/ScriptReference/AnimatorOverrideController.ApplyOverrides.html

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

public class AnimationClipOverrides : List<KeyValuePair<AnimationClip, AnimationClip>>
{
    public AnimationClipOverrides(int capacity) : base(capacity) { }

    public AnimationClip this[string name]
    {
        get { return this.Find(x => x.Key.name.Equals(name)).Value; }
        set
        {
            int index = this.FindIndex(x => x.Key.name.Equals(name));
            if (index != -1)
                this[index] = new KeyValuePair<AnimationClip, AnimationClip>(this[index].Key, value);
        }
    }
}

public class PlayerScript : MonoBehaviour
{
    [SerializeField]
    private AnimationClip[] m_Animations;

    private Animator anim;
    private AnimatorOverrideController animatorOverrideController;
    private AnimationClipOverrides clipOverrides;

    void Start()
    {
        anim = GetComponent<Animator>();
        animatorOverrideController = new AnimatorOverrideController(anim.runtimeAnimatorController);
        anim.runtimeAnimatorController = animatorOverrideController;

        clipOverrides = new AnimationClipOverrides(animatorOverrideController.overridesCount);
        animatorOverrideController.GetOverrides(clipOverrides);
    }

    public void Play(int numberClip)
    {
        clipOverrides["myAnimation"/*name *.anim file in State inspector*/] = m_Animations[numberClip];
        animatorOverrideController.ApplyOverrides(clipOverrides);
        anim.Play("start");

    }
}

```

---
Tags: unity
---


# Question
Title: Is it ok to commit to git while my Unity project is still open?
I tend to have big commits and it is related to me being tool lazy to close Rider and Unity, commit changes and then start both programms back up to make changes and repeat. I just assumed that this is the correct way of doing it, but is this even the case?

Thanks in advance!

# Answer
git does not work with your memory ram. git works with what is in hard-disk. it means git commits everything you saved. so it means you can commit when unity is open. just save every thing before you commit and push.
> 2 votes

---
Tags: unity, git
---


# Question
Title: Saving and loading a GameObject's full state easily in Unity3D?
I'm working on **placing predesigned tilemap rooms** in my **procedural dungeons**, and I would like to **design the items' and monsters' placement in these special rooms** as well.

Currently I **"compile"** my predesigned room **scene** into a **scriptable object**, and the map generator loads that tilemap into "gameplay" tilemap.

I already parse the **special game objects** in the scene (like items and monsters), and **store their transforms** and **prefab paths** in the **scriptable object**.

But this has **2 problems**:

* Having every item and monster in the **resources folder** would make my executable **huge**.

+ But this could be solved by making a **"MonsterPrefabDictionary"** on a manager like gameobject, and **drop every prefab into this list in the editor**. The map generator would simply use this dictionary to find the object's prefab.
* The **biggest problem** is that **every variation of monster would need another prefab** (or prefab variation). And by variation I mean the little changes as well.

+ *Want a mob to have only 50% health in the room at start? Make a prefab for this?*
    + *Want a monster to start with a specific buff in this room? Make a prefab for this?*
    + *Want a monster to start in a different stance than usual in this room? Make a prefab for this?*
    + So as you can see, **this scales pretty badly**.
    + But this could be solved by **storing the MonsterScript's every data in the scriptable object**.
    + But this would **scale badly as well**, because every new information about a monster would have to be added to this serialization process as well.

Is there a **built-in, automatic, easy way** to just **save a GameObject's full state** and just **load everything with one line** later on?

# Answer
> 2 votes
I think that you went down the wrong rabbit hole and should take a step back instead of going deeper.

You goal is to generate levels proceduraly. For that you want predesigned rooms containing different kinds of entities. So you why not create a prefab for every room?

Unity would serialize all child GameObjects of the room together with the room. Additional room-specific information can also be stored on a MonoBehaviour, let's call it `RoomData`, that is placed on the root object. You can copy and paste all fields and methods of your `RoomScriptableObject` into the new `RoomData` component.

On the class (`LevelGenerator`?) that previously hold a reference to all instances of your `RoomScriptableObjects` you now instead add a field `public List<RoomData> rooms` that holds a list of room prefabs. You can then create rooms by instantiating prefabs from the List. This should only change your generation code by a little bit and all GameObjects of the rooms are serialized.

This would also allow for room variants, something that you can't really do with scriptable objects without getting some sort of redundancy.

**EDIT:**

## Naive approach:

To avoid multiple tilemaps you could load each room-tilemap, after instantiation, into the gameplay-tilemap and delete the room-tilemap. Then profile performance of this naive approach.

## Approach similiar to yours:

You keep the `RoomScriptableObject` approach for rooms and instead of having one prefab of the whole room you only create a prefab that contains every GamObject of the room **but** the rooms tilemap. Then store this prefab in a single field `GameObject roomContent` of the `RoomScriptableObject` class. You still serialize the tilemap into the `RoomScriptableObject` like you did before. On generation you extend the gameplay-tilemap via the serialized data in the `RoomScriptableObject` like before and then instantiate the `roomContent` prefab.

## On Optimization

It is common knowledge that premature optimization should be avoided and that simple solutions are desirable over complex ones. So I would encourage you to try the naive approach first before you invest time into optimizing something that doesn't necessarily needs it. This is especially true if optimizing makes content creation harder for designers or more prone to buggs.

This of cource has no meaning if you already know that this approach is too slow from prior experience or profiling.

---
Tags: unity, procedural-generation, serialization
---


# Question
Title: CenterContainer makes my button too small
I get the perfect width for my buttons, but CenterContainer overrides that value of theirs to make the button as wide as the biggest text length of the buttons when I put the buttons inside of the container

godot 3.1

# Answer
Easiest solution is to change the text of one to add space characters before and after the text.

```
Start

    Start

```
> 0 votes

---
Tags: gui, godot
---


# Question
Title: Is there a way to set a range on a case argument in a switch statement in Game Maker: Studio?
Okay so I am making a tower defense game in GML and I came across a small problem when making a switch statement, I want to have anything from 1-10 to result in a variable changing to 1, anything from 11-20 result in the variable changing to 2, and anything 21-30 to change to 3. It would look something like this. Yes I know I'm new to coding..

```
switch(test)
{
    case (1-10):
        test = 1;
        break;

    case (11-20):
        test = 2;
        break;

    case (21-30):
        test = 3;
        break;
}

```

Except for the fact that that does not work and to actually do something like that, in my knowledge you'd have to make a case for every single number in the range which would take ~3 years. Help?

# Answer
> 1 votes
According to the documentation it looks like the switch works like it does in other languages and needs to have values known at compiletime, which means you can't use an expression as a case in a switch.
But there is a way to do a switch with a range and that is by skipping the break in some of the case statements. That can become quite tedius and it is probably simpler to use if else, especially in your exemple where it will look like this.

```
if(test > 0 and test <= 10)
{
    test = 1;
}
else if (test > 10 and test <= 20)
{
    test = 2;
}
else if (test > 20 and test <= 30)
{
    test = 3;
}

```

But if you really want to use a switch it will look something like this

```
switch(test)
{
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
case 10:
   test = 1;
   break;
case 11:
case 12:
case 13:
case 14:
case 15:
case 16:
case 17:
case 18:
case 19:
case 20:
   test = 2;
   break;
case 21:
case 22:
case 23:
case 24:
case 25:
case 26:
case 27:
case 28:
case 29:
case 30:
   test = 3;
   break;
}

```

# Answer
> 3 votes
You should use `if`:

```
if test < 11
{
    test = 1;
}
else if test < 21
{
    test = 2;
}
else if test < 31
{
    test = 3;
}

```

Another example with different ranges:

```
if test >= 5 and test <= 10
{
    test = 1;
}
else if test >= 15 and test <= 17
{
    test = 2;
}
else
{
    test = 3;
}

```

# Answer
> 0 votes
Instead of using a switch or an if-else, you can attempt a math-based approach.

test = floor((test + 9) / 10);

# Answer
> 0 votes
In example if you don't need 1 last digit you can use "div" operator - div, mod (%) - Division and modulo, where div gives you the amount a value can be divided into producing only an integer quotient, while mod gives you only the remainder of a division. Examples of use: secs = time mod 60; time\_str = string(time div 60);

# Answer
> -1 votes
```
key = (test-1) div 10

switch (key) {
    case 1:
    break;

    case 2:
    break;

    case 3:
    break;
}

```

---
Tags: game-maker
---


# Question
Title: How to validate that certain fields are nonempty before the program starts?
I want to check that some fields are nonempty before any of the `Start()` functions run.

I tried to put checks in `Awake()` and `Empty()` and to quit Unity if they fail:

```
    #if UNITY_EDITOR
        Debug.Log("exit from editor");
        UnityEditor.EditorApplication.isPlaying = false;
    #else
        Debug.Log("exit from game");
        Application.Quit();
    #endif

```

It hits this code but it doesn't actually quit the game. I found that the `Quit` / `isPlaying = false` commands only work from `Update`

# Answer
Since what you are trying to do is somewhat related to exception handling consider the exception guidelines from Microsoft:

* > Use try/catch blocks around code that can potentially generate an exception and your code can recover from that exception.
* > For conditions that are likely to occur but might trigger an exception, consider handling them in a way that will avoid the exception.
* > When your code cannot recover from an exception, don't catch that exception. Enable methods further up the call stack to recover if possible.

In your case we:

* Have conditions that are likely to occur (accidental change of inspector values etc)
* But (and I only asume this) we can't recover and thus wish to quit the app

Instead of implementing logic to quit the game for every `MonoBehaviour` you could try to process otherwise unhandled exceptions at a higher level, the application root, by notifying the user and then quitting the game. This would then also work for unhandled exceptions originating from other parts of your code.

We can do this in Unity with the Application.logMessageReceived callback. See this on how it works.

As pointed out by DMGregory you can use MonoBehaviour.OnValidate to validate fields before startup.
> 0 votes

---
Tags: unity
---


# Question
Title: Error(45,74): Identifier 'collision' is not declared in the current scope
```
func _physics_process(delta):
    direction = Vector3(0, 0, 0)
        if Input.is_action_pressed("ui_left"):
            direction.x += 1
        if Input.is_action_pressed("ui_right"):
            direction.x -= 1
        if Input.is_action_pressed("ui_up"):
            direction.z += 1
        if Input.is_action_pressed("ui_down"):
            direction.z -= 1
        direction = direction.normalized()
        direction = direction * speed * delta
        if velocity.y > 0:
            gravaty = -20
        else:
            gravaty = -30

        velocity.y += gravaty * delta
        velocity.x = direction.x
        velocity.z = direction.z

        velocity = move_and_slide(velocity, Vector3(0, 1, 0))

        if is_on_floor() and Input.is_key_pressed(KEY_SPACE):
            velocity.y = 10
        var hitCount = get_slide_count()
        if hitCount > 0:
            var collision = get_slide_collision(0)
        if collision.collider is RigidBody:
            collision.collider.apply_impulse(collison.position, -collision.normal)

```

# Answer
Consider what happens in your code when `hit_count` is `0`.

```
# This line is skipped, so collision is never defined
if hitCount > 0:
    var collision = get_slide_collision(0)

# This still executes, but collision is not defined
if collision.collider is RigidBody:

```

You should only perform the latter check if `hit_count > 0`:

```
if hitCount > 0:
    var collision = get_slide_collision(0)
    if collision.collider is RigidBody:
        collision.collider.apply_impulse(collison.position, -collision.normal)

```
> 1 votes

---
Tags: godot
---


title: C++ Object management/deletion

text:
# Question
Title: C++ Object management/deletion
I am working on a game with a lot of bullets, currently every second it loops through a vector of bullet objects and checks if its marked for erasure or not.

```
if (timer2>=120){

    auto it = Bulletlist.begin();
    while (it != Bulletlist.end())
    {
    if ((it->del)) {
             it = Bulletlist.erase(it);
         }
         else {
             ++it;
         }
    }
    timer2=0;
    }else{
    timer2++;
    }

```

This works fine for around 0-200 bullets, however when I try to scale it larger the delay becomes very noticeable. I am still very new to C++, And was curious if there is a better way of doing this. The bullet class automatically marks itself for deletion when it goes out of bounds.

```
    int update(){
    if (acceleration!=0){
    if (speed < acceleration){
    speed+=increment;
    }
    }
    x=(speed*cos(angle)) + x;
    y=(speed*sin(angle)) + y;

    if (x<0) del=true;
        if (x>1000) del=true;
        if (y<0) del=true;
        if (y>750) del=true;
    circ.setPosition(x,y);
    window.draw(circ);
};

```

Edit: Bullets are generated right now on a loop within a enemy class

void shoot(int which){
    Bullet B1;
    B1.setsprite();
    currentangle+=(6.2832/bnum)+0.05;
        B1.setvars(x,y,currentangle*which,1.f,2.f,0.01f);
    Bulletlist.push_back(B1);
    }
    void update(){
     movtimer+=0.01f;
     //x += sin(movtimer);
     //std::cout<<x;
     //printf("\n");
     sprite.setPosition(x,y);
      if (timer>=10){
      for (int i=0; i<bnum; ++i) {
      shoot(1);
      }
      timer=0;
      }else{
      timer++;
      }
      window.draw(sprite);
      for (std::vector<Bullet>::iterator it = Bulletlist.begin() ; it !=    Bulletlist.end(); ++it){
       it->update();
      }
```
</code></pre>

# Answer
> 7 votes
You're using a `std::vector<Bullet>`. This has the advantage of keeping data contiguous in memory, so iterating over it is *fast* (it has something to do with cache efficiency vs cache misses).

The way you're using it is *slow*.

```
auto it = Bulletlist.begin();
while (it != Bulletlist.end())
{
  if ((it->del)) {
    it = Bulletlist.erase(it);
  }
  else {
    ++it;
  }
}

```

When you erase an item, it has to make sure that the order is preserved, and that the data is still contiguous in memory. To do so, it will move (or copy) *all* the items that come after the erased one so that it "fills the hole" left. This is very long.

There are a couple of "cheap" alternatives:

* Use a std::list instead of a std::vector. The list will preserve the order, but does not have the constraint of keeping the items contiguous in memory (at the cost of a little speed).
* Use a smart pointer such as std::unique\_ptr to store your objects. You'll also lose a bit of speed during the iteration because the code will jump all over in memory too, but your removal of the bullets will be much faster because copying/moving a smaller object is faster.

More complex alternative involve to copy (or move, if your Bullet is move-able) a bullet from the end of your vector to the "slot" where the to-be-deleted Bullet is.

It goes a bit like this (pseudo-code):

```
int index = 0
while index < vectorSize
  if vector[index] is to be deleted
    vector[index] = vector.lastElement
    vector.popLastElement
  else
    index ++

```

You could also evaluate the cost of having dead bullets in your collection: if it's not that high, keep them there, then when you need to add a new one, instead of *creating* one, resurrect one that is dead (and keep an index to it to go from there when you'll be seeking a new bullet spot). That's a bit like object pooling. I haven't tried that personally.

I'm sure that if you wait a bit, some other users will post more smart(er) answers :)

# Answer
> 3 votes
If performance is an issue, you might wanna use a design method/pattern called Object pooling. What this method/pattern actually means is that you, at the start-up of the game/level/scene, fill a container (an std::vector, an std::list etc) with a fixed number of objects, bullets in your case. When a bullet is supposed to be shot in the game, the code retrieves a bullet from the container, marks it as used, moves it across the screen, renders it and whenever it should be destroyed (at collision with ground, walls, characters etc), stop rendering it and then finally mark it as free so the code knows it's ok to pick that bullet from the container later, for later usage. At the game/level/scene shutdown, the bullets are destroyed. By using this method/pattern, no bullets are created and/or destroyed during run-time.

I have added some example code below.

```
#include <vector>

// Bullet object
struct SBullet
{
    Vector2D    Position;
    float       Speed;
    float       Damage;
    bool        InUse;
};

typedef std::vector<SBullet*> BulletVector;

// Will be filled at the startup of the game/level/scene and destroyed/cleared at game/level/scene shutdown
BulletVector Bullets;
Bullets.clear();

// Will be filled with bullet pointers during run-time
BulletVector ActiveBullets;
ActiveBullets.clear();

int main()
{
    // Fill the bullet vector with bullets
    for(unsigned int i = 0; i < 128; ++i)
    {
        SBullet* pBullet = new SBullet;

        pBullet->Position   = Vector2D(0.0f, 0.0f);
        pBullet->Speed      = 16.0f;
        pBullet->Damage     = 2.0f;
        pBullet->InUse      = false;

        Bullets.push_back(pBullet);
    }

    While(Running)
    {
        Update();
        Render();
    }

    // Destroy the bullet vector
    BulletVector::const_iterator ItBeg = Bullets.begin();
    BulletVector::const_iterator ItEnd = Bullets.end();

    for(; ItBeg != ItEnd; ++ItBeg)
    {
        delete (*ItBeg);
    }

    Bullets.clear();
}

void Update()
{
    // Mouse button has been pressed so it's time to add a free bullet into the active bullets vector
    if(InputHandler.MouseButtonClicked)
    {
        SBullet* pBullet = RetrieveFreeBullet();

        if(pBullet)
        {
            pBullet->Position   = pPlayer->GetPosition();
            pBullet->InUse      = true;

            ActiveBullets.push_back(pBullet);
        }
    }

    unsigned int NumBullets = ActiveBullets.size();
    unsigned int Index      = 0;

    while(Index < NumBullets)
    {
        SBullet* pBullet = ActiveBullets[Index];

        MoveBulletAcrossScreen(pBullet);

        /*
        The bullet has collided with an enemy, mark it as free, remove it from the active bullets vector and maybe render some explosion/particles etc
        Removing the bullet from the active bullets vector wont destroy the actual bullet, only remove the actual pointer from the vector
        */
        if(CollisionCheck(pBullet, pEnemy))
        {
            pEnemy.ReduceHealth(pBullet->Damage);

            pBullet->Position   = Vector2D(0.0f, 0.0f);
            pBullet->InUse      = false;

            SBullet* pTemp = ActiveBullets[Index];

            /*
            Swap the current bullet's and the last bullet's container position
            It's better to remove an object in the end of the vector since the rest of the objects after won't have to be moved back in the vector to fill up the empty space (which is costly)
            */
            ActiveBullets[Index] = ActiveBullets[NumBullets - 1];
            ActiveBullets[NumBullets - 1] = pTemp;

            ActiveBullets.pop_back();

            --NumBullets;
        }

        // The bullet has collided with some ground - the same procedure as above to remove the bullet
        else if(CollisionCheck(pBullet, pGround))
        {
            pBullet->Position   = Vector2D(0.0f, 0.0f);
            pBullet->InUse      = false;

            SBullet* pTemp = ActiveBullets[Index];

            ActiveBullets[Index] = ActiveBullets[NumBullets - 1];
            ActiveBullets[NumBullets - 1] = pTemp;

            ActiveBullets.pop_back();

            --NumBullets;
        }

        else
            ++Index;
    }
}

void Render()
{
    BulletVector::const_iterator ItBeg = ActiveBullets.begin();
    BulletVector::const_iterator ItEnd = ActiveBullets.end();

    for(; ItBeg != ItEnd; ++ItBeg)
    {
        RenderSprite((*ItBeg), pBulletSprite);
    }
}

SBullet* RetrieveFreeBullet()
{
    // Might wanna have a variable containing the last used index into the bullet vector for faster returning of a bullet

    BulletVector::const_iterator ItBeg = Bullets.begin();
    BulletVector::const_iterator ItEnd = Bullets.end();

    for(; ItBeg != ItEnd; ++ItBeg)
    {
        if((*ItBeg)->InUse)
            continue;

        return (*ItBeg);
    }

    // No free bullet available, might wanna return the bullet at the start of the vector instead of nullptr so that a valid bullet is always returned
    return nullptr;
}

```

---
Tags: c++, performance, game-loop, optimization
---


# Question
Title: Find the direction a Projectile should be fired from a Moving Object to hit another moving Object?
I am trying to do a simple AI Controller, which fires Missiles at the surrounding targets in the Scene.

* The AI Controller can fire projectiles when moving or stationary.
* The Targets are either stationary or move around in the scene with a Constant Velocity and can't fire projectiles.

I did some searching on Stack overflow and came up with this code to find the direction the AI controller must fire the projectile (constant speed) to hit a target travelling at a constant velocity(it can also be stationary):

```
private bool GetProjectileDirection(GObject target, GObject source, out Vector3 direction)
{
    // Initialize direction to Zero
    direction = Vector3.zero;

    // The Relative Position between the AI Controller and the target.
    Vector2 w = new Vector2(target.Position.x - source.Position.x, target.Position.y - source.Position.y);

    // The Relative Velocity between the source and the target.
    Vector2 v = new Vector2(target.Velocity.x - source.Velocity.x, target.Velocity.y - source.Velocity.y);

    // Quadratic Equation Co-efficients
    float a = Vector2.Dot(v, v) - BULLET_SPEED * BULLET_SPEED;
    float b = Vector2.Dot(w, v);
    float c = Vector2.Dot(w, w);

    float root = (b * b) - (a * c);

    // The Problem seems to occur here as this becomes less than zero most of the time,
    // and exits the function.
    // But on the screen, the object is well within the range for the AI to fire at it
    if (root < 0)
        return false;

    // If root < 0, then this becomes NaN and brings the simulation to a crawl
    double t = (-b - Math.Sqrt(root)) / a;

    double shootX = w.x + t * v.x;
    double shootY = w.y + t * v.y;

    double theta = Math.Atan2(shootY, shootX);
    direction = BULLET_SPEED * new Vector3(Math.Cos(theta), 0, Math.Sin(theta));

    return true;
}

```

I am pretty sure I am missing something. I just can't pinpoint what exactly is it. As a result, the AI seems to miss most of the targets around it.

# Answer
> 2 votes
This is the updated code, with code for handling some edge cases. Also, I made sure the `BULLET_SPEED` large enough for the Equations to work:

```
 private bool GetProjectileDirection(GObject target, GObject source, out Vector3 direction)
{
    direction = Vector3.Zero;

    Vector2 w = new Vector2(target.Position.x - source.Position.x, target.Position.y - source.Position.y);
    float ww = Vector2.Dot(w, w);
    float r = target.BoundingRadius;

    Vector2 v = new Vector2(target.Velocity.x - source.Velocity.x, target.Velocity.z - source.Velocity.z);

    double a = Vector2.Dot(v, v) - (BULLET_SPEED * BULLET_SPEED);
    double b = 2 * Vector2.Dot(w, v);
    double c = Vector2.Dot(w, w);

    double h = -b / (2 * a);
    double k2 = h * h - (c / a);

    double t = 0.0f;

    if (k2 < 0)
        return false;

    if (k2 == 0)
    {
        if (h > 0)
            t = h;
        else
            return false;
    }

    if (k2 > 0)
    {
        double k = Math.Sqrt(k2);
        double r0 = h - k;
        double r1 = h + k;

        if (r0 > 0)
            t = r0;

        else if (r1 > 0)
            t = r1;

        else
            return false;
    }

    double shootX = w.x + t * v.x;
    double shootY = w.y + t * v.y;

    double theta = Math.Atan2(shootY, shootX);
    direction = new Vector3(Math.Cos(theta), 0, Math.Sin(theta));

    return true;

}

```

Here is the answer that I based this code off.

---
Tags: mathematics, ai, projectile-physics
---


title: Comments getting executed as command

text:
# Question
Title: Comments getting executed as command
I have a script to edit my world on run time and a script to generate a world. When i tried to place a block, something wrong happened, so I tried to make my script into command until I find which line was wrong. However, my comments still seem to execute. I made all the lines of update into comments, I still detect my mouse click, and it is the only script to use mouse click. Infos: -using IEnumerator to generate world. -using /*...*/ for comments -if I try to put a Debug.Log("..."); in the comment part, it doesnt show up in the console, which is even weirder.

# Answer
Well this usually happen due to 2 reasons:

1. You have not saved the script. so try to save using **Ctrl+Shift+S** this will save all of the edits happen in all of the scripts.
2. This might have happen due to your IDE is not synced with unity so close your IDE and unity and then restart unity and double click on the script to open it up in IDE. Now do some change in the script and save, then move back to unity check if the loading ring is rotating at lower right end if it does rotating this means unity is compiling the script so wait for it and then Play.

I hope this will help...
> 1 votes

---
Tags: unity, c#, 3d-meshes, perlin-noise
---


# Question
Title: How to make a cube fall from the edge when part of it is outside in Unity
Let's assume I have a 1x2x1 cube and it is balanced over an edge, since the weight of the cube is distributed perfectly, it doesn't fall, how to make it fall when part of the cube is over the edge?

I have tried adding invisible objects to both ends of the cube and then adding another invisible object on the edge so when they collide I change the center of mass of the cube, this seems to work but I think it is overly complex since I have to add that invisible object around all edges of my scene.

# Answer
> 1 votes
https://docs.unity3d.com/ScriptReference/Rigidbody-centerOfMass.html

for falling or everything dependent to physics you need to add rigidBody to it. rigidBody has a property name **CenterOfMass**. its a **vector3** property. you need to position it far from that edge to put force on outer side of that edge.

---
Tags: unity
---