# Question
Title: Is it possible to create accelerated 3D graphics on Windows using one's own API?
Say I want to come up with a way to replace what OpenGL and DirectX specifications do: communicate with GPU to get some functions done that help hardware-acceleration and rapid drawing of screen data. Is it possible to write some mock-up copy that can communicate with the GPU the same way that, say, an OpenGL specification could or DX to drive the same functions (or similar ones)?

What I'm saying is, somebody somehow made a way to communicate with a device driver to get acceleration and faster graphics, 3-D functions, etc. Is it possible one can create the same "inbetween" library or software that can do pretty much the same thing -- interact with the device driver and drive OpenGL/DX similar operations or some other specification, **but using my own self-written procedures to do so**?

In other words, is it possible to replace OpenGL/DX code that communicates with a graphics driver with your own code that does the same thing, but is instead written by you?

**I'm not asking about writing a device driver**, but writing something that communicates with it, such as how DX/OpenGL does. OpenGL is 100% open-source and you can see how every single function/operation/line of code works when you link with it and use a debugger, etc.

We know OpenGL usually doesn't directly interact with a GPU most of the time, and although it does sometimes, the identic function can easily be replaced by debugging.

# Answer
> 9 votes
You have some fundamental misunderstandings.

> What I'm saying is, somebody somehow made a way to communicate with a device driver to get acceleration and faster graphics, 3-D functions, etc.

This is incorrect; it is the *driver* that provides access to the acceleration hardware (the GPU). It isn't OpenGL or D3D itself, which are simply API specifications (with corresponding implementations). GPU vendors, such as Nvidia, will provide drivers that implement OpenGL/D3D in a fashion that communicates to their hardware via the driver (typically there is both a kernel mode driver and a user-mode DLL involved in this implementation).

> OpenGL is 100% open-source and you can see how every single function/operation/line of code works when you link with it and use a debugger, etc.

OpenGL is *not* open-source at all. There is no "source" to OpenGL, it's just a specification. Individual implementations may or may not be open-source (most, such as those offered by Microsoft, Apple, AMD, et cetera, are not); Mesa is a common open-source OpenGL implementation.

You can see how any function of any library, open or closed, works in the debugger - debuggers often have the ability to disassembly machine language even if there's no mapping back to higher-level source available.

---

So, as for your actual question, yes, it's possible to write something that communicates with the device driver for a GPU. This is how Mesa works; it runs against a handful of drivers. If you knew the exposed endpoints of other drivers you could write user-mode DLLs to communicate with them.

This is generally a waste of time though, and will not get you to your stated goal because it's the driver that actually "helps with the hardware acceleration," and it's the driver you say you don't want to write (correctly so, because it's a *huge* amount of work requiring *extensive* knowledge of the details of individual hardware that is not easily accessible).

# Answer
> -1 votes
Theoretically yes, it is possible. People here love to dislike similar questions, but such project can be a nice practice in graphics programming, getting you from zero to an expert in the field, if you won't abandon it half way.

Although industry already began standardizing and exposing bare metal features, under say Vulkan API. But such work could help making emulators for older GPUs, so it would have more value than say reverse engineering some older video game to make it run on modern hardware.

1. You will have to reverse engineer existing driver, or convince GPU producing company to share their source code with you.
2. Design your own graphics API with its own rationale.
3. Have enough patience to undertake the project.
4. Publish the findings.

That is in principle all that is required. Although I would suggest finding some debug version of a driver, which retains symbol table. People are lazy and sometimes leave such stuff inside the release product. Symbol names and source file lines greatly simplify reverse engineering.

So yeah, do it, if you want to improve your skills and to understand how it all works.

---
Tags: graphics-programming, gpu
---


# Question
Title: What are the reasons to reset MMR and introduce seasons?
I have a game with a ranked mode that keeps track of MMR.

Players have been asking me to have "seasons" so we can reset it and help people who are "stuck in ELO hell" climb better.

My thought is that people who are stuck in elo hell are just bad and that resetting per-seasons are pointless, why not just climb? I'm going to add rewards for the highest rank achieved every 4 months but not reset MMR.

Is there any real reason to reset MMR?

# Answer
> 3 votes
## An "even" playing field

If you put the average player at the same starting point as all other players, there's a small hope of them actually ending up on top. One's logical mind may realise it's completely unrealistic, but this hope may still be there.

If you can see all those players between you and the top, this is much more demotivating than a clean slate (even if the end result would be roughly the same).

This also applies to any rewards and your hope of getting those.

## Seeing how you do against the best

This is similar to the above, but goes beyond that.

Often it would be roughly impossible for an average player to get matched against the best of the best players, due to how the matching system works.

It can simply be a nice challenge to directly face one of the best players (or at least a much better player), see how you'd actually do against them, see how they'd respond to what you do and potentially learn from it, even if you get completely demolished.

Resetting rankings gives a much better chance of this happening.

## Variation in ranking is a fact, how much is hard to determine

