# Question
Title: How to use "Input.GetButtonDown" in the new Input System?
I'm making a 2d platformer game with Unity using the new Input System and Player Input component. I want to make a shooting system for the game but I need to use "Input.GetButtonDown" which is for the old Input System. Is there any equivalent for it and if not, how can I make this in the new Input System?

Here's my player controller code:

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

public class PlayerController : MonoBehaviour, PlayerInputActions.IPlayerActions
 {
   private PlayerInputActions controls;
   private Rigidbody2D rb;
   private Animator anim;
   private bool facingRight = true;
    private Vector2 moveInput;

 [SerializeField] private float jumpForce;
    float JumpPressedRemember = 0;

   [SerializeField] float JumpPressedRememberTime = 0.2f;
    float GroundedRemember = 0;

   [SerializeField]  float GroundedRememberTime = 0.25f;
   [SerializeField]  float HorizontalAcceleration = 1;
   [SerializeField] [Range(0, 1)] float HorizontalDampingBasic = 0.5f;
   [SerializeField] [Range(0, 1)] float HorizontalDampingWhenStopping = 0.5f;
   [SerializeField] [Range(0, 1)] float HorizontalDampingWhenTurning = 0.5f;
   [SerializeField] [Range(0, 1)] float JumpHeight = 0.5f;

   private void Awake()
   {
      controls = new PlayerInputActions();

      controls.Player.SetCallbacks(this);
    }
     void Start()
    {
      rb = GetComponent<Rigidbody2D>();
      anim = GetComponent<Animator>();
}
   void PlayerInputActions.IPlayerActions.OnMove(InputAction.CallbackContext context)
   {
      moveInput = context.ReadValue<Vector2>();

   }

   void PlayerInputActions.IPlayerActions.OnJump(InputAction.CallbackContext context)
   {
       jumpForce = context.ReadValue<float>();
       switch (context.phase)
       {
            case InputActionPhase.Performed:
               this.Jump();
               break;
       }
   }

   public void Jump()
   {
     rb.AddForce(Vector2.up * this.jumpForce, ForceMode2D.Force);
   }

  void FixedUpdate()
  {

   if(facingRight == false && moveInput.x > 0){

    Flip();

   }else if (facingRight == true && moveInput.x < 0){

    Flip();

   }
 }
    void Flip(){

    facingRight = !facingRight;
    Vector3 Scaler = transform.localScale;
    Scaler.x *= -1;
   transform.localScale = Scaler;
 }

 void OnEnable()
 {
     controls.Enable();
 }

 void OnDisable()
 {
     controls.Disable();
 }
 void Update()
  {

   Vector2 GroundedBoxCheckPosition = (Vector2)transform.position + new Vector2(0, -0.01f);
   Vector2  GroundedBoxCheckScale = (Vector2)transform.localScale + new Vector2(-0.02f, 0);
   bool Grounded = Physics2D.OverlapBox(GroundedBoxCheckPosition, transform.localScale, 0);

    GroundedRemember -= Time.deltaTime;
    if (Grounded)
    {
      GroundedRemember = GroundedRememberTime;
    }

    JumpPressedRemember -= Time.deltaTime;
   if (controls.Player.Jump.triggered)
   {
      JumpPressedRemember = JumpPressedRememberTime;
   }
     if (controls.Player.Jump.triggered)
        {
            if (rb.velocity.y > 0)
            {
                rb.velocity = new Vector2(rb.velocity.x, rb.velocity.y * JumpHeight);
            }
        }
    if ((JumpPressedRemember > 0) && (GroundedRemember > 0))
    {
       JumpPressedRemember = 0;
       GroundedRemember = 0;

      rb.velocity = new Vector2(rb.velocity.x, jumpForce);
    }
     float HorizontalVelocity = rb.velocity.x;
      HorizontalVelocity += moveInput.x;

        if (Mathf.Abs(moveInput.x) < 0.01f)
            HorizontalVelocity *= Mathf.Pow(1f - HorizontalDampingWhenStopping, Time.deltaTime * 10f);
           else if (Mathf.Sign(moveInput.x) != Mathf.Sign(HorizontalVelocity))
           HorizontalVelocity *= Mathf.Pow(1f - HorizontalDampingWhenTurning, Time.deltaTime * 10f);
        else
            HorizontalVelocity *= Mathf.Pow(1f - HorizontalDampingBasic, Time.deltaTime * 10f);

        rb.velocity = new Vector2(HorizontalVelocity, rb.velocity.y);

  }
}

```

# Answer
This seems to be answered by Unity's own documentation on Migrating from the old Input System:

> **UnityEngine.input.GetButtonDown**
>
> See UnityEngine.Input.GetAxis for how to set up a Binding to a button or axis. You can use the press Interaction to detect when a button is pressed.
>
> You can also use ButtonControl.wasPressedThisFrame to detect if a button Control was pressed down this frame directly without using Bindings.
> -2 votes

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


# Question
Title: Generate plane with script missing triangles
I am trying to do a simple script to generate a plane from a script by creating a new mesh. After trying it, it seems like some of the triangles aren't showing up. I checked if they were in the list by making it publci and they are in it, so I dont understand why the last triangles aren't showing while the others are.

```
int size = 4;
Mesh meshy;
public List<Vector3> vert = new List<Vector3>();
public List<Vector2> uv = new List<Vector2>();
public List<int> tri = new List<int>();
void Start()
{
    vert = new List<Vector3>();
    tri = new List<int>();
    meshy = new Mesh();
    for (int x = 0; x < size; x++)
    {
        for(int z = 0; z < size; z++)
        {
            vert.Add(new Vector3(x, 0, z));
        }
    }
    meshy.vertices = vert.ToArray();
    for (int i = 0; i < ((size-1)*(size-1));i++)
    {
        tri.Add(i);
        tri.Add(i+1);
        tri.Add(i+size);
        tri.Add(i + size +1);
        tri.Add(i + 1 +(size - 1));
        tri.Add(i + 1);
    }
    meshy.triangles = tri.ToArray();
    for(int i = 0; i < ((size - 1) * (size - 1)); i++)
    {
        uv.Add(new Vector2(0, 0));
        uv.Add(new Vector2(1, 0));
        uv.Add(new Vector2(0, 1));
        uv.Add(new Vector2(1, 1));
    }
    meshy.uv = uv.ToArray();
    GetComponent<MeshFilter>().mesh = meshy;
}

```

# Answer
> 1 votes
I find it often helps to jot down on paper a small version of the problem you're trying to solve, say `size = 3` so you have just 3x3 vertices, and pretend to be the CPU, working through the set of instructions you've given it one by one.

First we generate the vertices, running up the z columns then across the x rows:

The first iteration of your triangles loop tries to join...

```
    // In red
    tri.Add(i);                  // 0
    tri.Add(i+1);                // 1
    tri.Add(i+size);             // 3

    // In orange
    tri.Add(i + size +1);        // 4
    tri.Add(i + 1 +(size - 1));  // 3
    tri.Add(i + 1);              // 1

```

Then we can just add one to these numbers for each of the following iterations. The second iteration joins 1 2 4 (yellow) and 5 4 2 (green). Then the third iteration joins 2 3 5 (blue) and 6 5 3 (purple)... uh oh.

We made a bogus pair of triangles joining the first column to the second column. But our loop condition says we're only allowed to loop `(size - 1) * (size - 1) = 2 * 2 = 4` times, so if we run this code to completion we stop at `i = 4`, before we've drawn the final quad worth of triangles.

Your code gets confused when it hits the end of a column, because the way you've written your loop it's no longer aware of the row-column structure of your vertices. Let's fix that.

```
for(int x = 0; x < size - 1; x++) {
    for(int z = 0; z < size - 1; z++) {
         // Index of the bottom-left vertex in this quad.
         int i = size * x + z;

         // Bottom-left triangle.
         tri.Add(i);
         tri.Add(i + 1);
         tri.Add(i + size);

         // Upper-right triangle.
         tri.Add(i + size + 1);
         tri.Add(i + size);
         tri.Add(i + 1);
    }
}

```

Now we loop over only those vertices that are the bottom-left corner of some quad in our mesh (0, 1, 3, 4 in this example), and skip creating bogus triangles using vertex 2 as our start point, since it's at the end of a column, on the open edge of the mesh.

---
Tags: unity, 3d, procedural-generation, mesh, vertex
---


# Question
Title: Implementing a Turn Radius for a Character
I'm working on a 3rd person platformer in Unity where I'm attempting to capture a Mario 64 style feel. Part of the game involves attaining really fast speeds. Currently, my turning code is pretty simple, and is essentially a mapping of the left-stick onto the character.

Omitting some more complex logic (accounting for smooth acceleration & the like), the base of my movement code is:

```
rigidbody.AddForce(direction * speed);
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(direction, normal), delta);

```

This is really responsive and feels good, but at the high speeds the player will attain, it starts to break down. As such, I wanted to add a "turn radius" so that it feels more realistic to attempt to turn at high speeds and face some resistance.

Really, I don't want to go full on "Arthur Morgan" super belabored semicircle turns, but just provide some sense of "weight" and momentum influence to directional changes. Given how simple my current movement is, I'm not sure where to start when it comes to adding in this type of behavior.

I checked out questions like this mario one and lots of other turning related questions, but most I could find were related to the direciton the character was facing, and less about it's movement or velocity. Any input here is appreciated!

# Answer
> 1 votes
The Methods `Vector3.RotateTowards` or `Quaternion.RotateTowards` can help you here.

They turn the object towards the desired direction, but put a limit on how far the object is allowed to turn by specifying a `maxDegreeDelta` parameter. So when you put this in your `Update` method to turn the object into the direction of the stick, but set a small `maxDegreeDelta` limit (remember to multiply by `Time.deltaTime`), you have a lazy turning of the character not unlike Mario 64.

If you want to simulate angular momentum and have the rotation be faster at slower speeds and slower and faster speeds, then you might want to adjust the maxDegreeDelta by `rigidbody.velocity.magnitude`.

---
Tags: unity, physics, 3d, character-controller
---


# Question
Title: How to randomly generate biome with perlin noise?
I want to generate a procedural world using perlin noise. As expected, my terrain is generating with a repetitive patern. I'd like to add biomes, zones separated with higher or lower amplitude to simulate mountains or plain. I first thought I could randomly select rectangles of verticesof random sizes and then give them bigger amplitude to simulate mountains. The problem with that is that It wont seem natural, since I will only have rectangle biomes and also I don't know how to make it so the mountains would connect with the plain to avoid things like this

Here is my script:

```
public int size = 10;
public float amplitude;
public float frequence;
void GenerateTerrain(float amp, float freq)
{
    Mesh meshy;

    MeshRenderer meshRenderer = GetComponent<MeshRenderer>();
    meshRenderer.sharedMaterial = new Material(Shader.Find("Standard"));
    MeshFilter meshFilter = gameObject.GetComponent<MeshFilter>();

    List<Vector2> uv = new List<Vector2>();
    Vector3[] vert = new Vector3[size * size];
    List<int> tri = new List<int>();
    List<Vector3> norm = new List<Vector3>();
    meshy = new Mesh();

    for (int i = 0, x = 0; x < size; x++){
        for(int z = 0; z < size; z++){
            float y = Mathf.PerlinNoise(x * amp, z * amp) * freq;
            vert[i] = new Vector3(x, y, z);
            i++;}}

    for (int i = 0; i < vert.Length; i++){
        norm.Add(-Vector3.forward);}

    for (int x = 0; x < size - 1; x++){
        for (int z = 0; z < size - 1; z++){
            int i = size * x + z;

            tri.Add(i);
            tri.Add(i + 1);
            tri.Add(i + size);
            tri.Add(i + size + 1);
            tri.Add(i + size);
            tri.Add(i + 1);}}

    for (int i = 0; i < vert.Length; i++){
        uv.Add(new Vector2(vert[i].x, vert[i].z));}

    meshy.vertices = vert;
    meshy.triangles = tri.ToArray();
    meshy.uv = uv.ToArray();
    meshy.normals = norm.ToArray();
    meshFilter.mesh = meshy;
}

