title: Why do Monsters drop things?

text:
# Question
Title: Why do Monsters drop things?
Why do Monsters drop things in so many games?

It creates all sorts of problems, including:

* in-game gold hyper-inflation
* questionable moral implications, if there is a strong incentive toward killing things but no incentive not to

Monster-killing giving XP is equally bad - you rename an ingame currency to XP, the mechanics stay the same. Here you have something like "fighting force inflation," so after some levels you have to have giant giants attacking your small figure or it stops being interesting. This is just hyper-inflation written a different way.

Is it enough reward if a monster stops killing you?

What benefits of monster-killing rewards make up for these problems, or how can we compensate for those problems?

# Answer
**TL;DR**

> is there any good reason to let monsters drop things

It is a cheap mechanism (in terms of development time) to keep your players playing and motivated. Quests and storylines are complicated to integrate/come up with and are no longer of interest to a player once he has completed and replayed them 2-3 times. On the other hand, the need to kill 200 monsters to get a single item that you need 100 times to get your favorite armor design takes not much development time and keeps your players playing for hours and weeks.

---

**Full answer**

> Why do Monsters drop things in so many games? It creates all sorts of problems, one problem being for example ingame gold hyper-inflation.

> Monster killing giving XP is equally bad

You are questioning the whole game design of Diablo and similar games with those two sentences. However, they are quite successful.

I think the answer is related to what kind of game you are making and what your target audience is. Games like Diablo target an audience that gets "addicted" by finding and collecting stuff to develop their characters. If you want to be one of the top players, you need the best gear and a lot of XP. Each killed monster brings you closer to this goal. This is enough motivation for many players to come back and keep on playing. You don't need to develop a complex quest or storyline for that (who played Diablo for the story/quests? - I didn't :) ). Hyperinflation is no problem in these games since your gear gets useless equally fast until you get closer to the level cap. It is actually a feature of the game. The inflation will slow down the higher you climb on the ladder.

The thing here is, that it is an easy mechanism to keep players playing your game. You don't need much development time to add stronger monsters with better loot. Recolor existing ones and adjust some numbers.

On the other hand, developing and integrating smart and interesting quests/storylines is much harder. You must keep track of all possible outcomes and the effects on your game world. --\> What happens to the story and other quests if character XYZ dies during quest ABC? What happens if the player does something that wasn't expected - how to prevent him from being stuck in the story? How do we connect all storylines to make sense from a global point of view?

> I am thinking about giving reward for fulfilling missions but not for each and any monster. Like that it might be equally good to avoid detection. Also, Monsters keep their ingame value longer if player figures can't level up so much.

> Isn't it enough reward if a monster stops killing you?

Just think about how long do you play a purely story-based game? Resident Evil for example. Monsters don't drop anything there (except for some key items), stay equally strong and you have to follow the story to finish the game. I played the last one for about 40 hours (have to check my steam account to get the exact number). Now how long is the average time players spend in those grinding games? I can't give you any numbers here, but I think it is much higher. Also, the chances of players returning after years to replay a game are much higher for those grinders. Don't know how often I restarted playing Diablo 2 or Path of Exile.

The point here is, that you can generate much more play-time with the same development effort by just letting the player grind monsters for loot or XP than with adding quests. Additionally, the whole grinding loot/XP stuff tends to let your players compete for the best gear/character which lets them play even more.

I have to admit, that I enjoy playing story driven games more than games that focus on loot/XP driven character development. However, once I finished the story and explored the game world, I rarely keep on (re-)playing these games. On the other side, I kept on playing some grinders for weeks and started replaying them year over year.

"You know... I just needed that super cool looking level 90 armor but I had to kill 10.000 goblins to get it... took me 2 weeks... was totally worth it!"
> 2 votes

# Answer
Other answers are great, but I want to answer from a game design point of view.

Dropping loot really depends on the game. On an open-world game, where monsters are scattered around, if they don't drop anything, there is no reason for the player to fight them. Worse is if they spend resources fighting them, which they can't recover. At that point it becomes a hassle to fight a monster, but it might make sense on a game that doesn't expect people to fight many monsters (maybe a zombie survival kind?).

On the other hand, if a game has linear maps, with enemies as obstacles, or locked rooms that only open when all enemies are killed (like Devil May Cry series), it might make more sense to think of enemies as "Obstacles", in which case they don't have to drop anything to motivate the player to kill them, they prevent the mission from being completed.

So the question is, what does your game expect users to do? There is no right answer if monsters should drop loot or not, as it depends on the game. If monsters don't drop loot, how does the player get stronger? Do they find treasure? Do they get XP by completing missions? The player needs to feel they get stronger over time, and giving a small amount of XP for each kill, makes them feel they are one step closer to that.
> 4 votes

# Answer
It would be more weird if they do NOT drop something. I mean depending on how you see it. If someone would kill you now, they would probably find

* a mount in form of a summing key (also known as car keys)
* a key to your dwelling
* some coins stored next to funny looking plastic cards
* some rather bad armor
* maybe one or two cosmetic items
* a small bag
* etc

One of the most frustrating thing are quests like collect 10 wolf teeth and you are wondering why after the 150th wolf you still fight those damn vegan wolfs with no teeth that are living on cabbage soup. If your monster is powerful enough to steal the queen without destroying the whole city, you might have other worries. Or if you really want to save the damsel after it got abducted by a dozen goblins (or if there is anything left to save). As for stealing some kind of jewelry, this sounds more like quests that do not necessary involve monsters.

Exchange your exp with proficiency. You don't magically level up, your use with the weapon of your choice just gets better. There is only so much you can gain from stabbing weak looking beings that are 1/2 your size. At one point you are looking for the next challenge, beings that are 3/4 your size (you have to dream big!)

As for why to kill monsters? Depends on your monsters. Do you ask the same about why kill mosquitoes? Or the cockroaches under your bed? What about the 1m rat in your cellar? Or the cute 2m spider that loves to hang out in your attic? Most people don't even get along with their normal neighbors.
> 2 votes

# Answer
The reason why monsters drop things is because that's an easy way to give artifacts to our character and give meaning to existence of monsters.

The player feels motivated to kill a monster as he or she knows they might get something rare or new out of killing.

This aspect keeps the game interesting. If you remove item drops, player might try to avoid the fights as its not giving them any benefit.

Your idea of removing monster-killing rewards will work if you are creating a game that is based on stealth and is not monster fight centric. If you are trying to create a game that is mainly monster slashing, at least give some incentive to the player to keep them motivated.
> 2 votes

---
Tags: game-design, rpg, balance
---


# Question
Title: How to select parent of currently selected object?
When i select an object, i can't find a function to select its parent. Does this basic feature exist ? I want to select the parent of selected object and then step up to find parent of parent so on without using the hierarchy window.

# Answer
> 0 votes
You can use the `parent` property on the `GameObject`’s `transform`.

So given a `GameObject` called `player`, you can do

```
player.transform.parent

```

See https://docs.unity3d.com/ScriptReference/Transform-parent.html for more.

---
Tags: unity
---


# Question
Title: Interactive texture modification (such as swirling) in Unity
I am working on a game where I want to allow users to mix multiple colors (similar to shown in this video): https://youtu.be/11UFYyv8hjs?t=316.

I have the following questions:

1. I am expecting that this is done using shaders. What kind of shader I have to use for such implementation? What will be the logic to create this type of shader?
2. Are there any other ways using which this feature can be implemented?
3. Are there any open source tutorials or examples?

I would appreciate any suggestions and thoughts on this topic. Thank you.

# Answer
> -1 votes
I ended up using Jos Stam's stable fluid simulation on Unity. Here is the one Unity plugin for that simulation. For WebGL, there are plenty of open-source implementation available to refere.

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


# Question
Title: Blender / Unity - Which one do I paint on? low poly or high poly
I created two versions of my object. One high poly and one low poly. I sculpted the high poly one and plan on baking a normal map so that my low poly one can have more detail.

My question is, once all the sculpting is done and I get everything ready to create a normal map. Which object do I begin painting on the high poly (sculpted) or low poly(non sculpted)?

# Answer
May I answer you now. Normal Game Art workflow: Map shall be paint on high poly in Blender, bake high-poly details (Texture maps, normal maps, etc.) to Low-poly. Or Map can be painted on 3rd party software(Photoshop, etc) after maps and low-poly exported. Thank you.

Tutorials:

1. Gamedev Fred (2018). Blender Bake to Lowpoly. https://youtu.be/o568T79egTs\]\[1: https://www.youtube.com/watch?v=o568T79egTs
> 1 votes

---
Tags: unity, blender
---


# Question
Title: How do i change the material of a object separate from the script
I just need to know how to change the material of an object from another's script so that I don't have to make a script in the other object and change the material from their.

# Answer
> 1 votes
Since you didn't list what engine or programming language you are using I'm going to assume it is Unity and C# since that is where most beginners get started. If writing a script to switch materials is pretty simple you just need referenced to the objects you want to change or if it is attached to the object you want to change, you can just get references. I think you want to change one object material from a second object in which case something like the code below should work.

In the future, please try to be a bit more detailed in your questions. The more vague they are the more difficult it is to help. I hope that doesn't come off as rude, but I honestly have no idea if the script below solves your problem since it is designed for Unity and not another engine like Unreal.

```
using UnityEngine;

public class MaterialChangingScript : MonoBehaviour
{
    public bool changeMaterial = false;
    public Material nextMaterial;
    private Material originalMaterial;
    public Renderer target;

    private void Awake()
    {
        originalMaterial = target.material;
    }

    private void Update()
    {
        if (changeMaterial)
        {
            changeMaterial = false;
            ChangeMaterial();
        }
    }

    private void ChangeMaterial()
    {
        target.material = target.material == originalMaterial ? nextMaterial : originalMaterial;
    }
}

```

---
Tags: materials
---


# Question
Title: Algorithm to check whether pizza toppings are divided half-and-half
Using Unity, I am creating a 2D pizza game and I am stuck at finding an algorithm to solve this problem which is **Detecting if the pizza is half and half** taking into consideration that the user can put the toppings in all rotations shown in the picture and lot more possible distributions.

I used `Physics2D.OverlapAreaAll` to get position of ingredients on the pizza and I tried getting the **sumX** and **sumY** of coordinates of all **topping A** and **sumX** and **sumY** of all **topping B** and adding **A.sumX** \+ **B.sumX** and **A.sumY** \+ **B.sumY** and if the 2 totals are **between 0 and 1** then A and B are on opposite sides but the bad distribution of toppings in the second pic is also accepted by my algorithm. The toppings must be spread like in the 1st pic

I need some easier way to detect the correct distribution of ingredients maybe using collisions or something.

```
if (sumX > -ErrLvl && sumX < ErrLvl && sumY > -ErrLvl && sumY < ErrLvl)
    Debug.Log("APPROVED HALF-HALF PIZZA");
else
    Debug.Log("BAD HALF-HALF PIZZA");

```

# Answer
> 3 votes
After getting help from @DMGregory I was able to solve this by :

1. Getting the center of the toppingsA and toppingsB
2. Finding 6 most far toppings from the centers
3. generate 2 polygons based on these 6 vertices for each topping
4. check if polygons have the minumum area needed to cover most of the half and that they don't collide

This gives accurate half-half pizza detection

# Answer
> 1 votes
This is probably not the best solution in terms of performance but the easiest thing you could do (and this may be okay if you limit the number of toppings) would be to iterate though all topping positions and check the angles between them (you can find someone looking for a similar solution here) This would require iteration through an array while in array giving you performance of O(n^2) which is usually not okay but in some cases could be acceptable.