Many games have some element of randomness, having bad days happens and the ranking system may have some issues. This may also disproportionately affect certain players, characters, roles, etc. (e.g. certain characters may heavily rely on randomness or a "support" character may have a harder time supporting teammates that can't fulfil their role, or be in a much better position to highlight the strengths or negate the weaknesses of their team).

Now you may say this effect these factors has on ranking is minor and you'd never be too far from your "true" ranking, and this may be true, but this effect may also be much greater than you imagine.

One way to potentially test this, of course, would be to reset rankings.

## Mentality is reality

Believing something to be true can *make* it true. If a player believes they're in "elo hell", they may be demotivated and end up playing significantly worse than how they'd play under other circumstances (or they may end up saying or doing things that demotivate their teammates, even if they themselves don't play much worse).

## How long would it take to climb?

Let's say you're not where you belong. What percentage of games would you win? How long would it take to climb to where you belong at that percentage? Of course you should win a lot more if you're far below from where you belong, but it may still take quite a while to get where you "belong".

There are also high ranking players playing on low ranking accounts, to either just increase ("boost") the ranking or because they enjoy the easy wins. Whether this makes up a noteworthy portion of accounts (and thus affect one's ability to climb at that level) would likely depend on the game and the ranking level.

## Players need to actually play

If there's no reset and a top player stops playing or just plays less, they may actually keep getting the top player rewards for a few seasons. A reset forces players to play ever season to get rewarded, which encourages players to play more (increased engagement is good) and makes it more likely for players to rank higher (since they won't be competing with players no longer playing the game).

## Making players happy

Sometimes you give in to the requests of players, instead of dismissing them, because making and keeping your players happy is important, even if what they're asking makes no sense to you. Although there is a risk that they're not being realistic and it ends up being a disappointment or your idea of what they want is different from what they actually want. Might the majority of players be disappointed enough with ending up at the same place after a reset to stop playing? I suspect not, but I might be wrong.

---

As an anecdote, I was quite an avid Dota 2 player a few years ago. I hypothesised that the ranking I was stuck at may not have reflected my ability (especially since I've learnt a ton since getting that ranking). So I created a new account (since there is/was no free ranking reset). With that account I ended up getting a ranking significant higher than my original account (from about 3.5k to 4.5k, if I recall correctly). I suspect demotivation was a big contributor to being stuck.

Although I do suspect most players who believe they're stuck in "elo hell" may be misjudging their own ability and resetting their ranking would likely put them in roughly the same spot.

---

Note some games have **a season ranking separate from your regular ranking**, and in some cases allow you to *optionally* replace your regular ranking with your season ranking (if it's better). Dota 2 is/was one example, I believe. This might be a negate the downside of resetting ranking, which is that **players become attached to their ranking** and resetting it would frustrate them.

# Answer
> 4 votes
Instead of fixing the symptom (people being dissatisfied with their ELO rank), let's try to find the root cause.

So there are players who feel "trapped in ELO hell". What exactly about their game experience feels like "hell"? Why don't they enjoy playing against players with a similar ELO rating? If we can answer these questions, we might find a much better solution which doesn't lead your whole ranking system *ad absurdum*.

You are not writing anything about your game mechanics at all, so we can only guess widely here. So here are some of my guesses what I could imagine to be wrong:

* **Players just are frustrated by their lack of advancement**. So they are looking for some system to blame. The whole purpose of ELO ranking is that everyone's rank eventually stabilizes and they have a 50:50 win/lose rate. The idea is that this is the way players will enjoy the game the most. However, that's not always the case. Players want visible advancement and they want to win. If this is the case in your game, then some things you can try to tweak are:
    + Track the player's performance with other metrics which only ever go up and never down, like experience points, kill counts etc. Keep the ELO rating for matchmaking. But redesign your UI in a way which de-emphasizes the player's ELO rating and draws attention to the more motivating progression measurements.
    + Make losing fun. When you have a zero-sum game where each match has one winner and one loser, then it is of course impossible to make wins more frequent than loses. But what you can do is lessen the emotional impact of losing. Make sure that the player still has a positive experience and a feeling of accomplishment even if they don't win. This is a more complex issue which requires you to go into details about your game mechanics and how you present them, so if you are interested in more information, please open a new question.
* **Players keep playing against the same opponents.** This has two problems: The players can't grow their skills because they are always confronted with the same opponents using the same strategies and they can't grow their ELO rating quickly because they rarely face much stronger opponents. To fix this problems, widen the ELO bracket from which you select opponents. Also consider to take short-term performance into account. When a player is on a winning streak, give them a much stronger opponent so they have the opportunity to outgrow their current ELO rank. When a player is on a losing streak, give them a much weaker opponent to boost their confidence.
* **Players can't get out of "ELO hell" because the game won't let them.** They keep losing games against inferior opponents not because they make mistakes but because the random number generator seems to hate them or because your adaptive difficulty within the game itself goes over board and handicaps a winning player too much. To avoid this:
    + Make sure your game is less luck-based and the mechanics are more competitive. The random number generator might spice up the game by creating interesting situations, but it should not decide the game.
    + When one player dominates the other, make sure the game ends soon instead of extending it by giving the losing player an advantage.
* **Players can't get out of "ELO hell" because their teammates won't let them.** This is a problem in team-oriented multiplayer games where a team of strong players can lose when there is one bad (or worse: actively obstructive) player on the team who drags them down. If an individual strong player can't decide the game if they are not properly supported by their team, then the win/lose rating of an individual player doesn't accurately reflect their skill level. If that's the case:
    + Look for a way to measure player skill which is not solely bound to the success of the whole team. (but be careful to not encourage behavior which doesn't contribute to winning the match either)
    + Have a way for players to cope with obstructive players on their team and win nevertheless.
    + Provide ways for strong players to decide the match which do not require the cooperation of their team (even if that goes against the philosophy of team-based multiplayer games).

---
Tags: game-design, matchmaking
---


title: Alpha Blending older Images

text:
# Question
Title: Alpha Blending older Images
I am working on re-writing an old game, and have faced some issues with the older images that were used, the first thing we done was convert all the old images and set the alpha channel on black pixels so they are transparent, and then built our image libraries. However, the animated images have had some conversion issues it appears the edges of the images were not all set to true black so the conversion never set the transparency on these pixels. The value on the edges varies between R0 G0 B1-16 we have seen but we can't be sure as there is 1000s of images.

If we use additive blending it allows us to blend without showing the noisy outline but the additive blending does not display the images exactly how they should be to reproduce the old style of the game of course.

Question is, what options are available to either fix the image, or render it properly at run time using a HLSL.

I am hesitant to run a conversion on the known black ranges as we might miss a lot out and extending the range might set stuff we should set wrongly. Has anyone faced this before and how did you solve it?

# Answer
> 0 votes
It was the default blending state used in MonoGame, I rigged up a custom one as below.

Here is how it rendered before and how I wanted it to render:

```
var blend = new BlendState
{
     AlphaSourceBlend = Blend.InverseSourceColor,
     ColorSourceBlend = Blend.InverseDestinationColor,
     ColorDestinationBlend = Blend.One,
     AlphaDestinationBlend = Blend.One
};

```

The default blend state uses

```
ColorSourceBlend = Blend.One,
AlphaSourceBlend = Blend.One,
ColorDestinationBlend = Blend.InverseSourceAlpha,
AlphaDestinationBlend = Blend.InverseSourceAlpha,

```

# Answer
> 0 votes
Older games used a kind of cheap alpha blending emulation, called "additive blending", where visual effect sprite was just added to pixels in the framebuffer, instead of doing the complete blending equation.

When you see visual effects with black background, and without a hint of an alpha channel, they are meant to be blended using additive blending. You convert these images back into normal alpha-channel images by setting alpha channel to (R+G+B)/3. Similarly, converting alpha channel images into additive blended ones is done by blending on top of black background.

---
Tags: monogame, hlsl, alpha-blending, image-processing
---


# Question
Title: Why do games usually don't allow arbitrary window resize?
Why do games usually only allow some specific resolutions, instead of allowing arbitrary window resizing? Are there any technical difficulties for arbitrary window resizing?

# Answer
> 5 votes
There are plenty of games out there, some are from big studios, some use well established and battle tested tools, plenty don't. I can think of plenty of things that could go wrong when it comes to resolution.

*I am leaving aside the fact that on full-screen the monitor and driver combo will have a set of supported modes (and there is no point in emulating modes), and I am also leaving aside the fact that some platforms will force the resolution (some even handle the scaling).*

**Motivations for a minimum**:

* Some UI elements and spacing will just break if the window size is too small. Depending on you do your layout, you could end up computing negative sizes (e.g. position an element to leave a margin to the left and a margin to the right, and then there is no room for the element).
* Too small UI elements are bad accessibility. So you avoid your negative sizes by just scaling everything uniformly, now you can end up with too little space for texts, should you add a scroll bar? Tough luck, there is no room, gotta make that scroll bar tiny. ¡Arg! nobody can see it, let alone click it, and don't get me started on touch screens.
* Smaller resolution come with better performance. For a competitive game where responsiveness is an important consideration, having a resolution that is too small but performs better than the average could be seen as a form of cheating.

**Motivations for a maximum**:

* More pixels to draw is less performance. Although, granted, on a traditional pipeline the number of objects is the bottleneck.
* Your textures pixelate. You can have higher resolution textures – or if your engine allows, vector graphics – at a cost on performance.
* You have to worry about scaling up fonts. Will you allow more text on screen or use bigger text? The text could end up too small on the screen, because resolution and real screen size could change independently. This is an added difficulty.
* When it comes to a competitive game… similarly to how a small resolution could make things harder to click, a bigger resolution could make hit-boxes too easy. Assuming the developers are using a traditional pipeline with moderately sized textures and a limited number of objects on screen, the additional resolution has a small impact on performance… then the large hit-boxes are all win for the player, and thus an unfair advantage (over players with smaller screens) in the competitive game.

**Motivation to preserve aspect ratio**:

* You cannot just scale uniformly. If you choose to scale, you got to consider the aspect ratio to avoid distortions. The code is no big deal, but has consequences.
* Since you want to avoid distortions you will scale to match one axis (often the vertical), thus, a different aspect ration would mean that a player could see more of the world than another. Perhaps that is feature, perhaps that is an unfair advantage. Sounds like something to avoid if you hope to create an e-sport. Should you add black bars?
* That list view where the users picks whatever, it is perfect for some aspect ratios, on others it is a waste of space. On the list, unless you want distorted text, the text can only scale with the vertical, thus on a wide enough aspect ratio you are wasting a lot of space. Should it be a grid?
* How many columns should that grid have? We need to write code to determinate how many columns, considering the width of the text, with the added difficulty of keeping the columns the same width.
* You could flow elements instead. Now you need to figure out when to push an item to a new row. Advise: make all the elements the same size (perhaps by using an icon to represent them and dedicate a sidebar for the description of the selected item), so you do not have to deal with elements of different sizes. *Thankfully we get solutions to flow text in most environments, however, remember somebody had to solve that.*

**Motivations for discrete resolutions**:

* If you support only a discrete set of resolutions, you do not need code to decide how to flow or to compute number of columns. Why? Because you can solve and hard-code the solutions for a discrete number of cases.
* Not all layouts make sense. Going back to the problem of having a resolution that is too small, perhaps you could flow elements. That sidebar should be pushed to a footer if the resolution is too narrow. Do we want to handle that dynamically?
* It can be hard to convey to user where things are if they can move around.

Extra wrench: we should let the user scale up the text and the UI elements for accessibility. Yeah, plenty of games do not have that.

We effectively need modern browsers' CSS to deal with all of it with relative ease. However, most game engines and UI tool-kits designed to integrate with games don't have tools that are that powerful. If there aren't available for the platform & engine & language combo you use... It is much easier to support a discrete set of resolutions on which we can test the game, than to retrofit content flow on a UI solution that does not support it, or roll your own. *And even if you have a good UI toolkit, you still should have a minimum.*

This is particularly true if you do not have developers working exclusively on the UI. Arguably you should have them, if you can afford them. Can you? How many? Perhaps you should be placing resources in making a more entertaining and fun game, in particular if you are an indie developer or a small studio. *Unless the game is about resizing windows.*

The flip side is when we are a big studio, have developers working exclusively on the UI, and we are making an e-sport-ish competitive game. We do not want to give unfair advantages to players such as extra performance with small resolution, or extra field of view. Nor we want players taking advantage of high resolution for ease of aiming.

# Answer
> 2 votes
It’s already something of a chore to support multiple fixed window sizes and aspect ratios in terms of UI scaling, managing the visible play area (especially in some kinds competitive games), render target sizing and compositing, and so on. Just look around here at the number of questions focused on aspect ratio handling and scaling issues.

The added difficulty of an effectively infinite number of width / height combinations often doesn’t seem worth the effort as most of the time folks play games such that the game takes over the full real estate of the display.

More casual games, which may be played in non-full screen windowed mode more commonly tend to support it. But those casual games have found a more welcoming home on mobile platforms in the last decade, where it’s generally not possible to do arbitrary window sizes anyhow.

---
Tags: window-management
---


# Question
Title: How should I structure the layout and saving system of my game concept?
I am a huge fan of Minecraft and (to an extent) Terraria. I’ve always wanted to make my own version of that type of Creative sandbox game, and recently I’ve been thinking of so many things I could add to it.

The game I’m imagining is a very different style from these two games. It’s 3D, and cartoony to a point but not too cartoony to not be realistic. I’m talking more realistic than Fortnite’s style but I definitely do not want to attempt to make a photo-realistic game.

I want my games world to be more fluid than the worlds of Minecraft and Terraria. I don’t want the player to be necessarily limited to a grid of blocks, though that should maybe be implemented at some points, like when the player is placing pieces of a structure down (blocks).

Generated structures such as trees, rocks, and the terrain I don’t really want to be blocky or constrained to a set grid.

The things that I see players being able to place into the world are things like wood columns to form the base of a house, wall blocks for a house, tables and chairs, doors, and different blocks required to create different items.

I like how the Minecraft and Terraria worlds are generated and saved. It’s simple: each coordinate is a block and that can be stored away very easily. I still haven’t figured out how I can save the type of world I want in my game, though.

So my question is: how should I structure the terrain, structures, and player-placed blocks layout/saving system so that I can save it efficiently and write it relatively simply as well?

Something I’ve thought about: there is a mod for Minecraft called the no cubes mod which essentially removes all the cubes from the game and seamlessly blends blocks together. That might be a good way to make this game since the blocks are still stored the same way but they are not actual blocks, and terrain can be made more realistic through this method.

# Answer
A lot of game with modifiable terrain actually use a grid structure to store blocks internally (called "voxels" in game dev terminology, which is short for "volumetric pixels") but they are using processing algorithms like Marching Cubes to smooth them and make them look less blocky. A more advanced algorithm is Dual Contouring. Developers have come up with a lot more interesting algorithms to smooth out voxel data into good looking high-polygon landscapes. Judging from the screenshots, the "No cubes" Minecraft mod seems to do the same thing.

The advantage of voxels is that each block is just a number in a 3-dimensional array which represents the type. The location of the block is derived from its location in the array. That results in very little memory usage per block. And on top of that, the terrain data is usually pretty compressible with standard compression algorithms like Deflate or LZW, so you can save space when you save chunks of terrain to disk or exchange them via network.

If you have objects which are not constrained to integer-coordinates within the grid, then you usually store their position as a set of floating-point coordinates within each object.
> 1 votes

---
Tags: game-design, game-mechanics
---


title: Infinite Loop in AStar (A*) Algorithm

text:
# Question
Title: Infinite Loop in AStar (A*) Algorithm
Alright, so I've run into a problem where when trying to find a path that you cannot reach because it is blocked, it will continually loop and loop and loop (the 'open' list is ALWAYS filled). I understand the open set cannot contain things that the closed set contains. I cannot understand where the open set is getting things from the closed set.

I make sure to check if the neighbor is within the closed set, so it shouldn't be added to the open set. I'm confused...

```

    public static LinkedList<Node> findPath(World world, Node start, Node goal) {
        final PriorityQueue<Node> open = new PriorityQueue<>();
        final HashSet<Node> closed = new HashSet<>();

        open.add(start.setHeuristic(start.heuristic(goal)));
        Node current = null;
        Node best = start;
        while (!open.isEmpty()) {
            current = open.poll();
            if (current.equals(goal))
                return construct(start, current);
            closed.add(current);
            Tile tile = world.getTile(current.getX(), current.getY(), current.getZ());
            ArrayList<Tile> neighbors = tile.getNeighbors();
            for (Tile n : neighbors) {
                if (n == null)
                    continue;
                Node neighbor = new Node(n.getGlobalX(), n.getGlobalY(), n.getZ(), current);
                neighbor.setCost(neighbor.distance(current));
                neighbor.setHeuristic(neighbor.heuristic(goal));
                if (closed.contains(neighbor))
                    continue;
                closed.add(neighbor);
                if (!n.isWalkable())
                    continue;
                if (neighbor.equals(goal))
                    return construct(start, neighbor);
                double tentative_cost = current.getCost() + current.distance(neighbor);
                if (!open.contains(neighbor) || tentative_cost < neighbor.getCost()) {
                    best = neighbor;
                    neighbor.setCost(tentative_cost);
                    open.add(neighbor);
                }
            }
        }
        return construct(start, best);
    }

    private static LinkedList<Node> construct(Node start, Node goal) {
        LinkedList<Node> path = new LinkedList<>();
        Node last = goal;
        while (!last.equals(start)) {
            path.addFirst(last);
            last = last.getParent();
        }
        path.addFirst(start);
        return path;
    }

```

Node class

package com.entity.world.path;

import java.util.Objects;

/**
 * @author Albert Beaupre
 *
 */
public class Node implements Comparable<Node> {

    private final int x, y, z;
    private final Node parent;
    private double cost, heuristic;

    public Node(int x, int y, int z) {
        this.x = x;
        this.y = y;
        this.z = z;
        parent = this;
    }

    public Node(int x, int y, int z, Node parent) {
        this.x = x;
        this.y = y;
        this.z = z;
        this.parent = parent;
    }

    public double distance(Node from) {
        double dx = Math.pow(Math.abs(from.x - x), 2);
        double dy = Math.pow(Math.abs(from.y - y), 2);
        return Math.sqrt(dx + dy);
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    public int getZ() {
        return z;
    }

    public Node getParent() {
        return parent;
    }

    public double getCost() {
        return cost;
    }

    public Node setCost(double cost) {
        this.cost = cost;
        return this;
    }

    public double getHeuristic() {
        return heuristic;
    }

    public Node setHeuristic(double heuristic) {
        this.heuristic = heuristic;
        return this;
    }

    public double getF() {
        return cost + heuristic;
    }

    public double heuristic(Node goal) {
        double dx = Math.abs(x - goal.x);
        double dy = Math.abs(y - goal.y);
        return Math.sqrt(dx + dy);
    }

    @Override
    public int hashCode() {
        return Objects.hash(x, y, z);
    }

    /**
     * {@inheritDoc}
     */
    public boolean equals(Object o) {
        if (o instanceof Node) {
            Node n = (Node) o;
            return x == n.x && y == n.y && z == n.z;
        }
        return false;
    }

    /**
     * {@inheritDoc}
     */
    public String toString() {
        return "[x=" + x + ", y=" + y + "]";
    }

    /*
     * (non-Javadoc)
     *
     * @see java.lang.Comparable#compareTo(java.lang.Object)
     */
    public int compareTo(Node o) {
        return Double.compare(getF(), o.getF());
    }

}
```
</code></pre>

# Answer
> 2 votes
There are a few misunderstandings of A\* here.

1. You add every node to the closed set before you add it to the open set, but that's strictly speaking premature: at this point, we know we've found *a* route here, but we don't yet know whether it's the shortest route possible.

We know we've found the shortest route to `current`, since it was at the head of the priority queue. If there were any shorter route available, we'd have processed it earlier. But we can't say what might be next in queue. Let's say `current` has a link of length 2 to reach `neighbor`. If the very next node in the queue is no further than `current`, and has a link of length 1 to reach `neighbor`, then there's still a shorter route to be found later on. So we can't close it off just yet.

For the same reason, we can't return a path to the goal from inside the neighbour enumeration loop - we might return a longer-than-optimal route if we do.

You *can* make these assumptions if all your links have the same length, but if that's the case then you might do better with breadth-first search instead of the complexity of A\*.
2. What you're doing with `tentative_cost` isn't meaningful.

Given that you compute both `tentative_cost` and your first pass at `node.setCost()` using the same distance calculation, but you add `current_cost` to `tentative_cost`, it will never be less than `node.getCost()`.

It looks like you might be trying to selectively replace a node in the open set queue if you've found a faster route there. You can do this by...

* calculating the correct cost in the first place (including `current.getCost()`),
    * walking the open set queue to find the current instance of the node if there is one
        + if there is, and it has cost less than or equal to the one you're considering, continue without adding a copy
        + if there is, and it has more cost than than the one you're considering, remove it from the queue
    * finally, add your new node, if you haven't already earlied-out

Below, I'll show a simpler approach where we just let bad nodes accumulate in the queue, knowing we'll look at the best ones first anyway. But this can strictly be improved upon.

If you're trying to find the path that gets closest in the event that none reach the goal, then you need to keep track of the closest you've seen in your whole search and compare against that.
3. Your heuristic can be improved. Currently you're paying the expensive part of a Euclidean heuristic (the square root) but getting a substantial under-estimate because you're missing the squares on each term inside. This will make every direction look closer than it really is (assuming your distances are \>= 1, otherwise this heuristic is inadmissible), weakening A\*'s ability to select the closest routes.

```
public double heuristic(Node goal) {
    double dx = (x - goal.x);
    double dy = (y - goal.y);
    return Math.sqrt(dx*dx + dy*dy);
}
```

You can apply this same form to your `distance` function to skip the `abs` and `pow`
4. You can rearrange your early-outs to better prune out unnecessary work.

Here's a rewrite of your core loop fixing some of these issues:

```
double leastHeuristic = Double.POSITIVE_INFINITY;

while (!open.isEmpty()) {
    current = open.poll();

    // We already found a faster route here. Discard a bad dupe.
    if (closed.contains(current))
        continue;

    if (current.equals(goal))
        return construct(start, current);

    // No shorter route can be found to this node. Close it out.
    closed.add(current);
    // Log best only as we close-off nodes (happens less often than adding dupes).
    if(current.getHeuristic() < leastHeuristic) {
        leastHeuristic = current.getHeuristic;
        best = current;
    }

    Tile tile = world.getTile(current.getX(), current.getY(), current.getZ());
    ArrayList<Tile> neighbors = tile.getNeighbors();

    for (Tile n : neighbors) {
        // We don't care if we can't walk on it.
        if (n == null || !n.isWalkable())
            continue;

        Node neighbor = new Node(n.getGlobalX(), n.getGlobalY(), n.getZ(), current);

        // We already found the shortest possible route to this node.
        if (closed.contains(neighbor))
            continue;

        neighbor.setCost(current.cost + neighbor.distance(current));
        neighbor.setHeuristic(neighbor.heuristic(goal));

        open.add(neighbor);
    }
}

```

---
Tags: java, path-finding, path, path-tracing
---


# Question
Title: How can I apply UV mapping in parent space?
I'm trying to apply UV mapping in parent space - ie. taking into account the object's own transformation matrix but no matrices further up the transformation hierarchy.

For example, I'd want to be able to transform a cube mesh (rotate/scale) and have UVs based on that, not the mesh vertices themselves. Then any transforms above that would not impact that object’s UVs.

What’s the best way to access the local transform matrix of an object in a shader in Unity?

I know that I can use objectToWorld to get access to the entire hierarchy’s flattened transform matrix, but I want to specifically access only the bottom most transform (the local one produced by the transform component on an object)

Do I have to pass this in as a custom variable each frame? Or is there a better method to use?

# Answer
> 1 votes
I think you're right that the only way to get this is to pass a custom variable each frame:

```
public class LocalMatrixToShader : MonoBehaviour
{
    Renderer _renderer;

    static MaterialPropertyBlock _block;
    static int _propertyIndex;

    void Start()
    {
        _renderer = GetComponent<Renderer>();

        if(_block == null) {
            _block = new MaterialPropertyBlock();
            _propertyIndex = Shader.PropertyToID("_LocalMatrix");
        }
    }

    void LateUpdate()
    {
        var worldToParent = transform.parent == null ?
                     Matrix4x4.identity
                     : transform.parent.worldToLocalMatrix;

        var localToParent = worldToParent * transform.localToWorldMatrix;

        _block.SetMatrix(_propertyIndex, localToParent);
        _renderer.SetPropertyBlock(_block);
    }
}

```

---
Tags: unity, shaders, hierarchy
---


title: Bizarre Physics FixedUpdate Lag spikes

text:
# Question
Title: Bizarre Physics FixedUpdate Lag spikes
So I have this large forest of around 2M tris:

Same chunk selected with view on the whole level:

It's been generated within Blender and exported as fbx into Unity. Exporting each tree as an individual object is very performance expensive so the whole forest is split into 2 Objects: Treetrunks and leaves. The Treetrunks all have meshcolliders on them, the leaves obviously don't. (However I do split the forest into chunks as seen above, each chunk roughly 400k tris)

When the Player gets outside visible range of the forest it is disabled, and enabled when the Player gets within a certain range. When it is enabled ***sometimes*** it causes a massive lag. When looking into the Profiler it shows this:

Physics? FixedUpdate? The leaves have absolutely no colliders on them, why does it take up Physics.Processing? So I wanted to search further what part of Physics.Processing takes up so much processing time but the top process already shows nothing:

I have an 8 year old GTX760 but it still manages to render the entire forest at 200fps so no, the 2 million Tris are definitely not overkill for my computer.

I've tried this and that and 3 things managed to stop the issue (as seen in the profile screenshots above, the Physics processing time significantly reduced a few frames later)

* Pausing & Unpausing the game or simply Alt-Tabbing outside the Unity Player and back (not always effective)
* Disabling the Player & Reenabling it (almost always effective)
* Starting the Scene with the Player (including Rigidbody, Camera and raycasting scripts) disabled and enabling him a few seconds later via script. (almost always effective) However this only worked if ***ALL*** of the forest was set active (roughly 2M tris). If half the forest was disabled on start, and activated after the Player was enabled: LAG.

The Player is the only thing in the game (at this moment) that has a Rigidbody, Raycasting Scripts and a camera.

Things that didn't work:

* Waiting a few minutes
* Disabling & Reenabling the Players Character Controller at any time
* Disabling & Reenabling the camera on the Player at any time.
* Disabling & Reenabling the fucking trees

Anyone got an idea? I'm dumbfounded over here.

# Answer
> 1 votes
I reduced the Polygon count on each object to below 65536 and it removed all issues. Don't know wether 65536 is the magic number here, but it's certainly one of the most common "magic numbers" so I went with it. Maybe someone can explain why.

---
Tags: unity, physics, debugging, profiler
---


title: LibGDX FileHandle does not delete file

text:
# Question
Title: LibGDX FileHandle does not delete file
I'm using this line of code to delete a file:

```
if(Gdx.files.local("/files/ids.json").exists()) {
   Gdx.files.local("/files/ids.json").delete();
}

```

The same code works for all previous levels except the last one. The file does exist, but the `delete()` method returns `false`.

Any help would be greatly appreciated as it has exhausted me. I've seen similar topics in Java but nothing has worked for me. It's really weird that the same code works in some cases.

**Edit**

Also, in case this provides any information, when I step through the program with the debugger, the `delete()` returns `true`.

# Answer
> 0 votes
You are missing a bracket there in if statement

> Gdx.files.local("/files/ids.json").exists()**)**

I wonder how that code got compiled in the first place

If you just missed it while writing the post, then make sure that file is not used somewhere else when you are trying to delete it.

There is that scenario when delete() method returns false:

the **delete** method looks like this:

```
public boolean delete () {
    if (type == FileType.Classpath) throw new GdxRuntimeException("Cannot delete a classpath file: " + file);
    if (type == FileType.Internal) throw new GdxRuntimeException("Cannot delete an internal file: " + file);
    return file().delete();
}

```

and the delete from **file.delete()** looks like this :

```
public boolean delete() {
    SecurityManager security = System.getSecurityManager();
    if (security != null) {
        security.checkDelete(path);
    }
    if (isInvalid()) {
        return false;
    }
    return fs.delete(this);
}

```

You can notice the **isInvalid()** method which is checking for a NULL character in the path (basicly checks if the the path is invalid) :

```
/**
 * Check if the file has an invalid path. Currently, the inspection of
 * a file path is very limited, and it only covers Nul character check.
 * Returning true means the path is definitely invalid/garbage. But
 * returning false does not guarantee that the path is valid.
 *
 * @return true if the file path is invalid.
 */
final boolean isInvalid() {
    if (status == null) {
        status = (this.path.indexOf('\u0000') < 0) ? PathStatus.CHECKED
                                                   : PathStatus.INVALID;
    }
    return status == PathStatus.INVALID;
}

```

Im mentioning that because i have been in situations when i used strings that contained weird unicode chars in it and even thou I couldn't see it normally it was there and IntelliJ was the root cause (what came out much later). Make sure that the path you specified is correct, try to invalidate the files, clean and rebuild the project.

---
Tags: libgdx, file
---


title: Screen Space vs World Space Canvas

text:
# Question
Title: Screen Space vs World Space Canvas
When should I use one over the other? I'm pretty sure I understand the key differences, but I'm not sure which use cases would prefer one over the other. For example, let's say I have objects on the ground in my 3D game and they have UI Images above them with the objects' names. Which method is better? Should I stick to world space for objects which are located in the 3D world and screen space for overlay type stuff?

# Answer
The Unity Canvas has three different modes, the two you're asking about are:

Screen Space-

> This render mode places UI elements on the screen rendered on top of the scene.

This is the typical UI. It exists on top of everything else in the view. Useful for things like menus, heads up displays and overlays.

World Space-

> In this render mode, the Canvas will behave as any other object in the scene.

This is for in-game UIs. Where you want the UI to appear to be like an object in game. Useful for nametags, in-game computer screens and diegetic interfaces.

---

> Should I stick to world space for objects which are located in the 3D world and screen space for overlay type stuff?

Yes, that's exactly how you should use them. One is not better than the other, they are each better at different things.
> 5 votes

# Answer
Unity Canvas are widely used and accordingly to Unity's documentation we have three types of it:

1. **Screen Space - Overlay**

> This render mode places UI elements on the screen rendered on top of the scene . If the screen is resized or changes resolution, the Canvas will automatically change size to match this.

2. **Screen Space - Camera**

> This is similar to Screen Space - Overlay, but in this render mode the Canvas is placed a given distance in front of a specified Camera . The UI elements are rendered by this camera, which means that the Camera settings affect the appearance of the UI. If the Camera is set to Perspective, the UI elements will be rendered with perspective, and the amount of perspective distortion can be controlled by the Camera Field of View. If the screen is resized, changes resolution, or the camera frustum changes, the Canvas will automatically change size to match as well.

3. **World Space**

> In this render mode, the Canvas will behave as any other object in the scene. The size of the Canvas can be set manually using its Rect Transform, and UI elements will render in front of or behind other objects in the scene based on 3D placement. This is useful for UIs that are meant to be a part of the world. This is also known as a “diegetic interface”.

The *main difference* is that in World Space the Canvas units are in metters whereas in Screen Space they are pixels relative to screen's resolution.

As rule of thumb, if we were to consider creating a VR environment we will probably use World Space Canvases instead of Screen Space Canvases (pretty much what you said).
> 3 votes

---
Tags: unity
---


# Question
Title: Is it really more efficient to have a local variable for transform here or is Rider being over-zealous?
I'm just going through a quick C# / Unity crash course (coming from Java) and I recieved a warning about "Repeated property access of a built-in component is inefficient" while working in Jetbrains Rider for the following code snippet.

```
if (Mathf.Abs(horizontalMovement) > Mathf.Epsilon) {
        horizontalMovement += horizontalMovement * Time.deltaTime;
        var position = transform.position;
        horizontalMovement += position.x;

        position = new Vector2(horizontalMovement, position.y);
        //warning is for this line
        transform.position = position;
    }

```

It was already complaining about using transform.position.x and transform.position.y which seemed fair enough so I created the position var but would declaring `var cachedTransform = transform; ...; cachedTransform.position = position` really be more performant here or is the overhead of creating the local variable just going to negate it?

I'm not asking if this is a valid warning in general, it seems to be. I'm asking if it's valid when you're literally just reassigning in the same statement as I am in the last line of my code above

For reference here's what I would end up with if I followed the warning -

```
 if (Mathf.Abs(horizontalMovement) > Mathf.Epsilon) {
            horizontalMovement += horizontalMovement * Time.deltaTime;
            var cachedTransform = transform;
            var position = cachedTransform.position;
            horizontalMovement += position.x;

            position = new Vector2(horizontalMovement, position.y);
            cachedTransform.position = position;
        }

```

# Answer
> 4 votes
Sinse you are new to C#, make sure you read up on properties if you haven't already done so. Because over-simplified, they are basically special methods that look like a variable to the end user.

Due to them actually being methods, the C# compiler can't know for sure what you are doing to retrieve the value. So that warning might be over-zealous yes, but that depends on the actual property in question. So if you create a property that does a lot of stuff and is very slow as a result, then you get a huge benefit by caching it. If your property is basically just returning a backed field without any checks, then there is little to no benefit caching the property.

On whether the transform property in your question is fast/slow and therefore needs to be cached, see this forum post (I advise you to read the whole thing, or just test it yourself to be sure).

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


# Question
Title: Selling Android game with using Google Play Games
I'm making an Android Game that using Google Play Games for authentication, and storing user data to cloud.

Originally I planned this game as free, and put some in-app-purchasement stuffs in it, but unfortunately there is a serious technical issue, so that I have to rid off IAP from my game.

I spent lots of my time to developing this game, and I want to get some reward from my work, so I decided to sell this stuff with reasonable cheap price, but is it ok to sell the game that using Google Play Games? I googled it already, but couldn't find any related information about this.

# Answer
> 1 votes
Yes, it's totally OK to use Google Play Games in both free and premium apps.

You just have to accept the Google Play Games Services Terms of Service and Google APIs Terms of Service.

You agree to accept these terms when you use the API.

---
Tags: unity, android, google-play
---


# Question
Title: Alpha Blending in Software with Gamma Correction
How does one efficiently implement alpha blending, without botching gamma?

Alpha blending is basically the following expression:

```
result_color = (dst_color*src_alpha - dst_color*src_alpha*dst_alpha + src_color - src_color*src_alpha)/(1 - src_alpha*dst_alpha)
result_alpha = src_alpha*dst_alpha

```

The formula is unusual because I use inverted alpha, where 0 means opaque and 1 - completely transparent. Rationale: many CPUs have instruction to compare with zero, but no instruction to compare with 0xff000000. Also, I can pass just 0xRRGGBB to set\_pixel instead of 0xffRRGGBB for opaque color.

For gamma-packed 8-bit RGB I've managed to implement that expression somewhat efficiently in early 90ies style code:

```
void ablend(int dr,int dg,int db,int da, int *sr,int *sg,int *sb,int *sa) {
  int ya = (da * *sa)>>8;
  uint32_t d = idiv_lut[255 - ya];
  uint8_t *st = ab_lut[255 - *sa];
  uint8_t *dt = ab_lut[*sa - ya];
  *sr = ((dt[dr] + st[*sr])*d)>>8;
  *sg = ((dt[dg] + st[*sg])*d)>>8;
  *sb = ((dt[db] + st[*sb])*d)>>8;
  *sa = ya;
}

```

Obviously working with RGB, without unpacking it first, produces incorrect result (it is the most common graphics programming pitfall), so they must be unpacked (i.e. pow(x,2.2)), and now one can't use ab\_lut anymore, because it would require 2^30 bytes, and replacing division with multiplication would be impossible on a 32-bit system either.

Give that, this question implies some side questions:

1. Is using float the only solution for unpacked RGB processing?
2. How can I perform alpha blending with gamma correction?
3. Is it worth it (L1 cache-wise) to still use gamma packed sRGB, instead of a simple array of 4 32-bit float R,G,B,A components, or would memory access become a bottleneck on a majority of CPUs?

So maybe I just have this 90's mindset, where keeping data size small meant difference between 1 and 60 frames per second, and today we can safely use as many additional bytes as required?

# Answer
Most games don't do blending in gamma space.

Instead, on read, we'll unpack a gamma-encoded source into linear RGB. Our calculations, blending, and intermediate storage are all in linear space.

Then, once we've fully composited the frame we want to display, then at that time we'll perform gamma encoding to convert it into the right curve for display.

This can cut down on the total number of gamma calculations you need to do in a blending-heavy scene with lots of overdraw, making the calculations you do frequently cheap and saving the expensive stuff for a batch at the end. I'd expect this to typically be faster than adapting all of your blending operations to occur in gamma space.

If we're using a low bitdepth format for intermediate storage - like 8 bpc / 4 Bpp - then this linear working space does entail some information loss. Two different gamma-encoded colour values could decode and quantize to the same value when stored in 8 bits of linear space, then recompress back to the same value, and some gamma-encoded values might be skipped (have no 8-bit pre-image in linear space), leading to subtle banding artifacts. You'll see this in some older games in particular.

As you say, you can store your colours as floats to maintain high precision throughout all your intermediate calculations and storage, at the cost of quadrupling the data size up to 16 Bpp and needing floating point math (something we tend to take for granted on GPUs made to chew through floats). Whether that's a desirable trade-off for your use case is something you'll need to profile and evaluate for yourself.

You can also go halfway, say decoding to 16 bpc / 8 Bpp. This is a halfway step, giving you a compromise of storage efficiency between 8 bpc and float, while still gaining 256 times the precision - enough to eliminate most banding.

Or, since you're doing this in software and aren't bound by conventionally-supported GPU types, you can use custom solutions. Like for instance decoding your sRGB into linear YCbCr to use as your intermediate. This is a linear transformation of linear RGB space, so it's fast to convert back and forth, and it doesn't introduce non-linearity into any of our familiar colour blending operations. Its main feature is that it concentrates the luminance information to which the eye is most sensitive in the Y channel. So you could store 2 bytes for luminance and just one for each chromaticity channel (and either one or two for alpha, for a 5-6 Bpp total), to get back in the ballpark of 8 bpc / 4 Bpp storage compactness. This is the same trick that JPEG and video compression codecs use to concentrate their limited data payload on the signals with the most perceptual impact.
> 0 votes

---
Tags: graphics-programming, alpha-blending
---


# Question
Title: Unity 2D: Smooth ease-out movement on grid
I'm trying to create a **grid movement in Unity**, as where the player will ease-out on a tile when stopping, but I can't seem to get it right. I need a little nudge in the right direction for how to implement something like this:

I used a coroutine to execute the movement when input is requested and use an ease-out curve to make the player stop smoothly. But, when walking multiple tiles it is jittery because the ease-out is applied. Also, the smoother I want the ease-out to be, the slower the player moves.

My full code.

```
public float moveDuration = .5F;
public AnimationCurve moveCurve = AnimationCurve.Linear(0F, 0F, 1F, 1F);

private Rigidbody2D rigidBody;
private BoxCollider2D boxCollider;
private bool isMoving;

void Start() {
    rigidBody = GetComponent<Rigidbody2D>();
    boxCollider = GetComponent<BoxCollider2D>();
}

void Reset() {
    moveSpeed = 8F;
    moveDuration = .5F;
    moveCurve = AnimationCurve.Linear(0F, 0F, 1F, 1F);
    isMoving = false;
}

void Update() {
    if (!isMoving) {
        int x = 0;
    int y = 0;

    x = (int)(Input.GetAxisRaw("Horizontal"));
    y = (int)(Input.GetAxisRaw("Vertical"));
    if (x != 0) y = 0;
    if (x != 0 || y != 0) {
            AttemptMove(x, y);
        }
    }
}

private void AttemptMove(int x, int y) {
    Debug.Log("Attempt move: "+x+","+y);

    Vector2 startPosition = transform.position;
    Vector2 endPosition = startPosition + new Vector2(x, y);

    StartCoroutine(SmoothMovement(endPosition, moveDuration));
}

protected IEnumerator SmoothMovement(Vector3 endPosition, float duration) {
    float elapsed = 0F;
    Vector3 startPosition = transform.position;

    isMoving = true;

    while (elapsed < duration) {
        Vector3 newPosition = Vector3.Lerp(startPosition, endPosition, moveCurve.Evaluate((elapsed/duration)));

        rigidBody.MovePosition(newPosition);
        elapsed += Time.deltaTime;
        yield return null;
    }

    isMoving = false;

}

```

# Answer
you have mentioned that you want to ease the movement in or out. in this case you do not want to use lerp with a linear percentage of progress.

the problem

> Also, the smoother I want the ease-out to be, the slower the player moves.

you are looking for Easing Curves. a different type of curve achieves a different gradient of smoothing and thus allows for appropriate smoothness without changing duration. i may be missing something, but your animation curve class appears to be using a linear curve. i believe you want a Quadratice curve if i am understanding you correctly.

```
moveCurve = AnimationCurve.Linear(0F, 0F, 1F, 1F);

```

needs to be something like

```
moveCurve = AnimationCurve(new Keyframe(0, 0), new Keyframe(.5f, .8f), new Keyframe(1, 1))

```

https://easings.net/en

when faced with similar problems, i actually dislike unity's animation classes, however I wont tell you to use a 3rd party for something natively supported. If you want to use the above line of code to try solving the problem you can,

if you want something a little more straight forward with more fine grain control. Without going to the trouble of writing a bunch of classes, you could simply add a function

```
Tween(float percentage){
    var val = //YOUR EASING CURVE HERE
    return val
}

```

for tile movement i recommend a Quartic Ease Out. and if you refer to one of many sites which elaborate on such curves you can find a straight forward function to convert a linear percentage to this percentage

http://www.gizma.com/easing/

```
//quartic easing out - decelerating to zero velocity

Math.easeOutQuart = function (t, b, c, d) {
    t /= d;
    t--;
    return -c * (t*t*t*t - 1) + b;
};

```

Further, in a similar situation to yours, i found that the smoothest appearance of movement is actually for new movement to immediately stop the current movement where it is. and start a movement to the new destination. depending on if you want to restrict movement time you can set the new movement's time to equal normal movement time + the cancelled movement's remaining time

I also found(in high performance situations) that coroutines do not invoke regularly as reliably as Invoke repeating. this may add to smoothness if you are observing missing frames of movement.
> 0 votes

# Answer
Should only call the smooth when the player intends to stop moving so let's say. I am not sure if u have player class or if u have multiple class calling function so here is two different ways to do. 2nd way u would inherit from with you player and just call the function.

PLAYERCLASS

Psuedocode If player press walk input Apply movement without smoothing.

If player release walk input Apply smoothing.

SMOOTHING CLASS.

If movement is applied and player still pressing walk input Apply walk without smooth. Else player has released the walk input Apply smooth
> 0 votes

---
Tags: unity, 2d, movement, grid
---


# Question
Title: Instantiate player prefab using player data
When my scene loads, I want to add my prefab to it along with its components.

Here is what I mean:

1. scene loads
2. player gender is determined via playerprefs or playfab sdk
3. player prefab is loaded and displayed using said gender

The prefab would have a script components attached for the current data etc.

I might be approaching this wrong, but I want this to work with multiplayer in the future, so that's why I didn't just add the prefab directly to the hierarchy.

What is the correct way of doing this?

# Answer
> 0 votes
Can you use DontDestroyOnLoad for your player ? Maybe you could use an external script that assign what you want in your player script depending of what you want. Ex:

```
GameObject player;

void Start()
{
    player = GameObject.Find("player");
    if(//insert condition)
    {
        player.GetComponent<playerManager>().gender = "man";
    }
}

```

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


# Question
Title: Implementing a main loop with rendering in a Windows Desktop Application
I'm writing the beginnings of a small game engine in Visual C++. What I have so far doesn't seem to be updating the rendering each frame, but I don't understand where I'm going wrong with it.

The code is mostly the boilerplate that Visual Studio generates. I added the `draw()` and `main_loop()` functions.

```
#include "stdafx.h"
#include "Windows.h"

#include "Keyboard.h";
#include "Photon.h"
#include "Player2D.h"

#define MAX_LOADSTRING 100

// Global Variables:
HINSTANCE hInst;                                // current instance
HWND Window;
WCHAR szTitle[MAX_LOADSTRING];                  // The title bar text
WCHAR szWindowClass[MAX_LOADSTRING];            // the main window class name
Player2D player;
Keyboard keyboard;

// Prototypes
ATOM MyRegisterClass(HINSTANCE hInstance);
BOOL InitInstance(HINSTANCE, int);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM);
void draw ();
void main_loop ();

int APIENTRY wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPWSTR lpCmdLine, _In_ int nCmdShow)
  {
  UNREFERENCED_PARAMETER(hPrevInstance);
  UNREFERENCED_PARAMETER(lpCmdLine);

  // Initialize global strings
  LoadStringW(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
  LoadStringW(hInstance, IDC_PHOTON, szWindowClass, MAX_LOADSTRING);
  MyRegisterClass(hInstance);

  // Perform application initialization:
  if (!InitInstance (hInstance, nCmdShow))
    {
    return FALSE;
    }

  HACCEL hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_PHOTON));

  MSG msg;

  // Main message loop:
  while (GetMessage(&msg, nullptr, 0, 0))
    {
    if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
      {
      TranslateMessage(&msg);
      DispatchMessage(&msg);
      }
    }

    return (int) msg.wParam;
  }

// Registers the window class.
ATOM MyRegisterClass(HINSTANCE hInstance)
  {
  WNDCLASSEXW wcex;

  wcex.cbSize = sizeof(WNDCLASSEX);

  wcex.style          = CS_HREDRAW | CS_VREDRAW;
  wcex.lpfnWndProc    = WndProc;
  wcex.cbClsExtra     = 0;
  wcex.cbWndExtra     = 0;
  wcex.hInstance      = hInstance;
  wcex.hIcon          = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_PHOTON));
  wcex.hCursor        = LoadCursor(nullptr, IDC_ARROW);
  wcex.hbrBackground  = (HBRUSH)(COLOR_WINDOW+1);
  wcex.lpszMenuName   = MAKEINTRESOURCEW(IDC_PHOTON);
  wcex.lpszClassName  = szWindowClass;
  wcex.hIconSm        = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));

  return RegisterClassExW(&wcex);
  }