void Update()
{
    if (Input.GetKeyDown("u"))
        GenerateTerrain(frequence, amplitude);
}

```

# Answer
There are three main steps here:

1. Use some method to **assign biomes to regions** (this is the hard part, with multiple strategies I'll break down shortly)
2. For each point in your mesh or tile/node in your world, determine which biome it's in, as well as which neighbouring biomes it's *close* to. Compute an **interpolation weight** representing the influence of each nearby biome.
3. **Evaluate your terrain generation logic for each of the nearby biomes** separately. (In practice, this means you've computed 3-4 possible heights or other characteristics for this point/node) The final height for this location is a **weighted average** of the results from the nearby biomes, according to their influence.

It might seem wasteful to compute multiple full biome results for a single point, but this is a necessary evil if you want to get sensible blending between them. If you try to interpolate the generation input parameters alone (particularly the noise frequency or number of octaves) and generate just one height result based on the blended parameters, you'll get non-sensical looking blends with nasty artifacts, especially when far from the origin. You also limit how complex and varied your terrain generators can be, since they all have to use the same rules.

---

There are lots of different strategies for step 1. I'll classify the main families as "zoned" and "emergent".

# Strategy 1: Zoned

For this strategy, we start by **dividing our world into a collection of zones**.

A popular method for this is using a Voronoi diagram (also sometimes referred to as a Worley noise basis in procedural generation contexts), where we pseudorandomly scatter points across our map. The set of all locations closer to *this* point than any *other* point forms one zone, which is guaranteed to be a convex polygon. This gives us a nice structured region to work with that's still a little more organic than strict rectangles:

(See also this Red Blob Games article for some discussion of how we can tweak the standard Voronoi approach to something we might prefer for world generation)

You can get arbitrarily more complex with your region selection, of course. Maybe applying domain warping to make the borders between regions more organic, etc. Though I recommend starting simple - most of the hard geometric borders will be hidden by the time we do our blending/interpolation, so they might not be a problem.

Next, we **assign a biome to each zone**.

We could do this randomly, using the zone location/ID to seed a weighted random lookup into a table of biomes. The risk with this is that adjacent biomes make their determinations separately, and so you can get combinations of adjacent zones that don't follow any coherent geographical logic - like a lush jungle completely surrounded by desert, with no fresh water nearby or flowing through it.

We could also use rule-based zone assignments. Maybe we randomly assign a certain fraction of the zones to be water - lakes, seas or oceans. Then we designate any non-water zone adjacent to a water zone must be a beach, cliff, or marsh. Forests and jungles can appear 2 zones away from the nearest water, and mountains only 3+ zones away. You could accomplish this with cellular automata or other adjacency-based rules.

Then for **step 2**, we can compute where our point-to-be-generated sits relative to its nearest neighbouring zones, and use that to compute the interpolation weights to use for each biome's result. One way we can do that is to compute a Delaunay triangulation of the seed points we used to create our zones. This is the dual of the Voronoi diagram, where each triangle represents a junction between three adjacent zones. We can then use the barycentric coordinates of our point-to-be-generated within this triangle to compute the weight to give to each of the three nearest neighbouring zones.

(Diagram showing the relationship of Voronoi cells and Delaunay triangles from here)

# Strategy 2: Emergent

Here we try to model/approximate some of the real-world processes that give rise to different biomes, as a way to get more natural / logical relationships between the different structures. The biomes then "emerge" as a consequence of the simulated natural processes that shape your terrain.

Th first step is to **generate the underlying drivers of biome formation** in our model, like temperature and moisture, to pick a popular pair of inputs. We could generate a moisture map and a temperature map as two separate, low-frequency Perlin noise maps, for example, though going this route these won't have any particular relationship to landforms or location on your map/planet.

Another route is to **generate your broad-scale elevation** up-front - say the first couple octaves of your terrain height function. This isn't biome-level detail yet, more like the underlying bedrock *under* the biomes. Some folks will even generate tectonic plates and simulate their motion to find where there should be mountain ranges formed by two plates colliding, etc.

Once you have this coarse-grained elevation detail (and correspondingly, the locations of oceans/seas based which areas are below sea level), you can **generate other metrics like temperature and moisture** from that. Say, the temperature gets colder as you move higher in elevation or away from the equator in latitude. You can model the moisture based on proximity to an ocean or sea, or the prevailing winds: if winds at a particular latitude run mostly west-to-east, then areas on the east side of a mountain range will tend to be wetter, and areas on the west side dryer, as the mountain wrings the rain out of the air as it passes.

Now you have, for each site in your map, a collection of input values like latitude, elevation, moisture, and temperature. You can use these as coordinates to **look up into a biome assignment map**.

Here's an example diagram from Navarras on Wikipedia, showing how real-world biomes relate to precipitation (moisture) and temperature:

A game might use a more abstracted version, like this example from an older version of Minecraft, via the Minecraft wiki:

You could even add more inputs like the elevation or latitude into the mix, like this plot of the Holdridge Life Zone Classification Scheme from Wikipedia:

With our computed biome driver values for a given point, we can find which region of this plot we fall into, to determine the predominant biome for this location.

For **step 2**, we can also determine how close we are to other biomes in this map, but this time instead of computing our distance in barycentric coordinates within our triangle of zones, or world-space distances across our terrain, we're computing our distance in moisture-temperature space (or whatever driving inputs you've chosen for biome selection).

This route ostensibly gives a stronger connection between the landforms of your continents and the details of your biomes, but it comes at the cost of less direct control over the placement of those biomes. With the wrong parameters, you could easily end up with a whole world of deserts, or a world with only scarce islands of a particular biome. And maybe that's desirable for the variety of worlds from your procedural generator. Or maybe it's not, and you'd prefer to sacrifice some geographical logic (that maybe only the hardcore Earth sciences geeks will notice or appreciate anyway) in order to have more hands-on control over the gameplay combinations of biomes the players will encounter, as you can get with zoning-style approaches.

---

Whichever route we've taken, we now have a list of nearby biomes influencing this point, and a relative weight to apply to each one. Now we can run our terrain generation logic for each biome at this point, and blend the results using those interpolation weights, to arrive at one consensus elevation (and other properties) for this location.

For the emergent scheme, note that you might already have a coarse-grained elevation selected, so your individual biome generators can be more flat, capturing only local terrain shapes, and delegating the broad-scale landforms to the bedrock pass you did earlier. This makes it easier to get a clean blend between adjacent biomes that won't have a sudden artificial-looking ramp between them because they disagree about the average elevation in their domain.

You can even use the coarse elevation value as a bias to your blending function, allowing eg. forest biomes to creep further into the valleys while letting rocky biomes dominate the higher elevations, adding a little non-linearity so the blend feels more organic.
> 16 votes

---
Tags: unity, procedural-generation, mesh, vertex
---


title: Check if coroutine crashed

text:
# Question
Title: Check if coroutine crashed
I can check if coroutine still running by setting boolean variable outside the coroutine and then letting the coroutine itself set the value to true when it runs and set it to false when it decide to stop .

But this method of detecting whether coroutine still active or not doesn't work when the coroutine crashed due to error (invalid input, null reference , ect) because the boolean variable remain true while the coroutine itself has stopped due to error.

How do i check if coroutine still running or not in current frame ? i can't spend my code checking for next frame .

Preferably C# , but answer in javascript also accepted.

# Answer
Oh nevermind , the answer was to use `try { } catch { }` block

```
bool iscrashed = false;
IEnumerator Example() {

try {
//some operation
}
catch {
// if error encountered
iscrashed = true;
}

}

```
> 1 votes

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


# Question
Title: Is Time.deltaTime the last frame time or it is the time difference between frames?
I just came across the unity blog and found that unity 2020.2 trying to fix Time.deltaTime which is good for more smooth movement (correct me if I am wrong). But when I am reading the blog I found this thing:

> In layman’s terms, delta time is the amount of time your last frame took to complete.

Then, i realized i don't know what exactly the delta time is because i was thing that it actually the difference between the two frame. Then, i consult the unity docs again and find this thing

```
The completion time in seconds since the last frame (Read Only).

```

the second line telling something different (isn't it?) which i am thinking is the defination of deltaTime

```
This property provides the time between the current and previous frame.

```

I try to understand it through an example: time - difference:

4

5 (1)

6 (1)

6 (0)

5 (1)

3 (2)

If you see the above what will be the delta time?

# Answer
> 3 votes
> This property provides the time between the current and previous frame.

That definition is correct. *We can argue that it could be clearer.*

---

> In layman’s terms, delta time is the amount of time your last frame took to complete.

That is an over-simplification.

*After looking for the article in question… I can see the break it down very well afterwards.*

---

First of all, delta is NOT a difference between how much frames took to complete. That is not at all the case. If it where, it would not be useful for physic simulations.

Imagine a floor tiling. If you measure the length of a tile, then the length of another tile, and then take the difference… THAT IS NOT DELTA. Delta is not a deviation.

Instead, delta is closer to a measure of length of the tile, but not quite.

Delta is the measure from the start of a tile to the start of the next.

That is a very good approximation of the length of a tile. And we can - for most purposes - pretend it is a measure of the length of a tile. In reality, that isn't a measure of the length of a tile. Because there is a gap between tiles.

---

Going back to game engines. The usual approach is the following:

1. Take the time from the prior cycle.
2. Take the current time.
3. Compute the difference. That difference is your delta time.

*Make sure that the time you took this cycle is available on the next one, so store it on a variable outside the cycle.*

Taking the naive example from the article in question:

```
var time = GetTime();
while (true)
{
    var lastTime = time;
    time = GetTime();
    var deltaTime = time – lastTime;
    ProcessInput();
    Update(deltaTime);
    Render(deltaTime);
}

