title: Bullet Physics Invalid Pointer on Free

text:
# Question
Title: Bullet Physics Invalid Pointer on Free
I'm writing a game engine in C++ with Irrlicht and Bullet Physics. All of my Irrlicht code works perfectly, but upon creating Bullet Physics objects with new, and later freeing them, my program throws a `free(): invalid pointer` error.

Backtracing with gdb shows that the error is a libc `raise()` when Irrlicht tries to delete an Octree I am using for the game map: `irr::scene::COctreeSceneNode::deleteTree().`

The full gdb backtrace is:

```
free(): invalid pointer

Program received signal SIGABRT, Aborted.
0x00007ffff7455f25 in raise () from /usr/lib/libc.so.6
(gdb) bt
#0  0x00007ffff7455f25 in raise () from /usr/lib/libc.so.6
#1  0x00007ffff743f897 in abort () from /usr/lib/libc.so.6
#2  0x00007ffff7499258 in __libc_message () from /usr/lib/libc.so.6
#3  0x00007ffff74a077a in malloc_printerr () from /usr/lib/libc.so.6
#4  0x00007ffff74a214c in _int_free () from /usr/lib/libc.so.6
#5  0x00007ffff7bd3b69 in irr::scene::COctreeSceneNode::deleteTree() ()
   from /usr/lib/libIrrlicht.so.1.8
#6  0x00007ffff7bd41ae in irr::scene::COctreeSceneNode::~COctreeSceneNode() ()
   from /usr/lib/libIrrlicht.so.1.8
#7  0x00007ffff7bd4474 in virtual thunk to irr::scene::COctreeSceneNode::~COctreeSceneNode() () from /usr/lib/libIrrlicht.so.1.8
#8  0x00007ffff7bf2706 in irr::scene::CSceneManager::removeAll() ()
   from /usr/lib/libIrrlicht.so.1.8
#9  0x00007ffff7bf971e in irr::scene::CSceneManager::~CSceneManager() ()
   from /usr/lib/libIrrlicht.so.1.8
#10 0x00007ffff7bf9c54 in virtual thunk to irr::scene::CSceneManager::~CSceneManager() () from /usr/lib/libIrrlicht.so.1.8
#11 0x00007ffff7d45e5e in irr::CIrrDeviceLinux::~CIrrDeviceLinux() ()
   from /usr/lib/libIrrlicht.so.1.8
#12 0x00007ffff7d45f54 in virtual thunk to irr::CIrrDeviceLinux::~CIrrDeviceLinux() () from /usr/lib/libIrrlicht.so.1.8
#13 0x000055555556b97e in irr::IReferenceCounted::drop() const ()
#14 0x000055555556a88f in IrrlichtHandler::drop_device() ()

```

The code which seems to be the cause of the error is the initialization:

```
    /* PHYSICS SETUP*/
    btDefaultCollisionConfiguration *col_config = new btDefaultCollisionConfiguration();
    btCollisionDispatcher *dispatcher = new btCollisionDispatcher(col_config);
    btBroadphaseInterface *overlapping_pair_cache = new btDbvtBroadphase();
    btSequentialImpulseConstraintSolver *solver = new btSequentialImpulseConstraintSolver;
    btDiscreteDynamicsWorld *dynamics_world = new btDiscreteDynamicsWorld(
        dispatcher, overlapping_pair_cache, solver, col_config
    );

    dynamics_world->setGravity(btVector3(0,-10,0));

```

and deletion of Bullet:

```
irrlicht_handler.drop_device();

    for(int i=dynamics_world->getNumCollisionObjects()-1; i>=0; i--)
    {
        btCollisionObject *obj = dynamics_world->getCollisionObjectArray()[i];
        btRigidBody *rb = btRigidBody::upcast(obj);
        if(rb && rb->getMotionState())
        {
            delete rb->getMotionState();
        }
        dynamics_world->removeCollisionObject(obj);
        delete obj;
    }

    delete dynamics_world;
    delete solver;
    delete overlapping_pair_cache;
    delete dispatcher;
    delete col_config;

```

The full code is on Github.

# Answer
> 0 votes
I fixed this by switching from the latest github code to the release code. When I posted this question I didn't realize I was using the latest github code.

---
Tags: c++, bullet-physics, irrlicht
---


title: Wonky perlin noise

text:
# Question
Title: Wonky perlin noise
I am quite new to the wondrous world of "Procedural Textures", and I am trying to create a double precission perlin noise algorithm.

I am almost done with it except for the fact that the coordinates seem to be off, any idea what I've done wrong? Here's the code:

```

public static class Noise {
    static int[] p = new int[Convert.ToInt32(Math.Pow(2,16))];
    public static vector2dDouble v1i;
    public static vector2dDouble v2i;
    public static vector2dDouble v3i;
    public static vector2dDouble v4i;

    public static double[,] GenerateNoiseMap(int mapWidth, int mapHeight, int seed, float scale, int octaves, float persistance, float lacunarity, Vector3 offset) {
        double[,] noiseMap = new double[mapWidth, mapHeight];

        System.Random prng = new System.Random(seed);
        Vector2[] octaveOffsets = new Vector2[octaves];
        for (int i = 0; i < octaves; i++) {
            float offsetX = prng.Next(-100000, 100000) + offset.x;
            float offsetY = prng.Next(-100000, 100000) + offset.z;
            octaveOffsets[i] = new Vector2(offsetX, offsetY);
        }

        if (scale <= 0) {
            scale = 0.0001f;
        }

        float maxNoiseHeight = float.MinValue;
        float minNoiseHeight = float.MaxValue;

        float halfWidth = mapWidth / 2f;
        float halfHeight = mapHeight / 2f;

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

                float amplitude = 1;
                float frequency = 1;
                double noiseHeight = 0;

                for (int i = 0; i < octaves; i++) {
                    double sampleX = (double)(x - halfWidth) / scale * frequency + octaveOffsets[i].x + 0.001;
                    double sampleY = (double)(y - halfHeight) / scale * frequency + octaveOffsets[i].y + 0.001;

                    double perlinValue = Noise2d(sampleX, sampleY);
                    noiseHeight += perlinValue * amplitude;
                    //Debug.Log(perlinValue);

                    amplitude *= persistance;
                    frequency *= lacunarity;
                }

                if (noiseHeight > maxNoiseHeight) {
                    maxNoiseHeight = (float)noiseHeight;
                }
                else if (noiseHeight < minNoiseHeight) {
                    minNoiseHeight = (float)noiseHeight;
                }
                noiseMap[x, y] = noiseHeight;
            }
        }

        for (int y = 0; y < noiseMap.GetLength(1); y++) {
            for (int x = 0; x < noiseMap.GetLength(0); x++) {
                noiseMap[x, y] = (double)Mathf.InverseLerp(minNoiseHeight, maxNoiseHeight, (float)noiseMap[x, y]);
            }
        }

[![enter image description here][1]][1]
        return noiseMap;
    }

    public static void init(int seed) {
        createGradients(p, seed);
    }

    public static int[] createGradients(int[] p, int seed) {
        System.Random prng = new System.Random(seed);
        for (int i = 0; i < p.GetLength(0) / 2; i++) {
            p[i] = prng.Next(0, 256);
            p[i + ((int)p.GetLength(0) / 2)] = p[i];
        }

        return p;
    }

    static vector2dDouble generateGradient(int val) {
        int hash = val & 3;
        switch (hash) {
            case 0:
                return new vector2dDouble(1.0, 1.0);
            case 1:
                return new vector2dDouble(-1.0, 1.0);
            case 2:
                return new vector2dDouble(-1.0, -1.0);
            case 3:
                return new vector2dDouble(1.0, -1.0);
            default: return new vector2dDouble(0, 0);
        }
    }

    static double Noise2d(double x, double y) {

        int ix = Convert.ToInt32(Math.Floor(x)) & (p.GetLength(0) / 2 - 1);
        int iy = Convert.ToInt32(Math.Floor(y)) & (p.GetLength(0) / 2 - 1);

        x -= Math.Floor(x);
        y -= Math.Floor(y);

        vector2dDouble v1 = new vector2dDouble(x - 1, y),
                       v2 = new vector2dDouble(x - 1, y - 1),
                       v3 = new vector2dDouble(x, y),
                       v4 = new vector2dDouble(x, y - 1);

        int g1 = p[p[ix + 1] + iy + 1],
            g2 = p[p[ix] + iy + 1],
            g3 = p[p[ix + 1] + iy],
            g4 = p[p[ix]  + iy];

        double u = fade(x);
        double v = fade(y);

        double f1 = v1.dot(generateGradient(g1)),
               f2 = v2.dot(generateGradient(g2)),
               f3 = v3.dot(generateGradient(g3)),
               f4 = v4.dot(generateGradient(g4));

        return lerp(u, lerp(v, f2, f4), lerp(v ,f1, f3));
    }

    static double lerp(double t, double argc, double argv) { return argc + t * (argv - argc); }

    static double fade(double t) { return t * t * t * (t * (t * 6 - 15) + 10); }
}

[System.Serializable]
public struct vector2dDouble {
    public double x, y;

    public vector2dDouble(double argx, double argy) {
        x = argx;
        y = argy;
    }

    public double dot(vector2dDouble argc) {
        argc.x *= x;
        argc.y *= y;

        return argc.x + argc.y;
    }

    public void print() {
        Debug.Log(x + "," + y);
    }
}

```

# Answer
Found The answer! My linear interpolation values were just flipped and when I flipped them back, instead of being inverted and creating layers, it was reverted to its normal state. Code Changed:

```

return lerp(u, lerp(v, f2, f4), lerp(v ,f1, f3));

// To:

return lerp(u, lerp(v, f4, f2), lerp(v ,f3, f1));

// Also my v and g vectors were unaligned

```
> 1 votes

---
Tags: c#, perlin-noise, objects
---


# Question
Title: Adding JavaFX GUI to an MVC based terminal card game
I have written a version of Castle that so far plays through the terminal. I have recently refactored my code (which can be found here) to use the MVC design pattern. After I have added a GUI I will add networking capabilities. The game at the moment should be thought of as a local single (human) player game against AI's.

The game controller holds the gameState, gameView and then the business logic to run the game. The business logic is essentially just a loop that loops over the players in turn telling each to pick a move, applying the move to the state and then telling the view to print the state (to the terminal atm).

The game is made up of the 3 types of players:

* An Information Set MCTS AI player
* AI player that just plays a basic strategy of playing the lowest possible card(s)
* Human player

The AI players have a controller that holds the player model and business logic and the player view (but only for human players). The player model is a generic POJO containing hand, castle cards etc. The logic is different from player to player but is all held in the controller. The game controller calls playerController.getMove(), the player then chooses their move depending on their strategy/implementation and returns it to the gameController.