While I haven't been able to test this, you could possibly reduce performance to O(n) by iterating through the array of toppings once and comparing the angle between topping 0 and topping n to find the topping with the largest angle. Then iterate through again and compare all toppings to the previous max. If any angle is greater than 180 then you know your player is not yet good enough to work at Papa's Pizzeria.

Here is some rough pseudo code. Note that the GetAngleBetween function might not be able to handle obtuse angles, you may need to use cross products to check what side of the line transform B is when compared to the line formed by transform A and the pizza origin. Note that this also doesn't check things like the bounds of your topping only the center point (which honestly is probably fine as long as none of your virtual clients have allergies).

```
float GetAngleBetween(Tranform a, Transform b)
{
    return angle = Mathf.Atan2(b.position.y - a.position.y, b.position.x - a.position.x) * 180.0f / Mathf.PI; // You may need to use cross product for angles over 180
}

bool CheckToppings(List<Transform> toppings, float angleLimit)
{
    // Find farthest topping to one side
    int maxToppingIndex = 0;
    float maxAngle = 0.0f;

    for (int toppingIndex = 0; toppingIndex < toppings.Count; toppingIndex++)
    {
        float angle = GetAngleBetween(toppings[maxToppingIndex], toppingx[toppingIndex]);

        if (angle > maxAngle)
        {
            maxToppingIndex = toppingIndex;
            maxAngle = angle;
        }
    }

    // Find farthest topping to the other side
    int maxToppingIndex2 = maxToppingIndex; // cache this for later
    maxAngle = 0.0f;

    for (int toppingIndex = 0; toppingIndex < toppings.Count; toppingIndex++)
    {
        float angle = GetAngleBetween(toppings[maxToppingIndex], toppingx[toppingIndex]);

        if (angle > maxAngle)
        {
            maxToppingIndex = toppingIndex;
            maxAngle = angle;
        }
    }

    return GetAngleBetween(toppings[maxToppingIndex], toppings[maxToppingIndex2]) <= angleLimit;
}

```

# Answer
> -2 votes
One simple but likely good enough solution would be to brute-force it. Try many different possible pizza layouts and rate the player based on the one which is most favorable to them.

For the half-and-half layout, you could calculate the layouts with lines of separation in increments of 10° to get 18 different ratings (the other 180° would be redundant as they would just be mirrors of the 18 cases tested before) and pick the best one.

---
Tags: unity, c#, collision-detection, algorithm, coordinates
---


# Question
Title: Incorporating HttpSession into libGDX communication
I wrote my server-side code prior to learning libGDX and writing my client-side code. Gdx.net provides for the http get communication I designed for, except for session authentication. I say that based on not finding sessions mentioned in the API, and a couple heavies confirming it on the libGDX discord.

Are there any libraries / examples out there of libGDX developers who mirrored session authentication functionality? The key limitation here is I want to stay with http request/response communication.

---

Minus any such direction, my next step will be to try using the "javax.servlet" libraries I used server-side on the client, and forgo the http classes that come included in the Gdx.net package. I'm reluctant to take this step noting that libGDX has its own versions of lots of classes, for efficiency and to prevent memory leaks given how libGDX programs execute. It'll be a while yet before my programming skills can detect and address such subtle issues. Also, I think that browsers and the server servlets run on participate in session architecture. With neither component in a libGDX PC app for "javax.servlet" to collaborate with, I'm doubtful this solution can work.

If it doesn't work, I'll think about moving up my goal of researching and learning how to use cloud hosting services. Some of these were recommended to me on discord as having frameworks with built-in support for authentication.

# Answer
> 0 votes
I learned more about what was going on under the covers in regards to sessions, namely that they manifest as cookies in the headers:

```
static String session = null;

public static void get(HashMap<String, String> parameters) {
    HttpRequest httpGet = new HttpRequest(HttpMethods.GET);
    if (session != null)
        httpGet.setHeader("Cookie", session);
     httpGet.setUrl("http://localhost:8080/server");
     httpGet.setContent(HttpParametersUtils.convertHttpParameters(parameters));

     Gdx.net.sendHttpRequest (httpGet, new HttpResponseListener() {

            public void handleHttpResponse(HttpResponse httpResponse) {

                String cookie = httpResponse.getHeader("Set-Cookie");
                if (cookie != null) {
                    String delims = "[;]+";
                    String[] tokens = cookie.split(delims);
                    session = tokens[0];
                }

```

---
Tags: java, libgdx, http
---


# Question
Title: How to get "this" object collider name when OnTriggerEnter is fired?
I have a "car" object with 2 colliders attached, a base and a top collider. Then I have a script attached to my car. I'm using OnTriggerEnter event to detect collisions with an invisible "Checkpoint". The problem is that OnTriggerEnter is called twice, I suppose because it is called either from the base collider and top collider. I want to check my object collider's name. OnTriggerEnter expose me with "other" collider; however, how can I test my collider's name?

# Answer
## SPOILER

You still **CANNOT** check for "source" trigger collider that triggers OnTriggerEnter, at least today or what I know at the time of writing (2020). But there is workaround.

## For your racing game case

(This is 4 years after, you probably finished and mastered your cool racing game :). But I will include a specific answer to your question here, since it is manner for SO site, but I will keep it brief.)

Your racing game case is more trivial, since `OnTriggerEnter( Collider other )` offers information on other object, in this case the checkpoint being hit. You could identify checkpoint in some way, such as its name "Checkpoint1". Store and process it on your racing car player object, such as putting it in `List`, `HashSet`, or anything, check to prevent duplication so that it run once.

If you need more detailed checkpoint object, such as passing this checkpoint will extend timer by +60sec. You could make a `Checkpoint` MonoBehaviour Component and attach that to checkpoint object, add any properties you want. Then on player car when collide with these checkpoints, `GetComponent<Checkpoint>`, process your checkpoint, again save it in `List`, `HashSet` to prevent duplication.

## For detecting trigger source

Now the fun part. First, you need to understand nature of how physics engine call those events. I recommend to skim over this official document also:

The following are not stated in document but they are from what I observed:

* If 2 colliders are on same game object, it acts as **compound colliders**. OnTrigger\*** will called once.
* If each collider is on different game object, such as parent-child (OP's case). OnTrigger\*** will called **once for each**.
* First OnTrigger will called on-site of the source trigger (if there is script with OnTrigger\*** on it),
* Then event will **"bubble up"** along the way and called on first RigidBody it reaches.

In both way, you still wont be able to know source trigger, because all events lead to one `OnTriggerEnter( Collider other )` which provide no source information at all.

You need to distribute relay/satellite scripts to each trigger collider. Some example or discussion, see:

This way, if we can catch OnTrigger\*** first hand at source game object, we can know source trigger collider. Application such as detecting head shot, leg shot, arm shot is now possible.

## To prevent event bubbling

Sometimes you don't want event to bubbling up. For example, player can use their attack (which parented to player object) to cut down the flying arrow. With normal event bubbling, when slash attack meets with arrow, signal will bubble to player's rigidbody as if his slash is extending player's own collision! (bad)

In such case, you don't want trigger event to bubble up to player game object. This is done by inserting **kinematic rigidbody** into slash attack, disconnecting it to form its own collision group.
> 9 votes

# Answer
You don't need to check the current object tag, since the OnCollisionEvent would only fire on the object you attached your monobehaviour script to.

Either your GameObject is bouncing and is registering two collision enter events in quick succession -- or it is colliding with at least 2 other colliders.

Tag your collider types so you can easily check to see what you are colliding with. Then you can add a debug statement in your OnCollisionEnter to see what is going on:

```
Debug.Log("Collided With: " + collider.gameObject.tag);

```
> -1 votes

---
Tags: unity
---


# Question
Title: Using proxy servers to tunnel data between clients and world servers
**Background**

I've read up a little on the concept of splitting the world into regions which in turn can each be run on a node within a cluster. However my game concept revolves less around zones but rather bubbles.

In short, a bubble is a region of space defined by a radius which dynamically expands and contracts depending on how many players are in close enough proximity.

---

For example if two players are over 1000KM apart and there is no one else that close to them, then those two players will be in their own bubbles. However once they come within 1000KM to each other, their bubbles connect, effectively creating a larger bubble.

In terms of the server space, one of those players is switched to the others instance. In practice it may be the case that a single server node could handle multiple bubbles, but for arguments sake we'll say that each bubble is run on a different server.

**Problem**

Secrecy may well be a big part of this game, so its important that when one player is close to another they aren't able to detect this by listening for connections to new instances.

My current thinking is that players would be grouped into proxy servers which in turn dynamically connect and disconnect from the bubbles therefore separating the client from this process.

---

The problem of course is latency. There is already latency in the communication itself, and I am concerned that this additional step of tunneling data like this may unnecessarily make it worse.

---

I would also love to find material to read on this type of instancing.

# Answer
If your gateway servers players are connecting to are in the same data center as your simulation servers, then the added latency would be much smaller than a hop through the Internet and might not be a problem at all.

But you could also look at it another way. Instead of hiding the server change from the players, instead let them see it, but empty it of its meaning.

In order to support the bubble merging mechanic you have in mind, it already has to be the case that migrating players to a different server instance is a safe, and reasonably cheap/efficient operation (if it's not, your plan needs changes before it can scale).

So, it it's cheap and efficient to do, you can afford to do it more than you need to. Introduce a chance of migration to a randomly-chosen instance on a similar or slightly greater frequency as you expect player bubble mergers.

This only doubles your migration workload (maybe less, since these migrations can be pure state swaps with no merging), but it's enough to mean that a player who detects a migration can't tell whether they got close to a new player, or if it was just a random migration.

Also, because players now don't have a stable instance they're routinely connecting to, I can't use the IP of the server instance to identify a group of players I've previously encountered who I might have just re-encountered. Their bubble will likely be on a different instance by the time I bump into them a second time.

So the amount I can deduce from watching my connection IP is now much lower, and full of noise that would frustrate attempts to sneak useful information out of it.
> 1 votes

---
Tags: performance, mmo, server
---


# Question
Title: How to return the scene view camera to the default view
By the "scene view camera" I don't mean a `GameObject` with a `Camera` component, I mean the camera used to draw the Scene window in the Unity editor, controlled by this "Scene Gizmo" widget:

The default view shows an almost isometric perspective, where all three X Y Z axes are visible.

But when I clicked the green Y cone, my view changed to look straight down the Y axis, and I can't seem to return to the 3-axis view.

Clicking the other cones on this widget just switchest to look along the X or Z axis instead, and clicking the cube in the middle or the "Top" label just toggles between orthographic and perspective projection.

How can I get back to the default 3-axis view?

# Answer
Orthographic/perspective camera in the Scene View is toggled by clicking the text underneath the X/Y/Z widget (which says 'Top' in your screenshot).

Perspective view will show converging lines there, while isometric view will show parallel lines.
> 1 votes

# Answer
Remember to check the documentation for the tools you're using! In this case, the Scene View Navigation page explains how to control the scene view camera:

> If your Scene view is in an awkward viewpoint (upside-down, or just an angle you find confusing), **Shift-click the cube** at the centre of the Scene Gizmo to get back to a Perspective view with an angle that is looking at the Scene from the side and slightly from above.

Other ways to adjust the view angle include:

> **Orbit**
>
> Hold **Alt** (Windows) or **Option** (macOS), and left-click and drag to orbit the Camera around the current pivot point.
>
> This option is not available in 2D mode, because the view is orthographic.

and

> **Flythrough mode**
>
> Use the Flythrough mode to navigate the Scene view by flying around in first-person, similar to how you would navigate in many games:
>
> * Click and hold the **right mouse button**.
> * Move the view around using the mouse, the WASD keys to move left/right/forward/backward, and the Q and E keys to move up and down.
> * Hold down Shift to move faster.
> 1 votes

---
Tags: unity, camera, perspective, editors
---


# Question
Title: Is there a way to get relative center of a Rect object in pygame?
Now, suppose I always want to draw a circle at the center of a rect object, now, the problem is:

For example, if I do

`pygame.draw.circle(Surface, BLUE, Surface.rect.center, radius, width=3)`

This will and does fail because `Surface.rect.center` is actually the coordinates of the center of the Rect object relative to the (0,0) point -top left corner- of the display screen, not relative to the (0,0) point of the Rect object. However, the draw() function works relative to the Surface coordinate axis.

As far as here, those are my knowledge and I just think so, might be wrong in some aspects, if so, please let me know.

So, I can solve this simply by replacing `Surface.rect.center`, with:

`(Surface.rect.width // 2, Surface.rect.height // 2)`

However, I wonder, is there a way to get that center coordinate of the Rect object relative to its (0,0) point(origin) ?

# Answer
Looking at the pygame docs on the Rect class, there doesn't seem to be any specific to obtain what you're looking for, but it's easy enough to calculate the way you did.

Is there any reason you want to avoid using `(Surface.rect.width // 2, Surface.rect.height // 2)`? If not, I'd say it's the best option.
> 1 votes

---
Tags: python, pygame
---


# Question
Title: Only 1 TextMeshProUGUI being affected by coroutine
I have a prefab m\_wordContainer which is empty other than having a TextMeshProUGUI as a child (I did this so that I could position this container freely not being bugged by an animation played by the TMPUGUI object). At the start of the program I start a coroutine (SpawnWordPopups) which splits the words in a sentence, making a copy of m\_wordContainer and assigning that word to the text property of its TMPUGUI, spawning such m\_wordContainer in a random location within the screen, and then starting a coroutine (FadeText) that fades in the text of every TMPUGUI. The problem is that only one of the TMPUGUI has its text faded, even though the FadeText coroutine is called seemingly correctly. All words are shown as expected, only thing missing is the fading effect on all but the first word that fades. If I called FadeText like this: if (i \> 0) { yield return FadeText(true, tmpText, 2); } then only the second word will be faded.

```
 [SerializeField] private GameObject m_wordContainer;

    void Start()
    {
        yield return StartCoroutine(SpawnWordPopups("test foo bar"));
    }

private IEnumerator SpawnWordPopups(string l_line)
    {
        string[] words = l_line.Split(' ');
        List<Vector3> wordPositions = new List<Vector3>();
        for (int i = 0; i < words.Length; ++i)
        {
            Vector3 spawnLocation = new Vector3(Random.Range(m_wordScreenDistanceOffset, Screen.width - m_wordScreenDistanceOffset), Random.Range(m_wordScreenDistanceOffset, Screen.height - m_wordScreenDistanceOffset), 0);
            if (IsWordOverlapping(wordPositions, spawnLocation))
            {
                --i;
                continue;
            }
            wordPositions.Add(spawnLocation);
            GameObject wordContainer = Instantiate(m_wordContainer, transform.parent);
            wordContainer.transform.position = spawnLocation;
            TextMeshProUGUI tmpText = wordContainer.GetComponentInChildren<TextMeshProUGUI>();
            tmpText.text = words[i];

            yield return FadeText(true, tmpText, 2);
        }
    }

    private IEnumerator FadeText(bool l_fadeIn, TextMeshProUGUI l_textBox, float l_time)
    {
        float time = Time.time;
        float until = Time.time + l_time;
        int alphaFrom = l_fadeIn ? 0 : 1;
        int alphaGoal = l_fadeIn ? 1 : 0;
        Color textColor = l_textBox.color;
        textColor.a = l_fadeIn ? 0 : 1;
        l_textBox.color = textColor;

        while (time < until)
        {
            textColor = l_textBox.color;
            textColor.a = Mathf.Lerp(alphaFrom, alphaGoal, Time.time / l_time);
            l_textBox.color = textColor;
            time += Time.deltaTime;
            yield return null;
        }
        textColor.a = l_fadeIn ? 1 : 0;
        l_textBox.color = textColor;
    }

```

Could anyone shed some light into this issue I'm having? Why are not all the words being faded?

# Answer
I think the problem is the equation you're using for the `t` argument of `Mathf.Lerp`:

```
Time.time / l_time

```

Let's say your game has been running for 10 seconds. Then `Time.time` is `10`, but `l_time` is `2`, so your `t` is `10 / 2 = 5` which gets clamped to `1`. What you should have written is `(Time.time - time) / startTime`. Your time-tracking solution is also messy in general. Here's the whole function with additional improvements:

```
private IEnumerator FadeText(bool l_fadeIn, TextMeshProUGUI l_textBox, float l_duration)
{
    float start = Time.time; //clearer name
    float until = start  + l_duration;
    int alphaFrom = l_fadeIn ? 0 : 1;
    int alphaGoal = 1 - alphaFrom;
    Color textColor = l_textBox.color;
    //removed redundant code here

    while (Time.time < until) //simplified
    { //don't need to keep reading the color from the text field each frame
        textColor.a = Mathf.Lerp(alphaFrom, alphaGoal, (Time.time - start) / l_duration);
        l_textBox.color = textColor;
        yield return null;
    }
    textColor.a = alphaGoal; //no need to recalculate the value
    l_textBox.color = textColor;
}

```
> 0 votes

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


# Question
Title: Can't build UE4 new mod kit - UGCExampleProject - UE4
I am trying to build the new mod kit to support modding for my new game.

I am following the QuickStart Guide:

1. Place your project in a directory under your UE4 root directory (such as /Games or /Projects) and add the directory to UE4Games.uprojectdirs using your favorite text editor. Save this file.
2. NOTE: If you cannot move your project's location for one reason or another, skip this step and move the SimpleUGC.Automation project and scripts to your Engine directory as oulined in the Adding Automation Projects documentation.
3. Run GenerateProjectFiles.bat in your UE4 root directory.
4. Open the Visual Studio solution.
5. If you haven't yet, build the UE4 and UnrealPak projects.
6. Verify that the build scripts are listed in the Programs/Automation directory
7. Open Properties for SimpleUGC.Automation and choose the Build tab on the left. Set the Output Path to your source build's Engine\Binaries\DotNET\AutomationScripts\ directory for both Development and Debug Configurations. The "Browse..." button makes this easy.
8. Build the AutomationTool project.
9. Build your project in the Development configuration.
10. Build and run your project in the Development Editor configuration.

I am getting stuck at step 10, basically I can't get the solution running.

I get these error messages:

```
'UnrealBuildTool.exe' (CLR v4.0.30319: DefaultDomain): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_64\mscorlib\v4.0_4.0.0.0__b77a5c561934e089\mscorlib.dll'.
'UnrealBuildTool.exe' (CLR v4.0.30319: DefaultDomain): Loaded 'E:\UnrealModKit\UnrealEngine\Engine\Binaries\DotNET\UnrealBuildTool.exe'. Symbols loaded.
'UnrealBuildTool.exe' (CLR v4.0.30319: UnrealBuildTool.exe): Loaded 'E:\UnrealModKit\UnrealEngine\Engine\Binaries\DotNET\DotNETUtilities.dll'. Symbols loaded.
'UnrealBuildTool.exe' (CLR v4.0.30319: UnrealBuildTool.exe): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System\v4.0_4.0.0.0__b77a5c561934e089\System.dll'.
'UnrealBuildTool.exe' (CLR v4.0.30319: UnrealBuildTool.exe): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Core\v4.0_4.0.0.0__b77a5c561934e089\System.Core.dll'.
'UnrealBuildTool.exe' (CLR v4.0.30319: UnrealBuildTool.exe): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Xml\v4.0_4.0.0.0__b77a5c561934e089\System.Xml.dll'.
'UnrealBuildTool.exe' (CLR v4.0.30319: UnrealBuildTool.exe): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Configuration\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Configuration.dll'.
XXXPlatformFactory.RegisterBuildPlatforms: XXXPlatformSDK using manually installed SDK 1.0.0
MacPlatformFactory.RegisterBuildPlatforms: UnrealBuildTool.MacPlatformSDK using manually installed SDK
TVOSPlatformFactory.RegisterBuildPlatforms: UnrealBuildTool.IOSPlatformSDK has no valid SDK
AndroidPlatformFactory.RegisterBuildPlatforms: UnrealBuildTool.AndroidPlatformSDK has no valid SDK
HoloLensPlatformFactory.RegisterBuildPlatforms: UnrealBuildTool.HoloLensPlatformSDK using manually installed SDK
IOSPlatformFactory.RegisterBuildPlatforms: UnrealBuildTool.IOSPlatformSDK has no valid SDK
LinuxPlatformFactory.RegisterBuildPlatforms: UnrealBuildTool.LinuxPlatformSDK has no valid SDK
LuminSDKVersionHelper.HasAnySDK: *** Unable to determine MLSDK location ***
LuminSDKVersionHelper.HasAnySDK: *** Unable to determine MLSDK location ***
LuminPlatformFactory.RegisterBuildPlatforms: UnrealBuildTool.LuminPlatformSDK has no valid SDK
WindowsPlatformFactory.RegisterBuildPlatforms: UnrealBuildTool.WindowsPlatformSDK using manually installed SDK
BuildMode.Execute: Command line: "E:\UnrealModKit\UnrealEngine\Engine\Binaries\DotNET\UnrealBuildTool.exe"
Exception thrown: 'UnrealBuildTool.BuildException' in UnrealBuildTool.exe
UnrealBuildTool.Main: ERROR: No platforms specified for target
UnrealBuildTool.Main: BuildException: No platforms specified for target
UnrealBuildTool.Main: at UnrealBuildTool.TargetDescriptor.ParseSingleCommandLine(CommandLineArguments Arguments, Boolean bUsePrecompiled, Boolean bSkipRulesCompile, List`1 TargetDescriptors) in E:\UnrealModKit\UnrealEngine\Engine\Source\Programs\UnrealBuildTool\Configuration\TargetDescriptor.cs:line 272
UnrealBuildTool.Main: at UnrealBuildTool.TargetDescriptor.ParseCommandLine(CommandLineArguments Arguments, Boolean bUsePrecompiled, Boolean bSkipRulesCompile, List`1 TargetDescriptors) in E:\UnrealModKit\UnrealEngine\Engine\Source\Programs\UnrealBuildTool\Configuration\TargetDescriptor.cs:line 192
UnrealBuildTool.Main: at UnrealBuildTool.BuildMode.Execute(CommandLineArguments Arguments) in E:\UnrealModKit\UnrealEngine\Engine\Source\Programs\UnrealBuildTool\Modes\BuildMode.cs:line 158
UnrealBuildTool.Main: at UnrealBuildTool.UnrealBuildTool.Main(String[] ArgumentsArray) in E:\UnrealModKit\UnrealEngine\Engine\Source\Programs\UnrealBuildTool\UnrealBuildTool.cs:line 550
Timeline.Print: Timeline:
Timeline.Print:
Timeline.Print: [ 0.000]
Timeline.Print: [ 0.008](+0.002) FileMetadataPrefetch.QueueEngineDirectory()
Timeline.Print: [ 0.011](+0.073) XmlConfig.ReadConfigFiles()
Timeline.Print: [ 0.084](+0.000) SingleInstanceMutex.Acquire()
Timeline.Print: [ 0.084](+0.159) UEBuildPlatform.RegisterPlatforms()
Timeline.Print: 0.085 [ 0.000](+0.041) Initializing InstalledPlatformInfo
Timeline.Print: 0.127 [ 0.042](+0.000) Querying types
Timeline.Print: 0.128 [ 0.044](+0.095) XXXPlatformFactory
Timeline.Print: 0.224 [ 0.139](+0.002) MacPlatformFactory
Timeline.Print: 0.226 [ 0.141](+0.005) TVOSPlatformFactory
Timeline.Print: 0.232 [ 0.147](+0.003) AndroidPlatformFactory
Timeline.Print: 0.235 [ 0.151](+0.001) HoloLensPlatformFactory
Timeline.Print: 0.236 [ 0.152](+0.001) IOSPlatformFactory
Timeline.Print: 0.238 [ 0.154](+0.002) LinuxPlatformFactory
Timeline.Print: 0.240 [ 0.156](+0.002) LuminPlatformFactory
Timeline.Print: 0.243 [ 0.158](+0.000) WindowsPlatformFactory
Timeline.Print: [ 0.250](+0.001) DeleteJunk()
Timeline.Print: [ 0.252](+0.012) TargetDescriptor.ParseCommandLine()
Timeline.Print: [ 0.264](+0.021) <unknown>
Timeline.Print: [ 0.286](+0.000) FileMetadataPrefetch.Stop()
Timeline.Print: [ 0.289]
The program '[69760] UnrealBuildTool.exe' has exited with code 6 (0x6).

```

More details here.

Did anyone encounter this as well?

Many thanks!

# Answer
> 1 votes
Ok, my bad...

I was building the UnrealBuildTool project instead of the UGCExample project.

All I had to do was:

* in you Solution Explorer right click the UGCExample project and select Debug-\>Start New Instance or directly set it as Startup Project.

---
Tags: unreal-4, unreal, visual-studio, modding, build-process
---


# Question
Title: How can I create multi objects in modern OpenGL?
I am trying to do make a 3D game in modern OpenGL where the player throws a ball and when it hits a cube, the score will be increased by one. I created a 3D object and camera. Right now I'm stuck because I want to draw a crosshair and HUD. I know that I need to do it in 2D space (textures should be stuck on screen) but when I render a 2D object, I can't move my camera and I only see a 2D rectangle. Source code looks like this:

```
#include <GL/glew.h>
#include <GLFW/glfw3.h>

#include <glm.hpp>
#include <gtc/matrix_transform.hpp>
#include <gtc/type_ptr.hpp>

#include <iostream>
#include <fstream>
#include <string>

#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"

glm::vec3 cameraPos = glm::vec3(0.0f, 0.0f, 3.0f);
glm::vec3 cameraFront = glm::vec3(0.0f, 0.0f, -1.0f);
glm::vec3 cameraUp = glm::vec3(0.0f, 1.0f, 0.0f);

float deltaTime = 0.0f;
float lastFrame = 0.0f;
float pitch;
float yaw;
float lastX = 600, lastY = 360;
float fov = 45.0f;

bool firstMouse = false;

static unsigned int CompileShader(unsigned int type, std::string source)
{
    unsigned int id = glCreateShader(type);
    const char* src = source.c_str();
    glShaderSource(id, 1, &src, nullptr);
    glCompileShader(id);

    int result;
    glGetShaderiv(id, GL_COMPILE_STATUS, &result);
    if (result == GL_FALSE)
    {
        int length;
        glGetShaderiv(id, GL_INFO_LOG_LENGTH, &length);
        char* message = (char*)_malloca(length * sizeof(char));
        glGetShaderInfoLog(id, length, &length, message);
        std::cout << "Failed to compile " << (type == GL_VERTEX_SHADER ? "vertex" : "fragment") << "shader" << std::endl;
        std::cout << message << std::endl;
        glDeleteShader(id);

        return 0;

    }

    return id;
}

static unsigned int CreateShader(const std::string& vertexShader, const std::string fragmentShader)
{
    unsigned int program = glCreateProgram();
    unsigned int vs = CompileShader(GL_VERTEX_SHADER, vertexShader);
    unsigned int fs = CompileShader(GL_FRAGMENT_SHADER, fragmentShader);

    glAttachShader(program, vs);
    glAttachShader(program, fs);
    glLinkProgram(program);

    glDeleteShader(vs);
    glDeleteShader(fs);

    return program;
}

std::string readFromFile(const char* pathToFile)
{
    std::string content;
    std::ifstream fileStream(pathToFile, std::ios::in);

    if (!fileStream.is_open()) {
        std::cerr << "Could not read file " << pathToFile << ". File does not exist." << std::endl;
        return "";
    }

    std::string line;
    while (std::getline(fileStream, line)) {
        content.append(line + "\n");
    }

    fileStream.close();
    std::cout << content << std::endl;
    return content;
}

void processInput(GLFWwindow* window)
{

    float currentFrame = glfwGetTime();
    deltaTime = currentFrame - lastFrame;
    lastFrame = currentFrame;

    float cameraSpeed = 2.5f * deltaTime; // dopasuj do swoich potrzeb
    if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS)
        cameraPos += cameraSpeed * cameraFront;
    if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS)
        cameraPos -= cameraSpeed * cameraFront;
    if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS)
        cameraPos -= glm::normalize(glm::cross(cameraFront, cameraUp)) * cameraSpeed;
    if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS)
        cameraPos += glm::normalize(glm::cross(cameraFront, cameraUp)) * cameraSpeed;
}

void mouse_callback(GLFWwindow* window, double xpos, double ypos)
{

    if (firstMouse) // ta zmienna bool jest początkowo ustawiona na true
    {
        lastX = xpos;
        lastY = ypos;
        firstMouse = false;
    }

    GLfloat xoffset = xpos - lastX;
    GLfloat yoffset = lastY - ypos;
    lastX = xpos;
    lastY = ypos;

    GLfloat sensitivity = 0.05;
    xoffset *= sensitivity;
    yoffset *= sensitivity;

    yaw += xoffset;
    pitch += yoffset;

    if (pitch > 89.0f)
        pitch = 89.0f;
    if (pitch < -89.0f)
        pitch = -89.0f;

    glm::vec3 front;
    front.x = cos(glm::radians(yaw)) * cos(glm::radians(pitch));
    front.y = sin(glm::radians(pitch));
    front.z = sin(glm::radians(yaw)) * cos(glm::radians(pitch));
    cameraFront = glm::normalize(front);

}

void scroll_callback(GLFWwindow* window, double xoffset, double yoffset)
{
    if (fov >= 1.0f && fov <= 45.0f)
        fov -= yoffset;
    if (fov <= 1.0f)
        fov = 1.0f;
    if (fov >= 45.0f)
        fov = 45.0f;
}

int main(void)
{
    GLFWwindow* window;

    /* Initialize the library */
    if (!glfwInit())
        return -1;

    /* Create a windowed mode window and its OpenGL context */
    window = glfwCreateWindow(1200, 720, "Shoot The Cube!", NULL, NULL);
    if (!window)
    {
        glfwTerminate();
        return -1;
    }

    /* Make the window's context current */
    glfwMakeContextCurrent(window);

    if (glewInit() != GLEW_OK)
        std::cout << "Error" << std::endl;

    std::cout << glGetString(GL_VERSION) << std::endl;
    glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
    glfwSetCursorPosCallback(window, mouse_callback);

    float vertices[] = {
        -0.5f, -0.5f, -0.5f,    0.0f, 0.0f,
         0.5f, -0.5f, -0.5f,    1.0f, 0.0f,
         0.5f,  0.5f, -0.5f,    1.0f, 1.0f,
         0.5f,  0.5f, -0.5f,    1.0f, 1.0f,
        -0.5f,  0.5f, -0.5f,    0.0f, 1.0f,
        -0.5f, -0.5f, -0.5f,    0.0f, 0.0f,

        -0.5f, -0.5f,  0.5f,    0.0f, 0.0f,
         0.5f, -0.5f,  0.5f,    1.0f, 0.0f,
         0.5f,  0.5f,  0.5f,    1.0f, 1.0f,
         0.5f,  0.5f,  0.5f,    1.0f, 1.0f,
        -0.5f,  0.5f,  0.5f,    0.0f, 1.0f,
        -0.5f, -0.5f,  0.5f,    0.0f, 0.0f,

        -0.5f,  0.5f,  0.5f,    1.0f, 0.0f,
        -0.5f,  0.5f, -0.5f,    1.0f, 1.0f,
        -0.5f, -0.5f, -0.5f,    0.0f, 1.0f,
        -0.5f, -0.5f, -0.5f,    0.0f, 1.0f,
        -0.5f, -0.5f,  0.5f,    0.0f, 0.0f,
        -0.5f,  0.5f,  0.5f,    1.0f, 0.0f,

         0.5f,  0.5f,  0.5f,    1.0f, 0.0f,
         0.5f,  0.5f, -0.5f,    1.0f, 1.0f,
         0.5f, -0.5f, -0.5f,    0.0f, 1.0f,
         0.5f, -0.5f, -0.5f,    0.0f, 1.0f,
         0.5f, -0.5f,  0.5f,    0.0f, 0.0f,
         0.5f,  0.5f,  0.5f,    1.0f, 0.0f,

        -0.5f, -0.5f, -0.5f,    0.0f, 1.0f,
         0.5f, -0.5f, -0.5f,    1.0f, 1.0f,
         0.5f, -0.5f,  0.5f,    1.0f, 0.0f,
         0.5f, -0.5f,  0.5f,    1.0f, 0.0f,
        -0.5f, -0.5f,  0.5f,    0.0f, 0.0f,
        -0.5f, -0.5f, -0.5f,    0.0f, 1.0f,

        -0.5f,  0.5f, -0.5f,    0.0f, 1.0f,
         0.5f,  0.5f, -0.5f,    1.0f, 1.0f,
         0.5f,  0.5f,  0.5f,    1.0f, 0.0f,
         0.5f,  0.5f,  0.5f,    1.0f, 0.0f,
        -0.5f,  0.5f,  0.5f,    0.0f, 0.0f,
        -0.5f,  0.5f, -0.5f,    0.0f, 1.0f
    };

    unsigned int VBO;
    glGenBuffers(1, &VBO);
    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)0);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)(3 * sizeof(float)));
    glEnableVertexAttribArray(1);

    float hudVertices[] = {
        -1.0f,  1.0f, 0.0f,
        -1.0f, -1.0f, 0.0f,
         1.0f, 1.0f, 0.0f,
         1.0f,  1.0f, 0.0f,
         1.0f, -1.0f, 0.0f,
        -1.0f, -1.0f, 0.0f
    };

    unsigned int CVB;
    glGenBuffers(1, &CVB);
    glBindBuffer(GL_ARRAY_BUFFER, CVB);
    glBufferData(GL_ARRAY_BUFFER, sizeof(hudVertices), hudVertices, GL_STATIC_DRAW);
    glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
    glEnableVertexAttribArray(2);

    std::string vertexShaderSource = readFromFile("vertexShader.shader");
    std::string fragmentShaderSource = readFromFile("fragmentShader.shader");
    std::string hudVertex = readFromFile("hudVertex.shader");
    std::string hudFragment = readFromFile("hudFragment.shader");
    unsigned int shaderProgram = CreateShader(vertexShaderSource, fragmentShaderSource);
    unsigned int hudShader = CreateShader(hudVertex, hudFragment);
    glUseProgram(shaderProgram);
    glUseProgram(hudShader);

    unsigned int bodyTex;
    glGenTextures(1, &bodyTex);
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, bodyTex);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    stbi_set_flip_vertically_on_load(true);
    int width, height, nrChannels;
    unsigned char* data = stbi_load("C:/Users/Antoni/Desktop/container.jpg", &width, &height, &nrChannels, 0);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
    glGenerateMipmap(GL_TEXTURE_2D);
    stbi_image_free(data);

    unsigned int faceTex;
    glGenTextures(1, &faceTex);
    glActiveTexture(GL_TEXTURE1);
    glBindTexture(GL_TEXTURE_2D, faceTex);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    data = stbi_load("C:/Users/Antoni/Desktop/face.png", &width, &height, &nrChannels, 0);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
    glGenerateMipmap(GL_TEXTURE_2D);
    stbi_image_free(data);

    glUniform1i(glGetUniformLocation(shaderProgram, "playerBody"), 0);
    glUniform1i(glGetUniformLocation(shaderProgram, "playerFace"), 1);

    glEnable(GL_DEPTH_TEST);

    /* Loop until the user closes the window */
    while (!glfwWindowShouldClose(window))
    {
        /* Render here */
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        glClearColor(0.2, 0.5, 1.0, 0.5);

        processInput(window);
        glfwSetScrollCallback(window, scroll_callback);

        glm::mat4 lookAt(1.0f);
        unsigned int lookAtLoc = glGetUniformLocation(shaderProgram, "lookAt");
        lookAt = glm::lookAt(cameraPos, cameraPos + cameraFront, cameraUp);
        glUniformMatrix4fv(lookAtLoc, 1, GL_FALSE, glm::value_ptr(lookAt));
        glm::mat4 projection(1.0f);
        projection = glm::perspective(glm::radians(fov), (float)1200 / (float)720, 0.1f, 100.0f);
        unsigned int projectionLoc = glGetUniformLocation(shaderProgram, "projection");
        glUniformMatrix4fv(projectionLoc, 1, GL_FALSE, glm::value_ptr(projection));
        glm::mat4 hudScaleMatrix(1.0f);
        unsigned int hudScaleLoc = glGetUniformLocation(hudShader, "hudScale");
        hudScaleMatrix = glm::scale(hudScaleMatrix, glm::vec3(0.3f, 0.3f, 0.0f));
        glUniformMatrix4fv(hudScaleLoc, 1, GL_FALSE, glm::value_ptr(hudScaleMatrix));
        glm::mat4 hudTrans(1.0f);
        unsigned int hudTransLoc = glGetUniformLocation(hudShader, "hudTrans");
        hudTrans = glm::translate(hudTrans, glm::vec3(3.0f, 3.0f, 0.0f));
        glUniformMatrix4fv(hudTransLoc, 1, GL_FALSE, glm::value_ptr(hudTrans));

        glDrawArrays(GL_TRIANGLES, 0, 42);

        /* Swap front and back buffers */
        glfwSwapBuffers(window);

        /* Poll for and process events */
        glfwPollEvents();
    }

    glfwTerminate();
    return 0;
}

```

vertex shader

```
#version 330 core
layout(location = 0) in vec3 PlayerPositions;
layout(location = 1) in vec2 aCords;
out vec2 texCords;

uniform mat4 projection;
uniform mat4 lookAt;

void main()
{
    gl_Position = projection * lookAt * vec4(PlayerPositions, 1.0);
    texCords = aCords;
}

```

fragment shader

```
#version 330 core

out vec4 Color;
in vec2 texCords;

uniform sampler2D playerBody;
uniform sampler2D playerFace;

void main()
{
    Color = mix(texture(playerBody, texCords), texture(playerFace, texCords), 0.2);
}

```

hudVertex shader

```
#version 330 core
layout(location = 2) in vec3 aLines;

uniform mat4 hudScale;
uniform mat4 hudTrans;

void main()
{
    gl_Position =  hudScale * hudTrans *  vec4(aLines, 1.0);
}

```

hudFragment shader

```
#version 330 core

out vec4 ColorHud;

void main()
{
    ColorHud = vec4(1.0 , 0.0, 0.5, 0.0);
}

```

One guy told me that this code won't work

```
glUseProgram(shaderProgram);
glUseProgram(hudShader);

```

but I don't know why. I also tried to reload the shader program by making something like this

```
shaderProgram = CreateShader(hudVertex, hudFragment);
glUseProgram(shaderProgram);

```

Why doesn't it work? How can I draw my hud (and in a future more 3D objects like enemies) with a movable camera and see all objects that I want?

# Answer
I am a bit rusty regarding low-level OpenGL API calls but I think the problem here is your understanding of what `glUseProgram` actually does.

OpenGL is a state machine. It's like a rail system where the global state is determined by the current state of all railway switches. In this example, issuing a draw call is like sending a train through your railway system. Where it ends up, depends on the global state.

Now one of the relevant states in OpenGL is the currently used shader program. You set it with ´glUseProgram´. (Also see this link)

> One guy told me that this code won't work
>
> ```
> glUseProgram(shaderProgram);
> glUseProgram(hudShader);
>
> ```

All this does is changing the state twice, where the first call is totally pointless since the resulting state is never used. So what you need to do instead is calling `glUseProgram(shaderProgram);` and draw your whole game scene. When you have done this, call `glUseProgram(hudShader);` and draw your HUD.

Also be careful in this section here:

```
glm::mat4 lookAt(1.0f);
unsigned int lookAtLoc = glGetUniformLocation(shaderProgram, "lookAt");
lookAt = glm::lookAt(cameraPos, cameraPos + cameraFront, cameraUp);
glUniformMatrix4fv(lookAtLoc, 1, GL_FALSE, glm::value_ptr(lookAt));
glm::mat4 projection(1.0f);
projection = glm::perspective(glm::radians(fov), (float)1200 / (float)720, 0.1f, 100.0f);
unsigned int projectionLoc = glGetUniformLocation(shaderProgram, "projection");
glUniformMatrix4fv(projectionLoc, 1, GL_FALSE, glm::value_ptr(projection));
glm::mat4 hudScaleMatrix(1.0f);
unsigned int hudScaleLoc = glGetUniformLocation(hudShader, "hudScale");
hudScaleMatrix = glm::scale(hudScaleMatrix, glm::vec3(0.3f, 0.3f, 0.0f));
glUniformMatrix4fv(hudScaleLoc, 1, GL_FALSE, glm::value_ptr(hudScaleMatrix));
glm::mat4 hudTrans(1.0f);
unsigned int hudTransLoc = glGetUniformLocation(hudShader, "hudTrans");
hudTrans = glm::translate(hudTrans, glm::vec3(3.0f, 3.0f, 0.0f));
glUniformMatrix4fv(hudTransLoc, 1, GL_FALSE, glm::value_ptr(hudTrans));

```

As specified in the official Khronos documentation `glUniformMatrix4fv` works on the current program object. So this line for example:

```
glUniformMatrix4fv(lookAtLoc, 1, GL_FALSE, glm::value_ptr(lookAt));

```

most likely doesn't do what you think it does. Instead of setting `uniform mat4 lookAt;` in your scene vertex shader, you either set `uniform mat4 hudScale;` or`uniform mat4 hudTrans;` in your HUD shader (Depends on how the GLSL compiler enumerated them). This is because the last program you activated was your `hudShader`. The location you get when calling `glGetUniformLocation` is just an integer number that serves as an index. Usually, such mistakes cause the program to crash or to render nothing because of type or index mismatches. However, all your uniforms have the same type and you use the same number of uniforms in both shaders. You got "lucky" here. So before you set your uniforms, you have to activate the correct program first. Alternatively, in later OpenGL versions (4.?), direct state access (DSA) was added. This gives you a new set of functions to update uniforms in programs without the need to activate the corresponding program first. Here is a link to the DSA function documentation to set uniforms: click me

I don't know if there are any other issues in your program I didn't catch since I only had a closer look into the parts that are relevant to your question. So if it still not working as expected after you corrected the mentioned mistakes, feel free to ask again. However, I would highly recommend that you do some basic tutorials like these ones before you continue making a game. It is really essential to have a good understanding of how OpenGL works before you try to make a game with it. Otherwise, you will get stuck over and over again or rewrite your code thousand times just because you realize how wrong your previous approach was... Believe me, I know it since I have experience with that ;)
> 0 votes

---
Tags: opengl, c++, game-mechanics
---


# Question
Title: Publish to folder equivalent for a desktop GL project with visual studio Mac 2019
I'm not home so the only computer I have access to is a Macbook, and now I would like to see how I could pack up projects to export for various platforms. But when I build my project it only produce a windows executable. Since the project is DesktopGL I can execute it via the command

```
mono-sgen64 DesktopGL.exe

```

but this requires to include as redistributable the mono runtime. can't I publish the project in order to target Mac OS specific output and then get a fully packed .app executable like I can with the publish to folder thingy on windows?

I'll appreciate any help and really thank you for your attention.

Also if I could have access to linux executables I would be highly thankful.

Here is a recap of what I've found already:

> the publish to folder is only available for Mac with a .asp.net or core console project
> https://docs.microsoft.com/en-us/visualstudio/mac/publish-folder?view=vsmac-2019
>
> We can use appify.sh script but I don't know how it would read the content files etc. and this won't be compatible with linux
> I've allready used this script to create a packed php executable but I never included ressources https://mathiasbynens.be/notes/shell-script-mac-apps
>
> as I mentioned earlier I can execute the game properly using the mono executable so if I go that way I could create a run.sh script but this won't be the thing I'm looking into
> i figured it by looking where was located the actual executable of the game once I've run the project
>
> I've also found this nugget package which seems to add publishing parameters but I don't know if I can trust it https://www.nuget.org/packages/InfinitespaceStudios.MonoGame.Packaging/0.1.4-alpha

# Answer
in order to create a .app executable for Mac OS with a DesktopGL project from Visual Studio Mac 2019 , you can create a second project and make a git that shares the code for the two projects. Then you can just compile the MacOS project and get your packed project but this is clearly a workaround rather than a real solution to the question I've asked. Else the easiest solution is to include the linux and the Mac OS executables for mono like said earlier.
> 1 votes

---
Tags: c#, monogame, visual-studio, publishing, macos
---


# Question
Title: LWJGL GLFW hangs on native glfwInit call
For the past months I've been working on creating my own game engine *for personal use* in LWJGL using pieces here and there, especially from developer ThinMatrix's rightfully credited code, to learn as much as I can while building it. Only recently there has been strange behavior happening when I launch the engine from IntelliJ for testing:

* After about 6-10 individual times I click run, all subsequent runs suddenly take about 60 seconds for the window to appear.
* Whenever I restart my PC this hanging resets and I have another 6-10 runs before it hangs everytime again.
* I located the issue to `glfwInit`, more specifically at the call to the native method:

```
  @NativeType("int")
  public static boolean glfwInit() {
      long __functionAddress = Functions.Init;
      return invokeI(__functionAddress) != 0; // Right here
  }

```
* I also noticed that this issue only started when I attempted to implement text support in my engine using the STBTrueType library. It was perfectly fine before that. I tried removing the TrueType code but it didn't fix it.

Here's a list of things I've tried:

* Clearing my temp folder in case a buggy or corrupted file was present.
* Recompiling and rebuilding the entire LWJGL jars twice.
* Building `glfw.dll` from the GLFW sources and replacing the `glfw.dll` in the native jars with the former.
* Reinstalling Java and actually upgrading JDK versions (from 13.0.2 to 14.0.2)
* Switching IDEs even if I suspected it wouldn't work.
* Updating my NVIDIA drivers, and reinstalling them.

I'm quite confused as to what it could be, and I'd be more than happy to share code, thread dumps, or debug info if you deem it necessary. Here is the Github repository with the latest, "faulty" code (fault in quotes because I'm not too sure the code is the problem.)

Thank you very much for any guidance.

P.S: Please tell me if this is better asked in StackOverflow instead of here.

# Answer
> 0 votes
So I fixed the issue, it turns out it wasn't even related to anything to do with programming, or STBTrueType, or the library itself. The problem was as pointed out in this StackOverflow post, where this hanging behavior was due to a faulty driver or, in my case, my keyboard USB being plugged in the "wrong" USB port. I moved my computer at the same time I started working on text in my engine, hence why I wrongly linked the issue with the TrueType library. If you're having the same issue, look at the aforementioned post or if that doesn't work, look for a peripheral that might cause interference.

---
Tags: java, lwjgl, glfw
---


title: Using Async Await in Unity

text:
# Question
Title: Using Async Await in Unity
I am trying to make a reload mechanism in Unity, but the function is in a scriptable object. This means I cannot use Coroutine as it is in MonoBehaviour. I could think of solving with a simple timer with Time.time and Time.deltaTime but for that, I should call the function every frame which seems not too right for me, I'd like to avoid this solution.

I thought about using C#'s built-in Async Await functions but I never used it before and it's quite confusing, I have no idea how to implement it after looking at Microsoft's documentation. I've tried implementing it but I always get an error saying

`The body of 'Weapon.Reload()' cannot be an iterator block because 'void' is not an iterator interface type`

I've done a coroutine implementation so it's easier to see what I want to achieve using Async/Await.

```
public virtual IEnumerator Reload()
{
    if (currentMagazine == magazineSize)
        yield break;

    if (!reloading)
    {
        Debug.Log("Started reloading");
        reloading = true;
    }
    else
    {
        yield return new WaitForSeconds(reloadTime);
        currentMagazine = magazineSize;
        reloading = false;
        Debug.Log("Reload time over");
    }

    Debug.Log("Finished reloading");
    yield break;
}

```

I want to be able to call this function and just let it do its job over time, without stopping code execution. At first, I tried the simple timer solution with a while loop then realized that just stops code execution so it's not working properly.

How could I do this using C#'s Async/Await?

# Answer
> 3 votes
You can have a coroutine runner MonoBehaviour that runs coroutines defined elsewhere. For example:

```
public class CoroutineRunner : MonoBehaviour {
  private static CoroutineRunner instance;
  public static void RunCoroutine(IEnumerator coroutine) {
    if (instance == null) {
      instance = new GameObject("runner").AddComponent<CoroutineRunner>();
    }
    instance.StartCoroutine(coroutine);
  }
}

```

And to use it:

```
CoroutineRunner.RunCoroutine(Reload());

```

I know this doesn’t answer your question, but it does solve your problem by challenging your assumption that you cannot use coroutines in a scriptable object (or anywhere you want).

# Answer
> 0 votes
```
public virtual async void Reload()
{
    if (currentMagazine == magazineSize)
        return;

    if (!reloading)
    {
        Debug.Log("Started reloading");
        reloading = true;
    }
    else
    {
        await Task.Delay(reloadTime * 1000);
        currentMagazine = magazineSize;
        reloading = false;
        Debug.Log("Reload time over");
    }

    Debug.Log("Finished reloading");
}

```

To call, just use `Reload()`.

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


# Question
Title: Howto use the depth buffer in DirectX 12
To make things short: I am trying to bind and use a depth buffer in D3D12, but it is not working. The depth buffer gets created and bound properly (I can see it in nsight graphics) but does only take either 0.0f or 1.0f (Clear value). I first thought that it might be a problem with my projection matrix so I played around with the near and far Z but I didn't get any improvements.

The following code was used to create the depth buffer:

```
// === Create DSV descriptor heap
D3D12_DESCRIPTOR_HEAP_DESC dsvHeapDesc;
ZeroMemory(&dsvHeapDesc, sizeof(D3D12_DESCRIPTOR_HEAP_DESC));

dsvHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_DSV;
dsvHeapDesc.NumDescriptors = 1;
dsvHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE;
dsvHeapDesc.NodeMask = NULL;

ptrDevice->CreateDescriptorHeap(&dsvHeapDesc, IID_PPV_ARGS(&m_ptrDsvDescriptorHeap))

// === Create depth buffer resource
// Describe heap
D3D12_HEAP_PROPERTIES dsHeapProperties;
ZeroMemory(&dsHeapProperties, sizeof(&dsHeapProperties));

dsHeapProperties.Type = D3D12_HEAP_TYPE_DEFAULT;
dsHeapProperties.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
dsHeapProperties.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
dsHeapProperties.CreationNodeMask = NULL;
dsHeapProperties.VisibleNodeMask = NULL;

// Describe resource
D3D12_RESOURCE_DESC dsResDesc;
ZeroMemory(&dsResDesc, sizeof(D3D12_RESOURCE_DESC));

dsResDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
dsResDesc.Alignment = 0;
dsResDesc.Width = width;
dsResDesc.Height = height;
dsResDesc.DepthOrArraySize = 1;
dsResDesc.MipLevels = 1;
dsResDesc.Format = DXGI_FORMAT_D32_FLOAT;
dsResDesc.SampleDesc.Count = 1;
dsResDesc.SampleDesc.Quality = 0;
dsResDesc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
dsResDesc.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL;

// Describe clear value
D3D12_CLEAR_VALUE clearValueDs;
ZeroMemory(&clearValueDs, sizeof(D3D12_CLEAR_VALUE));

clearValueDs.Format = DXGI_FORMAT_D32_FLOAT;
clearValueDs.DepthStencil.Depth = 1.0f;
clearValueDs.DepthStencil.Stencil = 0;

ptrDevice->CreateCommittedResource(
    &dsHeapProperties,
    D3D12_HEAP_FLAG_NONE,
    &dsResDesc,
    D3D12_RESOURCE_STATE_DEPTH_WRITE,
    &clearValueDs,
    IID_PPV_ARGS(&m_ptrDepthStencil)
);

// === Create view description
D3D12_DEPTH_STENCIL_VIEW_DESC dsViewDesk;
ZeroMemory(&dsViewDesk, sizeof(D3D12_DEPTH_STENCIL_VIEW_DESC));

dsViewDesk.Format = DXGI_FORMAT_D32_FLOAT;
dsViewDesk.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2D;
dsViewDesk.Flags = D3D12_DSV_FLAG_NONE;
dsViewDesk.Texture2D.MipSlice = 0;

D3D12_CPU_DESCRIPTOR_HANDLE heapHandleDsv = m_ptrDsvDescriptorHeap->GetCPUDescriptorHandleForHeapStart();

ptrDevice->CreateDepthStencilView(m_ptrDepthStencil, &dsViewDesk, heapHandleDsv);

```

In my frame begin method the following code is executed

```
D3D12_CPU_DESCRIPTOR_HANDLE dsvHandle = m_ptrDsvDescriptorHeap->GetCPUDescriptorHandleForHeapStart();

ptrCmdList->OMSetRenderTargets(1, &rtvHandle, FALSE, &dsvHandle); // RTV Handle works

ptrCmdList->ClearDepthStencilView(dsvHandle, D3D12_CLEAR_FLAG_DEPTH, 1.0f, 0, 0, NULL);

```

The `D3D12_DEPTH_STENCIL_DESC` descriptor of my pipline state is set as follows

```
D3D12_DEPTH_STENCIL_DESC depthDesc;
ZeroMemory(&depthDesc, sizeof(D3D12_DEPTH_STENCIL_DESC));

depthDesc.DepthEnable = TRUE;
depthDesc.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL;
depthDesc.DepthFunc = D3D12_COMPARISON_FUNC_LESS_EQUAL;
depthDesc.StencilEnable = FALSE;

```

The DSV format in also set `psoDesk.DSVFormat = DXGI_FORMAT_D32_FLOAT;`

The viewport also has the correct min and max depth values set.

My Projection matrix is generated statically and uploaded once with the following code:

```
DirectX::XMStoreFloat4x4(&m_constBuffer.getPointer()->matView, DirectX::XMMatrixPerspectiveFovLH(DirectX::XM_PIDIV2, (FLOAT)width / (FLOAT)height, 0.5f, 400.0f));

```

The `m_constBuffer` is an instance of a template class witch is capable of uploading any kind of c++ class members to the GPU as buffer (Here: `DirectX::XMFLOAT4X4`)

My vertex shader just multiplies the model matrix and projection matrix (Currently I have no view matrix!)

```
#include "RootSignature.hlsl"

struct camerCbuf{
    float4x4 matProject;
};

struct modellCbuf{
    float4x4 matModell;
};

struct sOut{
    float4 pos : SV_Position;
    float2 tex : TEXCOORD;
};

ConstantBuffer<camerCbuf> constBufferView : register(b0);
ConstantBuffer<modellCbuf> constBufferModell : register(b1);

[RootSignature(ROOTSIG)]
void main(float3 pos : POSITION, float4 tex : TEXCOORD, out sOut outData){
    outData.pos = mul(float4(pos.xyz, 1.0f)     , constBufferModell.matModell);
    outData.pos = mul(outData.pos               , constBufferView.matProject);
    outData.tex = tex;
}

```

Currently I have no clue why my depth buffer is not working. Thanks for your answers in advance!

# Answer
You should check that matrix.

The DirectXMath function `XMMatrixPerspectiveFovLH` returns 'row-major' memory order, but HLSL defaults to 'column-major' unless you specifically specify otherwise. See Microsoft Docs

Try:

```
XMMATRIX proj = DirectX::XMMatrixPerspectiveFovLH(DirectX::XM_PIDIV2, (FLOAT)width / (FLOAT)height, 0.5f, 400.0f);
DirectX::XMStoreFloat4x4(&m_constBuffer.getPointer()->matView, XMMatrixTranspose(proj));

```

> Note that you may find using SimpleMath a little easier. It's part of *DirectX Tool Kit* for DX11 and DX12.
> 2 votes

---
Tags: c++, depth-buffer, directx12
---


# Question
Title: How to make collisionshape2D work from other scene in Godot?
I have created a scene which contains `Area2D`, `CollisionShape2D` & `AnimatedSprite`. Then I imported that scene into a level. At this moment the player should collide with the object taking it as a obstacle. But it doesn't collide with the coin. How can I make collision work from other scene?

# Answer
So, by default, and Area2D doesn't count as a solid object. It's used for reporting when other Area2Ds or other PhysicsBodys overlap with it.

If you want the coin to act as an obstacle, you'd want to change that to use either a RigidBody or a StaticBody.

There are scripting options to address this as well, but that's likely out of scope for this.
> 2 votes

---
Tags: collision-detection, godot
---


title: Mesh shaded as single pixel

text:
# Question
Title: Mesh shaded as single pixel
I am trying to procedurally generate planets in Unity. The actual planet is already done, but now I am trying to add clouds. For this I created a PBR-Graph shader that draws the clouds based on some noise. It works fine on a quad and even on a plane.

The problem is, that I now created 6 meshes that form a sphere, using a script to go around the planet. I have applied the shaded material to the meshes, but for some reason it behaves, as if the entire mesh would be a single pixel, as in I don't get the white cloud shapes moving around with transparent parts inbetween, like I do on a plane, but instead the entire mesh is transparent or white or gray or partially transparent, like a single pixel from the plane. As the clouds move on the plane, the meshes around the planet flicker and change accordingly.

Could someone help me to figure this out? I don't know why its doing that and its really weird.

Basically the entire mesh acts like a single pixel of the texture, while objects like planes and quads work correctly. I can even get it to work on a sphere, but only on one I created manually by doing new 3D-Object - Sphere and then applying the shaded material to it.

As I want to be able to generate planets with a script, this wouldn't work as it involves me doing something manually...

Here is my code:

This is how the meshes are created:

```
for (int i = 0; i < 6; i++){

        if(cloudMeshFilters[i] == null){

            GameObject meshObj = new GameObject("cloudMesh");
            meshObj.transform.parent = transform;

            meshObj.AddComponent<MeshRenderer>();
            cloudMeshFilters[i] = meshObj.AddComponent<MeshFilter>();
            cloudMeshFilters[i].sharedMesh = new Mesh();

        }

        cloudMeshFilters[i].GetComponent<MeshRenderer>().sharedMaterial = cloudMaterial;

        cloudMeshes[i] = new CloudMeshes(shapeSettings, cloudHeight, cloudMeshFilters[i].sharedMesh, resolution, directions[i]);

    }

```

And this is the cloudMeshes class:

```
public class CloudMeshes
{

int resolution;
Vector3 localUp;
Vector3 axisA;
Vector3 axisB;
Mesh mesh;
ShapeSettings settings;
int height;

public CloudMeshes(ShapeSettings settings, int height, Mesh mesh, int resolution, Vector3 localUp)
{
    this.mesh = mesh;
    this.resolution = resolution;
    this.localUp = localUp;
    this.settings = settings;
    this.height = height;

    axisA = new Vector3(localUp.y, localUp.z, localUp.x);
    axisB = Vector3.Cross(localUp, axisA);
}

public void ConstructMesh(){

    Vector3[] vertices = new Vector3[resolution * resolution];
    int[] triangles = new int[(resolution - 1) * (resolution - 1) * 6];
    int triIndex = 0;

    for(int y = 0; y < resolution; y++){
        for(int x = 0; x < resolution; x++){

            int i = x + y * resolution;
            Vector2 percent = new Vector2(x,y) / (resolution - 1);
            Vector3 pointOnUnitCube = localUp + (percent.x - .5f) * 2 * axisA + (percent.y - .5f) * 2 * axisB;
            Vector3 pointOnUnitSphere = pointOnUnitCube.normalized;
            vertices[i] = pointOnUnitSphere * (settings.planetRadius + height);

            if (x != resolution - 1 && y != resolution - 1)
            {
                triangles[triIndex] = i;
                triangles[triIndex + 1] = i + resolution + 1;
                triangles[triIndex + 2] = i + resolution;

                triangles[triIndex + 3] = i;
                triangles[triIndex + 4] = i + 1;
                triangles[triIndex + 5] = i + resolution + 1;
                triIndex += 6;
            }

        }
    }

    mesh.Clear();
    mesh.vertices = vertices;
    mesh.triangles = triangles;
    mesh.RecalculateNormals();

}

}

```

The ConstructMesh() method is called after the for loop at the top has run.

Sorry for any incorrect indentations, that happend when pasting the code here...

# Answer
> 1 votes
Thanks to @DMGregory! I had indeed forgotten to generate the uvs for the meshes. I fixed that and now the shaded material is displayed correctly!

Here is the new ConstructMesh Method:

```
    public void ConstructMesh(){

    Vector3[] vertices = new Vector3[resolution * resolution];
    int[] triangles = new int[(resolution - 1) * (resolution - 1) * 6];
    Vector2[] uvs = new Vector2[(resolution * resolution)];
    int triIndex = 0;

    for(int y = 0; y < resolution; y++){
        for(int x = 0; x < resolution; x++){

            int i = x + y * resolution;
            Vector2 percent = new Vector2(x,y) / (resolution - 1);
            Vector3 pointOnUnitCube = localUp + (percent.x - .5f) * 2 * axisA + (percent.y - .5f) * 2 * axisB;
            Vector3 pointOnUnitSphere = pointOnUnitCube.normalized;
            vertices[i] = pointOnUnitSphere * (settings.planetRadius + height);
            uvs[i] = new Vector2((float)x / resolution, (float)y / resolution);

            if (x != resolution - 1 && y != resolution - 1)
            {
                triangles[triIndex] = i;
                triangles[triIndex + 1] = i + resolution + 1;
                triangles[triIndex + 2] = i + resolution;

                triangles[triIndex + 3] = i;
                triangles[triIndex + 4] = i + 1;
                triangles[triIndex + 5] = i + resolution + 1;
                triIndex += 6;
            }

        }
    }

    mesh.Clear();
    mesh.vertices = vertices;
    mesh.triangles = triangles;
    mesh.RecalculateNormals();
    mesh.uv = uvs;

}

```

# Answer
> 0 votes
> I can even get it to work on a sphere, but only on one I created manually by doing new 3D-Object - Sphere and then applying the shaded material to it.

> As I want to be able to generate planets with a script, this wouldn't work as it involves me doing something manually...

Have you considered creating a prefab from the "Create" menu sphere and simply changing the material assigned to instances of the prefab? If you need to distort the mesh afterward, you can do this with a shader, or by copying the mesh data into a new mesh and manipulating the vertices of the new mesh.

---
Tags: unity, 3d, shaders, 3d-meshes
---


# Question
Title: How do I zoom in and out in a fully tiled based game
I am currently developing a tile based game in Java and trying to add the option of zooming. I do the zoom by reducing and enlarging the tiles, but the problem is that it creates spaces between the tiles.

The default form, in which I created all of these tiles from the beginning:

When zooming out - width -= 2 and height -= 2:

Bigger zooming out:

My question is very simple, how do I zoom in and out on a tile based world?

# Answer
> 0 votes
Your idea of zooming is wrong. I believe your problem is to distinguish between real coordinates and sizes to scaled coordinates and sizes. In other words, you need to respect the position and size of the tiles, while scaling them down. The Tiles themselfs only have the information, what position and width they have in world space.

This is without the zoom. In this example, every tile is 1 wide and 1 tall, this is obviously not the size in pixel, as a tile is more like 64 pixels in size. Lets just say, you paint a cube by giving it the top left corner as base position and the size for width and height. so *public drawCube(int posx, int posy, int size)* for example. Now your cube object has pos (0, 0) with width 1 in world space. Your object would be drawn with the top left corner being (0,0), but since you draw pixels, the bottom right corner would be at (63, 63). The cube with pos (1,1) would then be painted at top right (64, 64) to bottom left (127, 127). This is only, if you have no zoom.

Now lets zoom out by 0.5, so everything has only half the size. Your topleft cube Object still has pos (0,0) and size 1, but if you call *public drawCube(int posx, int posy, int size)* on it. now you have to calculate position and size in pixel. In pixels, the top left is still (0,o), but your cube is only 32 pixels wide and tall, so the bottom right corner is (31, 31). The cube at (1,1) will then be drawn at top left (32, 32) to bottom right (63, 63). Basically you have to half the position values and the size values.

Obviously the cube does not need to know, what zoom factor your game currently has. For that you normally have a camera object that knows the the camera position (in world space). Your renderer then uses those informations to draw the tiles at the right position with the right size. But that is way more complicated to explain and needs alot more informations on your current code.

---
Tags: java, camera, game-mechanics, tilemap, swing
---


# Question
Title: How would I detect a collision between a rigidbody and a static
I have an object with a rigid body. How would I go around detecting collisions between this object and any other object with a collider on it?

I know you can enable/disable collision detection (https://docs.unity3d.com/ScriptReference/Rigidbody-detectCollisions.html). Is there an event that gets fired whenever an object collides?

My Rigidbody object:

A typical object that it would collide with:

Extra info: This is Unity 3D, with version 2019.4.8f1o on the Universal Render Pipeline

# Answer
> Is there an event that gets fired whenever an object collides?

OnCollisionEnter

```
//Automatically fired when a collision occurs
void OnCollisionEnter(Collision collision) {

}

```

This is something you could easily have found with a web search.
> 0 votes

---
Tags: unity, collision-detection, 3d, rigidbody, collider
---


title: Force change prefab source

text:
# Question
Title: Force change prefab source
I have a prefab A and i use it in scene A (as gameobject A). Then i to save that scene A as scene B and also renamed the gameobject A to gameobject B. Then inside unity (in project window ) , i duplicated the prefab asset A to prefab B.

Fyi, i'm using .blend (blender file) as the prefabs.

in scene B, i want the gameobject B which refers to prefab A , to switch its prefab's source to prefab B.

This way , i have 2 different scenes which has independent gameobjects which refer to unique prefab. So i can modify prefab A and will affect scene A but not scene B.

Ussually, i can drag the gameobject to project window and choose/create 'new original prefab' option, but this method can't be used, since i want both prefab as .blend file (so i can modify them directly using blender).

What i did so far, is to drag prefab B to scene B, which then i have to manually redo all the setting which has been done in scene A . I want to avoid this tedious process.

Does anyone have any idea ?

# Answer
> 0 votes
Found the solution. This is the dirty way. It only works if the sources are identical like in my case.

1. Duplicate scene A to B.
2. Duplicate prefab (A.blend to B.blend).
3. In file explorer, open the meta files of these prefabs (blend files) using text editor (i use sublime text) and record the guid (object id) of each prefab.
4. Open the scene B in text editor and do find/replace . Replace all the old guid of A.blend and replace it with guid of B.blend and save it.
5. Open unity ( and reload the scene if it's open). Now in scene B , the gameobject is linked to the new B.blend. While in scene A, still link to A.blend. Now each scene has unique prefab while in scene B , i can still keep the gameobject setting from scene A.

---
Tags: unity
---


# Question
Title: Weird shader behavior on different devices
I'm trying to combine an ordinary shader with a Single Distance Field shader (for fonts and scalable icons) into one shader program. The idea is simple - if uv.x is less than 1.0, it is drawn as usual, and if more than 1.0 then SDF is used (using GL\_REPEAT uv.x and uv.x + 1.0 look similar)

Fragment shader code:

```
precision mediump float;
precision mediump int;

uniform sampler2D u_texture;
varying vec4 v_color;
varying vec2 v_texCoords;
uniform float u_smoothing;

void main() {
  // SDF
  float distance = texture2D(u_texture, v_texCoords).a;
  float alpha = smoothstep(0.5 - u_smoothing, 0.5 + u_smoothing, distance);
  vec4 sdfColor = vec4(v_color.rgb, alpha * v_color.a);

  // Regular
  vec4 regularColor = v_color * texture2D(u_texture, v_texCoords);

  // Making a choice
  gl_FragColor = mix(regularColor, sdfColor, step(1.0, v_texCoords.x));
}

```

It works and looks fine on desktop and most of popular Android devices but not on Oneplus One, Xiaomi Redmi 4A and Moto G devices. This is how it must look like and how it actually looks on desktops and many other devices (Samsung S8, Xiaomi 3s, Pixel 2 etc.):

And this is how it looks like on Moto G, Oneplus One & some others:

I tried to find a problematic function, but without success. First I tried to use the usual condition instead of mix():

```
void main() {
  // ...

  // Making a choice
  // gl_FragColor = mix(regularColor, sdfColor, step(1.0, v_texCoords.x));
  if (v_texCoords.x < 1.0) {
    gl_FragColor = regularColor;
  } else {
    gl_FragColor = sdfColor;
  }
}

```

Nothing has changed - this shader works well on most devices and is still bad on some others. I decided that the problem lies in the calculation of sdfColor and changed fragment shader code a bit to check:

```
void main() {
  // ...

  // Making a choice
  gl_FragColor = sdfColor;  // Always using SDF
}

```

But this shader worked equally on all devices, which indicates that sdfColor is calculated correctly. This next screenshot was taken on Moto G:

Then I tried to differentiate the regions of textures with different colors:

```
void main() {
  // ...

  // Making a choice
  if (v_texCoords.x < 1.0) {
    gl_FragColor = regularColor;
    gl_FragColor.r = 1.0;  // Full red channel for regular texture regions without SDF (UV.x < 1.0)
  } else {
    gl_FragColor = sdfColor;
    gl_FragColor.r = 0.0;  // No red channel for SDF
  }
}

```

On Moto G and other devices it looks as expected:

It seems to me that using mix() or conditions implicitly changes something else.

**Update 1:**

Using different precision qualifier (highp / lowp) or completely removing it didn't help and made no visual changes.

This bug starts to appear on desktop (OpenGL) if I add `#version 100`. Changing it to `#version 110` or higher returns normal rendering.

When `#version 100` is used on Android (OpenGL ES 2.0) it renders as if there were no `#version` qualifier at all (exactly the same as described in my question - on Nexus 5x it looks good, on Moto G it doesn't).

Using `#version 300 es` on Android (OpenGL ES 3.0, looks like it is supported Moto G 3rd) with respective changes to the code (uniform, varying, texture2D replaced by in, out, texture) doesn't fix the problem (good on Nexus, bad on Moto).

Precision qualifier was not used in both cases. Looks like `#version` does no effect to this problem on Android but makes it appear on desktop when set to 100 (is it OpenGL 1.0?...)

**Update 2:**

Writing `v_texCoords.x` to the separate `float` and using it in `mix()` fixes this bug but only for desktop when `#version 100` is also used:

```
#version 100
uniform sampler2D u_texture;
varying vec4 v_color;
varying vec2 v_texCoords;
uniform float u_smoothing;

void main() {
  float x = v_texCoords.x; // Writing to the separate float

  // SDF
  float distance = texture2D(u_texture, v_texCoords).a;
  float alpha = smoothstep(0.5 - u_smoothing, 0.5 + u_smoothing, distance);
  vec4 sdfColor = vec4(v_color.rgb, alpha * v_color.a);

  // Regular
  vec4 regularColor = v_color * texture2D(u_texture, v_texCoords);

  // Making a choice
  gl_FragColor = mix(regularColor, sdfColor, step(1.0, x)); // Using x instead of v_texCoords.x
}

```

It doesn't fix the problem on Moto G. Also when I move `float x = v_texCoords.x;` to the line right before `gl_FragColor = ...` the problem remains on desktop:

```
void main() {
  // SDF
  float distance = texture2D(u_texture, v_texCoords).a;
  float alpha = smoothstep(0.5 - u_smoothing, 0.5 + u_smoothing, distance);
  vec4 sdfColor = vec4(v_color.rgb, alpha * v_color.a);

  // Regular
  vec4 regularColor = v_color * texture2D(u_texture, v_texCoords);

  // Making a choice
  float x = v_texCoords.x; // Writing to the separate float, this time it doesn't fix the bug
  gl_FragColor = mix(regularColor, sdfColor, step(1.0, x)); // Using x instead of v_texCoords.x
}

```

# Answer
This isn't a complete answer, but for whatever reason, you're getting major precision loss in your texture coordinates (on some platforms). You can tell this is the problem because the blockiness isn't isotropic: Your textures actually still have their full resolution in the Y direction, they're only getting chunked up in the X direction.

One way you can further tell if/that this is the problem is that if you change your SDF condition to 2.0, and adjust your code to match, the problem should become twice as bad.

Given that your test with just sdfColor was OK (I assume that was still with UV.x \> 1.0), I feel like this is probably the GLSL compiler doing some bad floating-point optimizations on you. The part where storing the number to a separate float helped for desktop OpenGL but not your other platforms adds weight to that.
> 1 votes

# Answer
For whatever reason the texel values are different ( \> 1.0) on the other platforms. Are they using high-res screens? The pixel depth might be double (e.g. check for uv.x \> 2.0) Might need to write a separate shader for those devices.
> 0 votes

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


# Question
Title: How does a game like Enter the Gungeon handle forward and backwards movement with their orthographic set up?
So I've been scratching my head at this problem for over a week now, and would love some insight from anyone who might know a bit more.

In my game I have the floor flat on the X/Z plane with walls/characters rotated +45 degrees about the X axis. The orthographic camera is pointing down also at 45 degrees about the x axis, parallel with my walls/characters:

As a result, I dont see any distortion for players/characters since they face the camera directly on, while the ground however sees a distortion of sqrt(2) shorter. This makes sense considering how an orthographic camera works. To fix this, I've made my Tilemap set up with X:1 Y:1 Z:Sqrt(2) so that each tile is stretched on the Z axis by Sqrt(2) to compensate for this distortion.

All looks well with only one problem now... foreshortening with regards to **movement**: Forward and backwards movements of objects/characters along the z axis are perceived to be slower than movements left/right on the x axis. This makes sense because while each tile is perceived to be a square in the **camera view** thanks to scaling Z on the tilemap by sqrt(2), **the real world** tile is, well, sqrt(2) times taller than its width, so obviously it takes longer to travel forwards / backwards.

I've found another post here that also touches on this: How to handle forward/backward movement in an oblique top-down view

Now looking at this thread: https://www.reddit.com/r/EnterTheGungeon/comments/4sed7a/developers\_how\_did\_you\_get\_into\_programming\_and/d7p3jjv/?utm\_source=share&utm\_medium=web2x

It seems to me that DodgeRollBrent is describing almost an identical setup in their game, Enter the Gungeon, with the minor exception that their camera is facing directly along the z axis and the floor and walls are rotated +45/-45 instead. And yes they choose to also scale their walls/characters by sqrt(2) as they're parallel with the floor.

I think the part where I'm particularly confused is where the user HubT initially asks:

> I mean if I create an orthographic camera and tilt it by 45 degrees the sqrt(2) distorted walls (the walls have Z depth and are perpendicular to the ground) align up nicely but the ground gets distorted (obviously). So I distort the ground tiles by sqrt(2) **but this essentially stretches the ground by 40% so every vertical movement now has to be increased by 40%.**

And DodgeRollBrent responds with:

> so the walls are tilted 45 degrees toward the camera, and the floors are tilted 45 degrees away from the camera, meaning that each should experience sqrt(2) distortion because of the additional length along the z-axis
>
> **however, the vertical (y-axis) floor length shouldn't be perceptually changed.** i think it sounds like the element you're missing is that the ground is **tilted with respect to the camera as well.**

So it looks like indeed their camera is facing the floor at an angle, but from what they've described they don't seem to be having the foreshortening problem that both me and the other user have described (movement being slowed down by ~40%).

**My summed up question:**

What does he mean by:

> the vertical (y-axis) floor length shouldn't be perceptually changed.

This seems to contradict what they say about the 45 degree angled floor / both the floor/walls being distorted by sqrt(2).

I would love someone else's interpretation of all this. If I have an orthographic camera facing the floor at an angle as I've pictured above, are my only two options to fix foreshortened movement (based on the other question on gamedev stack exchange linked above) to either:

1. Amend vertical movement to be faster (would it be as simple as setting the z component of the velocity to be sqrt(2) times faster?)
2. Set up my camera to be "Oblique" with a scale set to the z - axis (As mentioned here: How to handle forward/backward movement in an oblique top-down view)

Or is there another way of solving this? I'm very wary of changing the vertical speed as I can very well see some knockons of this in the other systems of my game.

I'm also a bit worried about messing around with the projection matrix. Just from testing using this script provided here: https://github.com/keijiro/unity-oblique-projection I'm having some confusion understanding what the z scale should be in my case, and also why the camera seems to get offset when I set the z scale (although I'll save these questions maybe for another post since this one is plenty long now).

If you've read through this, thank you. Any help with this would be massively appreciated.

# Answer
> 1 votes
So, this screenshot (linked from the Reddit thread you linked) helps clear things up: https://twitter.com/DodgeRollGames/status/593625936131653632/photo/1

Their camera points directly down Z (unrotated). Their walls are tilted 45 degrees toward the camera (so, on the ZY plane). The floor is tilted 45 degrees away (so, on the -ZY plane).

This means both the floor and walls are distorted, but they're distorted *by the same amount*.

When they say

> the vertical (y-axis) floor length shouldn't be perceptually changed

I take that to mean that movement on the y-axis needs to be the same speed as movement on the x-axis. Depending on how they've set things up, this isn't a contradiction. For instance, if they're representing their world in some sort of "tile coordinates", and then applying the sqrt(2) stretch + rotate as a matrix in the tail of their transform chain (which is my first impulse), this falls out naturally. There's no need to work in stretched-out space all the time.

---
Tags: unity, 2d, camera, movement, projection-matrix
---


# Question
Title: What's the difference between Collision layers and Collision masks?
In *PhysicsBody* and *PhysicsBody2D* in **GoDot**, there are two attributes called Mask (PhysicsBody| Collision| Collision and Mask). I noticed that a body collides with another body if they have a layer in common or a mask in common. But then, if there's already a collision layer, what's the purpose of the mask?

# Answer
> 2 votes
thanks to this answer

'collision mask\` bit is for choosing *what layer should be collided*.

Let's assume we set `collision layer` and `mask layer` as below.

> Player node: collision layer is on 1st bit/mask layer is on 2nd,3rd bit
> Enemy node: collision layer is on 2nd bit/mask layer is on 1st bit
> Object node: collision layer is on 3rd bit/mask layer is on 1st bit

then

> Player mask(2) == Enemy layer(2)
> Player mask(3) == Object layer(3)
> so, Player can be collided with Enemy and Object.

but Enemy nodes do not collide each other or Object nodes, Because:

> Enemy mask(1) != Enemy layer(2) / Enemy mask(1) != Object layer(3)

---
Tags: godot
---


# Question
Title: How do I manually change a sliding ball into a rolling ball in Unity 3D?
I'm a little new to this so any help will be appreciated.

---

**Context:** I'm creating a simulated VR billiard game and trying to get the physics as realistic as possible. I have a cue ball being hit with a cue across a surface with accurate friction values calculated from real world trials.

---

**Problem:** The cue ball slides for longer than what it would slide in the real world. Realistically, when the velocity reaches 5/7th (~71%) of its initial velocity the ball transitions from sliding to rolling. However, in Unity, the transition happens much later at around 20-10% of the initial velocity. (this is due to how Unity calculates physics of interaction as a point of contact rather than an area of contact)

---

**Question:** I want to hard code it so that when the cue ball loses 5/7th of its initial velocity (at 71%\*initial velocity), the sliding velocity is set to 0 and the cue ball continues to roll from its angular velocity. Theoretically, is this possible? or will changing the velocity/speed to zero instantly stop the ball from moving in its place? And how do I go about doing this? Thanks in advance.

# Answer
This sounds like it should be possible, though I've never tried it. The following code should get you most of the way there. You could then determine through experimentation how to adjust the velocity and angular velocity to achieve the desired effect.

private Rigidbody body;

void Start() {
    body = GetComponent<Rigidbody>();
}

void OnCollisionEnter(Collision collision) {
    StartCoroutine(SlideThenRoll());
}

IEnumerator SlideThenRoll() {
    yield return null; //wait a frame to make sure our velocity updates
    float initialSpeed = body.velocity.magnitude;
    float targetSpeed = .71 * initialSpeed;
    yield return new WaitUntil(() => body.velocity.magnitude <= targetSpeed);

    //you'll need to fill in this part
    body.velocity = //??
    body.angularVelocity = //??
}
```

> 1 votes

---
Tags: unity, physics
---