```

Please, read the code, it tells you what `deltaTime` is better than anything else.

*Note: We want a high resolution monotone time, when available. See how to measure time.*

Game engines take the name "delta" from math. In math "∆" (Capital Greek letter Delta) means increment or change in a variable. In this case, the variable is time (not duration).

---

Here is the deal: There are other things the engine does every cycle aside from calling `Update`/`Render`. In the example above, we see it also processes input, and that takes some time. *There is a gap between the tiles. There is time used for things other than running `Update`/`Render`.*

Do not take `deltaTime` as a measure of the time your code took to run. If you want that, measure it yourself, with a profiler if possible. *Much less as a deviation of how much your code took to run. To reiterate, `deltaTime` is not a deviation*.

The practical takeaways is that `deltaTime` as the time the engine is asking you to simulate. Why is the engine asking you to simulate that amount of time? Because it has measured that is how much it takes for a game loop cycle, and we expect them to be stable.

You would be simulating more time than your code should take to run. In doing so, movement should appear smooth. Because it accounts for the time time engine takes to do other things.

The engine, can - of course - do better than the naive code I posted above. The article in question is, in fact, dedicated to how they improved it in Unity.

# Answer
> 0 votes
Not really different, you are getting confused by the English language nuances. The Delta Time is the time that the very last frame took to complete, from start to finish. The idea is that every frame will take the same time (or so) therefore, it can be used to compute a movement/rotation in terms of a single frame.

As you might suspect, this is not an exact science because on the current frame you might do something entirely different compared to the last one, and that is what translates into lags or twitches in movement/rotation of objects.

It might be possible to add more intelligence in it, resulting in computing the Adjusted Delta Time, but the adjustment itself takes away precious nanoseconds especially on a game that must run at a high frame-rate, which is why we all end up using the basic Delta Time, giving up the adjustment.

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


# Question
Title: Handling complex selection mechanics in RTS-style game
When we look at complex RTSs where a simple left button mouse click can mean twenty or more different things, depending on the game and UI state, the code handling this interaction and assigning the right interaction action to the input can easily end up messy and tightly coupled to everything, creating a ball-of-mud architecture/The Class That Does Everything related to interaction.

How can I deal with this situation?

Here's an example of the complex selection mechanics that I'm looking for:

* Single left click to select a friendly unit.

+ If friendly unit is in a group, the group is selected.
    + If the group is already selected, select the unit.
* Single left click to select an enemy unit.

+ If friendly unit/group already selected, then issue attack order on unit.
    + If friendly unit/group already selected and enemy unit is in an enemy group, then issue attack order on enemy group.
* Same thing but if target is allied non-controllable, then friendlies move towards target.

Etc.

How can I handle this complex selection system, taking into account complex states?

# Answer
I would solve this by creating click handler behaviors for everything which is clickable. But the primary purpose of that behavior would not be to actually act on the click event but rather find out what the users intention is, convert it into a command and then delegate the execution of that command to a central command handler.

For example, the behavior I would put on enemy-controlled units would look something like this:

```
public class EnemyUnitClickHandler : MonoBehaviour, IPointerClickHandler
{
    public void OnPointerClick(PointerEventData pointerEventData)
    {
        UnitGroup myGroup = GetComponent<GroupMembership>()?.group;
        UIManager uiManager = UIManager.GetInstance();
        CommandHandler commandHandler = CommandHandler.GetInstance();

        if (uiManager.currentlySelected?.faction == Factions.PLAYER) {
            // player-unit is selected - give an attack command
            if (myGroup == null) {
                commandHandler.giveAttackOrder(uiManager.currentlySelected, this);
            } else {
                commandHandler.giveAttackOrder(uiManager.currentlySelected, myGroupMembership.group);
            }
        } else {
            // something else selected - select this unit or its group
            if (myGroup == null || myGroup == uiManager.currentlySelected) {
                commandHandler.selectUnit(this);
            } else {
                commandHandler.selectGroup(myGroup);
            }
        }

    }
}

```

The reason for this layer of indirection is that `commandHandler.selectUnit` or `commandHandler.giveAttackOrder` are now no longer explicitly *mouse click* events. Decoupling them from the input method which was used to trigger them allows you to reuse them for other ways in which commands can be given. Like via a hotkey, via the AI controller, via another player connected via network or as part of the tutorial.

The purpose of the CommandHandler would then be to route those events back to the objects which concern them. What exactly it means to "giveAttackOrder(subject, target)" should be handled by the component which handles unit AI. What exactly it means to "change the selected entity" should be implemented in the class(es) which control the UI.
> 1 votes

---
Tags: unity, software-engineering, input, rts, selection
---


# Question
Title: How can I to get an animation to be triggered by proximity of a mesh actor (an object)?
So I'm making my first build in Unreal 4 using Blueprint. The "game" calls for the player character to grab a particular object (a static mesh actor) and bring it close to a door that will slide open if detects the item near. I have the door slide animation and a trigger volume around the door but I can't get it to work with the mesh actor I want. So far I've managed to get it to open with by pressing a keyboard key while being inside the trigger volume. I believe the volume trigger can detect any actor that is within its border, right? What nodes could I use to make this work?

UPDATE: Thanks to @Stephen I tried using the cast node solution but I still can't get it to work

If it helps, I've added an updated screenshot of my blueprint.

Cheers!

# Answer
> 1 votes
The Generate Overlap Events box of the StaticMesh (the item) not ticked (set to false) so the trigger volume was not detecting anything. After ticking the Generate Overlap Events box, the Generate Overlap Events During Level Straming setting the Update Overlap Method to Always Update the Tigger Volume detected the item, the casting worked and the door would open.

# Answer
> 0 votes
You are correct in that the trigger volume can detect any actor that passes through it and calls OnBeginOverlap and when it leaves, calls OnEndOverlap.

What you're not doing in your blueprint above is telling the trigger what is overlapping.

If you need a specific actor, pull off the Other Actor node and cast to your door opening object. From the cast node, use the Execution pin for success and put it into the Enter pin of the gate. This should cause your animation to play.

---
Tags: unreal-4, blueprints, puzzle, gameplay3d-engine
---


# Question
Title: Getting angle from current position and next position
I am using pathfinding to move a train along rails, but I need the train to rotate. I have the next intended position and the current position at my disposal, how would I go about this? Pseudocode will do as an answer since I am using a specialized programming language for the engine that I use.

# Answer
This is a prototype lookat function , in which an object forward will point towards a defined position. In your case the Up vector can be set to fixed value since the object does not need to pitch up or down. Hope this helps

```
  //your object
     glm::vec3 obPos = glm::vec3(sceneEntity->getPostion().x(),sceneEntity->getPostion().y(),sceneEntity->getPostion().z());

    //Next positon
    glm::vec3 tarPo = glm::vec3(ptl.x(),ptl.y(),ptl.z());

            glm::vec3 delta = tarPo - obPos;//targetPosition-objectPosition
            glm::vec3 up;
            glm::vec3 dir(glm::normalize(delta));

            if(abs(dir.x) < 0.00001 && abs(dir.z) < 0.00001){
                if(dir.y > 0)
                    up = glm::vec3(0.0, 0.0, -1.0); //if direction points in +y
                else
                    up = glm::vec3(0.0, 0.0, 1.0); //if direction points in -y
            } else {
                up = glm::vec3(0.0, 1.0, 0.0); //y-axis is the general up
            }
            up = glm::normalize(up);
            glm::vec3 right = glm::normalize(glm::cross(up,dir));
            //up = glm::normalize(glm::cross(dir, right));

            rotationMatrix *= glm::mat4(right.x, right.y, right.z, 0.0f,
                                        up.x, up.y, up.z, 0.0f,
                                        dir.x, dir.y, dir.z, 0.0f,
                                        obPos.x, obPos.y, obPos.z, 1.0f);

```
> 0 votes

---
Tags: 2d, mathematics
---


title: Potion effect never wears out

text:
# Question
Title: Potion effect never wears out
I am writing a mod for Minecraft (in Java, duh) and want to apply a random potion effect like this:

```
    private static Effect[] poss_effects = new Effect[]{
        Effects.SPEED,
        Effects.SLOWNESS,
        Effects.HASTE,
        Effects.MINING_FATIGUE,
        Effects.STRENGTH,
        Effects.INSTANT_HEALTH,
        Effects.INSTANT_DAMAGE,
        Effects.JUMP_BOOST,
        Effects.NAUSEA,
        Effects.REGENERATION,
        Effects.RESISTANCE,
        Effects.FIRE_RESISTANCE,
        Effects.WATER_BREATHING,
        Effects.INVISIBILITY,
        Effects.BLINDNESS,
        Effects.NIGHT_VISION,
        Effects.HUNGER,
        Effects.WEAKNESS,
        Effects.POISON,
        Effects.WITHER,
        Effects.HEALTH_BOOST,
        Effects.ABSORPTION,
        Effects.SATURATION,
        Effects.GLOWING,
        Effects.LEVITATION,
        Effects.LUCK,
        Effects.UNLUCK,
        Effects.SLOW_FALLING,
        Effects.CONDUIT_POWER,
        Effects.DOLPHINS_GRACE,
        Effects.BAD_OMEN,
        Effects.HERO_OF_THE_VILLAGE
    };

    private long prev_milli = System.currentTimeMillis();

    @Override
    public ActionResult<ItemStack> onItemRightClick(World worldIn, PlayerEntity playerIn, Hand handIn) {
        if (System.currentTimeMillis() - this.prev_milli >= 60000) {
            Effect to_apply = poss_effects[(int) (Math.random() * poss_effects.length)];
            int duration = (int) (Math.random() * 15 * 20);
            int amplifier = (int) (Math.random() * 2);
            playerIn.addPotionEffect(new EffectInstance(to_apply, duration, amplifier));
            this.prev_milli = System.currentTimeMillis();
        }
        return super.onItemRightClick(worldIn, playerIn, handIn);
    }

```

However, when the timer ticks down to zero on the potion effect, the effect stays there with the timer at `0:00`. The *first* time I right-click it, I get two potion effects: one that works properly and only lasts for the given amount of time and one that has the problem described previously. All subsequent right-clicks produce the latter.

When I do this:

```
    @Override
    public boolean hitEntity(ItemStack stack, LivingEntity target, LivingEntity attacker) {
        target.addPotionEffect(new EffectInstance(Effects.WITHER, 60, 2));
        target.setHeadRotation((float) (Math.random() * 360), (int) (Math.random() * 180 - 90));

        return super.hitEntity(stack, target, attacker);
    }