// In this function, we save the instance handle in a global variable and
// create and display the main program window.
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
  {
  hInst = hInstance; // Store instance handle in our global variable

  Window = CreateWindowW(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
  CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, nullptr, nullptr, hInstance, nullptr);

  if (!Window)
    {
    return FALSE;
    }

  ShowWindow(Window, nCmdShow);
  UpdateWindow(Window);

  return TRUE;
  }

// Processes messages for the main window.
//  WM_COMMAND  - process the application menu
//  WM_PAINT    - Paint the main window
//  WM_DESTROY  - post a quit message and return
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
  {
  main_loop ();

  switch (message)
    {
    case WM_COMMAND:
      {
      int wmId = LOWORD(wParam);
      // Parse the menu selections:
      switch (wmId)
        {
        case IDM_ABOUT:
          DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
          break;

        case IDM_EXIT:
          DestroyWindow(hWnd);
          break;

        default:
          return DefWindowProc(hWnd, message, wParam, lParam);
        }
      }
    break;

    case WM_DESTROY:
      PostQuitMessage(0);
      break;

    default:
      return DefWindowProc(hWnd, message, wParam, lParam);
    }
  return 0;
  }

// Message handler for about box.
INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
  {
  UNREFERENCED_PARAMETER(lParam);
  switch (message)
    {
    case WM_INITDIALOG:
      return (INT_PTR)TRUE;

    case WM_COMMAND:
      if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
        {
        EndDialog(hDlg, LOWORD(wParam));
        return (INT_PTR)TRUE;
        }
      break;
    }
  return (INT_PTR)FALSE;
  }