The 'Move' objects are created by the playerController and passed back to the gameController and hold information like the card played or if they can't play then its a PickUp move etc. The move objects hold the choices made by the player and the business logic of how they change the game state.

1. GameController calls player.getMove(gameState)
2. PlayerController selects a move and returns it
3. Game controller calls move.doMove(gameState)
4. Next player until someone wins

My first question is, is it ok that the 'Moves' store logic or is there a better way? They are the only components that don't strictly follow MVC.

Secondly and more importantly, I can't seem to get my head around how the game runs using JavaFX as a GUI. I haven't got any experience with JavaFX until now and little UI experience in general but I'm trying. I've read that the Controller/View can become a bit convoluted. I've tried to find videos and resources to help give me some understanding but none seem to be in quite the right context - turn based, animationless (for now), card game. In my head I imagine the GUI displaying the players cards face up and the opponent's cards hidden but displayed with their backs up. The game waits for the human to select the card(s) to play and validates them. Then it updates to show the move completed. On AI opponent turns it waits until a move has been chosen and then updates on screen. But where does this go and how does it interact? I think the GameController/View should display the game state for the player to see and interact with? Is the playerView unnecessary then?

I think I'm struggling to get my head around how the GUI is running all the time for the player and doesn't care about their input until its their turn and how this fits in with the game loop I have created so far.

## **EDIT:**

I have managed to create a scene with ListView's to display the players' cards that have been dealt to them. However, I cannot figure out how my game loop is added to the code.

```
    boolean print = true;
    boolean gameOver = false;

    do {
        for (PlayerController player : players) {
            if (gameOver) {
                break;
            }
            boolean playersTurn = true;
            while (playersTurn) {

                CastleMove move = player.getMove(gameState);
                doMove(move);

                // If the player does not burn the pile then it is the next players turn
                if (!move.burnsPile()) {
                    playersTurn = false;
                }
                if (gameState.isGameOver()) {
                    gameOver = true;
                    break;
                }
            }
        }
    } while (!gameOver);

```

If I add the code to the start() method then the window displaying the cards never shows because it hasn't been executed yet. Where does it go?

# Answer
> 2 votes
if you want to implement a minimal M-VC you have to structure your application kind a like this:

(This is only an example Diagramm)

## Model

The Game is your Model. It stores information about *who's turn is it now* or *how many cards are on this stack* (or *on that stack*). It also provides minimal methods to change these values, e.g. `endTurn()` turnes the next player into the current player or `drawCard()` takes a crad from the open stack and adds it into the players hand. It also provides Methods to get the Status of the Model, maybe a method `getActivePlayer()` will return the current Player, or maybe a method `getOpenStack` will give you a List of all the Cards form the open Stack of your Game.

**IMPORTANT** if you create a Model there is **NO REFERENCE** to the `Controller` allowed - believe me, this will help you in any further activities on your work. The Model should be a standalone!

## Controller (With View)

The Controller is responsible for Drawing the Game and Handle Input - as you mentioned in your question, they have often similar responsibilities and resources.

The Controller in your case should be responsible for creating a GUI with Canvas and Buttons. Maybe it has also an `animationThread` that frequently updates the screen (for animations and other fancy stuff).