```

the effect applies normally and runs out normally every time I hit an entity.

What's wrong?

# Answer
> 2 votes
*I haven't actually implemented a Minecraft Mod. This answer is a bit of speculation, based on some old tutorials.*

Your method `onItemRightClick` will be called twice. Once for the client, and once for the server. *And, this remains true in single player on modern Minecraft, given that it uses an internal server.*

On the other hand, `hitEntity` would run only on the server.

In `onItemRightClick`, you need to check `world.isRemote`. More precisely, when `world.isRemote` is true, you are in the client (then you can play sound effects, and stuff), while the logic (applying a potion effect in this case) should run on the server (that is when `world.isRemote` is false).

As it stand, you get a real effect applied on the server, and a fake one applied on the client.

It appears that the fake effect keeps being applied while the real one isn't. It makes sense that it does not apply the real effect again, given the time out. And it also makes sense that it does not sync `prev_milli` between server and client. However that does not explain why it does not timeout on the client. On that part, I have no idea... But a suggestion: use `addChatMessage` (I think that is the method, should be on the player object) to show the value of `prev_milli` on the chat and see what you get. Show `world.isRemote` while you are at it. That should help debugging.

---

*Unless I'm all wrong about this. I also want to mention that I have seen many tutorials not call `super.onItemRightClick`, I don't know what difference it makes. To guess over my guess, removing it prevents `onItemRightClick` from running on the client.*

---
Tags: java, minecraft-modding, modding
---


# Question
Title: Understanding Screen Position Node in Unity Shader Graph
I'm struggling to understand what exactly the Screen Position node outputs in Unity's Shader Graph.

I'm using the screen position with scene depth to calculate the distance between two objects.

Every tutorial I saw (like Brackey's forcefield one) is using the **alpha channel** of the Screen Position output:

I read that the Screen Position node outputs the mesh vertex screen positions.

* Does it means the 2D position on the screen projection?
* Or the vertex 3D position from the eye space?
* And more importantly, what is exactly the apha channel of this output? (I have the feeling this is related to the "clip space W component" in the documentation)

# Answer
> 4 votes
It sounds like when the Screen Position mode is **in the "Raw" mode** as used in the tutorial you linked, it's giving you the same result as you'd get from this shader...

```
struct v2f {
    float4 vertex : SV_POSITION;
    float4 screenPosition : TEXCOORD0;
}

v2f vert (appdata v) {
    v2f o;
    // This is effectively a multiplication by the Model-View-Projection matrix,
    // taking the vertex from object space to clip space (before the perspective divide)
    o.vertex = UnityObjectToClipPos(v.vertex);

    // This copies the information from the "special" vertex position semantic that in
    // older shader models we can't read directly in the fragment shader. Copying it out
    // lets us interpolate it and read it just like any other texture coordinate.
    o.screenPosition = o.vertex;
    return o;
}

fixed4 frag (v2f i) : SV_Target {
    // Here we get the per-pixel value, after it's been
    // interpolated between the three vertices in the triangle.
    float4 shift = i.screenPosition;

    // Ordinarily, 0,0 would be the center of the screen, but Unity calls
    // that mode "Center" not "Raw". In Raw mode, the center of the screen is 0.5
    shift.xy += 0.5f;
    return shift;
}

```

In this `screenPosition` value, the 4th component of the vector, "**w**" (or "Alpha / a" when you think of the vector as an RGBA colour), is the easiest to understand: **it's the world-space depth** of the pixel being drawn, measured from the camera, along its viewing axis. (Also called **eye-space depth**)

The x, y, and z components have been mangled by the projection in a way that makes them a bit more complicated to explain, so I'll attack them separately:

If we do "the perspective divide" on **x and y**, dividing them by the depth w, this brings them into normalized device coordinates, telling us **where the pixel sits within our rendering viewport**. x/w = -1 is the left edge, x/w = 0 is the center, and x/w = 1 is the right edge. Likewise for y/w along the vertical. The further away a point is in depth, the more it gets crunched-in by this perspective divide, creating the effect where objects appear smaller as they move further away.

The values before the division are related to the eye-space position of the point, scaled according to the horizontal and vertical field of view, and occasionally shifted if we're using an oblique frustum. Suffice it to say, they're "whatever we need them to be so that the perspective divide puts them into the right place on the screen" - it's usually not very meaningful to operate on these values before the division.

Note that in the Unity Shader graph node these x and y values have been shifted to keep (0.5, 0.5) at the center of the screen, presumably so that if you're using this to map a texture in screen space, it stays centered by default.

**The z component** has a different mangling applied, to handle **clipping against the near and far planes**, at z = -1 and z = 1 respectively. Values between these extremes are non-linearly distributed, and end up getting mapped to the **values we use for depth-testing** the fragment and ultimately **writing into the depth buffer**.

This non-linear z is useful for depth buffering, but not very intuitive for our purposes, which is why Unity includes macros and shader nodes that automatically decode it back to linear, world-space/eye-space depth for our convenience.

---

This node also has other modes:

* **Default:** post perspective divide, and scaled/shifted so that x, y = (0, 0) is the bottom-left of the screen, (1, 1) is the top-right
* **Center:** post-perspective divide, with no scale/shift, so x, y = (0, 0) is the center of the screen (-1, -1) is the bottom-left, and (1, 1) is the top-right
* **Tiled:** like Center, but with the negative coordinates wrapped, so the values go from (0, 0) to (1, 1) over each quadrant of the screen.

# Answer
> 0 votes
I might not have completely gotten your question , so ill give you what i would be contemplating.

Everything starts of in screen space , meaning everything is 2D to begin with , your primitives are rasterised and the depth(normalized) is calculated implicitly based on the z of the primitive coordinates .

When you apply transformation matrices(MVP) onto your primitive , stuff like perspective divide ,view and model-space transformations happen on the initial primitives to give the end transformed result(which is the generic 3D object).

I don't know from a Unity stand point but it might be that an inverse of Projection matrix is multiplied to the MVP(witch means you remove the P from MVP) ,to give you the vertex coordinates with no perspective.

Sorry English is not that great.

---
Tags: unity, shaders, unity-shader-graph
---


# Question
Title: Flipped vertical button element on Canvas not reacting
I have a small refresh arrow circle that I wanted to use for an indicator in which direction the tile gets rotated on click. After I rotated it by 180 under the rect Transform rotation Y to spin the opposite direction, it does not react anymore for OnClick events. Probably since we are technically clicking on the backside of the image. The non rotated version works, changing the rotation from 180 to 0 works as well.

Is there any way to get a flipped image working without duplicating the source image and flip it before assigning it to the button?

The scene is a simple screen space camera, one canvas with 2 buttons (having the same image source), one button has 180 under Y Rotation and the default EventSystem.

# Answer
The canvas event system does not detect clicks on the backside of UI elements. So rotating by 180° on the Y-axis makes the button unresponsive.

But you can achieve the same effect by setting the Y-Scale of the RectTransform of the button to -1 (or -whatever its regular scaling is). The click detection will then still work as normal.

The drawback is that if you want to animate the flip and want it to look like a rotation and not like shrinking and growing, you might need to put a bit of effort into tweaking the animation curve to look more like a sine curve.
> 1 votes

# Answer
If I understand correctly you want to flip an image like this

Into one like this:

And you want to flip it, not to create an actual animation.

If my understanding is correct, all you have to do is to set the image scale multiplying X by -1. In my example, the first image has a scale of 1,1,1, while the second image has the scale set at -1,1,1. In case you want to flip in Y, then you go from scale 1,1,1 to scale 1,-1,1. Quite simple.

EDIT: I forgot to mention that this applies to the Button Rect Transform as well as any other image.
> 1 votes

---
Tags: unity
---


# Question
Title: Gyroscope scrolling using Input.gyro.eulerAngles.x reverses direction at 90°
I am working on a project where I want to create a 'scrolling' effect using the gyroscope on mobile devices. The basic idea is that I have an `Image` object in my scene and I want to be able to show different parts of it based on device rotation with the gyroscope. For example, you see the wall of a room, and by rotating your phone you can turn to see different parts of the room (but in 2D).

For now I managed to move my `Image` using `Input.gyro.attitude.eulerAngles.x;` from `Gyroscope` like this:

```
protected void Update()
{
    var x = transform.localPosition.x;
    var gyroX = Input.gyro.attitude.eulerAngles.x;
    x += -gyroX * Speed;

    BackgroundImage.transform.localPosition =
        new Vector3(x, transform.localPosition.y, transform.localPosition.z);

}

```

The problem I am seeing is that when `Input.gyro.attitude.eulerAngles.x` reaches `86.0` it starts decreasing. Even if you are rotating your phone to the right, it changes its direction.

I checked the documentation, examples over internet, but didn't find anything about that.

The only rotation axis which I am interested in is X, because the app will be in portrait mode and I want to be able to move the image only horizontally (by x).

So the phone's rotation has to be similar to what a user would do while taking a panoramic photo:

If you have any idea what can cause that issue and how can I fix it, or any other suggestions for how can I achieve the thing I want to create, please share your knowledge.

# Answer
> 1 votes
`rotationRateUnbiased` will give you the change in rotation. Try summing the `rotationRateUnbiased.x` value by multiplying it by `delta.time` and speed. I had the same problem and solved like this:

```
float angle;
float speed = 100;

void Start()
{
    Input.gyro.enabled = true;
    angle = 0;
}

void Update()
{
    if (Input.gyro.enabled)
    {
        float gyroXin = Input.gyro.rotationRateUnbiased.y * Time.deltaTime * speed;
        angle -= gyroXin;

        // And do whatever you like with angle
    }
}

```

# Answer
> 0 votes
To pan your image based on the relative rotation of your phone, you'll want to use `Gyroscope.rotationRateUnbiased` instead of `Gyroscope.attitude`. The latter describes the current orientation of the phone, which means it will wrap around when you rotate your phone a full 360 degrees, and your magnitude depends on how far you are from Unity's global zero, not how fast you're turning your phone.

In contrast, `rotationRateUnbiased` gives the instantaneous speed of rotation about each axis, which sounds more like what you're looking for. Remember to scale the speed by `deltaTime` so your movement doesn't jump/stutter or show inconsistencies under framerate changes.

```
protected void Update()
{
    var x = transform.localPosition.x;

    // I'm assuming the x axis of the phone is the one crossing the phone's
    // long axis - the Unity docs are a bit coy about important details like this....
    var gyro = Input.gyro.rotationRateUnbiased.x * Time.deltaTime;

    x -= gyro * Speed;
    // You may want to clamp or wrap x here in your image space.

    BackgroundImage.transform.localPosition =
        new Vector3(x, transform.localPosition.y, transform.localPosition.z);
}