void main_loop ()
  {
  player.x += 1;
  draw ();
  }

void draw ()
  {
  PAINTSTRUCT ps;
  HDC hdc = BeginPaint (Window, &ps);

  // clear background
  RECT screen;
  GetWindowRect (Window, &screen);
  screen.left = 0;
  screen.top = 0;
  COLORREF color_black = RGB (0, 0, 0);
  COLORREF color_red = RGB (255, 0, 0);
  HBRUSH brush_black = CreateSolidBrush (color_black);
  HBRUSH brush_red = CreateSolidBrush (color_red);
  FillRect (hdc, &screen, brush_black);

  player.position_rect ();
  FillRect (hdc, &player.render_rect, brush_red);

  EndPaint (Window, &ps);
  }

```

I've updated it to this after some suggestions from Josh♦:

```
#include "stdafx.h"
#include "Windows.h"

#include "Keyboard.h";
#include "Photon.h"
#include "Player2D.h"

#define MAX_LOADSTRING 100

// Global Variables:
HINSTANCE hInst;                                // current instance
HWND Window;
WCHAR szTitle[MAX_LOADSTRING];                  // The title bar text
WCHAR szWindowClass[MAX_LOADSTRING];            // the main window class name
Player2D player;
Keyboard keyboard;
bool Exit = false;