The second responsibility of the Controller would be to handle User Input. The Controller provides for example a button named `@FXML Button endTurn;`. Here is the controller responsible to grab the input from the User (mostly by attaching a `Listener` on that Button) and execute the method `endTurn` **on the model side**. The controller would also be responsible to execute an Update on the GUI after the button has been pressed, so that the current Player name would be displayed properly. Again, the value of the current Player would com from the model and the Controller would ask the model for the value (by calling the method `getCurrentPlayer()`on the model.

## JavaFx Implemetation Hints:

```
public class App extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    private Pane root;

    @Override
    public void init() {
        Game game = new Game();
        ControllerFactory controllerFactory = new ControllerFactory(game);
        try {
            FXMLLoader fxmlLoader = new FXMLLoader(getFxml());
            fxmlLoader.setControllerFactory(controllerFactory);
            root = fxmlLoader.load();
        } catch (IOException e) {
            //Log output please (I use a Logger for that)
        }
        RootController rootController = controllerFactory.getRootController();
        game.init();
        rootController.init();
    }

    @Override
    public void start(Stage stage) {
        if (root != null) {
            stage.setScene(new Scene(root));
            stage.setTitle("title");
            stage.show();
        } else {
            //Log output please (I use a Logger for that)
            Platform.exit();
            System.exit(0);
        }
    }

}

```

```
public class ControllerFactory implements Callback<Class<?>, Object> {

    private final Game game;

    private RootController rootController;

    public ControllerFactory(Game game) {
        this.game = game;
    }

    @Override
    public Object call(Class<?> type) {
        if (type == RootController.class) {
            //inject the Model in the controller
            rootController = new RootController(game);
            return rootController;
        } else {
            // default behavior for controllerFactory:
            try {
                return type.getDeclaredConstructor().newInstance();
            } catch (Exception exc) {
                exc.printStackTrace();
                throw new RuntimeException(exc); // fatal, just bail...
            }
        }
    }

    public RootController getRootController() {
        return rootController;
    }

}

```

**Conclusion** What this points out is that the controller is depending on the Game, but the Game is independent from the Controller.

**Think of it: you can create new Controllers for any GUI: Android, Console, JavaFX, Swing, TCP/IP, whatever ^\_^ - all without ever changing the Game-class!**

---
Tags: java, card-game, mvc, javafx
---


# Question
Title: Why do games have credits more often than other software?
Lately I have seen several videos that discuss how important it is to have your name in the credits of the game you've worked on. And it kinda makes sense - it's a way to prove to your future employers what experience you have.

However what puzzles me is that games seem to be the only software that does it. Unless it's a small one-man project, most software - especially closed-source commercial stuff - doesn't list any credits at all. Nor does anyone expect them to. It seems that neither employees nor their (future) employers have any problem with that.

How come there is this huge difference?

# Answer
As someone who does business application development as their primary job and game development on the side, I would not want my name in publicly visible credits of the business applications I worked on.

## Keeping the privacy of the developers

The reason is that while games are supposed to provide entertainment and fun, business application software is supposed to just get work done in the least intrusive way possible. We application developers do a good job when people don't realize we exist.

If an end-user contacts me because of an application I developed, then that's usually a misdirected support request. People complain that it doesn't do what it's supposed to be doing or that they don't understand it. And I really don't want those emails. Not that I am not proud of my work or refuse to admit my mistakes, but we got a support department as the primary point of contact for customer requests. End-users are not supposed to contact developers directly. They are supposed to contact the user help desk, so the developers can focus on their actual work. *If* it is a problem which requires developer attention, then the help desk is supposed to phrase the issue as a proper bug report or feature request, so the developers can work on it efficiently. So it's best when the end-users never know the names of the developers.

Gamers, on the other hand, are not nearly as needy. They are far more likely to ask each other for help than to expect others to solve their problems.

## Proving your work history

When it comes to proving my work history to potential employers, then those credits wouldn't be useful either. Publicly available software is actually just a small niche in the world of software development. Most application software which is being developed in the world never leaves the organization it got developed for. People from other companies couldn't look at the credits of the software I claim to have written because it's unavailable to them. So having the credits in the software I wrote over the years wouldn't help my employability at all.

## Credits as a measure of success

Success in the game industry is often measured in number of units sold. So the amount of people who read my name in the credits of the games I were involved in is a good measure for how successful I am as a game developer. Not so with application development. There is software which runs on just one single computer in the world and yet makes (or saves) millions each year. There is just a hand full of people who would have the access to the application to read my name in the credits (if it would have any), and yet if I was the developer of this software, that would make me a very successful software developer. Most of the people who indirectly benefit from this software would never read my name. Would you care that the invoice you just got in your mail was calculated, composed and printed by a program I wrote? So why would I care about adding credits?
> 4 votes

# Answer
Games make a big deal about credits for the same reason movies do, and commercial software doesn't for the same reason that TV shows don't. When you work on a game or a movie, it is often for a single term of project where there is a good chance you will be out of a job and in need of proving your experience to your next employer. An obvious credits section makes proving your work history easier when odds are that you, your supervisors, and coworkers will all be scattered to the winds when the project is done.

Project based industries like game and movie development are plagued by several issues that make permanent jobs rare including an asymmetry between labor requirements as projects are being planned, produced, and released, down periods between when a product is released and when it becomes clear that a sequel is economically viable, planned over-staffing & layoffs to meet publication deadlines, and a general inability to ensure that project phases line up well enough to move staff seamlessly between projects.

In contrast, publicly available commercial software development much more typically follows the agile development model where you have a product that is in a constant cycle of patches and incremental updates. A developer could easily spend 10 years working on the same program one quite release after another. Many of the companies that make them have been around for 20+ years and are expected to still be around in another 20 years doing more or less the same things. So, when you aren't planning to jump jobs every 1-2 years, credits just don't seem all that important.

In reality, many commercial software products and TV shows do have credits too, but they are generally not given the same prominence since the developers just don't have as much reason to care.
> 1 votes

---
Tags: game-industry
---


title: Let a point drive on a polyline

text:
# Question
Title: Let a point drive on a polyline
I want to create a polyline which should be quite smooth for my game. A point is following moving on the line, but can accelerate/brake and has to get slower in corners.

In the end I want to set up some stats (good acceleration, low topspeed, "good" cornering") and simulate the time it has taken to go from start to finish (drawning it to the player would be just a bonus). Yes, this will be some sort of a racing simulation.

I'm quite new to this style of games and I have no idea to do that. I don't even know how to create such a polyline I can easily use.

I don't want a finished algorithm but rather some hints in the right direction. I thought about using the angle of the corner to determine the speed, but that's not really much. I want to implement the time simulation in python, outputting the movement with html/javascript.

How would I start implementing such a mechanism?

# Answer
> 1 votes
Usually, you would want to look for an API or lib that provides you with sufficiently sophisticated curve rendering and querying, as the underlying math can be quite difficult.

However, if you want to figure it out yourself, you can look into Bézier curves, which are about the easiest clean curve definition.

Alternatively, a good-enough curve can be just a set of very short lines, so you could just ditch more complicated math and work on point/list arrays.

---
Tags: simulations, racing, path
---


# Question
Title: Which files of addressable assets should be committed to Git?
I would like to keep my Git repository as small as possible and exclude any automatically generated files. The developers can re-build their Unity Addressable Assets themselves. Any developer should be able to build the final project and the final result should contain the same assets packed in the same way.

I noticed that Unity generates the following files and folders:

Which of these files are important settings that should be included and which files are safe to exclude from a Git repository?

# Answer
It broke when I removed any of these:

```
/AddressableAssetsData/AssetGroups
/AddressableAssetsData/DataBuilders

```

Nothing broke (no obvious errors) when I removed

```
/AddressableAssetsData/AssetGroups/Schemas
/AddressableAssetsData/AssetGroupTemplates

```

... but when I build the application, the Addressables were missing and after further investigation I noticed that each Group's Content Packing & Loading "Component" (actually "Schema") was obviously missing so I assume Unity just silently ignored the packing of my assets. And without the AssetGroupTemplates, my AddressableAssetSettings asset showed that the Asset Group Templates were missing, so I guess that is also a required folder.

The following addition to the .gitignore will only remove the binaries generated by the Asset packing and keep all the other settings.

```
/[Aa]ssets/[Aa]ddressable[Aa]ssets[Dd]ata/*/*.bin*

```
> 2 votes

---
Tags: unity, assets, git
---


# Question
Title: User magic creation system that isn't programming
I would love to create an RPG with a magic system in it that gives the player a LOT of freedom.

To the extent they can make their own spells, systems of magic etc., bind spells to items, and so on.

Spells and magic would obviously have constraints, but doing lots of research into magic, and spending time creating spells etc. should allow players to create more and more powerful spells.

I'm really struggling how to come up with an interface through which they can create spells that isn't directly similar to programming. I don't want it to be so simple/boring as typing a sequence of commands that get triggered by clicking on a wand and calling that a spell.

I would love it if it were less human-intuitive, linearity combinations etc. weren't obvious or easy to figure out, and it was possible to explore the magic system deeply to discover more complex ways to piece together magics.

Are there any precedents? Does anyone have any ideas on how such a system could be implemented?

# Answer
> 5 votes
### A system of base spell types with a robust selection of modifiers may suit your needs.

For example, a fire ball spell might normally lob a ball of fire in an arc in front of you, that explodes upon hitting a surface or enemy.

At this point, modifiers can be linked to the spell. Depending on the style of the game, these can be explicit modifiers that state exactly what they do, or more esoteric runes that only hint at what effect they may have.

Some examples of possible modifiers:

* A modifier that makes a spell bouncy would make the fireball bounce off surfaces until it hits an enemy or times out and explodes anyway.
* Several mods could affect spell trajectory, making spells fly in a more predictable manner, or giving them a wild unpredictable snaking or zigzagging pattern.
* A mod could cause the spell repel itself from nearby surfaces
* Spells could leave a puddle of water when hitting a surface. Consider now that this might create a synergy with a fireball base and a bouncy modifier, where every time the fireball bounces it creates a puddle of water which is then turned into a cloud of hot steam on every collision with a surface.

To add some depth, modifiers that make a spell easier to use may decrease the overall power, while adding more chaos into the mix rewards the player with a higher damage but harder to use spell.

If a large variety of base spells and modifiers are created, the player can then explore and theory craft how different combinations will work for (*and against!*) them. A fire ball thrown like a boomerang, may not be ideal for the players well being, for example.

An example of a game that utilizes a system similar to this is **Noita**. It goes even a little bit further by having wands that effect the spells and modifiers slotted in them.

Here is a wiki link to a list of the spells / modifiers in Noita as a reference.

# Answer
> 3 votes
What you want is something that is unpredictable yet consistent but lets the player make an educated guess, with power progression.

# Unpredictable

The more "input" your spell system can take, the more chaotic the results can appear. Have your spells take both a mix of components as well as an incantation (arrange runes, take some text input, draw a constrained pattern with the mouse/touchpad/joystick).

# Consistent

A couple of behind-the-scenes formulas take the inputs, convert them to numbers and spit out more numbers that result in some basic values for your spell (its range, energy cost, power, effect strength). You can use the input or a part of it as a seed for a PRNG, which gives random numbers, but always the same ones if given a specific seed and state. The point is that if the player makes the spell exactly the same way twice, it should come out exactly the same way.

# Educated guessing

Add some rules to your calculations that let certain components vaguely relate to the final results. Perhaps a certain herb always makes the spells made with it affect the undead more. Maybe one of the runes (nearly) guarantees a longer range or wider spread.

# Power progression

Make more components available as the player progresses and have the player's own statistics play into the spells. The Fireball cast by a novice mage barely singes a monster's hair; the one a Grandmaster Wizard can muster will only leave a blackened spot and a foul smell in place.

# Multiple ways of casting

Make the magic effects different depending on who or how they're cast upon. An ice spell can make the ground slippery, freeze an enemy in place or extinguish the spellcaster who's been set on fire.

# Randomize the rules

If you want each playthrough to be unique and the spell creation, testing and learning aspect to be an important game mechanic, make the rules random every playthrough - so that people don't memorize/write down in a wiki all the strictly best combinations. Alternatively, don't, and now you have a nice emergent magic system going.

# Answer
> 0 votes
First of all you need to make it clear to yourself what kind of magic system you really want. As far as i know there is no common definiton for it, but i would call it scientific magic vs blackbox magic. You want **scientific magic.**

**Blackbox Magic** is somewhat unapproachable, unintuitiv and not explainable. Most games like Skyrim and most other games do it like that. There might be a source for the magic, but magic effects are just THERE. And either they are usable and recreatable (by casting spells or binding them to items) or they are part of the world (like magical creatures, portals and other magical effects).

**Scientific Magic** is what i like to call magic that is approachable, repeatable and able to get almost infinitly complex. Instead of the caster saying 'Fire ball' and a flaming ball of exploding fire flies in the enemies face, the caster understands, that his spell first weaves a ball of in a magic matrix, fill that ball with mana, adjust this infused mana with the aspect of fire and propel it with a fling of another magic matrix. If this sounds like an engineer process... well, it is. And as this all seems constructed, maybe there is a way around it.

So to design this engineering approach, i also want to adress some of htmlcoderexe's examples, as i find some of them quite fitting, while others not so much.

## Approachable

As i said, this kind of magic has to be approachable. What i mean is, that in its basics, it should seem logical. Fire is hot and the opposite of cold. If something is moving, a force has been applied, etc.
Your magic system needs to have basic elements, that do something, but not a lot.

In addition to that, if you combine two of those basic elements, something different might happen.

## Repeatable

Lets combine two elements and try the spell -\> Something happens.
Combine the elements in the same way -\> Same thing happens.
Combine the elements in another way -\> The same thing or something different happens.
Anything else and the player might be discouraged to try something new because... something new could happened if he does the same thing again... so why change?

## Infinitly complex

Now instead of two basic elements, build some more complex elements from several basic elements, combine those to a greater effect (and more mana required) and to create more complexe elements or to archive different effects.

I dont want to trick you. To archive this kind of depth, you certainly will to implement some kind of 'Programming', but the trick is to not let the player have the feeling that it is. So lets design it.

## The idea

Imagine this. In your world is a language, that conveys magic effects into the real world. Something like the dragon language from Skyrim.
Lets asume you have some basic words (our basic elements) your player starts with. Deep down in a ruin, he finds the word for **Iref**, but does not know, what it does. He speaks the word and something in his hands begins to burn, maybe even some of his clothes. From this he knows, that **Iref** is **Fire**. Not very useful yet, but somewhere else he finds the word **Llab** and casts it, and he sees a 'ball of magic' infront of him.
As a natural explorer, he tries '**Iref Llab**' and a magic ball filled with fire appeares. It does not move and if touched, it just bursts like a bubble, not like an explosion. And so he tries to find new words and combines them.

To implement it, let the player have some kind of writing board, where he writes those runes (maybe more like drag and drop) or something and arrange them like he thinks it is right. Technical this IS programming, but the fun behind is to figure out the way you are able to programm more complex stuff.

Now you can think of other ways to modify the interactions. E.g. instead of fire the player gets **Temperature**. Now it makes a difference how he combines that with the ball. '**Temperature Ball** would be a ball filled with fire, while **Ball Temperature** would be an ice ball. \** Temperatur Ball Velocity \** would push that Fireball away from the caster, while **Velocity Temperatur Ball** would push the ball against the caster etc.

Later on an experienced caster would get more complexe elements like \**temperature ball\* or \** ball temperature\* as an own Word to implement in the spell, and even this could be combined to more complex spells.

* A fire ball that really explodes
* A Healing Aura with different targets
* Creating intelligent creatures from differen basic elements
* A ball filled with multiple fireballs (something like a cluster grenade)

# Answer
> 0 votes
# Evolution instead of programming

Simply put: the player chooses spells and then obtains mutations and combinations of these spells. Repeating this step will eventually refine spells to a player's liking, without requiring any programming.

In the context of evolutionary algorithms, the player would determine the fitness of spells by experimentation.

But be warned, that writing good mutation and crossover functions, for things with the same level of sophistication as programming, can be very challenging.

# Answer
> 0 votes
Have each spell consists of a power level, a projection method, an element, and a series of optional modifiers controlled with slider bars.

The power level determines a spell's base mana cost, required user level, etc and will scale up the potency of the spell as it is increased.

The projection component says if it is a touch spell, a line of sight spell, an aura, an AOE etc. Each projection also has fixed co-effecants that apply to it such as base potency, range, radius, rate of fire, etc. These values are balanced against each other such that each projection's baseline efficiencies are make since against their weaknesses.

The element determines what a spell's power actually means. A fire element would turn a spell's potency into fire damage, but a heal element would turn it into a health recovery, and a root element would use the potency to determine how strong of a monster it can hold, etc.

Lastly you have your modifiers. These are sliders that are dynamically added to the UI based on the projection and element type. For example, an AOE might have sliders for More Damage \<-\> More Radius, More Damage \<-\> More Range, and More Mana \<-\> Longer Cool Down, etc. and a Fire element might have additional sliders for things like Quick Weak Burn \<-\> Strong Long Burn, and Burn Chance \<-\> Initial Damage, etc.

While this sort of system opens up countless spell combinations, the UI is can be entirely managed through a simple series of drop downs and sliders that anyone should be able to easily grasp.

**As for the research thing, this could be approached 2 ways:**

One is player knowledge based research (IE: Meta Gaming). If the system is complex enough, "un-intended" metas and exploits will crop up. You can leverage knowledge of these metas through intentionally lacking and vague in game descriptions of things. So don't tell players this effect has 50% armor penetration and 25% less damage, just tell them there is a trade off and force them to experiment to see when those trade offs yield the best results. You can further this by adding Easter Egg side effects to abilities that you just do not mention at all like making Light based AOEs and Auras break stealth or making casting ice spells break burn effects. As a result you will see more experienced players and factions naturally rise to the top by knowing how to exploit these esoteric knowledges.

Example of Meta gaming based research: Lightning attacks get a massive to-hit bonus against enemies in heavy armor; so a player cranks the accuracy \<-\> damage slider all the way to damage letting the lightning easter egg effect compensate for the inaccuracy, then push the range \<-\> cool down slider all the way to cool down because heavy armored opponents are slower meaning you get to dictate the engagement range. Then put armor penetration \<-\> damage slider all the way to armor penetration since this spell is specialized at killing tanks. By exploiting the natural weaknesses of heavy armor, a less armored faster opponent can run in close and bear into him with massive armor penetrating DPS killing an opponent who may theoretically be much stronger.

The other more common way to do it is that you could make all of the above unlockable content; so, you might just start off with 1-2 projection types, 1-4 elements, and no modifiers. Then as you achieve things whether it be through finding reagents or crafting tools, leveling up, or whatever, you unlock new types and elements as you progress. I personally find this approach more boring, but it tends to appeal better to mainstream audiences because newer players often mistake that which they do not understand with bugs, "bad game design", and hax. If you start them off limited to few enough options that they can understand it, and expose them slowly to emergent metas, then it's less of a shock to the player.

---
Tags: game-design
---


# Question
Title: Why would one use a separate alpha mask for sprites?
I've seen tilesets of the game Braid, and for each tileset in the main folder there is an alpha map for it in "alpha" folder.

I wonder, why just not to draw your image as it is (with transparent parts where you want), export to PNG format and parse it to RGBA texture?

Why would one use a separate alpha map for this, is there some kind of performance benefit?

# Answer
> 6 votes
The idea of using a separate transparency map is a bit of a throwback to an earlier era, where we would use black-and-white bitmaps as transparency masks to draw sprites.

That said, it's still a perfectly viable technique today. There's really no appreciable performance difference between using a color and alpha map versus one color map containing alpha as an additional color component. There may be some minor issues regarding disk or memory footprint, but those will mostly be irrelevant in the grand scheme of things.

A good reason to use separate image sources like this today is not for *game runtime* performance but *authoring* performance. If you only have tools available to you that don't work well with images containing alpha channels, or you simply prefer to work this way, it can be more efficient for you to do so rather than in a context where the alpha is embedded into the color.

Similarly if you've chosen a particular image format that doesn't support embedded alpha channels for *other* important reasons, you may end up using this "separate mask image" technique.

# Answer
> 13 votes
Sometimes RGBA compresses worse than RGB and A separately.

Also it is known technique to use JPG for resources, where game could sacrifice some picture quality in favor of smaller size (e.g. backgrounds). Standard JPG does not support Alphas, so resource has to be split into two - RGB + A. Note that also allows for different compression ratios. E.g. some RGBs is more forgiving to higher compression ratio artifacts.

\*as well noted in comments, JPG allows for different formats and even user-defined chunks that can include anything, yet majority of loaders will provide for just common JFIF / RGB data.

# Answer
> 0 votes
There is one really good reason for using alpha masks. A bunch of tilesets need an alpha mask variant to **not** look boring.

Say you have a tileset consisting of grass and dirt. In this example grass is the bottom layer and dirt is the top layer. You can easily blend the border between these, but it would look straight and dull. You could also create some algorithm that tries to do something pretty for you, but can become cumbersome and most likely performance costly.

Instead, enter "Alpha masks"! define e.g. 64 masks that create "variant" blending. Could be top-bottom, a hole inside the top layer, where you want grass to pop out from(or reverse) and so on.

An easy way to do this is to add an extra set to texture coordinates as vertex attributes in your shader and then blend based on the mask contained within those texture coordinates.

There are a ton of ways of doing this, Alpha masking is just one solution. The big **PRO** with alpha masking is using it in conjunction with texture atlases/sprite sheets, it can yield huge performance benefits! The big **CON** is that texture atlases are way harder to implement compared with precomputing a bunch of texture variants and then just using a texture array.

As a side note. If you are going to use texture atlases for tiling, you might want to read up on precomputed mipmaps.

---
Tags: opengl, 2d, alpha
---


title: Random point on a square floor

text:
# Question
Title: Random point on a square floor
I have a flat 10x10 surface (floor) made out of cubes of 1x1x1.

I am spawning objects from the "sky" and I want them to fall on random points of the surface without exceeding the surface limits.

Is there anything similar to `Random.onUnitSphere` to handle this case?

# Answer
The method `Random.Range(min, max)` allows you to generate pseudo-random numbers in a specific range. Use it twice, and you can get a random point in a rectangle:

```
Vector3 randomPoint = new Vector3( Random.Range(0f, 10f),
                                   0,
                                   Random.Range(0f, 10f) );

```

This of course assumes that your rectangle is between the coordinates 0:0:0 and 10:0:10 and that it's axis-aligned. If that's not the case, then you might have to transform the above vector to be relative to the position, rotation and scale of the rectangle. If your rectangle is a game-object, then you can actually do that by using its `transform` (which I here assume to be in a variable named `rectangleTransform`) using the method `Transform.TransformPoint`:

```
randomPoint = rectangleTransform.TransformPoint( randomPoint );

```
> 1 votes

# Answer
You can select a point in an axis-aligned rectangle uniformly at random by choosing:

```
point.x = center.x + Random.Range(-0.5, 0.5) * width;
point.y = center.y;
point.z = center.z + Random.Range(-0.5, 0.5) * depth;

```

In your case, width and depth are both 10.
> 0 votes

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


title: 2d Raycast detection doesn't work

text:
# Question
Title: 2d Raycast detection doesn't work
I want to check if the position I generated has another object or not. I do this by using Raycast:

```
private void RandomOBS()
{
    Vector3 pos = new Vector3(UnityEngine.Random.Range(-8f, 8f), UnityEngine.Random.Range(-4f, 4f), 0);

    while (Physics2D.Raycast(pos, pos).collider)
      pos = new Vector3(UnityEngine.Random.Range(-8f, 8f), UnityEngine.Random.Range(-4f, 4f), 0);
}

```

The code above doesn't work at all. I tested it with if statement and for some reason it cannot check that position.

```
private void RandomOBS()
{
    Vector3 pos = new Vector3(UnityEngine.Random.Range(-8f, 8f), UnityEngine.Random.Range(-4f, 4f), 0);

    while (Physics2D.Raycast(transform.position, transform.position).collider)
      pos = new Vector3(UnityEngine.Random.Range(-8f, 8f), UnityEngine.Random.Range(-4f, 4f), 0);
}

```

However when you check the `transform.position` instead of the `pos`, it works? How and why? All the game objects have the correct colliders & stuff.

# Answer
> 2 votes
I would assume you actually want to use the Physics2D.OverlapArea function instead.

It takes in two Vector2's which are the top left corner and bottom right corner of a rectangle. The result is a Collider2D that the function found was overlapping the input rectangle.

So your function would be:

```
private void RandomOBS()
{
    Vector2 pos = new Vector2(UnityEngine.Random.Range(-8f, 8f), UnityEngine.Random.Range(-4f, 4f);

    while (Physics2D.OverlapArea(pos - rectangleExtent, pos + rectangleExtent) != null)
        pos = new Vector2(UnityEngine.Random.Range(-8f, 8f), UnityEngine.Random.Range(-4f, 4f);
}

```

The variable rectangleExtent is also a Vector2 which is how far away the position has to be from another already existing collider

I should also say that this only works in 2D, Though you could use Physics.OverlapBox instead for 3D.

That function takes in a center and half extent as Vector3's

So in the case of 3D it would be something like this:

```
private void RandomOBS()
{
    Vector3 pos = new Vector3(UnityEngine.Random.Range(-8f, 8f), UnityEngine.Random.Range(-4f, 4f), 0);

    while (Physics.OverlapBox(pos, boxExtent).Length > 0)
        pos = new Vector3(UnityEngine.Random.Range(-8f, 8f), UnityEngine.Random.Range(-4f, 4f), 0);
}

```

And the variable boxExtent is basically the same as rectangleExtent just in 3D

# Answer
> 0 votes
I can solve the problem by using Physics2D.Linecast(pos, pos).collider instead of Physics2D.Raycast(pos, pos).collider if anyone has any idea please let me know.

---
Tags: unity, 2d, raycasting
---


title: Unity won't slice images properly

text:
# Question
Title: Unity won't slice images properly
Okay, so I am very new to Game Development and I imported a .png file(made in Paint) to the assets and that file contains just a circle and an oval, not touching and far apart from each other, both of them coloured blue. When I open the sprite editor and click on splice, then select Automatic and Delete existing options and then click slice, I do not get different sprites, one containing the circle and the other containing the oval. The image isn't sliced at all. I have also set the sprite mode to Multiple, but to no avail.

Can someone help me and tell me what I am doing wrong? The engine I am using is Unity.

This is the image.

# Answer
Unity will recognize this as one sprite because it doesn't realize that white is supposed to be non-solid. Why would it? White is a color like any other. You could slice this manually in the sprite editor by dragging a rectangle over each object with the left mouse button, but that way you will end up with a circle and an oval on white rectangles.

If the white parts are meant to be transparent, then you have to use an image editor which can create PNG images with actual transparency. MSPaint can't do that, but there are lots of alternatives available which can. GIMP, Krita or Paint.NET are some examples of alternatives which don't cost any money. Aseprite or Photoshop are examples of paid products which some game developers think are worth their money.
> 1 votes

---
Tags: unity
---


# Question
Title: Calculating 3D character movement based on YAW and Pitch
I'm not sure how to calculate an XYZ immediately to my characters left based on the direction they are facing.

I am learning to create a 3D game in Monogame on top of .Net Core 3.1 in c# using MonoGame.Framework.WindowsDX.Core.

Right now I'm just drawing a cube in the game world and learning to wire up the controls to freely move a camera around to look at the cube from different angles.

I believe my math to calculate the camera target based on pitch/yaw from the character's position is correct.

I have wired up the mouse so that if I move the mouse up the camera looks up, and if I move it down the camera looks down, and if I move it left|right the camera rotates left or right (yaw). I am using 360 on the X access and 360 degrees on the Y access for the pitch yaw for now.

Here is my player class.

```
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using System;
using System.Collections.Generic;
using System.Text;
using YAVBG.Core.Input;

namespace YAVBG.Core.Objects
{
    public class Player : Updateable
    {
        #region Fields
        private float _x;
        private float _y;
        private float _z;
        private float _pitch;
        private float _yaw;
        private float _height;
        private float _zoomLevel;
        private int _health;
        private int _level;
        private int _food;
        private float _experience;
        #endregion

        #region Properties
        public bool IsMainPlayer { get; private set; }
        public Vector3 Position { get => new Vector3(_x, _y, _z); }
        public float Pitch { get => _pitch; set => _pitch = value; }
        public float Yaw { get => _yaw; set => _yaw = value; }
        public float Height { get => _height; set => _height = value; }
        public float ZoomLevel { get => _zoomLevel; set => _zoomLevel = value; }
        #endregion

        #region Constructor/Destructor
        public Player(bool isMainPlayer = false) : this()
        {
            this.IsMainPlayer = isMainPlayer;
        }
        public Player()
        {

            _x = 0f;
            _y = 0f;
            _z = -12f;
            _yaw = 0;
            _pitch = 0;
            _zoomLevel = 500f;
        }
        #endregion

        #region Abstract Implementation
        public override void Update(GameTime gameTime)
        {
            //TODO
        }
        #endregion

        #region Methods
        public void StrafeLeft(float units)
        {
            _x += units;
        }
        public void StrafeRight(float units)
        {
            this._x -= units;
        }
        public void MoveForward(float units)
        {
            this._z += units;
        }
        public void MoveBackward(float units)
        {
            this._z -= units;
        }
        public void MoveUp(float units)
        {
            this._y += units;
        }
        public void MoveDown(float units)
        {
            this._y -= units;
        }
        public void MoveYaw(float y)
        {
            this._yaw += y;
        }
        public void MovePitch(float x)
        {
            this._pitch += x;
        }
        /// <summary>
        /// Get the matrix of where the player is looking based on their current position, zoom level, pitch, and yaw
        /// </summary>
        /// <returns></returns>
        public Matrix GetCameraViewMatrix()
        {

            var position = this.Position;
            var zoomLevel = this.ZoomLevel;
            var yaw = this.Yaw;
            var pitch = this.Pitch;

            //todo make headCamera higher than player position
            Vector3 headCamera = new Vector3(position.X, position.Y, position.Z);
            var cx = Math.Sin(yaw) * Math.Cos(pitch);
            var cy = Math.Sin(pitch);
            var cz = Math.Cos(yaw) * Math.Cos(pitch);
            var pX = zoomLevel * cx;
            var pY = zoomLevel * cy;
            var pZ = zoomLevel * cz;
            var camTarget = new Vector3((float)pX, (float)pY, (float)pZ);
            var matrix = Matrix.CreateLookAt(headCamera, camTarget, Vector3.Up);
            return matrix;
        }
        #endregion
    }
}

```

And here is my World Class

```
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using System;
using System.Collections.Generic;
using System.Text;
using YAVBG.Core.Input;
using YAVBG.Core.Primitives;

namespace YAVBG.Core.Objects
{
    public class World : Updateable
    {
        #region Fields
        private Cube _cube;
        private InputManager _input;
        #endregion

        #region Properties
        public MainPlayer MainPlayer { get; private set; }
        public Matrix ProjectionMatrix { get; private set; }
        public Matrix WorldMatrix { get; private set; }
        public Cube Cube { get => _cube; }
        #endregion

        #region Constructor/Destructor
        public World(float aspectRatio, float fieldOfView, int gameWidth, int gameHeight)
        {
            this._input = new InputManager(gameWidth, gameHeight);
            this._cube = new Cube();
            this.MainPlayer = new MainPlayer();
            this.ProjectionMatrix = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(fieldOfView), 1.5f, 0.01f, 10000f);
            this.WorldMatrix = Matrix.CreateWorld(new Vector3(0f, 0f, 0f), Vector3.Forward, Vector3.Up);

            this._input.KeysBeingHeldDown += InputManager_KeysBeingHeldDown;
            this._input.MouseMovedX += _input_MouseMovedX;
            this._input.MouseMovedY += _input_MouseMovedY;
        }
        #endregion

        #region Abstract Implementation
        public override void Update(GameTime gameTime)
        {
            this._input.Update(gameTime);
            this.MainPlayer.Update(gameTime);
        }
        #endregion

        #region Input Events
        private void _input_MouseMovedY(object sender, int e)
        {
            var modified = e < 0 ? 0.001f : -0.001f;
                this.MainPlayer.MovePitch(modified);
        }

        private void _input_MouseMovedX(object sender, int e)
        {
            var modified = e < 0 ? 0.001f : -0.001f;
            this.MainPlayer.MoveYaw(modified);
        }
        private void InputManager_KeysBeingHeldDown(object sender, Microsoft.Xna.Framework.Input.Keys e)
        {
            if (e == Keys.W)
                this.MainPlayer.MoveForward(0.1f);
            if (e == Keys.A)
                this.MainPlayer.StrafeLeft(0.1f);
            if (e == Keys.S)
                this.MainPlayer.MoveBackward(0.1f);
            if (e == Keys.D)
                this.MainPlayer.StrafeRight(0.1f);
            if (e == Keys.Space)
                this.MainPlayer.MoveUp(0.1f);
            if (e == Keys.LeftShift)
                this.MainPlayer.MoveDown(0.1f);
        }
        #endregion
    }
}

```

Notice that right now, my code to move the player when pressing "A" to the left (strafe left if you will) is just decreasing x, same thing with the other WASD keys.

This works great if the camera is pointed straight ahead, then you're moving on a 2D plane with WASD.

But when the camera changes positions to any YAW/Pitch, WASD is no longer correct, it will still move you on 1 axis and you're no longer oriented on that access.

So I'm looking for guidance on what kind of math I need to understand to be able to calculate the full xyz that's directly to the left.

Basically I want to calculate a line that is at axis 0 based on orientation. So Say I'm facing 45 degrees to the North East Exactly with 0 yaw (looking straight ahead), then I need to be able to calculate any point on the line exactly to the north west on the x/z plane.

In monogame the Y axis is height, X axis is (left/right) and Z is depth (forward backward).

I might not be using all the correct terms. Been programming for 20 years, this is my first shot at a 3D game.

# Answer
> 2 votes
A vector to your camera's right is the same as the forward vector of a camera that's looking 90 degrees further in yaw, and at zero pitch. So you can modify your look vector code to give you your right vector.

```
var rx = Math.Cos(yaw);
var ry = 0;
var rz = -Math.Sin(yaw);

this._right = new Vector3(rx, ry, rz);

```

(Here I used the identities that `Sin(a + 90°) = Cos(a)` & `Cos(a + 90°) = -Sin(a)`)

To strafe right, it's just:

```
this._position += this._right * strafeSpeed;

```

(Or negate it to strafe left)

---
Tags: c#, mathematics, monogame, directx11, sharpdx
---


# Question
Title: How to package a Unity Asset that depends on Addressables?
I'm creating a Unity Asset that I would like to publish on the Unity Store. However, this asset depends on the Addressables package and obviously require an Addressable Database which lives in a folder called AddressableAssetsData in the root directory of the Unity project.

If I don't include this in my package, the Asset won't work and if I do include it, it could conflict with the existing AddressableAssetsData of the user who install my package.

Is it possible to move AddressableAssetsData to a sub-folder of my own package or somehow configure it to not conflict with any future user AddressableAssetsData structures from another user? What would you suggest?

# Answer
> 1 votes
I noticed that the AddressableAssetsData/AssetGroups folder contains Asset files that matches the groups I had created in the AddressableAssets settings.

If I delete one of these groups, I don't see any obvious errors in the Unity editor besides that the Prefabs that used to had addresses no longer have addresses which is expected.

If I restore the previously deleted group, the Prefabs that used to had missing addresses automatically get their addresses back.

So it seems like I only have to package AddressableAssetsData/AssetGroups/\[my project's specific groups that I want to package\] assuming that the end user will already have his/her AddressableAssets setup by the time he/she imports my package.

---
Tags: unity, assets
---


# Question
Title: GLFW window becomes unresponsive when asking for input!
I am trying to write a simple C++ game using OpenGL. In my render loop i ask for text based input from the user but this causes the GLFW window to become unresponsive. I suspect that this happens because the window does not like it when the main thread is paused from std::cin so it behaves weirdly. If i remove the input prompt the window behaves perfectly. Can someone confirm if this is the case and what workarounds are there to fix it?

# Answer
> 1 votes
Yes. Your program is waiting for the user to give their input before continuing.

The workaround to this is to use asynchronous input.

An example of this in GLFW is to use something like this:

`// Set the callback
glfwSetKeyCallback(g_odin.windowManager.g_window, key_callback);
// The function that gets called on key events
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) { /* ... do something ... */ }`

---
Tags: c++, glfw
---


# Question
Title: How to tell which segment user is interacting with in dynamic road building system?
Im prototyping dynamic road building system as seen in most city builder games. I gather the points from user input (red dots) and programmatically generate mesh.

It's currently one big mesh, seems like a good default rendering performance wise.

---

Starting a new road/creating intersection from already existing road is a very important feature. Everything is pretty straight forward except how to know which segment user is hovering, clicking.

Options:

* split segments into separate gameobjects and attach collider to each
* use single big mesh and create empty gameobjects for colliders only

**Is there a better way besides these two?** That would be a lot of colliders if you consider the scale of city builders. I suspect there's a smarter way..

*Note:* on the other hand, if user adds new intersections, updating a huge mesh could be a problem. If I split meshes into reasonable chuncks, I could localize updates to only affected meshes.

---

Simplified data structure:

```
public class Road {
    public List<Segment> segments;
}

public class Segment {
    public Vector3 start;
    public Vector3 end;
}

```

# Answer
You can use a large, procedurally generated mesh collider for your whole road network and still detect on which segment the user clicked.

Use `Physics.Raycast` to detect the road mesh collider under the mouse cursor. The `RaycastHit` structure has a property `.triangleIndex` which contains the number of the triangle where the hit occurred.

So all you need to do is keep a lookup table during your mesh generation which remembers which triangle of your procedurally generated mesh belongs to which logical road segment.

However, you might still want to consider to split your road network into multiple meshes for performance reasons. When the whole road network of the whole city is one big ~~mess~~ mesh, then the Unity rendering engine can't apply frustum culling to ignore the off-screen parts of it. You can't even use LOD groups, because the whole object needs to be rendered in the same level of detail. I also see problems with constantly rebuilding the whole mesh when the player makes changes to the road network.

There are different approaches you could take here, like handling all the roads in rectangular areas as game objects or handling each road from intersection to intersection as one game object. The best approach depends on your game.
> 2 votes

# Answer
You can just loop on all the segments, Find the segment that is closest to the cursor position and get the exact location that you need from there.

As for keeping track of which segments you need to update\regenerate, just add a flag to the segment class that represents if the segment is generated or needs to be regenerated\update and integrate it with your mesh generation function. (you will probably need to separate the road mesh to chunks tho)
> 0 votes

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


title: 2-D character not falling to the ground

text:
# Question
Title: 2-D character not falling to the ground
I am very new to Game Development and I am making a game with a simple Ragdoll which has a body, a head, and 2 limbs(hands). The head and the limbs are hinged to the body and I have kept the Ragdoll above a cube to be used as the ground on which the Ragdoll falls. Till now, I haven't added any scripts for movement or anything, I just want my Ragdoll to fall on the cube below it properly. But when I click play, the Ragdoll just starts to float above its original position. When I move it through the editor away from the cube(ground), it does fall down. It's like the cube is opposing the downward acceleration of the Ragdoll. The Ragdoll won't land on the cube. All the bodies have Rigid body and collider scripts. The Ragdoll also doesn't disassemble, it manages to keep itself together. Can someone please tell me what I am doing wrong. I researched about this but I have found no solution. I am using the free version of Unity.

# Answer
> 1 votes
Your colliders are much larger than the visible portions of your torso or limbs.

In the screenshots you've shown, the green-outlined rectangle and circles are the extents of your colliders. This is the shape that processes collisions with other geometry.

Because these colliders are so huge, they can be resting in surface-to-surface contact with your platform while the visible portion of your body/limbs are still a long distance away, with a lot of apparently-empty space in between. This would account for the "hovering" behaviour you described.

To fix this, adjust the size and offset of your colliders to more accurately match the shape and size of the visual elements whose physical extents they represent. You can do this by editing the numeric fields on the component in the Inspector, or by clicking on the "Edit Collider" button to drag & size the collider visually in the scene view.

---
Tags: unity, 2d, collision-detection
---


title: Rectangular selection on isometric map

text:
# Question
Title: Rectangular selection on isometric map
Before we get started I checked the following questions:
Isometric Tile Selection with rectangular bounding boxes
Isometric rendering and picking?
Calculating the number of tiles shown on an isometric map \<- this is exactly how I get my top-left and bottom-right tile, but I can't calculate what's between them I can pick tiles perfectly, I'm struggling with the automatic selection given two tiles (top-left and bottom-right in screen coordinates).

I've attached a drawing to help you visualize:
As you can see it's a Diamond setup, not staggered isometric. I'm struggling with finding the orange tiles, I have the green tiles' coordinates.

Btw, it's not true isometric, it's 2:1 "isometric".

# Answer
> 2 votes
Let's define the row and column a particular diamond sits in:

```
// Increases top to bottom down the screen.
int Row(Vector2Int tile) { return tile.x + tile.y; )

// Increases left to right across the screen.
int Column(Vector2Int tile) { return tile.x - tile.y; }

```

Note that even rows contain diamonds on even columns, and odd rows contain diamonds on odd columns.

From this it follows that we can convert from rows and columns back to x & y:

```
Vector2Int TileSiteAt(int row, int column) {
    Assert(((row ^ column) & 1) == 0, "Both row & column must have the same parity");

    // row + column = (x + y) + (x - y) = 2 * x
    // (row + column) / 2 = x
    int x = (row + column) >> 1;

    // row - column = (x + y) - (x - y) = 2 * y
    // (row - column) / 2 = y
    int y = (row - column) >> 1;

    return new Vector2Int(x, y);
}

```

With this in hand, we can iterate over our rectangle from the least row to the greatest row, touching every second column in each row between our least column and our greatest column:

```
IEnumerator<Vector2Int> TileSitesInRectangle(Vector2Int start, Vector2Int end) {

    int firstRow = Min(Row(start), Row(end));
    int lastRow = Max(Row(start), Row(end));

    int firstColumn = Min(Column(start), Column(end));
    int lastColumn = Max(Column(start), Column(end));

    for(int row = firstRow; row <= lastRow; row++) {
        // If the row is even and our first column is odd, pick the next even column.
        // Or if the row is odd and our first column is even, pick the next odd column.
        int shift = ((row ^ firstColumn) & 1);
        for(int column = firstColumn + shift; column <= lastColumn; column += 2) {
            yield return TileSiteAt(row, column);
        }
    }
}

```

---

Lua 5.3 code

```
function Row(tile) return tile.x + tile.y end

function Column(tile) return tile.x - tile.y end

function TileSiteAt(row, column)
    local x = (row + column) >> 1
    local y = (row - column) >> 1
    return {x=x, y=y}
end

function TileSitesInRectangle(tile_start, tile_end)
    local firstRow = math.min(Row(tile_start), Row(tile_end))
    local lastRow = math.max(Row(tile_start), Row(tile_end))

    local firstColumn = math.min(Column(tile_start), Column(tile_end))
    local lastColumn = math.max(Column(tile_start), Column(tile_end))

    local result = {}
    for row = firstRow, lastRow do
        local shift = ((row ~ firstColumn) & 1)
        for column = firstColumn + shift, lastColumn, 2 do
            result[#result + 1] = TileSiteAt(row, column)
        end
    end
    return result
end

local res = TileSitesInRectangle({x=2, y=5}, {x=8, y=5})

```

---
Tags: algorithm, isometric
---


# Question
Title: SDL2 C++ How to make enemy move in random directions
How do i make an Enemy move in random directions? I tried this but it doesnt work how i want it to.. thats why im asking what i need to do, to achieve that? (Pseudo code would be cool)

```
 void Enemy::Update()
{
    Timer += Timer->GetTimeElapsed();
    int Random = (rand() % 4);
    if (Timer >= 2.0f)
    {
        switch (Random)
        {
        case(0):
            m_xPos += 10.0f * Timer->tElapsed();
        case(1):
            m_xPos -= 10.0f  * Timer->tElapsed();
        case(2):
            m_yPos -= 10.0f  * Timer->tElapsed();
        case(3):
            m_yPos += 10.0f  * Timer->tElapsed();
        }
    }
}

```

Thank you

Edit: This is the movement i get so far.

# Answer
First of all, you don't have `breaks` in your switch statement, that means that if your random number is for example 1, after subtracting the speed value from the position, the program will keep running inside the switch statement executing the case 2 and 3, so the case 3 will be always executed, making the object move to the bottom and the case 1 will be more executed than the 0 so the object would tend to move the left too.

Now your code would be like this:

```
    switch (random)
    {
    case(0):
        m_xPos += 10.0f * Timer->tElapsed();
        break;
    case(1):
        m_xPos -= 10.0f  * Timer->tElapsed();
        break;
    case(2):
        m_yPos -= 10.0f  * Timer->tElapsed();
        break;
    case(3):
        m_yPos += 10.0f  * Timer->tElapsed();
        break;
    }

```

But now if you run the code you will notice that your enemy tends to be just shaking in the same position, and that's actually moving to random directions each frame but I guess that is not your desired movement, and to have a "better" movement you can do a lot of different things that will give you different results.

**One solution: Moving the players towards a random target in a limited range, and when it reaches the target, set a new one.**

I will use the `Vector2f` struct to do simple calculations with points, `MoveTowards` is for moving a point into the target direction step by step and return true when reaches the target, and `RandomPointInRange`returns a point within a circle of a defined range.

```
struct Vector2f {
  float x;
  float y;

  Vector2f operator+(Vector2f other) {
    return Vector2f{x + other.x, y + other.y};
  }
  Vector2f operator-(Vector2f other) {
    return Vector2f{x - other.x, y - other.y};
  }
  Vector2f operator*(Vector2f other) {
    return Vector2f{x * other.x, y * other.y};
  }
  Vector2f operator/(Vector2f other) {
    return Vector2f{x / other.x, y / other.y};
  }

  Vector2f operator*(float scale) { return Vector2f{x * scale, y * scale}; }
  Vector2f operator/(float scale) { return Vector2f{x / scale, y / scale}; }

  float magnitude() { return std::sqrt(std::pow(x, 2) + std::pow(y, 2)); }
};

bool MoveTowards(Vector2f& originPosition, Vector2f targetPosition,
                 float deltaDistance) {
  Vector2f dif = targetPosition - originPosition;
  float mag = dif.magnitude();
  if (mag <= deltaDistance || mag == 0) {
    originPosition = targetPosition;
    return true;
  }
  originPosition = dif / mag * deltaDistance + originPosition;
  return false;
};

constexpr double PI() { return std::acos(-1); }
float randomFrom0To1() {
  return static_cast<float>(rand()) / static_cast<float>(RAND_MAX);
}

Vector2f RandomPointInRange(Vector2f origin, float range) {
  float r = range * std::sqrt(randomFrom0To1());
  float alpha = randomFrom0To1() * 2 * PI();
  return Vector2f{origin.x + r * std::cos(alpha),
                  origin.y + r * std::sin(alpha)};
}

```

Then you can do something like this in your code and even change your position to be a `Vector2f`:

```
float m_velocity;
const float m_maxStraightMove = 60.f;
Vector2f m_targetPosition =
    RandomPointInRange(Vector2f{m_xPos, m_yPos}, m_maxStraightMove);

void Enemy::Update() {
  Vector2f position{m_xPos, m_yPos};
  if (MoveTowards(position, m_targetPosition, m_velocity))
    m_targetPosition = RandomPointInRange(position, m_maxStraightMove);
  m_xPos = position.x;
  m_yPos = position.y;
};

```

**Another solution would be let the enemy move in a random direction and change the direction in `t + randomOffset` time** which is probably a bit more easy than doing what I did but I leave that for you if you want to try.
> 6 votes

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


# Question
Title: Fill a non rectangular grid with rectangles
I'm developing a city builder with a zoning system similar to Cities: Skylines. What I would need is an algorithm that would find all the way to fill this grid (in red) but with some constraints: In this case, one way to fill it would be to have a building on the left (size 4x3) and one building one the right (size 3x4). But to have some variety, I don't want to always minimize the number of buildings, so in this case I would like also to allow 2 buildings of 2x3 on the left + 1 building of 3x4 on the right. Someone pointed me toward the Dancing Links algorithm to solve this.

# Answer
> 2 votes
Given the requirement that all rectangular partitions must touch the side that goes to the street, the problem is just partitioning over one axis.

The shape we have is a set of rows of variable length. Since we want rectangle partitions, and these partitions must touch the street side, we are forced to partition at any place where the length of the rows change. *If we did not partition there, then we would have partitions that are not rectangular.*

That should convert your jagged area into a list of rectangular areas.

---

From there you can work recursively.

For each rectangular area, decide if it is worth partitioning※₁, decide by a (pseudo)random if you want to partition it, and where※₂. If you did not partition it, that's it. If you did, then you do the same for the partitions.

※₁: It could be that you would rather not partition rectangles of less than a given length, or of less of a given area. *It could even be based on the type of zone.*

※₂: Again, you may want to avoid placing the partition in such place that one of the part is too narrow or too small. Thus, the range of possible positions would avoid a margin. For example, if the minimum width is 2, and you have a rectangle of 5, you would only consider partitioning it at position 2 and 3. Because 1 and 4 are too close to the edge, and 0 and 5 are no partition at all.

*Possible places where you may partition, assuming minimum width of 2, depicted in blue*

---

You do not have to work recursively. This can also be done linearly... you start at one side, decide the minimum and maximum width for an area that starts there and pick by (pseudo)random. You would consider the width of the area that is left when picking the range. This should also make it easier to introduce a maximum width, plus it should work better for long rectangular areas.

---
Tags: grid, space-partitioning
---


# Question
Title: What is the Workflow? Blender -> Substance Painter -> Unreal Engine 4
My name is Jose and I'm pretty new to Game Art Development.

I know some intermediate UE4 (both C++ and Blueprints), but my weakest point has always been the workflow to import assets from Blender and Substance. Up to this point I have always bought external 3D assets.

As far as I know, the workflow is this (but I don't know if I'm correct):

1. **BLENDER:** Create a 3D model in Blender. Create the materials I need for each part of the mesh. UV unwrap it. Export as .fbx
2. **SUBSTANCE PAINTER:** Import the .fbx file into Substance Painter. Paint the 3D model. Export the .obj file AND the texture maps (albedo, roughness, metallic, normal, etc.)
3. **UNREAL ENGINE 4:** Import the .obj file AND the texture maps. Create a material based on these maps. Apply the material to the model.

I have a few questions now:

1. **Is this workflow correct?** Or is there something I'm misunderstanding?
2. What model do I have to import into UE4? The **.fbx from Blender**? Or the **.obj from Substance**? Is there any difference between these two?
3. When exporting the textures from Substance Painter, I can choose from a dropdown called config, to what game engine I'm exporting these textures to (Unity, Unreal, Lumberyard, Cryengine, etc.). What exactly does this option do? **What is the fundamental difference in exporting textures to Unreal or to Unity, for example?**

# Answer
> 1 votes
I'm also learning the ropes but here's how I figured so far.

Blender for modelling mesh, UV mapping, Sculpting
Substance Painter for Texturing, Map baking

Here's my workflow:

(!)At this point we have nothing.
1. Model mesh in detail(either subsurf or multires parts)
2. Sculpt details on multires parts(for organics generally)

(!)At this point we have high poly version of your mesh that cannot be used in a game.
3. Make low poly version of your High Poly mesh(Either by hand, by program or by shrinkwrap), this is called retopologizing which is your worst nightmare.
3.1. Go UV editing mode on LOW POLY mesh and Unwrap your model by seaming, you remember your worst nightmare? This is worster.

(!)At this point we have low poly version that can be put into a game but no textures. If your game isn't about grey people doing stuff in a grey world keep on reading.
4. Export your HIGH POLY mesh as fbx to folder WITH \_high as suffix, mymesh\_high.fbx
5. Export your LOW POLY mesh as fbx to folder WITH \_low as suffix, mymesh\_low.fbx
6. Open Substance Painter and make a new project with your LOW POLY fbx selected
7. Go to Bake Textures setting and select your HIGH POLY mesh(look up a youtube videos for the settings or just experiment)
8. Wait forever till textures bake
8.1. Use a smart material on ALL your materials to see bad parts. 8.2. Well, you see those warped and bad looking places on your textures? Go back to (STEP 3.1.) and seam better, you remember your worster nightmare? Welcome to an endlessly looping worster nightmare. Move on if you give up on correcting it and work with what's at hand.

(!At this point we start texturing)
9. Fail at making cool textures like you see online and make whatever you are able to.
10. Export your textures to a folder while trying not to be ashamed of your work.
IMPORTANT NOTE: You have to select your PLATFORM, I choose Unity you choose Unreal. Look up documentation for up-to-date selection.

(! At this point we have the textures and the mesh)
I don't know Unreal so I'll give the basis of what I do in Unity. I assume they're similar since it's basic work.
11. Open Unity, load project or make new.
12. Import your LOW POLY mesh into project.
13. Import your textures(albedo, metallic, normal in Unity), Substance should be creating the correct ones if you selected the PLATFORM correctly.
14. Apply your textures to material of your mesh.
15. End, you should be having your mesh and textured it in your platform.
16. Keep your chin up and try not to cry because of how horrid it looks.

These were my experiences, here's the answers to your questions.

1. Workflow seems correct
2. Use fbx from Blender
3. Here are the same textures exported by selecting Unreal and Unity. The naming and coloring seems to me are the only differences.

Oh, and if you don't want to work with cool looking game assets and instead make low poly trash use the workflow below:
1. Open blender make a box, do Smart UVing.
2. Select vertices and assign your colored materials on them, texturing DONE! Oh, you want to use Substance? Okay. Export to fbx.
2. Fire up Substance, load your mesh, bake to nothing, throw on fill layers, DONE.
3. Export textures, load everything into engine.
4. Make millions of dollars by making boxes float in mid-air.
5. Throw the money towards the sky while laughing at people who spent days on beautifully hand-painted or sculpt baked textures.

# Answer
> 1 votes
> Is this workflow correct? Or is there something I'm misunderstanding?

This workflow seems correct, although I'm sure someone else could chime in on some sort of integration between Substance Painter and UE4 that makes this easier.

> What model do I have to import into UE4? The .fbx from Blender? Or the .obj from Substance? Is there any difference between these two?

The OBJ from Substance Painter, since this program may affect the mesh data itself (such as UV maps). If possible, consider exporting as other more complex formats like FBX when possible. This may allow the FBX to hold references to the textures and auto-assign them, or even embed the textures inside the FBX.

> When exporting the textures from Substance Painter, I can choose from a dropdown called config, to what game engine I'm exporting these textures to (Unity, Unreal, Lumberyard, Cryengine, etc.). What exactly does this option do? What is the fundamental difference in exporting textures to Unreal or to Unity, for example?

You should export with the option that is most applicable to your situation. In your case, Unreal.

Different engines use different shaders and different types of maps. The default Metallic workflow in Unity for example, uses a "Metallic Map" where the Red channel defines Metallic, and the Alpha channel defines Smoothness (the inverse of Roughness). Other engines like Unreal will have separate Metallic and Roughness maps. Using the correct export function will ensure that the textures are in the correct format.

---
Tags: textures, blender, unreal-4, 3d-modeling, substance-engine
---


# Question
Title: How to make it so that players can only see one specific player but not the others?
I'm developing an educational game whose main mechanics are not multiplayer-oriented. However, I would like to add a feature that allows the teacher to enter the game and all students can see him, but no student can see the other students. Is there a way to do that?

# Answer
> -1 votes
If one object (teacher) could be seen by others (students) - it is multiplayer game.

If you want to students couldn't see each other - this is details of realization of multiplayer game.

Therefore, yes, there is a way to do that:

Packets about teacher send to all students. Packets about students send only to teacher, but not to another students.

---
Tags: unity, multiplayer, unity-networking
---


# Question
Title: How to structure tic tac toe game loop (or equivalent simple turn based game)?
I'm developing the simple Tic Tac Toe game in Java and got stuck on the **game loop architecture**.

The game must support local, remote and automatic players. The graphical interface is based on JavaFX.

How can I best structure the game loop so that the game logic is as separate as possible from the graphic interface?

I have thought of two approaches to solve this problem

# Approach 1 - wait/notify

The simplest approach I thought of is to develop classes for each type of player (remote, interactive and automatic) and implement the necessary code within the mark (Board) method. The update method iterates the players and for each one executes the mark method. In the case of the AI, no problem, but in the case of the interactive player I would find myself having to pause the current thread while waiting for input from the graphic interface thread. A solution that does not convince me.

```
public synchronized void mark(Board board) {
    nextMarkLocation = null;
    try {
        if(nextMarkLocation == null) {
            wait();
        }
    } catch (InterruptedException e) {
        // handling
    }

```

and

```
public synchronized void setNextMarkLocation(Location location) {
    nextMarkLocation = location;
    notify();
}

```

# Approach 2 - expose methods

The second approach would be to implement the methods for setting the current player's action in the game class. In this case, at each execution of the update method the routine would be the following (pseudo code):

```
public void update() {
    var player = getCurrentPlayer();
    var location = player.getNextMarkLocation();
    var symbol = player.getSymbol();
    board.markCell(location, symbol);
    updateCurrentPlayer();
}

```

The GUI will take care of updating itself according to the update of the match and setting the action for the current player. Here a check should be placed on the GUI owner. If the current player is not the same as the GUI owner, the game must ignore the action.

But the problem would be the reverse: And the automatic players?

Do you have any suggestions? Thanks

# Answer
## First of all: M-VC

Separate Game from GUI - a suitable approach might be M-VC (Model-View/Controller). If you do it right, there should be **NO REFERENCE** on the game towards the controller, but the controller knows about the game. Doing it that way you can create controllers for any GUI you want (Android, JavaFX, TCP/IP) without ever changing the game.

## Listener vs Polling

since you have a **turn-based application** you don't need neither nor. It is sufficient to get GUI-updates only when some action is performed. Actions are performed, when you press a button on your GUI (e.g. when you push with your mouse on the *draw card button*). To react on such an event you usually add action Listeners on the according buttons and delegate this action to the model, wich itself returns an animation. The controller is now responsible to draw this animation in a fancy way

## AI-Turn

so what to do when a Player is an AI player? Your Model should already provide methods for the human player, *e.g. `Animation drawCard()`* that executes an action and returns an animation. When a computer player now performs its turn it does the same as a human player, but it returns a bulk of action for it's whole turn *see `List<Animation> Player.playAiTurn()`* where all the actions from the ai player are performed and accumulated. The ai turn starts immediately after the human player ended its turn. Again the controller is responsible for drawing these animations in a fancy way.

## AI vs. AI

same applies as by AI vs. human

## example snippets

AI vs. AI turn is controlled in the controller:

```
private final Game game;

public Controller(Game game){
    this.game = game;
}

public void startGame(){
    do {
        Player current = game.getCurrentPlayer();
        if(player.isAI()){
            List<Animation> animations = current.performAiTurn();
            drawAnimations(animations); //in a fancy way
            game.endTurn();
        }
        //else wait for human player to end its turn via button
    }while(!game.isGameOver());
}

```
> 3 votes

---
Tags: java, game-loop, javafx
---


# Question
Title: Unity3D FindGameObjectsWithTag not recognizing any tags
I'm at a loss here because I'm not sure what's going on. I understand that tags need to exist first, and that you actually have to assign the tags after creating them, but `GameObject.FindGameObjectsWithTag` is not finding ANY tags, including the default tags.

If I try to find MainCamera, which is a built-in tag, I get the following error:

> UnityEngine.UnityException: Tag: MainCamera is not defined. at (wrapper managed-to-native) UnityEngine.GameObject.FindGameObjectWithTag(string) at UnityEngine.GameObject.FindWithTag (System.String tag) \[0x00002\]

What do I do about this? The exact line of code throwing this exception is:

```
mountingObjects = GameObject.FindGameObjectsWithTag(attachesTo);

```

I'm trying to load tags from a file and it's not working.

# Answer
I looked around for a long time for the solution to this and wound up solving it right before I clicked post, so here's the answer for anyone else having the same problem:

In loading from a file, I was splitting the text by the newline `\n` character -

```
string[] lines = fileData.Split('\n');

```

The problem is that, on Windows systems, new lines are defined by the carriage return/line feed sequence.

So, while splitting on `\n` was/is splitting each line at approximately the correct location, **`<string>.Split('\n')` leaves a carriage return on the end of each resulting string. That carriage return does not display in debug messages.**

Instead of trying to find the tag `MainCamera`, I was actually trying to find the tag `MainCamera\r` which does not actually exist.

I found this when putting in `"MainCamera"` worked but the data loaded from file did not. I used the following code to debug:

```
string output = "Hex string:";
byte[] bytes = System.Text.Encoding.ASCII.GetBytes(lineFromFile);
foreach(byte currentByte in bytes)
{
    output += " " + System.Convert.ToString(currentByte, 16);
}
Debug.LogFormat("lineFromFile string is {0}; converts to {1}.", lineFromFile, output);

```

For a line from file that read `MainCamera`, this produced:

```
lineFromFile string is MainCamera; converts to Hex string: 4d 61 69 6e 43 61 6d 65 72 61 d.

```

**Note the `d` at the end of that line!**

Going to an ASCII lookup table gives `0D` to be the carriage return operator.

---

So, ultimately, I think a good way to split a file into lines is to replace all the Windows-style line endings, `\r\n`, with the Unix-style (and maybe Mac-style?) `\n` line endings, then to split the file on the `\n`. In this way, if you're on a Unix system, the Replace command just returns the original string (because it didn't find any `\r\n` sequences), and then for both systems you're breaking the lines correctly.

```
string fileData = File.ReadAllText(filename);
string[] lines = fileData.Replace("\r\n", "\n").Split('\n');

```
> -1 votes

---
Tags: unity, loading
---


# Question
Title: Why it's not removing the right doors from the list?
```
GameObject[] doorsLeft = GameObject.FindGameObjectsWithTag(c_doorLeft);
        GameObject[] doorsRight = GameObject.FindGameObjectsWithTag(c_doorRight);

        List<GameObject> allDoors = doorsLeft.Union(doorsRight).ToList();

        for(int i = 0; i < allDoors.Count; i++)
        {
            if(allDoors[i].transform.parent.name != "Wall_Door_Long_01" && allDoors[i].transform.parent.name != "Wall_Door_Long_02")
            {
                allDoors.RemoveAt(i);
            }
        }

        foreach(GameObject door in allDoors)
        {
            Debug.Log("Door Parent : " + door.transform.parent);
        }

```

If it's not "Wall\_Door\_Long\_01" and not "Wall\_Door\_Long\_01" then remove the item from the list.

After that when I'm doing a loop on the allDoors again and debug log the parents I see that some of the parents are not "Wall\_Door\_Long\_01" and not "Wall\_Door\_Long\_02" but after removing they all should be only "Wall\_Door\_Long\_01" or "Wall\_Door\_Long\_02"

Maybe the comparison is wrong ?

# Answer
> 5 votes
Once you remove at index N, the next value in the list will take it place, and it will be skipped in verification, because you increment an index.

**Solution 1.** Firstly create a list of items to be removed, and then use it as source for removal.

```
    List<GameObject> allDoors = doorsLeft.Union(doorsRight).ToList();
    List<GameObject> toRemove = new List<GameObject>();
        for(int i = 0; i < allDoors.Count; i++)
        {
            if(allDoors[i].transform.parent.name != "Wall_Door_Long_01" && allDoors[i].transform.parent.name != "Wall_Door_Long_02")
            {
                toRemove.Add(allDoors[i]);
            }
        }
        foreach(var it in toRemove)
        {
             allDoors.Remove(it);
        }

```

**Solution 2.** Right after removing at index N, decrement index variable to check the new element at this index again next loop iteration.

```
allDoors.RemoveAt(i);
i--;

```

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


# Question
Title: How to avoid obvious triangle pattern when shading 2d quads?
I'm in the very early stages of writing a 2d tile-based game using Allegro. I've hacked the Allegro source to allow me to specify tint values at each corner of a bitmap, however the resulting image has very obvious patterning where the quad for the bitmap has been rendered as two triangles:

As you can see, there are clear diagonal patterns going from top-left to bottom-right of each quad.

I'm not really sure of the correct terms to be able to search for a solution...

Are there any techniques I can apply to avoid these sorts of artifacts?

Thanks!

UPDATE: To show an example, here is the lighting system with all corners red, except for the bottom-left green:

And now, here's the equivalent with all corners red apart from the bottom-right green:

You can see the patterning is very different - not simply a 90 degree rotation.

Here's some of the Allegro code I modified: https://github.com/stu-smith/allegro5/blob/al\_draw\_corner\_tinted\_scaled\_bitmap/src/win/d3d\_bmp.cpp#L187

# Answer
> 0 votes
Answering my own question here, based partly on some hints given in the comments (thanks!), and partly figuring things out on my own...

The eventual route I took was to scrap my modifications to the Allegro source, and instead render the lightmap using shaders.

As a bit of background: I compute the lightmap for the entire world "offline" in a separate thread.

In the render loop, I take just the visible area of the lightmap (plus an extra tile all around) and draw that to an Allegro memory bitmap.

I can then provide that bitmap as a sampler to the shader that will draw the tiles.

The trick is to realise that you can take the special `al_pos` vector from the vertex shader, that gives the screen position, transform it according to the offset and scale of the overall tile drawing and pass it through to the fragment shader, to be used as a texture coordinate of the lightmap sampler.

Vertex shader:

```
attribute vec4 al_pos;
attribute vec4 al_color;
attribute vec2 al_texcoord;

uniform mat4 al_projview_matrix;

uniform vec2 lightmap_scale;
uniform vec2 lightmap_offset;

out vec4 varying_color;
out vec2 varying_texcoord;
out vec2 varying_lightmap_texcoord;

void main()
{
    varying_color = al_color;
    varying_texcoord = al_texcoord;
    varying_lightmap_texcoord = (al_pos.xy + lightmap_offset) / lightmap_scale;

    gl_Position = al_projview_matrix * al_pos;
}

```

`lightmap_offset` and `lightmap_scale` are fed is as uniform `vec2`s on each frame.

* `lightmap_offset` ranges from 0 to the size of a tile. It is the offset of the overall drawing, modulo tile size.
* `lightmap_scale` is the size of the lightmap. It is the size of the lightmap times the size of a tile.

Now the fragment shader:

```
uniform sampler2D al_tex;
uniform sampler2D lightmap_sampler;

in vec4 varying_color;
in vec2 varying_texcoord;
in vec2 varying_lightmap_texcoord;

void main()
{
    vec4 texture_value = texture(al_tex, varying_texcoord);
    vec4 lightmap_value = texture(lightmap_sampler, varying_lightmap_texcoord);

    gl_FragColor = texture_value * lightmap_value;
}

```

This is very simple: just look up into the tile texture, and the lightmap sampler, and combine them.

Or to think about it another way: I stretch the lightmap over the entire window (and then some). The scale and offset calculations simply work out exactly how it is positioned.

---
Tags: allegro, triangulation
---


title: Quit from Unity to native iOS app

text:
# Question
Title: Quit from Unity to native iOS app
I'm working on iOS application which is going to include a few unity games.
And I investigate an opportunity to exit from the Unity game to the native iOS app with games list.
I know that the Unity provides methods `Application.Quit()` and `Application.Unload()`

I haven't try but I'm not sure that `Application.Unload()` is correct ways to exit from unity to the native iOS app.

# Answer
> 1 votes
You should not use Application.Quit() on iOS devices per unity documentation. If this is an embedded application inside an iOS application then Application.Unload() is exactly what you want. It will release the memory associated with Unity scenes and game elements.

If this isn't an embedded game you should let the user decide when to close the game application.

---
Tags: unity, ios
---


# Question
Title: How can I extend the FindObjectsByTag to filter multiple parents of the found objects?
```
private List<GameObject> FindDoors(string[] parents)
    {
        GameObject[] doorsLeft = GameObject.FindGameObjectsWithTag(c_doorLeft);
        GameObject[] doorsRight = GameObject.FindGameObjectsWithTag(c_doorRight);

        List<GameObject> allDoors = doorsLeft.Union(doorsRight).ToList();

        List<GameObject> toRemove = new List<GameObject>();
        for (int i = 0; i < allDoors.Count; i++)
        {
            for (int x = 0; x < parents.Length; x++)
            {
                if (allDoors[i].transform.parent.name != parents[x])
                {
                    toRemove.Add(allDoors[i]);
                }
            }
        }
        foreach (var it in toRemove)
        {
            allDoors.Remove(it);
        }

        foreach (GameObject door in allDoors)
        {
            Debug.Log("Door Parent : " + door.transform.parent);
        }

        return allDoors;
    }

```

Usage :

```
var allDoors = FindDoors(new string[]{ "Wall_Door_Long_01", "Wall_Door_Long_02" });

```

But in the function FindDoors the return allDoors is empty. I think the problem is at this IF :

```
if (allDoors[i].transform.parent.name != parents[x])

```

Once it's Wall\_Door\_Long\_01 so if it's Wall\_Door\_Long\_01 it will not remove the item but next it's Wall\_Door\_Long\_02 so now the it's true and will remove the even if the parent name is Wall\_Door\_Long\_01 and same if it's Wall\_Door\_Long\_02

And then in the end it will remove all the items. But I want it to remove only doors that the parents of them is not Wall\_Door\_Long\_01 and not Wall\_Door\_Long\_02

# Answer
> 1 votes
If you want to match all criteria you must check for all conditions before removing.

```
bool match = true;
for (int x = 0; x < parents.Length; x++){
  match &= allDoors[i].transform.parent.name != parents[x];
}
if(match){
  toRemove.Add(allDoors[i]);
}

```

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