```

---
Tags: unity, mobile, gyroscope
---


title: Large world pathfinding on server

text:
# Question
Title: Large world pathfinding on server
Just want to note first I know there are lots of topics on this. I've bought books, read tons of posts here, but still stuck on a few topics from a conceptual level. One of them is concerning how larger online games manage path finding server side when there are lots of actors.

My problem isn't necessarily how to program the path finding when it comes to move NPC from position1 to position2 that's pretty straight forward but if the goal is to have as little to no physics done as possible on the server side I'm stuck on: How do larger games manage pathfinding for lets say NPC's chasing players?

We know the following:

* Mobs will only chase x distance
* While not chasing players the mobs normally have a predefined path to follow so the server doesn't have to calculate that nonstop.
* If no players are around the calculations can stop and free that resource up.

Most of my server side code is easily managed without the need of running the client exe. Is it normal to lets say have a cluster of servers that does nothing but manage pathfinding for certain areas of the world? So for example the server exe would communicate to the client exe(sitting on a server) I need to move npc from current position (x,y,z) to the current player position of (x,y,z) calculate my path. The client does this, respond to the server.exe request, this is then shared with the player clients?

I guess the same could be said for players themselves. If we need to validate their movements are accurate we need to know that they were able to move to x/y/z coordinates by checking it against a client somehow? The only other option I can think of is that somehow these companies are exporting their navmesh in some format that the server exe can look at and run calculations against.

I hope one of y'all out there smarter then me will be able to see where I'm getting hung up on.

# Answer
> 1 votes
Without going much into specifics, as it differs game by game and company by company...

Pathfinding pretty much has to be done on an authoritative server unless you want serious hacking to be the norm on your clients. Coarse-grained pathfinding can be smoothed in terms of the final path displayed on clients. These coarser calculation results imply less work done on the server (enabling more clients to be calculated for, per computational unit).

Yes, the server needs access to terrain geometry, and indeed to the entire data model in most full-fledged MMOs. How could it be otherwise? Remember that there is an overlap between *logical* geometry and *renderable* geometry, in many if not most games.

Frequent validation (at least once in every five seconds, if not much more frequent) of positions is normal, with the server authoritatively redefining the client position if it is out of kilter with what the server expects.

Given the necessity of server-side pathfinding for security reasons, you need native server code that runs *very* fast indeed (bare metal), and this means the usual trade-offs seen in optimisation.

# Answer
> 0 votes
A way this is often handled is through microtasking. Imagine you have the geometry for a truly vast world. This world can be split into a grid of regions (to any level of detail wanted). The size of these regions will result in a storage/computation balance.

You can pre-calculate Which of these regions are 'connected'. That is, from which region one can directly move to another. Or, more like, which regions need to be crossed to get from A to B.

When it comes to then calculating long paths, we can query the region-to-region path, and only have to calculate the paths between these regions and solder those together. This cuts down on actual computation massively, but in a large complex world it does result in a storage requirement of up to N^3.

---
Tags: path-finding, mmo
---


title: OpenGL only rendering 4 tris of cube?

text:
# Question
Title: OpenGL only rendering 4 tris of cube?
I'm on Win10, OpenGL 4.5

I wrote some code that takes mesh data from an OBJ file and puts it into a vertex buffer. I used this code to import a cube OBJ and render it in OpenGL. For some reason, although the importer output shows that all tris (broken down into vert components) were put into the buffer, the actual rendered cube only has 4 tris showing. What could be happening here?

Here is my relevant code:

```
//Before the main loop
//Import mesh data
OBJ& cube = ImportOBJ("meshes/cube.obj");

//Bind mesh data
GLuint vertexArrID;
glGenVertexArrays(1, &vertexArrID);
glBindVertexArray(vertexArrID);

GLuint vertexBufferID;
glGenBuffers(1, &vertexBufferID);
glBindBuffer(GL_ARRAY_BUFFER, vertexBufferID);
glBufferData(GL_ARRAY_BUFFER, cube.vertBufferSize, cube.vertBuffer, GL_STATIC_DRAW);

//Inside the main loop
//Draw cube
glDrawArrays(GL_TRIANGLES, 0, cube.vertCount);
glDisableVertexAttribArray(0);

```

Here is what it looks like:

and here is the importer output broken down like `[face index][vert index] (x, y, z)`:

```
[0][0] (-0.5, 0.5, -0.5)
[0][1] (0.5, 0.5, 0.5)
[0][2] (0.5, 0.5, -0.5)

[1][3] (0.5, 0.5, 0.5)
[1][4] (-0.5, -0.5, 0.5)
[1][5] (0.5, -0.5, 0.5)

[2][6] (-0.5, 0.5, 0.5)
[2][7] (-0.5, -0.5, -0.5)
[2][8] (-0.5, -0.5, 0.5)

[3][9] (0.5, -0.5, -0.5)
[3][10] (-0.5, -0.5, 0.5)
[3][11] (-0.5, -0.5, -0.5)

[4][12] (0.5, 0.5, -0.5)
[4][13] (0.5, -0.5, 0.5)
[4][14] (0.5, -0.5, -0.5)

[5][15] (-0.5, 0.5, -0.5)
[5][16] (0.5, -0.5, -0.5)
[5][17] (-0.5, -0.5, -0.5)

[6][18] (-0.5, 0.5, -0.5)
[6][19] (-0.5, 0.5, 0.5)
[6][20] (0.5, 0.5, 0.5)

[7][21] (0.5, 0.5, 0.5)
[7][22] (-0.5, 0.5, 0.5)
[7][23] (-0.5, -0.5, 0.5)

[8][24] (-0.5, 0.5, 0.5)
[8][25] (-0.5, 0.5, -0.5)
[8][26] (-0.5, -0.5, -0.5)

[9][27] (0.5, -0.5, -0.5)
[9][28] (0.5, -0.5, 0.5)
[9][29] (-0.5, -0.5, 0.5)

[10][30] (0.5, 0.5, -0.5)
[10][31] (0.5, 0.5, 0.5)
[10][32] (0.5, -0.5, 0.5)

[11][33] (-0.5, 0.5, -0.5)
[11][34] (0.5, 0.5, -0.5)
[11][35] (0.5, -0.5, -0.5)

```

# Answer
> 1 votes
This issue looks to me like the array that you are feeding for the buffer binding process might be the issuse.

```
    glBufferData(GL_ARRAY_BUFFER, cube.vertBufferSize, cube.vertBuffer, GL_STATIC_DRAW);
--------------This*----------------------^^

```

this\* parameter requires a stride , `glBufferData(GL_ARRAY_BUFFER, vertexArray.size() * sizeof(float), vertexArray.data(), GL_STATIC_DRAW)`

Try looking into this.

Also try keeping the array as a serialised byte array meaning \[0\]x , \[1\]y, \[2\]z ---\> \[3\]x,\[4\]y,\[5\]z-----\>n and so on, for the code you have.

dosent have to be this way and can be any container structure you want but you will have to set the stride so that it knows what and how much it needs to move to get the info for one vertex that will be passes into the shader context.

you can also try this

```
void _Renderer::setModelDataInBuffers(std::vector<float> vertexArray)
{
    glGenVertexArrays(1, &VAO);
    glGenBuffers(1, &VBO);
    // bind the Vertex Array Object first, then bind and set vertex buffer(s), and then configure vertex attributes(s).
    glBindVertexArray(VAO);

    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    glBufferData(GL_ARRAY_BUFFER, vertexArray.size() * sizeof(float), vertexArray.data(), GL_STATIC_DRAW);

    glEnableVertexAttribArray(0);
    //(nth attribute index, no of elements per sample, type,bool, stride for thewhole data set, location in stride)
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);

    // note that this is allowed, the call to glVertexAttribPointer registered VBO as the vertex attribute's bound vertex buffer object so afterwards we can safely unbind
    glBindBuffer(GL_ARRAY_BUFFER, 0);

    glBindVertexArray(0);
}

```

# Answer
> 0 votes
I believe before your draw call "glDrawArrays" you need to enable the VBO attribute stored in your VAO. Try putting glEnableVertexAttribArray(0 or 1) whatever attribute index you are storing your VBO in, and be sure to disable after rendering with glDisableVertexAttribArray(0 or 1)

---
Tags: opengl, c++, rendering, 3d-meshes
---


# Question
Title: OpenGL convert mouse position to world coordinates without gluUnproject in Python?
EDIT: I changed the bottom left to -1,-1 and the top right to 1,1, and while I can draw objects within this range, I cannot map the mouse x,y to the world space.

I have been trying to learn OpenGL and my current goal is to move a circle on mouse drag. I have created the circle, but I cannot seem to be able to map my mouse coordinates to the world coordinates using glOrtho. I also set the initial window position to 100, 100, I don't know if that is relevant to the issue though.

For reference this is my init code:

```
def init():
    # select clearing color
    glClearColor(0.0, 0.0, 0.0, 0.0)

    # initialize viewing values
    glMatrixMode(GL_PROJECTION)
    glLoadIdentity()
    glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0)

```

I know that the glOrtho takes the left, right, bottom, top, near and far values, but when I try to convert to world space coordinates from mouse position(since I only need the x and y so I can calculate distance from the circle's origin) I end up with coordinates in the range 0.0 - 1.25, which makes no sense to me at all, because it should be 0.0 - 1.0.

This is my glutMotionFunc:

```
def click(x, y):
    global current_circle

    nx = float(x * SCREEN_SIZE / SCREEN_SIZE)
    ny = float(y * SCREEN_SIZE / SCREEN_SIZE)

    print("Mouse click", nx, ny)

    for circle in circles:
        print("Circle center", circle.cx, circle.cy)
        if (np.square(nx - circle.cx) + np.square(ny - circle.cy)) <= np.square(circle.r * (SCREEN_SIZE / 10)):
            current_circle = circle
            current_circle.set_position(nx, ny)

            glutPostRedisplay()

```

Also, why is my window 300x300 when it should be 250x250? I don't set the window size anywhere but the above init function.

# Answer
> 1 votes
I figured out my issues:

1. First off, I need to set the window size before I create it.
2. I was not using normalized device coordinates.
3. I found the simple equation to convert my mouse position to device coordinates: new\_x = glut\_mouse\_x / (SCREEN\_SIZE/2) - 1.0 new\_y = -1 * (glut\_mouse\_y / (SCREEN\_SIZE/2) - 1.0)

---
Tags: opengl, python, mouse, glut
---


# Question
Title: Text Mesh Pro edges are not smooth when viewed by orthographic camera
I have a minimap camera (orthographic camera) which is rendering text mesh pro but the problem is the text edges are not smooth. Here is the screenshot:

\[

The camera orthographic rendering on render texture.

Edit:

Some basic Orthogrphic camera setting are:

```
transform.localPosition = new Vector3(-26853f, 1165f, 24669f);
            transform.rotation = Quaternion.Euler(90f, -175.45f, 0f);
            miniMapCamera.orthographicSize = 110000;

```

Here is my text mesh pro, inspector: \[

Text mesh pro font size is 80.

# Answer
> 1 votes
I believe that there is a problem with your set up because you scale up the text, and that should not really be necessary. Here my result and its set up made using your camera settings:

As you can see the text is quite big, so I need to scale it down, not up, and not necessarily because I can make a ton of other adjustments before to have to go touch the scale.

Also, judging from your settings, here you are actually rendering a terrain. That is not really a good idea because it'd have a strong performance impact. Usually, for real-time map generation, you take a picture of the terrain in the 1024x1024 size or in any other acceptable texture size (not too high and without any MipMap) and you use that for your MiniMap, computing the scaled positions of the objects and player to show their representation. Even better, you create a stylised map in Photoshop in the correct scale to your terrain and use that.

**EDIT:** In case of the 3D Text Pro (no Canvas) then avoid scaling that much by delegating the scaling to Text Mesh Pro font engine. To do that create a copy of the original SDF (or generate a new one) then set the scaling in the SDF inspector as shown in the following image:

---
Tags: unity, antialiasing, text-mesh-pro, minimap
---


# Question
Title: Add buttons into List when mouse is HoldDown?
I have three buttons in my menu. What I need to do is when I click on first button it becomes the first element in my list. Now, when I keep mouse button down and move it to the second button it becomes the second second element in my list. The same with the third button.

```
public List<GameObject> UI_Button_List = new List<GameObject>(3);