// Prototypes
ATOM MyRegisterClass(HINSTANCE hInstance);
BOOL InitInstance(HINSTANCE, int);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM);
void draw ();
void main_loop ();

int APIENTRY wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPWSTR lpCmdLine, _In_ int nCmdShow)
  {
  UNREFERENCED_PARAMETER(hPrevInstance);
  UNREFERENCED_PARAMETER(lpCmdLine);

  // Initialize global strings
  LoadStringW(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
  LoadStringW(hInstance, IDC_PHOTON, szWindowClass, MAX_LOADSTRING);
  MyRegisterClass(hInstance);

  // Perform application initialization:
  if (!InitInstance (hInstance, nCmdShow))
    {
    return FALSE;
    }

  HACCEL hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_PHOTON));

  MSG msg;

  // Main message loop:
  while (!Exit)
    {
    if (PeekMessage (&msg, nullptr, 0, 0, PM_REMOVE))
      {
      TranslateMessage(&msg);
      DispatchMessage(&msg);
      }
    }

    return (int) msg.wParam;
  }

// Registers the window class.
ATOM MyRegisterClass(HINSTANCE hInstance)
  {
  WNDCLASSEXW wcex;

  wcex.cbSize = sizeof(WNDCLASSEX);

  wcex.style          = CS_HREDRAW | CS_VREDRAW;
  wcex.lpfnWndProc    = WndProc;
  wcex.cbClsExtra     = 0;
  wcex.cbWndExtra     = 0;
  wcex.hInstance      = hInstance;
  wcex.hIcon          = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_PHOTON));
  wcex.hCursor        = LoadCursor(nullptr, IDC_ARROW);
  wcex.hbrBackground  = (HBRUSH)(COLOR_WINDOW+1);
  wcex.lpszMenuName   = MAKEINTRESOURCEW(IDC_PHOTON);
  wcex.lpszClassName  = szWindowClass;
  wcex.hIconSm        = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));

  return RegisterClassExW(&wcex);
  }