void Update()
{

    if (Input.GetMouseButtonDown(0))
    {

    if (UI_Button_List[0] == null)
    {
        UI_Button_List[0] = EventSystem.current.currentSelectedGameObject.gameObject;
    }

    if (UI_Button_List[0] != null && UI_Button_List[1] == null)
    {
        UI_Button_List[1] = EventSystem.current.currentSelectedGameObject.gameObject;
    }

    if (UI_Button_List[0] != null && UI_Button_List[1] != null && UI_Button_List[2] == null)
    {
        UI_Button_List[2] = EventSystem.current.currentSelectedGameObject.gameObject;
    }

    } // end if

}

```

# Answer
> 0 votes
It seems to me you can simplify what (I think) you are trying to achieve

```
public List<GameObject> UI_Button_List = new List<GameObject>(3);

void Update()
{

    if (Input.GetMouseButtonDown(0))
    {
        GameObject targetObject = EventSystem.current.currentSelectedGameObject.gameObject;
        if (targetObject != null && !UI_Button_List.Contains(targetObject)
        {
            UI_Button_List.Add(targetObject);
        }

    } // end if
}

```

Every frame if the mouse button is pressed down, we check the target object isn't null and that it isn't already added to the list, if it meets both conditions we add it to the list.

*.Add* will automatically increment the list index when successfully adding an element, so there's no need to check if there's anything already there, We already did the checks to make sure its a valid object and not already in the list with *!UI\_Button\_List.Contains(targetObject)*

If holding the mouse button in and 'dragging' down the UI\_Buttons you want to click is what you are trying to achieve(which now I read it properly, it probably is) you can change the Input.GetMouseButtonDown(0) to Input.GetMouseButton(0) which will fire every frame the button is held.

```
public List<GameObject> UI_Button_List = new List<GameObject>(3);

GameObject lastObject = null;
void Update()
{
    //Each frame the mouse is down
    if (Input.GetMouseButton(0))
    {
        //Get object for current event
        GameObject targetObject = EventSystem.current.currentSelectedGameObject.gameObject;

        if (targetObject == lastObject)
        {
            //return this frame if this object has either been added or rejected
            return;
        }

        if (targetObject != null && !UI_Button_List.Contains(targetObject))
        {
            UI_Button_List.Add(targetObject);
        }
        lastObject = targetObject;

    } // end if

}

```

All I have added outside of the mouse event change is a check to make sure we're not dealing with an object same as last frame, no need to, but you can remove it without any trouble.

Edit: It is quite difficult without knowing how everything fits together how you want a particular piece of code to function, and I am not on my own PC to fire up unity but I think the below (untested) should set you on the right path, you can also use the https://docs.unity3d.com/2018.1/Documentation/ScriptReference/EventSystems.IPointerEnterHandler.html UI Events Interface to make your UI Objects react to mouse events.

```
public List<GameObject> UI_Button_List = new List<GameObject>();

GameObject targetObject = null;
GameObject lastObject = null;

void Update()
{
    //Each frame the mouse is down
    if (Input.GetMouseButton(0))
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        //Fire a ray from the Camera to the mouse position, using this function that converts from Screen Space (0,1) to World Space (x,y,z)
        if (Physics.Raycast(ray, out RaycastHit hit, Mathf.Infinity, LayerMask.GetMask("UI")))
        {
            //If we are here, we hit a valid object
            targetObject = hit.collider.gameObject;
            //same check as before, make sure it isnt null now (for whatever reason not likely but still) and that our list doesnt already contain it
            if (targetObject != null && !UI_Button_List.Contains(targetObject))
            {
                UI_Button_List.Add(targetObject);
            }
        }

        lastObject = targetObject;

    } // end if
}

```

Make sure your UI elements are on the UI Layer, or change the LayerMask.GetMask("UI") to whatever layer your UI is on.

Hopefully this is closer to what you want.

---
Tags: unity, gui
---


# Question
Title: How can I change the Value in HSV color via scripting?
I have a glowing object (point light attached to a ball with a default shader with the emission property) in my scene and I've added a script to make the point light flicker.

The script randomly changes the intensity of the point light to make it flicker.

Since I'm using an emission shader, the ball can also be seen without light.

I'm using HDR values in my emission shader and by changing the Value in the HSV Color picker I can change the color of the ball to black.

I need help in linking the value of the HSV color on the emission shader of the ball to the intensity of the point light.

Any help would be useful! Thanks!

# Answer
> 2 votes
Try

```
material.SetColor ("_Color", myColor)

```

or

```
material.SetColor ("_TintColor", myColor);

```

That changes the values directly on the shader material. I hope that helps!

# Answer
> 1 votes
Use:

```
Color newColor = Color.HSVToRGB(h, s, v, true); // "true" indicates to allow HDR values

material.Setcolor("_EmissionColor", newColor);

```

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


# Question
Title: what C++ library is this project using to render?
I was looking at this library https://github.com/blend2d/blend2d .It does not use gl , glut of glfw.How is it rendering?

# Answer
> 1 votes
From the project's website:

> It was written from scratch with the goal to achieve the best possible software-based acceleration of 2D rendering.

The answer is therefore: **no library** \- it uses it's own custom software renderer.

# Answer
> -2 votes
One rule of thumb , if it is cross compilable (meaning can be deployed multiple different devices) , over linux,windows etc then its opengl or vulkan . Glut ,glfw are wrappers that handle the Windowing context and provide some added tools over the core OpenGl Api spec.

The windowing is done by tools like Direct3D in windows and X11 in Linux that the os has provided and uses for its own window context generation.

The GPU vendor extends out functionality of there GPU by coupling it with the modern Rendering Apis that it would support. Getting access to these extensions and functionality directly is a tall order with a capital T and i highly doubt they would have done that.

Having said that you can develop a rasterizer on the CPU as well, but it would be far from performant. The idea is to have a set of nxn(where n is the resolution) 2D grid of pixels and populate it with bit information at least 30-60 times per sec for it to be considered real-time.

Hopefully with this info you can deduce something out.

---
Tags: rendering
---


# Question
Title: Lagging problem with chunk creation in Godot
We are developing a 2D game in Godot and we are stuck while trying to divide the map in chunks. Namely, the scene is a forest, where trees spawn positions were generated by noise: since the trees are too many to be loaded altogether, we created a Chunk node, which only instances trees contained in it, and gets instanced and deinstanced according to player's position. Though, this does not seem to be enough: each time a new chunk is to be instanced, we get a lag spike. How can we improve this? This is the script attached to Chunk:

```
extends Node2D

var noise

func _ready():
    randomize()
    self.name=str(global_position)
    noise=get_node("/root/global").noise
    LoadTrees()

func LoadTrees():
    var x=-38
    while x<39:
        var y=-14
        while y<15:
            if noise.get_noise_2d(global_position.x+float(10*x),global_position.y+float(12*y))>0.07:
                InstanceTree(Vector2(10*x+rng.randi_range(-3,3),12*y+rng.randi_range(-3,3)),self)
            y+=1
        x+=1

func _on_Exit_body_exited(body):
    if body.name=="Player":
        call_deferred("free")

func _on_AreaLeft_body_entered(body):
    if body.name=="Player":
        var NewChunkPos=global_position-2*Vector2(380,0)
        get_parent().InstanceChunk(NewChunkPos)

func _on_AreaRight_body_entered(body):
    if body.name=="Player":
        var NewChunkPos=global_position+2*Vector2(380,0)
        get_parent().InstanceChunk(NewChunkPos)

func _on_AreaDown_body_entered(body):
    if body.name=="Player":
        var NewChunkPos=global_position+2*Vector2(0,170)
        get_parent().InstanceChunk(NewChunkPos)

func _on_AreaUp_body_entered(body):
    if body.name=="Player":
        var NewChunkPos=global_position-2*Vector2(0,170)
        get_parent().InstanceChunk(NewChunkPos)

```

The functions the script calls from its parent's script go as follows:

```
func InstanceTree(pos,Parent):
    var tree=Tree.instance()
    tree.position=pos
    tree.name=str(global_position)+"_tree_"+str(pos)
    Parent.call_deferred("add_child",tree)

func InstanceChunk(NewChunkPos):
    if not self.has_node(str(NewChunkPos)):
        var NewChunk=Chunk.instance()
        NewChunk.global_position=NewChunkPos
        NewChunk.name=str(NewChunkPos)
        call_deferred("add_child",NewChunk)