// In this function, we save the instance handle in a global variable and
// create and display the main program window.
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
  {
  hInst = hInstance; // Store instance handle in our global variable

  Window = CreateWindowW(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
  CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, nullptr, nullptr, hInstance, nullptr);

  if (!Window)
    {
    return FALSE;
    }

  ShowWindow(Window, nCmdShow);
  UpdateWindow(Window);

  return TRUE;
  }

// Processes messages for the main window.
//  WM_COMMAND  - process the application menu
//  WM_PAINT    - Paint the main window
//  WM_DESTROY  - post a quit message and return
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
  {
  switch (message)
    {
    case WM_COMMAND:
      {
      int wmId = LOWORD(wParam);
      // Parse the menu selections:
      switch (wmId)
        {
        case IDM_ABOUT:
          DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
          break;

        case IDM_EXIT:
          DestroyWindow(hWnd);
          Exit = true;
          break;

        default:
          return DefWindowProc(hWnd, message, wParam, lParam);
        }
      }
    break;

    case WM_PAINT:
      {
      draw ();
      }
    break;

    case WM_DESTROY:
      PostQuitMessage(0);
      break;

    default:
      return DefWindowProc(hWnd, message, wParam, lParam);
    }
  return 0;
  }

// Message handler for about box.
INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
  {
  UNREFERENCED_PARAMETER(lParam);
  switch (message)
    {
    case WM_INITDIALOG:
      return (INT_PTR)TRUE;

    case WM_COMMAND:
      if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
        {
        EndDialog(hDlg, LOWORD(wParam));
        return (INT_PTR)TRUE;
        }
      break;
    }
  return (INT_PTR)FALSE;
  }