```

# Answer
I can think of a few options:

1. Since the tree count doesn't change, you could try making a scene with all of the trees already loaded, then just reposition them all when you load the scene.
2. Use the yield capability of GDScript. I've never used it, so I'm not sure if it would meet your needs.
3. Load the scene a bit earlier (before it's fully visible), and add a tree each frame until the scene is full.
4. If it's a single-player game, you can have a fixed number of trees, and just reposition them around the player instead of constantly needing to instantiate them. This allows you to do away with the chunking altogether.
> 2 votes

# Answer
If you are rendering many instances of the same mesh, consider using a `MultiMeshInstance`:

> MultiMeshInstance is a specialized node to instance GeometryInstances based on a MultiMesh resource.
>
> This is useful to optimize the rendering of a high amount of instances of a given mesh (for example trees in a forest or grass strands).
> 0 votes

---
Tags: godot, lag
---


title: How to inflate and deflated an object?

text:
# Question
Title: How to inflate and deflated an object?
I'm trying to find a way to make an object inflated/deflated in Unity, So I can change parameters via script and control a range of 0-100% inflation.

I have seen that there is a way to get this exact effect on Blender (it's in the pressure module), but as far as I understand, there is no option to get the same parameters in Unity and actually make them scriptable.

My whole game is based on this feature and I must find a way to achieve that effect.

Any help would be appreciated!

Thank you in advance, Omer

# Answer
> 1 votes
The best solution for your problem is to use blend-shapes (called Shape Keys in Blender) and export those along in the FBX. With Blender, there are a few known issues exporting blend-shapes, so you have to be prepared to give it a few tries.

Once you have that, just set up in Unity to use blend-shapes and you are ready to go.

---
Tags: unity, 3d-meshes, graphic-effects, soft-body-dynamics
---


# Question
Title: How do multiplayer servers handle receiving, handling, and sending packets?
I want to make a fighter jet simulator game.

The server (authoritative) and client communicate over udp.

The server sends out updates about the gamestate at a fixed rate. Think of plane positions, speeds, rotation, basically anything to do with physics.

On demand, the server sends out packets for spawning bullets and applying damage. So this is not at a fixed tickrate. This is done to sidestep the problem of superbullets and syncing fire rates with tick rates entirely. This class of packets also include chat messages.

How do I go about implementing this? I am using c/c++, programming raw sockets. I am running into the issue where the `recvfrom` function is blocking. I can set it to non-blocking using `fnctl`, yes, but that spams error messages because sometimes there are no packets waiting to be handled (I could handle it but egh, inelegant). Ideally I would like to prevent multithreading, but given that there seems to be no native event-driven or interrupt-driven way of receiving packets it seems I need to do that.

How do other game servers, like quake arena, set up their threads?

My idea:

1. Main thread calculates game state, sends out packets at a fixed rate
2. 1 child thread for listening for new packets (`recvfrom` loop)

* If the incoming packet is a "i am shooting" packet, it performs checks, and broadcasts to every client that a bullet has spawned. It adds the bullet to the world, and the main thread will calculate the continued trajectory in the next or current tickcycle, using the time difference and initial spawn data.
* if the incoming packet is a chat message, perform checks and just broadcast it across clients.
* if the incoming packet is any other kind of packet, put it in a queue for the main thread to handle (the queue is mutexxed)

Is this how I should make the child and main communicate?

# Answer
> 0 votes
First, I would recommend reading this. I think this style is the best combination of efficiency and elegancy.

Everything sounds good except for the fact that you can get client packets in the middle of your state loop, which I think would inevitably create errors and bugs due to concurrent reading/writing on your data. What I propose is having `actions` and `changes`. Store the `actions` in a double-linked list so that you can organize them in the order of their occurrence. The double-linked list is also one of the most performant ways to remove or add `actons` in Θ(1) time. Then in your loop, you iterate over your double-linked list of `actions` and produce `changes`. Now, every iteration you make `changes` and send them to every client.

---
Tags: networking, multiplayer, client-server, multithreading
---


# Question
Title: What do I risk if I name my game the same as another company?
I came up with the best title for my game - a title that is catchy and also indicative of the gameplay, plus there isn't any other game on the market with a similar name. But after a Google search, I found a company in another country using the same name.

To put my situation better in context, imagine a game like Minecraft being in development, only to find out that there's another company called something like Minecraft Studios in a far-off country dealing with digital graphics and art for media (including games).

*Aside from the legal aspect of it* (lawsuits, cease-and-desists, etc.), what disadvantages would there be to have my game named the same as a company dealing in a similar field?

# Answer
The biggest risk you face is a customer confusion issue. If your game has the same identifying name as a company, anybody who tries to search for your game will probably get the company in their search results instead, which lessens the searchability of your game - especially if you are a small indie developer and the game isn't popular yet.

---

That being said, Spooky's House of Jumpscares was forced to rename itself to Spooky's Jump Scare Mansion after a lawsuit from a company called Spooky House Studios. So you could absolutely have a lawsuit brought against you even if it's legally spurious to do so, hence why I recommend talking to a lawyer if you have genuine concerns.
> 4 votes

---
Tags: marketing
---


title: Multiple directx runtimes in game

text:
# Question
Title: Multiple directx runtimes in game
I see by Process Explorer that many of Unreal Engine games load multiple DirectX runtimes. For example game Gears 5 in requirements has DirectX 12 only support, but uses DirectX 9 and 11 runtimes also. Is it correct - this because unreal engine developers don't remove\rewrite some code which uses old DirectX versions features to new and now we have many legacy code inside and games need this runtimes because of legacy?

# Answer
Many existing game engines like UnrealEngine have large amounts of code recycled from earlier projects or revisions, and generally if it works they don't change it. Lots of games have ancient DirectInput-based mouse & keyboard code even though that API has been emulated since Windows XP. Particularly for the in-development builds, they often use stuff like the legacy D3DX11 library instead of modern replacements. Another example: the Source engine supported Direct3D 8 for many years after it wasn't strictly needed so they could support ancient hardware that lacked stable enough drivers for Direct3D 9.

> See The Zombie DirectX SDK, Living without D3DX, and DirectX SDKs of a certain age for a bunch more detail on the story here around the legacy DirectX SDK components.

There's also a fair amount of confusion over what "DirectX Runtime" means. Many games (basically every Steam title) still run the legacy *DirectX End User Runtimes* installer even though it is almost surely not needed, or could be avoided with a few minor tweaks. Microsoft trained developers for decades that they should include the "DirectX redist", so when we changed our approach in ~2004 most people didn't get the message and just kept doing what they always had done. See No So Direct Setup.

For DirectX 12 only games, in theory they should find everything they need already there as part of the OS and find utility code in open source on GitHub. Generally, however, this kind of clean-up work is low on the priority list compared to new features, new platforms, etc.

**WITH ALL THAT SAID**, another thing to keep in mind is that the modern DirectX DLLs on Windows are not isolated side-by-side affairs. Most of earlier versions of Direct3D have been 'lofted' to work on-top of the Direct3D 11 bits, and even a "pure" DirectX 12 application that makes no use of legacy code or versions is still going to have `D3D11.DLL` in the loaded image when running on Windows 10.

*TL;DR: If starting a project "from scratch" that uses Direct3D 11 and/or Direct3D 12, there's no reason to use the legacy DirectX SDK or legacy DXSETUP at all even if you are targeting Windows 7 as your minimum OS.*
> 2 votes

---
Tags: directx, unreal-4
---


# Question
Title: Specular reflections shine at the wrong angle when using a normal map
I'm using Unity with URP and I'm trying to include a normal map in my shader graph.

Here is a basic graph that just display a normal map, with properties to control tiling and smoothness.

When I render the scene, the sun reflection highlights the wrong parts of the surface.

In this example, we can see the shadow direction of the cube, and the light itself. The sun reflection is clearly at the wrong place.

I tried with several normal maps from the web, all maps behave exactly like this one, so I think I'm missing something.

Ah, and strangely, when I rotate the object, the light reflection origin seems to change!

Of course, without the normal map, the light reflects gracefully.

What am I missing?

# Answer
> 0 votes
Okay.
I found it.

The Sample Texture 2D has a *type* property, with options *Default* and *Normal*...

I don't know how I missed it. By selecting *Normal*, the reflection is not dependent anymore of object orientation and behaves... "normaly" (haha). Setting to *Normal* replace the use of the Unpack Normal node (or the hlsl relative function).

However, I'm curious of what upack normal really do.

---
Tags: unity, normal-mapping, unity-shader-graph
---


# Question
Title: What is the advantage of using .json to store dialogues instead of hard coding them in C# scripts?
This is a snapshot of the dialogues written in a .json file stored in the Resource folder, which I use to display dialogues in the game:

```
{
"dialogues":[
    {
        "characterType": 0,
        "name": "Hero",
        "atlasImageName": "Hero_Default",
        "dialogueText": "Time to address the call to adventure"
    }

```

An advantage I can think of using .json is that you can directly edit it in a text file.

Beyond this, is there a reason to prefer JSON over hard coding in C# classes or structs? I feel like managing hundreds of JSON files is equally difficult as managing hundreds of .cs files that are used for storing dialogues, but with .cs files I can rely enums (for character types) and string-constants (for hero names) to minimize typos.

# Answer
> 3 votes
The main advantage is not mixing data with process. Separating them out means it becomes far easier to not cross wires down the road, and work on one without accidentally touching the other.

Having dialogue in json, xml or custom data formats also tends to make it shorter and more human readable.

Finally, it prevents having to recompile your scripts every time you fix a typo.

---
Tags: unity
---


title: Accessing HDRP Volume in script

text:
# Question
Title: Accessing HDRP Volume in script
HDRP uses Volume for post processing. I am trying to access this feature in my C# script. I can however access the Depth Of Field attribute, how do I access the Near Blur and Far Blur values?

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Rendering.HighDefinition;
public class LimitDepthOfField : MonoBehaviour {

    public Volume postProcessVolume;
    DepthOfField dof;

    [Range(0.0f, 20f)]
    public float mySliderFloat = 0.10f;
    // Start is called before the first frame update
    void Start () {

    }

    void ChangeValue() {
            if (postProcessVolume.profile.TryGet<DepthOfField> (out DepthOfField tempB)) {
               dof = tempB;
               dof.farFocusStart = new MinFloatParameter(mySliderFloat, mySliderFloat, true); //Does not work
            }
    }
}

```

# Answer
> 0 votes
The 4 properties you want are

* nearFocusStart
* nearFocusEnd
* farFocusStart
* farFocusEnd

If you are in doubt about names of fields or variables, simply click on the class with ctrl + left mouse to open it. You can search for the name you see in the inspector and find the corresponding variable name.

You should set the parameter by the setter

```
dof.nearFocusStart.SetValue(new MinFloatParameter(mySliderFloat, mySliderFloat, true));

```

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


# Question
Title: How to rotate velocity Vector3 to always point the same direction so that it can be applied to 2d blendtree?
Given two variables, a Vector3 representing body velocity and a Quaternion representing body's local rotation, how could I normalize the velocity vector so that it's always oriented towards the default Vector3.forward direction?

The context of this problem is that I have a 2D blendtree for character movement animations. I wanted to use the `RigidBody.velocity` to control the two blendtree axes. This did not work as I initially expected because, depending on body rotation, the velocity also rotates to that direction and this when I'm moving forwards but my body is rotated 90 degrees to the right, my right (x) velocity would be 10 and my forward (z) velocity would be 0. In that case I would like to, using the current body rotation and velocity values, "normalize" the given velocity vector so that it has 10 in forward (z) velocity and 0 in right (x) velocity any time the entity is moving forward, no matter it's orientation.

I've tried playing with `Vector3.RotateTowards` and `Quaternion.LookRotation` but I haven't gotten the desired results and I don't really know what to look for.

# Answer
> 1 votes
Did you want this?

```
var localVelocity = transform.InverseTransformDirection(worldVelocity);

```

or

```
var localVelocity = Quaternion.Inverse(orientation) * worldVelocity;

```

This gives you a vector in the local coordinate frame of the transform/quaternion, where the z component is the forward velocity, the x component is the sideways velocity, and the y component is the upward velocity.

---
Tags: unity, mathematics, rotation, vector, quaternion
---


# Question
Title: How can I customize/remove the caret from Input Fields in Unity?
## Goal

Change the caret to a non-blinking asterisk.

## Description

I'm using the TextMeshPro variant of the InputField, and my Unity ver. is 2019.3.

## Potential Solutions

### Remove Caret

I could remove the caret and manually add an asterisk at the end — and remove it upon submission.

Problem: I don't know how to do that. Caret width doesn't go below 1, and I've yet to see an option to disable it.

### Change Caret

Self-explanatory. However, it doesn't appear that customizing the caret character is an option.

### Shove The Input Field Off-Scree And Copy Its Value + * To Text On-Screen

I can still use the Input Field (and I need to), but hide it off-screen and put a simple Text field in its place, which will display the Input Field's text + the caret (\*).

This could work, but I'm hoping there's a less hacky solution.

# Answer
## Set Caret Color Alpha = 0

This hews back to Potential Solution #1: Remove Caret.

Once that's done, you need to add a custom caret yourself. Here's my solution, keeping the input field constantly focused, the caret forcibly fixed rightmost, and validating that user input is within a subset of acceptable characters:

```
using System.Linq;
using UnityEngine;
using TMPro;

public class ChatInputTaker : MonoBehaviour
{
    public TMP_InputField inputField;

    private char[] _acceptableCharacters;
    private int _oldLength;

    #region Constants
    private const int LAST_CHAR_INDEX = 126;
    private const int FIRST_CHAR_INDEX = 32;
    private const string CARET = "*";
    #endregion

    private void Awake()
    {
        int inclusiveOffset = 1;
        _acceptableCharacters = new char[LAST_CHAR_INDEX - FIRST_CHAR_INDEX + inclusiveOffset];

        for (int i = 0; i < _acceptableCharacters.Length; i++)
        {
            int charIndex = FIRST_CHAR_INDEX + i;
            char character = (char)charIndex;
            _acceptableCharacters[i] = character;
        }
    }

    private void Start()
    {
        inputField.ActivateInputField();
        inputField.text = CARET;
        PutCaretInPosition();
    }

    private void Update()
    {
        if (Input.anyKey)
        {
            inputField.ActivateInputField();
            PutCaretInPosition();
        }
    }

    public void ValidateChatInput()
    {
        string text = inputField.text;

        if (text.Length == CARET.Length)
            return;

        string caretlessText = text.Substring(0, text.Length - CARET.Length);

        // If only deletion occurred, return.
        if (caretlessText.Length - _oldLength < 0)
        {
            _oldLength = caretlessText.Length;
            return;
        }

        int lastIndex = caretlessText.Length - 1;
        char newChar = caretlessText[lastIndex];

        if (!_acceptableCharacters.Contains(newChar))
            caretlessText = caretlessText.Substring(0, caretlessText.Length - 1);

        _oldLength = caretlessText.Length;
        SetInputFieldText(caretlessText);
    }

    private void PutCaretInPosition()
    {
        inputField.caretPosition = inputField.text.Length - CARET.Length;
    }

    private void SetInputFieldText(string newText)
    {
        inputField.text = newText + CARET;
        PutCaretInPosition();
    }
}

```
> 0 votes

---
Tags: unity, input, text, text-mesh-pro
---


# Question
Title: Half of my tris are textured in streaks and blurs
I have written code to import meshes from OBJs and textures from BMPs. My texture coordinates seem to be getting messed up somehow, or some other issue is occuring, because I am getting these effects with meshes and textures:

I do not know what to call these issues and I do not know what might cause them (I am new to OpenGL) so it is hard for me to figure out how to fix them. Does this look familiar to anyone? If so, what's up and how might I fix it?

Relevant code for importing mesh data:

```
obj.vertBufferSize = sizeof(GLfloat) * vertCount * 3;
obj.uvBufferSize = sizeof(GLfloat) * vertCount * 2;
obj.vertBuffer = vertBuffer;
obj.uvBuffer = uvBuffer;

glGenBuffers(1, &obj.vertBufferID);
glBindBuffer(GL_ARRAY_BUFFER, obj.vertBufferID);
glBufferData(GL_ARRAY_BUFFER, obj.vertBufferSize, &(obj.vertBuffer[0]), GL_STATIC_DRAW);

glGenBuffers(1, &obj.uvBufferID);
glBindBuffer(GL_ARRAY_BUFFER, obj.uvBufferID);
glBufferData(GL_ARRAY_BUFFER, obj.uvBufferSize, &(obj.uvBuffer[0]), GL_STATIC_DRAW);

```

Relevant code for importing texture data:

```
glGenTextures(1, &(bmp.ID));
glBindTexture(GL_TEXTURE_2D, bmp.ID);

glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, bmp.width, bmp.height, 0, GL_BGR, GL_UNSIGNED_BYTE, bmp.array);

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glGenerateMipmap(GL_TEXTURE_2D);

```

Before the main loop (for sending mesh data to shaders):

```
glBindBuffer(GL_ARRAY_BUFFER, mesh.vertBufferID);
glVertexAttribPointer
(
    0,
    3,
    GL_FLOAT,
    GL_FALSE,
    0,
    (void*)0
);

glBindBuffer(GL_ARRAY_BUFFER, mesh.uvBufferID);
glVertexAttribPointer
(
    1,
    2,
    GL_FLOAT,
    GL_FALSE,
    0,
    (void*)0
);

```

Samples from inside the main loop:

```
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);

glBindTexture(GL_TEXTURE_2D, texture.ID);

glDrawArrays(GL_TRIANGLES, 0, mesh.vertCount);

glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);

```

# Answer
> 1 votes
The issue turned out to be in my code for importing UVs. I was skipping indices in the UV buffer due to an arithmetic error.

---
Tags: opengl, c++, textures, 3d-meshes, uv-mapping
---


# Question
Title: Can I mod Among Us mobile so people don't get kicked because of network problems, and how?
I want to make a mod for Among Us which will allow people to stay in game despite short-lived connection problems (as opposed to being kicked after 1 second of network issues).

# Answer
> 1 votes
Connection timeouts are usually handled server-sided, not client-sided. That means that this is a problem which should be fixed by the developers themselves. I have not read their sourcecode (and I can not), but I doubt that this is a particularly difficult code change to make on the server-side (but I could be mistaken - this is very hard to judge from the outside).

However, there could be a workaround which I have seen in different contexts where unreliable clients needed a reliable connection to a server: Develop a proxy server - an intermediate server which lets players connect and then connects to the actual server on their behalf. Program the proxy server that it will keep the connection to the actual server alive when the client is temporarily unreachable. Then deploy that server in a reliable location (like a datacenter) and modify the client to connect to the proxy instead of the actual server.

But as I said, this would be a lot of effort in both development and logistics compared to just letting the developers fix the problem.

You also can not expect such a jury-rigged solution to get much support from the developers. In a competitive multiplayer game, any client modification or anything which tabs into the connection between clients and server could be a potential cheat. I do not know how cheater-infested *Among Us* is already, but if it goes the route of any other suddenly popular game, it will soon be in desperate need of a stop-gap measure against a rampant cheating problem. There will be a myriad of different hacks and cheats ruining the game, and the developers will have to quick and efficient find a way to get rid of them. As an *Among Us* player, you should be familiar with the collateral damage caused by justified paranoia: If you act suspicious, you go out the airlock! The usual solution developers go to in such cases is to slap on a client-sided anti cheat tool which does its best to prevent **any** kind of client modification or connection shenanigans (including benign ones) and automatically bans the players who use them.

So **tl;dr:** Your best strategy as a player to solve this problem for the community is to keep complaining to the developers until they fix it. (and then to thank them *after* they fixed it. We are all humans, you know. It's good for our motivation to hear that we did something right once in a while.)

# Answer
> 1 votes
Short answer: No

Long answer:

Theoretically you could if you knew the networking protocals that are involved and managed to compile a compatible version of the game with your fixes and got everyone in the game to swap a few DLL files.

But realistically this is only something that the developer can do as they are the ones that have the source code and control over the server infrastructure so thereby have the best overview of what the issues are and possible fixes for them. A normal person can't reasonably do this without getting into legal trouble and/or spending a lot of time decompiling the source and trying to recompile it in a way that makes the original game work without getting banned by the servers (if they have that capability).

Without the source code your out of luck, you could try emailing the developers to offer help in figuring out networking issues but I wouldn't get my hopes up that anything will happen as developers don't usually give away their games source to people outside the company/project.

---
Tags: android, multiplayer, client-server, modding, client
---


title: GUIObject.Button: how does it work?

text:
# Question
Title: GUIObject.Button: how does it work?
I was wondering how if(GUILayout.Button(..)) actually works internally.

It is a weird construction, since it returns "true" when the user presses the button, but on the other hand, it also creates a button and then just jumps to the next block of code, so this statement doesn't actually block execution. Then again, it's not of a known asynchronous model. How is this wired internally?

# Answer
Well, it actually does block execution. It is just called every frame (Or more then once actually), and when you press the button in one frame, it will return true that frame, all other frames it will return false.

For instance, this peace of code will completely fill up your console in no-time:

```
private void OnGUI()
{
    Debug.Log($"Frame: {Time.frameCount}, current onGUI type: {Event.current.type}");
}

```

This is because it is executed once with the 'layout' event, and once with the 'repaint' event **every frame**. Then other events like 'mousedown' and 'mouseup' also invoke OnGUI an additional time in the frames that these events occur.

Now how it is actually implemented, you'd have to check unity's reference on github. This is the part of interest, although it gets pretty complicated the deeper you go ;)

But to get an idea of how it somewhat works. Sinse it is called every frame, it can check Input.GetMouseButtonDown every frame just like you can, it can also check if the mouse position is inside the buttons rect (which you either provide in GUI.Button() or let unity create in the layout pass of OnGUI when you use GuiLayout.Button()). It then uses GUIUtility.hotControl to handle whether a button is clicked (both mousedown and mouseup event happened on the same button)

As you also might see in the implementation btw. GUILayout.Button always returns false in the layout and repaint passes, it will only return true in the mouseup pass. Which makes sense, because the code you place inside that if should only be executed once when you press it, not once for every event that frame (layout, repaint, mouseup).

On a sidenote, this (And everything that uses the OnGUI callback) is what Unity calls IMGUI, which is currently not recommended by unity to use for runtime game UI. See the documentation so see in which sutuations IMGUI is recommended.
> 1 votes

---
Tags: unity
---


# Question
Title: Unity3D: Convert all game objects to same size irrespective of it's scale
Suppose I have a reference GameObject, Cube, with scale (1,1,1). There is another GameObject with scale (1,1,1), but the size is 3 times bigger than the Cube. How do I dynamically change the scale of the Game objects to fit the size of the Cube?

# Answer
Untested, and completely from memory, but something kind of along these lines should work. I'll test it tonight when I have access to Unity.

```
//scales all GameObjects in goResizeList to have the same size as the referenceGO.
public void resizeAll(List<GameObject> goResizeList, GameObject referenceGO){
  Vector3 refSize = referenceGo.renderer.bounds.size;

  foreach(GameObject go in goResizeList){
     float resizeX = refSize.x / go.renderer.bounds.size.x;
     float resizeY = refSize.y / go.renderer.bounds.size.y;
     float resizeZ = refSize.z / go.renderer.bounds.size.z;

     resizeX *= go.transform.localScale.x;
     resizeY *= go.transform.localScale.y;
     resizeZ *= go.transform.localScale.z;

     go.transform.localScale = new Vector3(resizeX, resizeY, resizeZ);
  }

}

```
> 3 votes

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