void draw ()
  {
  // clear background
  RECT screen;
  GetClientRect (Window, &screen);
  InvalidateRect (Window, &screen, true);

  PAINTSTRUCT ps;
  HDC hdc = BeginPaint (Window, &ps);

  COLORREF color_black = RGB (0, 0, 0);
  COLORREF color_red = RGB (255, 0, 0);
  HBRUSH brush_black = CreateSolidBrush (color_black);
  HBRUSH brush_red = CreateSolidBrush (color_red);
  FillRect (hdc, &screen, brush_black);

  player.position_rect ();

  player.x += 1;
  if (player.x > screen.right)
    {
    player.x = 0;
    player.y += 1;
    }

  SetPixel (hdc, player.x, player.y, color_red);

  EndPaint (Window, &ps);
  }

```

The game logic updates each frame, and the game appears to render at least once (a black background with a red pixel representing the player's position). Breakpoints in the `draw()` function are hit on each frame, but the rendering doesn't update as the player moves.

I realize I could have started with a Direct-X project, but I wanted to try my hand at writing my own graphics code (eventually). So far, even basic functionality is eluding me, though.

# Answer
After following a few suggestions from Josh here on Stack and doing a bunch of research, here's what my working code looks like:

```
#include "stdafx.h"

#include "Keyboard.h";
#include "Photon.h"
#include "Player2D.h"

#include <windows.h>

#define MAX_LOADSTRING 100

// Global Variables:
HINSTANCE hInst;                                // current instance
HWND Window;
WCHAR szTitle[MAX_LOADSTRING];                  // The title bar text
WCHAR szWindowClass[MAX_LOADSTRING];            // the main window class name

Player2D player;
Keyboard keyboard;

bool Exit = false;

COLORREF color_black = RGB (0, 0, 0);
COLORREF color_white = RGB (255, 255, 255);
COLORREF color_red = RGB (255, 0, 0);

// Prototypes
ATOM MyRegisterClass(HINSTANCE hInstance);
BOOL InitInstance(HINSTANCE, int);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);

void draw ();
void main_loop ();

int APIENTRY wWinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow)
  {
  UNREFERENCED_PARAMETER(hPrevInstance);
  UNREFERENCED_PARAMETER(lpCmdLine);

  // Initialize global strings
  LoadStringW(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
  LoadStringW(hInstance, IDC_PHOTON, szWindowClass, MAX_LOADSTRING);
  MyRegisterClass(hInstance);

  // Perform application initialization:
  if (!InitInstance (hInstance, nCmdShow))
    {
    return FALSE;
    }

  HACCEL hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_PHOTON));

  MSG msg;

  // Main message loop:
  while (!Exit)
    {
    while (PeekMessage (&msg, nullptr, 0, 0, PM_REMOVE))
      {
      DispatchMessage(&msg);
      }
    main_loop ();
    }

  return (int) msg.wParam;
  }

// Registers the window class.
ATOM MyRegisterClass(HINSTANCE hInstance)
  {
  WNDCLASSEXW wcex;

  wcex.cbSize = sizeof(WNDCLASSEX);

  wcex.style          = CS_HREDRAW | CS_VREDRAW;
  wcex.lpfnWndProc    = WndProc;
  wcex.cbClsExtra     = 0;
  wcex.cbWndExtra     = 0;
  wcex.hInstance      = hInstance;
  wcex.hIcon          = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_PHOTON));
  wcex.hCursor        = LoadCursor(nullptr, IDC_ARROW);
  wcex.hbrBackground  = (HBRUSH)(COLOR_WINDOW+1);
  wcex.lpszMenuName   = MAKEINTRESOURCEW(IDC_PHOTON);
  wcex.lpszClassName  = szWindowClass;
  wcex.hIconSm        = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));

  return RegisterClassExW(&wcex);
  }

// In this function, we save the instance handle in a global variable and
// create and display the main program window.
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
  {
  hInst = hInstance; // Store instance handle in our global variable

  Window = CreateWindowW(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
  CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, nullptr, nullptr, hInstance, nullptr);

  if (!Window)
    {
    return FALSE;
    }

  ShowWindow(Window, nCmdShow);
  UpdateWindow(Window);

  return TRUE;
  }

// Processes messages for the main window.
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
  {
  switch (message)
    {
    case WM_DESTROY:
      PostQuitMessage(0);
      break;

    default:
      return DefWindowProc(hWnd, message, wParam, lParam);
    }
  return 0;
  }

void main_loop ()
  {
  player.x += 1;
  keyboard.get_state ();
  keyboard.handle_input (player);
  draw ();
  }

void draw ()
  {
  HDC hdc = GetDC (Window);

  SetPixel (hdc, player.x - 20, player.y, color_white);
  SetPixel (hdc, player.x, player.y, color_red);
  Sleep (5);
  }

```

This allows me to set pixels individually and render in a loop while still operating inside a window.

From here, I can work on speeding up the draw step and moving away from SetPixel().

**Parts I added:** \- An arbitrary Sleep() after the rendering is finished to make sure what's happening is slow enough to be visible.

**Parts I changed:**

* PostMessage() to PeekMessage().
* Calling main\_loop from inside wWinMain() instead of WndProc().
* Calling draw() from main\_loop() instead of from WndProc's WM\_PAINT case.
* Changed the red rectangle to a single red pixel. It's a more basic test case and eliminates some ambiguity.

**Parts I didn't need:**

* Clearing the screen - This was causing a lot of uneven flickering, I'm guessing because I was trying to use rectangle painting to do it. I'll bring it back later with a better method.
* WM\_PAINT and painting in general - Without the rectangles, it turns out I didn't need this logic at all. SetPixel() apparently doesn't require it.
* The menu - Unnecessary fluff for what I'm working on.
> 0 votes

# Answer
`GetMessage` blocks until a message matching the filter is available. Generally you want to use `PeekMessage` instead to implement a real-time game loop, in a fashion that looks roughly like:

```
while (!done) {
    if (PeekMessage(&message, window, 0, 0, PM_REMOVE)){
        TranslateMessage(&message);
        DispatchMessage(&message);
    } else {
        UpdateAndRender();
    }
}

```

Note that updating game logic and rendering happens in the main loop, *not* in the window procedure. Yours is in the window procedure, which isn't a good place for it. The window procedure will not get called until there's a message to handle, and sometimes it can be a long (in computer terms) time between any two messages. That's part of why you are not seeing any rendering updates.

The other reason is that `BeginPaint` sets the clip region of the device context to the invalidated update region for the paint, which is probably empty after the first draw because you never call `InvalidateRect` to reset it. Once you know the screen needs to be updated, you should call `InvalidateRect`.

It's also probably worth looking in to putting your drawing into the `WM_PAINT` handler of your window procedure since it looks like you're trying to create a proper Win32 application (with menus and dialogs and the like) based on the rest of your code, and `WM_PAINT` is where painting is "supposed" to happen.

Other issues that are problems but probably not related to the one you asked about:

`GetWindowRect` gives you the rectangle for the *entire* window, including the UI chrome and title bar and such. That's larger than the area you want to actually draw into; your drawing will get clipped in this case, but if you use that rectangle for computing certain things or coordinate conversion, you'll notice errors. `GetClientRect` will give you the client (interior canvas) part of the window.

A `RECT` also contains left, top, *right* and *bottom* coordinates. Not width and height. By getting the window rectangle and then zeroing out the top/left coordinates, you're not just positioning the rectangle at the origin, you're also resizing it.

When you create brushes, you should delete them when you are done. Otherwise you'll eventually exhaust the (relatively small) pool of device objects allowed and rendering will stop working; right now you're leaking two brushes per draw. Consider creating both brushes at startup and deleting them at shutdown, and just reusing them for each draw. It will be faster as well as use fewer objects.
> 4 votes

---
Tags: c++, rendering, game-loop, windows
---


# Question
Title: How to fix double click problem in this code?
Please see the gif below to better understand what's going on.

On first click they all work normally but after first click I have to double click them to select them. I'm not a advanced developer so I've been trying to figure this out for straight 2 hours and last choice I wanted to ask you guys.

I declared select effect here. (White circle) And added an Array to get all select effects.

```
    public GameObject selectEffect;
    private bool isSelected = false;
    public GameObject[] selectEffectArray;

```

I put them inside the Array.

```
    private void Awake()
    {
        selectEffectArray = GameObject.FindGameObjectsWithTag("planetSelected");
        selectEffect = transform.Find("selectEffect").gameObject;
    }

```

I deactivate all select effects on start.

```
    void Start()
    {
        Deactivate();
    }

```

Here's Deactivate code.

```
    void Deactivate()
    {
        foreach (GameObject effect in selectEffectArray)
        {
            effect.SetActive(false);
        }
    }

```

When I click one of the planets these happens. (I'm a little confused so I hope you can understand it.)

```
    void OnMouseUp()
    {
        if (isSelected)
        {
            selectEffect.SetActive(false);
            travelbutton.SetActive(false);
            isSelected = false;
        }
        else
        {
            Deactivate();

            planetName_text.text = planet.name;
            requiredFuel_text.text = planet.requiredFuel.ToString();
            travelbutton.SetActive(true);
            selectEffect.SetActive(true);
            isSelected = true;
        }

    }

```

I don't want to double click a planet to select it.

# Answer
What happens here is basically this:

When you click on a planet for the first time, isSelected is set to true. Then you click away, but since you don't check whether other planets were selected, isSelected remains true. The next time you try to select it, it first detects, that it is indeed the current active planet (based on the variable) and deactivates itself.

Instead of letting every planet handle this themselves, you need to make sure they consult with a parent object. Let's call it `SelectionManager`.

Every time a planet detects a click, send a message to the selection manager. This should set the selected planet to the one that sent the message:

```
class SelectionManager
{

    private GameObject selected = null; // null means no gameobject is currently the chosen one

    public void HandleSelection(GameObject planet)
    {
        if (selected == planet) // The user clicked on the selected planet again
        {
            selected = null;  // Deselect the planet
        }
        else
        {
            selected = planet;
        }
    }

}

```

And inside the planet gameobjects:

```
public SelectionManager selectionManager; // Set this using the drag 'n' drop feature

//....

void OnMouseUp()
{
    selectionManager.HandleSelection(this);
}

```

You can get the currently selected planet from the selection manager.
> 0 votes

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


title: Error Handling in Unity

text:
# Question
Title: Error Handling in Unity
I try to understand what's the best way to handle error conditions in Unity. In a lot of places I've read that throwing exceptions is a bad thing. Unfortunately, I have not found any guidance on Unity website on this matter as well finding clear guidance on the wide Internet is also difficult.

What I use quite often is `Debug.Assert` statements to check that certain conditions for proper operation are met.

But what to do, if something unexpected happens? Some examples could be:

* Network connection lost
* File write operation failed (for some reason)

What is a good practice to handle these situations? Just do a `Debug.LogError` to log important info and then let the game crash?

Happy to hear your thoughts on this.

Thanks!

**Update 12.08.2019 22:06**

Based on the comments received, I have added the code example below with some comments / thoughts from my side.

*Example: Load Level Data From JSON File*

In this example, I load level data from a JSON file (SceneData.json). It could theoretically happen, that the level file is not available. I do not check the result of `Resources.Load()` yet, but if the file cannot be found, a `NullReferenceException` is thrown. I have not tested this yet, but I think a `NullReferenceException` will terminate the whole Unity game at runtime. So how to improve this situation in a way, that informs the player about this problem? What can be done to support the developer in fixing the issue?

Some thoughts from my side for improving code:

* I should check the return value of `Resources.Load()`. If it is `null`, I also issue a `Debug.Error` log. That way, the problem gets logged to the console during testing/development but also to the `Player.log` on the target system (e.g: Windows).
* If I want to inform the player about the problem, I could return `null` in the `GetDragAndDropLevel` method to inform the caller about the fact, that no level was loaded. I could the further propagate this information up the call stack to display an error message in the GUI at the end.

Does this sound reasonable in the Unity context? Or do you guys do this stuff completely different?

```
public static DragAndDropLevel GetDragAndDropLevel(GameLanguage language, GameScene scene, int level)
{
    Debug.Assert(level >= 1);

    // Generate filename
    var sceneDataFilename = "SceneData/" + scene + "/SceneData";

    // Read JSON structure into SceneDataDragAndDropLevel object
    var textAsset = Resources.Load<TextAsset>(sceneDataFilename);
    var jsonData = textAsset.text;
    Logger.LogDebug(jsonData);
    var sceneData = JsonConvert.DeserializeObject<SceneData>(jsonData);

    var numLevels = GetNumberOfLevels(sceneData, GameType.DragAndDrop, scene);
    Debug.Assert(level <= numLevels);

    // Generate level object
    var dragAndDropLevel = GetDragAndDropLevelFromSceneData(sceneData, level);
    return dragAndDropLevel;
}

```

# Answer
In most cases you should avoid exception handling, and make sure your code deals with all the edge cases. It adds extra processing that is very noticeable. This is very easy when you control all the end points your code touches.

It is not possible when working with uncontrolled sources, like services, networks, and files. At these points, you are right to wrap them in try catches. You have no choice, unless the application has safety calls. Similar to TryParse on Int or Float.

In cases where you need to try catch, try to keep it as isolated as possible. No reason to keep try hooks on things that don't need it. In many cases, like the file system, there are checks you can do about permissions or availability. The chances of a file becoming inaccessible during play beyond that are typically related to something they are doing, like running a hack app on save files, or their system is crashing anyway.

In regards to repairing issues down the road, turn on Analytics in Unity. You can get reports on all kinds of stats including crashes. Or you can get similar checkups through google or other analytic API's. I recommend Unity Analytics, simply because its designed specifically for it, including crash reporting.

In regards to notifying the player, when you have minor items, like a section of the game doesn't come up, because the level doesn't load, then yes, you want to capture those situations by catch or by logic, and announce it to the player nicely, that this section is failing to load. Perhaps apologies in the message and offer a bonus of coins or something. Additionally, something I have done in the past, is record crash or blocking errors and the users associated with it. After resolving it, send a message out, (or post it though your game, filtered to the users affected) that calls out the issue, that it has been repaired, and offer a reward/welcome.
> 1 votes

---
Tags: unity
---


title: Debug.Assert Behavior in Unity

text:
# Question
Title: Debug.Assert Behavior in Unity
Is this normal behaviour that Unity continues to run after a condition in a `Debug.Assert` statement was NOT met when I launch the game within the Editor? I can see the assertion in the console output, but still would expect it to stop the game. `Development build` and `Script Debugging` are turned on in my player settings.

# Answer
If you want to know how a specific method is supposed to behave normally, then a good place to look is the documentation. In the case of `Debug.Assert`, it reads:

> Assert a condition and logs an error message to the Unity console on failure.

It says nothing about stopping the game. So yes, this is normal behavior.

And by the way: Your player build settings are only relevant if you *build* the project. They are not relevant when you test a game from the editor.
> 3 votes

---
Tags: unity
---


# Question
Title: How can I force a collider to move up stairs and ramps?
The bots have a simple Capsule collider which cannot tilt. Movement is applied across the horizontal axes, gravity is enabled on the rigidbody. It moves up stairs okay with steps roughly 0.2 units high. When the bots speed is too slow or he is moving up steep ramps he gets stuck. I've tried tinkering to fix the problem but to no avail.

```
    float gravity = currentMovementSpeed * 2f;
    Physics.gravity = new Vector3(0, -gravity, 0);

```

Here is the problem: https://youtu.be/ypCavT3\_As0

What is a simple way to consistently force a collider up ramps and stairs?

# Answer
> 1 votes
I managed to tinker my way to success. But if someone has a REAL answer to this question, please go ahead and post it.

I set an empty gameobject inside the collider and raycasted two rays, one straight down, one at a 45deg angle forward (The bots only move forwards). I calculate the incline of the slope from the two hitpoints of the rays.

The steeper the slope, the lower gravity acts onto the object.

Trouble is if the distance of the gameobject off the ground is too low it will not recognise a slope because the collider bumps into it much further away. If the distance is too high, the collider will think the slope has flattened before it actually has. To fix the issues I actually raycasted twice, once from very close off the ground, and one from a distance equal to the radius of the collider:

Seems to work: https://youtu.be/6qfwMhLqrfo

Code:

```
void setGravity()
{
    RaycastHit hitInfoDown;
    RaycastHit hitInfoAngle;

    Ray rayDown = new Ray(slopeReader.transform.position, -Vector3.up);
    Ray rayAngle = new Ray(slopeReader.transform.position, transform.forward + -Vector3.up);

    if (Physics.Raycast(rayDown, out hitInfoDown, 1000, shootLayerMask)) { }
    if (Physics.Raycast(rayAngle, out hitInfoAngle, 1000, shootLayerMask)) { }

    float angleHigh = Vector3.Angle(slopeReader.transform.forward, hitInfoAngle.point - hitInfoDown.point); //Angle 0.5m above the ground
    if (hitInfoDown.point.y > hitInfoAngle.point.y)
        angleHigh = -angleHigh;

    rayDown = new Ray(slopeReader.transform.GetChild(0).transform.position, -Vector3.up);
    rayAngle = new Ray(slopeReader.transform.GetChild(0).transform.position, transform.forward + -Vector3.up);

    if (Physics.Raycast(rayDown, out hitInfoDown, 1000, shootLayerMask)) { }
    if (Physics.Raycast(rayAngle, out hitInfoAngle, 1000, shootLayerMask)) { }

    float angle = Vector3.Angle(slopeReader.transform.GetChild(0).transform.forward, hitInfoAngle.point - hitInfoDown.point); //Angle 0.1m above the ground
    if (hitInfoDown.point.y > hitInfoAngle.point.y)
        angle = -angle;

    if (Mathf.Abs(angleHigh) > Mathf.Abs(angle))
        angle = angleHigh;

    float distanceToFloor = (hitInfoDown.point - slopeReader.transform.GetChild(0).transform.position).magnitude - 0.1f;
    if (angle > 0 && distanceToFloor < 0.4f)
    {
        angle = Mathf.Clamp(angle, 0, 60);
        float grav = Mathf.Pow(1 - (angle / 60), 5); //Increase power for higher slopes / higher speed on steep slopes (5 works fine for 60 degree slopes)
        float speedModifier = Mathf.Clamp(currentMovementSpeed / 2, 0, 1);

        grav = grav * speedModifier;
        grav = grav - 1; //-(1-grav)

        GetComponent<Rigidbody>().AddForce(Physics.gravity * GetComponent<Rigidbody>().mass * grav);
    }
}

```

---
Tags: unity, movement, collider
---


# Question
Title: Loading a heavy scene behind some loading screen in unity
Is there a way to load a heavy built scene behind a loading screen in unity to not make the game look like stuck loading the scene rather show the player some loading bar that would help the player think some background process is happening. any sites or vidoes that describe about this would be a great help! Thanks!

# Answer
> 1 votes
Yes, with `SceneManagement.LoadSceneAsync(newScene)`.

This method loads the new scene in a background task while the current scene keeps running. You can check the progress by keeping the `AsyncOperation` object returned by that method and checking its property `.progress`. If you do that in an `Update` method of the loader-scene, you can use its value to update a progress bar or similar.

Example script which represents the loading progress by updating a percent value on a UI text:

```
 using UnityEngine;
 using UnityEngine.UI;
 using UnityEngine.SceneManagement;

 public class Preloader: MonoBehavior {

      public Text progressText; // <-- Assign a text label on a canvas to this using the inspector

      private AsyncOperation loadOperation;

      void Start() {
           // start loading the scene "game"
           loadOperation = SceneManagement.LoadSceneAsync("game");
      }

      void Update() {
          // update the text on the UI
          progressText.text = Mathf.floor(loadOperation.progress * 100f).ToString() + "%";
      }
 }

```

---
Tags: unity, loading
---