# Question
Title: Change localScale.x in Unity without creating a new Vector3
Is it possible to change localScale.x in Unity without creating a new Vector3?

# Answer
Yes, simply write: `localScale.x = 100.0` or whatever you'd like.

This doesn't work when the `localScale` you're referring to (which is not clear) is a *property* of some instance, because C# properties are just syntactic sugar for function invocations and you'd thus be changing a member of a local temporary, not the *actual* backing `Vector3`. In those cases you must replace the entire `Vector3`, as in `foo.localScale = new Vector3(x, y, z);`.

This may be a minor inconvenience in terms of typing, but since `Vector3` is a value type there is no appreciable performance overhead (you're not creating garbage on the heap, for example, as you would if `Vector3` was a reference type).
> 2 votes

---
Tags: unity, transformation, scale
---


# Question
Title: How do I setup positional audio in Unity?
I'm trying to make an audio game where by players can tell the position of an object listening to whether the right or left speaker is playing the audio.

The idea is:

**If the object is on the left hand side**

**Play the audio of that object through the left speaker**

**Right hand side = right speaker**

How would I do this in Unity?

# Answer
Unity has a full-fledged system for 3d audio. Take a look at the components AudioListener and AudioSource.

When the game object with the AudioSource is right from the game object with the AudioListener, it will play on the right stereo channel, and when it is left from the AudioListener, it will play on the left.
> 4 votes

---
Tags: unity, audio
---


title: Chaining Melee Attacks

text:
# Question
Title: Chaining Melee Attacks
I am working on an action platformer using Pygame.

My player sprite has three melee attacks. Let's call them SLASH\_1, SLASH\_2, and SLASH\_3. Each of these attacks has, let's say, 2 animation frames, the same hit box, and results in the same amount of damage.

I want the mechanics of my game to be such that if the user presses the attack button three times in quick succession, the sprite will do each attack in turn (regardless of whether there's an enemy around). For an example of what I'm talking about, see here.

I have currently implemented this in the following way:

I have an empty list called "attack\_queue" into which I insert attack animation frames when the user presses the attack button. If they press it quick enough, the second and third attacks are added into the list. On each iteration of my game loop, I animate the first frame of the attack\_queue (if it's non-empty). The animation code also generates hit boxes for each attack as well as checks for whether the attacks land on an enemy. Once a frame has been animated, it is removed from the attack\_queue.

Here's some pseudo-code to give you a better idea:

```
...
now = get_current_time()

attack_queue = []
    if attack_button pressed:
        if now - last_attack > 50 ms:
        n = 0
        add attack_animations[n] to attack_queue
        last_attack = now
    else if now - last_attack < 50 ms:
        n += 1
        add attack_animations[n mod 3] to attack_queue
        last_attack = now

animate(attack_queue)
...

```

This works okay for the time being, but I doubt it's the most elegant way of implementing attack chains. (One problem I am having is that this method results in a bit of input lag, since the player is able to press the attack button a third time before the second attack animation has finished.)

My questions are:

1. In general, what are some other methods of implementing attack chains?
2. Specifically for Pygame, what are the best ways of implementing attack chains?

---

A similar question is addressed on Reddit here, but I am looking for a more fully fleshed out answer.

# Answer
The problem with this approach is that when the player presses attack three times, the player-character is locked into the attack chain and the player can not interrupt it. The player might perceive that as unresponsive controls.

Other options:

* Have the character cycle through all available attack animations while the player holds down the attack button. When an attack animation ends, check if the player is still holding the attack button. If it's still down, proceed with the next attack animation. When it's not down anymore, go back to the default pose.
* Alternatively, if you want to maintain the haptic of "three button presses = three attacks", add a short time-window after each attack animation:
    + If the player presses the attack button and the current animation is still playing, do nothing.
    + If the last attack ended less than `n` milliseconds ago, play the next attack animation.
    + If the last attack ended `n` or more milliseconds ago or this is the first time the player presses attack, play the first animation.
> 1 votes

---
Tags: animation, game-mechanics, python, pygame
---


# Question
Title: Making a scriptable dynamic Distance Joint in Unity
I have 2 2D RigidBodies that are connected together using a `Distance Joint 2D`...

I update the distance of said `Distance Joint 2D` (using a script) expecting the distance between the two RigidBodies to change, but nothing actually happens.

I'm guessing this is to do with the Physics engine not updating the positions of the RigidBodies?

# Answer
> 1 votes
I tried to do the same thing. My problem was solved by applying a force of size 0 to some body. My uneducated guess: just changing joint distances is not sufficient for the physics engine to update.

Try this on a rigidbody:

```
    body.AddForce (new Vector2 (0, 0), ForceMode2D.Impulse);

```

Hope it helps you!

---
Tags: unity
---


title: Spawn rates and variable time steps

text:
# Question
Title: Spawn rates and variable time steps
How would I work a spawning algorithm into a sim engine with variable time steps?

If each engine step is, say, 1/30 of a second and I have some event occur with a 0.001 probability each step, how do I translate this to an engine with a variable time step? At the end of 1 second I could have nothing spawned or (in a very unlikely event) I could have as many as 30 spawned.

Now if the engine hasn't done an update for a full second, how can my spawner simulate the same behaviour and probabilites? What if my steps are much smaller, say 1/100 or 1/1000 of a second?

What algorithms can I use?

# Answer
I'd go with something like this (pseudo-code):

```
spawnProbability     = 0.001 // Your original probability at fixed timestep
spawnAtThisFrequency = 1/30  // The original fixed timestep dt
dtAcc                = 0     // An accumulator that will accumulate the variable dt

update( dt )
{
  dtAcc += dt; // Accumulate

  while( dtAcc >= spawnAtThisFrequency ) // If enough time has accumulated...
  {
    dtAcc -= spawnAtThisFrequency // remove from the accumulator
    tryToSpawnWithProbability( spawnProbability ) // and try to spawn
  }
}

```

With this, you take into account that the dt can be smaller than what it was with a fixed timestep, and you can also handle larger dt.
> 4 votes

# Answer
The number of spawns will be distributed as a binomial, the sum of the Bernoulli RVs of your spawn windows.

E.g., say for a window *w* of some number of ticks per spawn opportunity, and an elapsed ticks *e* since last check, with Bernoulli probability of *p* per spawn window, the number of spawns will be distributed as

> B(e/w,p)

So, at each spawn check (end of period *e*), take one sample from the resulting distribution, and you have the total number to spawn.

Obviously, e/w is not always an integer, so round/floor/ceiling as desired.
> 0 votes

# Answer
I just used Random.Range for my spawn times. Could you use the same?
> -1 votes

---
Tags: timestep, spawning, probability
---


# Question
Title: increasing speed of sound as player approaches
I am trying to create a sound that increases in speed as the player gets closer to the object. The sound is just a single 'ping' and will increase in frequency as we approach, once we are on top of it, it should play a different sound. I can't seem to get it to work. Here is what I've done in blueprints:

I'm not extremely experienced with Blueprints and I have almost no experience with working with sound in it. From my understanding, the blueprint should be measuring the distance between the object and the player, dividing it by .5, and then returning the sound at that speed.

Currently, I'm getting no sound whatsoever.

# Answer
For anyone looking to fix this problem in the future, the problem was that I imported the sound but didn't actually create a real sound cue. If you right click, select create sound cue, it's pretty self explanatory from there. Also, you can set attenuation manually, but if you are going to be using multiple different sound assets and some of them may have the same attenuation settings, you can create an attenuation asset to reuse! Then just attach the sound cue to the hierarchy of the asset you want the sound to emanate from.
> 1 votes

---
Tags: unreal-4, sound, sound-effects, blueprints
---


# Question
Title: Best way to connect multiplayer users with each other (matchmaking) on a low powered server?
OK so I am using unity to make a multiplayer game, but I'm not sure how to connect players with each other over the internet.

Unlike other questions, this isn't a general problem of working out how to do UPnp or using unity's matchmaking server. My issue is that my server that I would use is a simple low powered pc (running normal windows 10, no idea how to use windows server).

I think it is powerful enough to match players with each other, but not to host more than one or two actual games.

The other issue is that I have a residential internet connection with a dynamic ip that changes every few months. However the speed should be ok (150Mb/s download, 20Mb/s download).

Also, I'm not planning to spend money on a monthly basis for a server (like unity's matchmaking service) as I plan to spend as little as possible (So far I've paid £12 to Microsoft for a dev account and I've received a £200 voucher from them so my current spending is -£189!)

So my question is should I use my server (would it work), are there any online services that are very cheap to use, or is there another way to make this work?

Only other thing is I could use the free 20 users at once on unity's matchmaking, but would this limit be too small?

EDIT: just for information, my game is a simple tank shooter. I was thinking about limiting the amount of tanks in a game somewhere around 8-20. The bullets in my game are physical objects with rigidbodys and they move at a slower speed (if you've ever played tank trouble, it looks like that). The world is in 3D. There is a potential for there to be up to a hundred bullets in a scene at once at the worst. After hosting a LAN world with 7 players connected for about 20-30 minutes, windows reports the data usage being around 3-4MB.

# Answer
Don't go the home server route. The hassle and reliablity problems (dynamic IP, power, etc.) aren't worth it.

* Get yourself a small VPS for a fiver per month.
* Amazon's AWS offers (or used to at least) a micro instance free for the first year
* Google's app engine (applicable if you implement the matchmaking service on one of their supported platforms) has a fairly generous free quota if I'm not mistaken.

Implementing a matchmaking service, which lets the player's connect to each other (i.e. isn't running the game itself) shouldn't require much resources, nor would it require a specific OS.

The above suggestions are also easy to scale if your game takes off.
> 1 votes

---
Tags: unity, multiplayer, server, online
---


# Question
Title: in unity, lightmap comes out blurry on android device
as you see, shadow is blurred. (see the tree's shadow)

What settings should I add?

# Answer
> -3 votes
Mkj6026, I think you should polish the gameObject which stands for the TREE. Because, look at the car. The car's shadow isn't blurred. There is something wrong only with the trees. Try re-implementing your lighting. Or you can also try adding more trees to your scene and see if the problem still persists. If it does, try changing the code of your tree gameObject and check if something's wrong.

I think think your code is correct and there shouldn't be any problem. You can also try testing on another Google Android device.

---
Tags: unity, android, lightmap
---


# Question
Title: C++ and TinyXML2 Error: **this** was nullptr
I'm trying to make a video game using Microsoft Visual Studio Community 2017 and Simple DirectMedia Layer 2 (SDL 2.0.5, and SDL image loading file version 2.0.3).

A map editor called 'Tiled!' was used by me to create the levels for the game. The files created using Tiled! are saved by the '\*.tmx' file extention, in the XML format. I decided to use an XML parser called TinyXML 2 , by Mr. Lee Thomson (a.k.a. 'Grinning Lizzard') to parse my TMX files, as they were in the XML format.

I wrote a whole lot of code in the C++ programming language to parse the files. There were no build errors as well. When I debugged all I could and finally compiled the program, there was a breakpoint error, an 'exception was thrown' and it crashed,... showing this on the output window:

```
Unhandled exception thrown: read access violation.
**this** was nullptr.

```

Here is the 'level.h' file:

```
 // LEVEL CLASS: Contains information regarding levels or maps

#ifndef LEVEL_H
#define LEVEL_H

#include <string>
#include <vector>
#include "asa_globals.h"
#include "asa_tile.h"

class Graphics;
class SDL_Texture;

struct SDL_Rect;
struct Tileset;

class Level {
public:
    Level();
    Level(std::string mapName, Vector2 spawnPoint, Graphics &graphics);
    ~Level();
    void update(int elapsedTime);
    void draw(Graphics &graphics);

private:
    std::string _mapName;
    Vector2 _spawnPoint;

    Vector2 _size;
    Vector2 _tileSize;

    SDL_Texture* _backgroundTexture;

    std::vector<Tile> _tileList;
    std::vector<Tileset> _tilesets;

    // void loadMap(...);
    // Loads the map onto the screen
    void loadMap(std::string mapName, Graphics &graphics);

};

// Tileset Structure
struct Tileset {
    SDL_Texture* Texture;
    int firstGid;

    Tileset() {
        this->firstGid = -1;
    }

    Tileset(SDL_Texture* texture, int firstGid) {
        this->Texture = texture;
        this->firstGid = firstGid;
    }
};

#endif

```

And here is the level.cpp file. Before modifying the 'void Player::loadMap(...) {...}' function, everything worked just fine. Now, when I added the XML parsing code, there seems to be a problem:

```
 // LEVEL CLASS: Contains information regarding levels or maps

#include "SDL.h"
#include "asa_level.h"
#include "asa_graphics.h"
#include "asa_globals.h"
#include "asa_tinyxml2.h"
#include "asa_player.h"

#include <sstream>
#include <algorithm>
#include <cmath>

using namespace tinyxml2;

Level::Level() {}

Level::Level(std::string mapName, Vector2 spawnPoint, Graphics &graphics) :
    _mapName(mapName),
    _spawnPoint(spawnPoint),
    _size(Vector2(0, 0))
{
    this->loadMap(mapName, graphics);
}

Level::~Level() {}

void Level::loadMap(std::string mapName, Graphics &graphics) {
    /* NOTICE: Element-to-Attribute order
         (i)   XML Document
         (ii)  Map ('mapNode')
         (iii) Tileset
         (iv)  Layer
         (v)   Data
    */

    // Parse the '*.tmx' file
    XMLDocument doc;
    std::stringstream ss;
    ss << "c:/Users/Utpal/Desktop/ASA Artwork/levels/lvl_1/" << mapName << ".tmx";
        // E.g.: Pass in 'lvl_1', get 'lvl_1.tmx'
    doc.LoadFile(ss.str().c_str());

    XMLElement* mapNode = doc.FirstChildElement("map");

    // Get the width and height of the map and store it in the variable called '_size'
    int width, height;
    mapNode->QueryIntAttribute("width", &width);
    mapNode->QueryIntAttribute("height", &height);
    this->_size = Vector2(width, height);

    // Get the width and height of each tile and store it in the the variable called '_tilesize'
    int tileWidth, tileHeight;
    mapNode->QueryIntAttribute("tilewidth", &tileWidth);
    mapNode->QueryIntAttribute("tileheight", &tileHeight);
    this->_tileSize = Vector2(tileWidth, tileHeight);

    // Loading the tilesets for the maps
    XMLElement* pTileset = mapNode->FirstChildElement("tileset");
    if (pTileset != NULL) {
        while (pTileset) {
            int firstgid;
            const char* source = pTileset->FirstChildElement("tileset")->Attribute("source");
            char* path;
            std::stringstream ss;
            ss << source;
            pTileset->QueryIntAttribute("firstgid", &firstgid);
            SDL_Texture* tex = SDL_CreateTextureFromSurface(graphics.getRenderer(), graphics.loadImage(ss.str()));
            this->_tilesets.push_back(Tileset(tex, firstgid));

            // If there is any next tileset, move on to it. Else, continue.
            pTileset = pTileset->NextSiblingElement("tileset");
        }
    }

    // Loading all the layers
    XMLElement* pLayer = mapNode->FirstChildElement("layer");
    if (pLayer != NULL) {
        while (pLayer) {

            // Loading the 'data' child-element of the 'layer' element
            XMLElement* pData = pLayer->FirstChildElement("data");
            if (pData != NULL) {
                while (pData) {

                    // Loading the tiles
                    XMLElement* pTile = pData->FirstChildElement("tile");
                    if (pTile = NULL) {
                        int tileCounter = 0;
                        while (pTile) {

                            // Each indivisual tile is to be built here
                            // If gid is 0, no tile should be drawn, continue loop
                            if (pTile->IntAttribute("gid") == 0) {
                                tileCounter++;
                                if (pTile->NextSiblingElement("tile")) {
                                    pTile = pTile->NextSiblingElement("tile");
                                    continue;
                                }
                                else {
                                    break;
                                }
                            }

                            // Get the tilest for this specific gid
                            int gid = pTile->IntAttribute("gid");
                            Tileset tls;
                            for (int i = 0; i < this->_tilesets.size(); i++) {
                                if (_tilesets[i].firstGid <= gid) {
                                    // Yeah, cool! This is the tileset we need for this tile
                                    tls = _tilesets.at(i);
                                    break;
                                }
                            }

                            // Check if the program was not able to find anything
                            if (tls.firstGid == -1) {
                                // No tileset was found for this particular gid
                                tileCounter++;
                                if (pTile->NextSiblingElement("tile")) {
                                    pTile = pTile->NextSiblingElement("tile");
                                    continue;
                                }
                                else {
                                    break;
                                }
                            }

                            // WARNING!: Confusing section. Keep an ice-pack ready
                            // Get the position of the tile on the map
                            int xx = 0;
                            int yy = 0;
                            xx = tileCounter % width;
                            xx *= tileWidth;
                            yy += tileHeight * (tileCounter / width);
                            Vector2 finalTilePosition = Vector2(xx, yy);

                            // WARNING!: More Confusing section. Keep an ice-pack ready
                            // Get the position of the gid on the tileset
                            int tilesetWidth, tilesetHeight;
                            SDL_QueryTexture(tls.Texture, NULL, NULL, &tilesetWidth, &tilesetHeight);
                            int tsxx = gid % (tilesetWidth / tileWidth) - 1;
                            tsxx *= tileWidth;
                            int tsyy = 0;
                            int amt = gid / (tilesetWidth / tileWidth);
                            tsyy = tileHeight * amt;
                            Vector2 finalTilesetPosition = Vector2(tsxx, tsyy);

                            // Build the actual tile and add it to the tile-list of the map
                            Tile tile(tls.Texture, Vector2(tileWidth, tileHeight), finalTilesetPosition,
                                finalTilePosition);
                            this->_tileList.push_back(tile);
                            tileCounter++;

                            // If there is any next tile, move on to it. Else, continue.
                            pTile = pTile->NextSiblingElement("tile");
                        }
                    }

                    // If there is any next data group, move on to it. Else, continue.
                    pData = pData->NextSiblingElement("data");
                }
            }

            // If there is any next layer, move on to it. Else, continue.
            pLayer = pLayer->NextSiblingElement("layer");
        }
    }
}

void Level::update(int elapsedTime) {}

void Level::draw(Graphics &graphics) {
    // Draws the background onto the screen (TEMPORARY CODE)
    for (int i = 0; i < this->_tileList.size(); i++) {
        this->_tileList.at(i).draw(graphics);
    }
}

```

The tile variable and the namespace named 'globals' is from other files. It's a huge project. If you insist, I can include more header or C/C++ source code files. Let me know via your comments.

Here is the main function:

```
  // The Main Entry Point of the Program

#include "asa_game.h"

#ifdef main
#undef main
#endif

int main(int argc, const char* argv[]) {
    Graphics graphics;
    Game game;

    return 0;
}

```

As, I said, running the program throws an exception (breakpoint), and displays Read access violation: this was nullptr These details are highlighted from the original 'tinyxml.h' file when the program crashes:

```
/** Given an attribute name, QueryIntAttribute() returns
    XML_NO_ERROR, XML_WRONG_ATTRIBUTE_TYPE if the conversion
    can't be performed, or XML_NO_ATTRIBUTE if the attribute
    doesn't exist. If successful, the result of the conversion
    will be written to 'value'. If not successful, nothing will
    be written to 'value'. This allows you to provide default
    value:
    @verbatim
    int value = 10;
    QueryIntAttribute( "foo", &value );     // if "foo" isn't found, value will still be 10
    @endverbatim
    */
    XMLError QueryIntAttribute(const char* name, int* value) const {
        const XMLAttribute* a = FindAttribute(name);
        if (!a) {
            return XML_NO_ATTRIBUTE;
        }
        return a->QueryIntValue(value);
    }

```

Here is the CPP version of the above:

```
const XMLAttribute* XMLElement::FindAttribute(const char* name) const
{
    for (XMLAttribute* a = _rootAttribute; a; a = a->_next) {
        if (XMLUtil::StringEqual(a->Name(), name)) {
            return a;
        }
    }
    return 0;
}

```

I'm sure I wrote the code correctly (I mentioned there were no build errors). The includes are perfect as well.

I know build errors don't mean the program is correct -- that's why I need the help of you guys.

I suspect there is something fishy with the initialization list, or some kind of pointer error.

Please provide any fixes of the **this** was nullptr breakpoint error fix, from your experience, if possible.

Thank you.

# Answer
> 1 votes
Your error is caused by you calling a method on a pointer that doesn't exist. It's impossible to tell which of your values is `nullptr` but it's really easy for you to figure that out. All you need to do is to look at the callstack in your IDE of choice when the game crashes.

```
class Foo
{
public:
    Foo() { }

    void Bar()
    {
        std::cout << a << std::endl;
    }

    int a = 0;
};

```

Take a look at this basic example class. `Bar` is a method that simply displays the value of the member `a`.

Now, if you do `Foo* f = nullptr; f->Bar()`, you'll get the same error:

> Exception thrown: read access violation. **this** was nullptr.

This happens because `f` doesn't exist, so there is no `a` that could be outputted.

The callstack shows the `Bar` method at the top, and the caller code is the step below that one. Using that you should be able to figure out what is going wrong. `nullptr` errors should be relatively trivial to fix. You're simply failing to load/find/create something.

---
Tags: c++, windows, sdl2, visual-studio, xml
---


# Question
Title: Unity - How to move a user controlled animated gameobject programmatically?
I have a player controlled gameObject with an attached script and animator with it's related animations. It all works great.

However the gameObject is on screen immediately on level startup.

I want to have the gameObject start off-screen so that story dialog can be displayed first and once completed the player gameObject will move onto the screen and then come under the players control.

I have been able to create a separate animator state for the "off-screen to on-screen" animation and it can be triggered separately in code. But I can't work out the logic needed to get the gameObject to do what I want.

In the enclosed image the PaddleIdle state keeps the paddle off screen. The PaddleStartup state moves the gameObjects position onto the screen. Once on-screen, the PaddleNormal state is supposed to start the gameObjects normal animations and allow player control.

I have tried a default transition from PaddleStartup to PaddleNormal but it performs one "PaddleStartup" sequence and then there is nothing.

I know I am missing something either I am not configuring a transition correctly or I am not scripting this correctly, can someone advise me on things I might try?

Thank you so much for your help

# Answer
> -1 votes
You have not given enough info. But you can use something like this (the code may differ depending on the version):

```
...
if (this->sceneManager.currentScene == "boot") {
  this->_status = INVISIBLE;
}
...
...
If (this->_status == INVISIBLE) {
  this->player.playAnimation("invisible");
}

```

You can add an invisible animation in the `void Player::setupAnimations(...)` function, in which there are sprites with only a black background. The `this->_status = INVISIBLE;` statement means there is a global enumeration called `_status` like given below:--

In the file `globals.h`:

```
...
enum PlayerStatus {
  ALIVE,
  DEAD,
  INVISIBLE
}
...

```

And, in the file 'player.cs' (for your player gameObject):

```
...
protected:
  PlayerStatus _status;
...

```

If the current scene is displaying your game's title then the `_status` will be `INVISIBLE`. and if the `_status` is `INVISIBLE`, the `"invisible"` animation will be played.

Hope that helped.

---
Tags: unity, animation
---


title: Calculating coordinates of a point

text:
# Question
Title: Calculating coordinates of a point
I struggle to find coordinates of point B in the picture below. I know the positions of `A` and `C`, the length of arm `c` and angle `beta`

I need it to make a gun next to the player point to the direction of a cursor. And the gun will rotate with the player. I think there must be a simple way to do it, but I'm missing it somehow. Could you point me to the right direction?

# Answer
> 2 votes
If beta is 90°:

The `CAB` angle is `angle = acos(c / AC)`, the B point is

```
A + (AC.x * cos(angle) - AC.y * sin(angle), AC.x * sin(angle) + AC.y * cos(angle)) / |AC| * c

```

Where `|a|` is the length of the a vector

If beta isn't 90°:

the law of sines (`a / sin(A) = b / sin(B) = c / sin(C)`) says, that

```
|AC| / sin(beta) = c / sin(gamma)

```

We can reorder this to get gamma:

```
gamma = asin(c / |AC| * sin(beta)

```

Then use the rotation above:

```
B = C + (CA.x * cos(gamma) - CA.y * sin(gamma), CA.x * sin(gamma) + CA.y * sin(gamma)) / |AC| * sqrt(|AC|^2 - c^2)

```

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


# Question
Title: Unity is Single Thread by how do WWW with coroutine work Async
When I used **HttpWebRequest** and **HttpWebResponse** classes for an API calling my game suddenly halt for some seconds but as i used same API calling through **WWW** with coroutine, it didn't halt.

I heard that unity is single thread but why my game not halt as i used WWW with coroutine? and is i am getting right that HttpWebRequest and HttpWebResponse are not better than WWW?

# Answer
A `coroutine` runs on the main thread but when ever you use a `yield return`, it tells the program to stop operating this function, save the state of the function and continue executing the rest of the frame.
You can determine when the function would allow the rest to execute by returning different values by `yield return`.
for example when you say `yield return null;` the method will resume functioning as soon as the updates have completed their work.
but if you use `yield return new waitForEndOfFrame();`, the function will resume as soon as all the work in the frame is done and the screen is ready to be updated.
usually when using a `WWW`, you would check for the `isDone` property and keep checking and coming back to the function until `isDone` returns true.

```
WWW www = new WWW(URL);
yield return www;
while (!www.isDone)
{
    yield return www.progress;
}
if (!string.IsNullOrEmpty(www.error))
{
    Debug.Log(www.error);
}
if (!string.IsNullOrEmpty(www.text))
{
    Debug.Log(www.text);
}

```
> -1 votes

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


# Question
Title: How should I implement an Observer patter in the following example
I am wondering how I implement an observer pattern in the following example. I am mostly wondering what should be in charge of subscribing.

**The Example**

A factory produces cars (Observable), they drive from A to B. Once at B the car has finished. The scoreboard increases by +1 (Observer).

**The Solution?**

Option A.) The factory spawns a car, it then calls a method to subscribe the car to the scoreboard

observableCar.FinishedEvent += observerScoreboard.HandleEvent;

Option B.) Should the cars on being created register / tell the the scoreboard to subscribe itself to it the cars finishedEvent()

this.FinishedEvent += observerScoreboard.HandleEvent;

Option C.) The scoreboard is subscribed to a 'carSpawned' event on the factory. On recieving this event it then subscribes itself to the cars finishedEvent(). It then unsubscribes.

Option D.) I am missing something fundamental about the observer pattern, do more homework

I'm thinking its something more akin to option C? I'm not sure.

Thanks very much

Jim

# Answer
> 1 votes
First of all, any of the three options is a valid solution. There is never just one right way to do something in software engineering.

However, I would recommend the option which results in the least coupling between car and scoreboard. Loose coupling means the less objects need to know about other objects, the better. In the ideal case, they would not even know that objects exist which are not relevant to their primary functionality. An event system is a great way to achieve loose coupling, because objects are able to post events without knowing anything about which objects are going to process them.

Another concern is trying to always do things the same way. Who is responsible in your system for subscribing and who is responsible for unsubscribing? The sender, the receiver or a middle-man? Whichever convention you pick, it can be useful to try to stick to it throughout your code-base. Otherwise you might get confused about when and where you set up your subscriptions and end up subscribing to something twice or not at all.

**Option A:** A factory is one of the few classes where tight coupling with its product can not be avoided. That's why factories exist. So the logic for setting up event subscriptions fits there quite well. But the question is, does the car factory need to be coupled to the existence of the scoreboard? What if you add more things which process car-related events? Does the factory really need a dependency on every one of these features?

**Option B:** Do the cars need to know that the scoreboard exist? If they know about the scoreboard, they would also be able to notify it by itself when it finished the race. You wouldn't need that detour via the event system in the first place. So cars shouldn't register themselves to the scoreboard. I would in fact try to make them completely oblivious to the existence of the scoreboard. I haven't seen your Car-class, but when it's the main game-object your game is about, it's quite likely already has more than enough responsibilities. Anything you can move somewhere else will likely keep it from mutating into a bloated god-object.

**Option C:** This option is the one I personally like best. The factory doesn't know about the scoreboard (it just knows something subscribed to `carSpawned`) and the car doesn't know about the scoreboard (just that something subscribed to `carFinished`). The only thing I don't like about it is that there is no clear concept of for who is responsible for setting up subscriptions. `carSpawned` is subscribed by the sender and `carFinished` is subscribed by the receiver.

Unfortunately there is no perfect solution to this conundrum. Objects don't exist in limbo. To glue two objects together with event subscriptions, there must be some object which knows both of them.

A solution which I prefer is having objects communicate only through a global `EventSystem` object. Observers don't subscribe to Observables, they subscribe for a specific event on the `eventSystem`. Observables don't post events to their Observers directly, they post them to the `eventSystem`. The `eventSystem` is then responsible for routing events to every object which subscribed to them. Such a system usually scales pretty well, because new features can often be added by simply using already existing events without having to do any changes at the objects which already send/receive them. However, for games with a very limited scope, such an event system can be overengineering. It also adds a layer of indirection which can make debugging harder and can cause performance problems when you overuse it.

---
Tags: c#, architecture, software-engineering
---


# Question
Title: How to await async operations / coroutines?
I'm looking for a generic / reusable way to wait for coroutines and asynchronous operations to finish in Unity 5, similiar to C#5's `await` keyword.

The simplest way I can think of is something like this:

```
 public class SomeUtility {
     public bool IsDoingSomething { get; private set; }

     public IEnumerator DoSomethingAsync() {
         IsDoingSomething = true;
         yield return new WaitForSeconds(2);
         IsDoingSomething = false;
     }
 }

```

and then in another coroutine:

```
 while(!someUtilityInstance.IsDoingSomething)
     yield return null;

```

However this is not very nice because it clutters the code with `while` statements, is not reusable (needs instances and dedicated classes even for simple utility functions!) and a lot of singleton or static stuff where it's not even needed.

The closest I found is using Unity's `AsyncOperation`. This here works very nicely:

```
public static IEnumerator Await(this AsyncOperation operation) {
    while(!operation.isDone)
        yield return operation;
}

yield return SceneManager.LoadLevelAsync("blaaaah").Await();

```

However.. the problem is: How to create an `AsyncOperation`? A few services, for examples `SceneManager` are using it, but the documentation completely lacks anything about creating custom operations or wrapping existing coroutines etc.

So, is there a way to create a simple, generic and resuable "await" for custom coroutines?

# Answer
```
yield return StartCoroutine(yourIEnumatorMethod());

```

Will wait until your method has completed, the only inconvenient with that solution is it forces you to make this call within an `IEnumator` method.

See http://docs.unity3d.com/ScriptReference/Coroutine.html
> 2 votes

# Answer
With Unity 2017 you can now use async await as an alternative to coroutines as described here
> 0 votes

---
Tags: c#, unity, multithreading, coroutines
---


title: Reflect Code Changes in a Current Run

text:
# Question
Title: Reflect Code Changes in a Current Run
I am developing a game in Python using Pygame. I am wondering whether there is a way to make changes to a currently running game by modifying the script (like Notch does in this clip).

For example, suppose I am doing a bit of testing and I want to increase my player jump height variable. I would like to simply go into the script while the game is running, change the value of the variable, and have the new value reflected in the current run. This would simplify the process of fine-tuning all my physics variables.

My IDE is Sublime Text (I know, it's actually just a glorified text editor, but you can run code from it).

Is there any way to do this? For example, with a particular IDE?

# Answer
*This answer will be short because I'm on my phone.*

---

I haven't watched the video from your link, but a way you could accomplish something like this this for your code's parameters is:

1. isolate all constant values of your game and somehow centralize them in a dictionary;
2. put all the values in a separate text file, and make sure you can retrieve them with a text key (this can be a JSON file, an XML file or simply something that looks like an INI file, or whatever you fancy);
3. implement a load/reload shorcut key in your game which will order it to re-populate the centralized dictionary based on the values in the text file.

This way you can start your game, play a bit, tweak a value, hit the reload key and you have your tweaked behaviour without the need to restart the game.

Going one step further: your game could detect that the file has changed (based on the OS' information of the last modification date/time of the file) and reload it for you.
> 2 votes

---
Tags: python, pygame, testing
---


# Question
Title: Matrix multiplication order for multiple model transformations
I have a problem in terms of what frame of reference, I should construct, scaling (S), rotation (R) and translation (T) for a model matrix (in that order). Let us assume the use of glm (or glsl), i.e. to mean column major representation.

I believe, it should be a matrix multiplication of:

```
M = T * R * S // S * R * T is what we want to apply, but due to being column major, the order gets reversed, due to (AB)^T =B^T*A^T

```

Now, if I have a previous transformation already applied (say M\_prev), and I want to apply a transformation M on top of that, then is the correct form:

```
M_new = M_prev * M // M_new and M_prev are both column major. I'm post multiplying due to being column major, but this is incorrect, I guess?

```

I believe this is incorrect (at least in some experiments I carried out, please correct me if I'm wrong), and it should be the reverse. What is the flaw in my calculation of M\_new?

# Answer
> 1 votes
taking into account that matrices are column-major as you said, then yes, it is incorrect.

so,

`M_new = M_prev * M` would apply first matrix `M` then `M_prev` which is not want what you want - think of them as some transformation matrices, like `S`, `T`, `R` and nothing more ...

Therefore if you want `M` be applied after 'M\_prev' just do

`M_new = M * M_prev`

---
Tags: mathematics, matrix, transformation
---


# Question
Title: Why do I get these packaging errors for my 32-bit build?
I am trying to package my game in 32 bit for testing purposes. However I keep getting an error during the process. I have no problems packaging 64 bit development versions. Only 32. Does anyone have any ideas on what the problem might be? Here is the log:

```
UATHelper: Packaging (Windows (32-bit)): Running AutomationTool...
 UATHelper: Packaging (Windows (32-bit)): Automation.ParseCommandLine: Parsing command line: -ScriptsForProject=C:/dev/projects/ue4/FarkleFriends/FarkleFriends.uproject BuildCookRun -nocompile -nocompileeditor -installed -nop4 -project=C:/dev/projects/ue4/FarkleFriends/FarkleFriends.uproject -cook -stage -archive -archivedirectory=C:/dev/package/debug/windows
 32 -package -clientconfig=Development -ue4exe=UE4Editor-Cmd.exe -pak -prereqs -nodebuginfo -targetplatform=Win32 -build -utf8output
 UATHelper: Packaging (Windows (32-bit)): BuildCookRun.SetupParams: Setting up ProjectParams for C:\dev\projects\ue4\FarkleFriends\FarkleFriends.uproject
 UATHelper: Packaging (Windows (32-bit)): Project.Build: ********** BUILD COMMAND STARTED **********
 UATHelper: Packaging (Windows (32-bit)): CommandUtils.Run: Run: C:\dev\UnrealEngine\UE_4.16\Engine\Binaries\DotNET\UnrealBuildTool.exe FarkleFriends Win32 Development -Project=C:\dev\projects\ue4\FarkleFriends\FarkleFriends.uproject  C:\dev\projects\ue4\FarkleFriends\FarkleFriends.uproject -NoUBTMakefiles  -remoteini="C:\dev\projects\ue4\FarkleFriends" -noxg
 e -generatemanifest -NoHotReload
 UATHelper: Packaging (Windows (32-bit)): CommandUtils.Run: Run: Took 2.7233461s to run UnrealBuildTool.exe, ExitCode=0
 UATHelper: Packaging (Windows (32-bit)): CommandUtils.Run: Run: C:\dev\UnrealEngine\UE_4.16\Engine\Binaries\DotNET\UnrealBuildTool.exe FarkleFriends Win32 Development -Project=C:\dev\projects\ue4\FarkleFriends\FarkleFriends.uproject  C:\dev\projects\ue4\FarkleFriends\FarkleFriends.uproject -NoUBTMakefiles  -remoteini="C:\dev\projects\ue4\FarkleFriends" -noxg
 e -NoHotReload -ignorejunk
 UATHelper: Packaging (Windows (32-bit)): UnrealBuildTool: Performing 14 actions (2 in parallel)
 UATHelper: Packaging (Windows (32-bit)): UnrealBuildTool: ERROR: UBT ERROR: Failed to produce item: C:\dev\projects\ue4\FarkleFriends\Binaries\Win32\FarkleFriends.exe
 UATHelper: Packaging (Windows (32-bit)): UnrealBuildTool: Total build time: 34.18 seconds (Local executor: 0.00 seconds)
 UATHelper: Packaging (Windows (32-bit)): CommandUtils.Run: Run: Took 34.6009145s to run UnrealBuildTool.exe, ExitCode=5
 UATHelper: Packaging (Windows (32-bit)): Program.Main: ERROR: AutomationTool terminated with exception: AutomationTool.CommandUtils+CommandFailedException: Command failed (Result:5): C:\dev\UnrealEngine\UE_4.16\Engine\Binaries\DotNET\UnrealBuildTool.exe FarkleFriends Win32 Development -Project=C:\dev\projects\ue4\FarkleFriends\FarkleFriends.uproject  C:\dev\
 projects\ue4\FarkleFriends\FarkleFriends.uproject -NoUBTMakefiles  -remoteini="C:\dev\projects\ue4\FarkleFriends" -noxge -NoHotReload -ignorejunk. See logfile for details: 'UnrealBuildTool-2017.07.26-21.49.41.txt'
 UATHelper: Packaging (Windows (32-bit)):    at AutomationTool.CommandUtils.RunAndLog(String App, String CommandLine, String Logfile, Int32 MaxSuccessCode, String Input, ERunOptions Options, Dictionary`2 EnvVars, SpewFilterCallbackType SpewFilterCallback)
 UATHelper: Packaging (Windows (32-bit)):    at AutomationTool.CommandUtils.RunAndLog(CommandEnvironment Env, String App, String CommandLine, String LogName, Int32 MaxSuccessCode, String Input, ERunOptions Options, Dictionary`2 EnvVars, SpewFilterCallbackType SpewFilterCallback)
 UATHelper: Packaging (Windows (32-bit)):    at AutomationTool.CommandUtils.RunUBT(CommandEnvironment Env, String UBTExecutable, String CommandLine, String LogName, Dictionary`2 EnvVars)
 UATHelper: Packaging (Windows (32-bit)):    at AutomationTool.CommandUtils.RunUBT(CommandEnvironment Env, String UBTExecutable, FileReference Project, String Target, String Platform, String Config, String AdditionalArgs, String LogName, Dictionary`2 EnvVars)
 UATHelper: Packaging (Windows (32-bit)):    at AutomationTool.UE4Build.BuildWithUBT(String TargetName, UnrealTargetPlatform TargetPlatform, String Config, FileReference UprojectPath, Boolean ForceMonolithic, Boolean ForceNonUnity, Boolean ForceDebugInfo, Boolean ForceFlushMac, Boolean DisableXGE, String InAddArgs, Boolean ForceUnity, Dictionary`2 EnvVars)
 UATHelper: Packaging (Windows (32-bit)):    at AutomationTool.UE4Build.Build(BuildAgenda Agenda, Nullable`1 InDeleteBuildProducts, Boolean InUpdateVersionFiles, Boolean InForceNoXGE, Boolean InUseParallelExecutor, Boolean InForceNonUnity, Boolean InForceUnity, Boolean InShowProgress, Dictionary`2 PlatformEnvVars, Nullable`1 InChangelistNumberOverride, Dictio
 nary`2 InTargetToManifest)
 UATHelper: Packaging (Windows (32-bit)):    at Project.Build(BuildCommand Command, ProjectParams Params, Int32 WorkingCL, ProjectBuildTargets TargetMask)
 UATHelper: Packaging (Windows (32-bit)):    at BuildCookRun.DoBuildCookRun(ProjectParams Params)
 UATHelper: Packaging (Windows (32-bit)):    at BuildCookRun.ExecuteBuild()
 UATHelper: Packaging (Windows (32-bit)):    at AutomationTool.BuildCommand.Execute()
 UATHelper: Packaging (Windows (32-bit)):    at AutomationTool.Automation.Execute(List`1 CommandsToExecute, CaselessDictionary`1 Commands)
 UATHelper: Packaging (Windows (32-bit)):    at AutomationTool.Automation.Process(String[] Arguments)
 UATHelper: Packaging (Windows (32-bit)):    at AutomationTool.Program.MainProc(Object Param)
 UATHelper: Packaging (Windows (32-bit)):    at AutomationTool.InternalUtils.RunSingleInstance(Func`2 Main, Object Param)
 UATHelper: Packaging (Windows (32-bit)):    at AutomationTool.Program.Main()
 UATHelper: Packaging (Windows (32-bit)): Program.Main: AutomationTool exiting with ExitCode=5 (5)
 UATHelper: Packaging (Windows (32-bit)): BUILD FAILED
 PackagingResults:Error: Error Unknown Error

```

**EDIT**
Here is what's in the UnrealBuildTool-....txt log file. The contents of the log for a more recent build with 4.16.3 is the same as the contents of UnrealBuildTool-2017.07.26-21.49.41.txt

```
Performing 14 actions (2 in parallel)
ERROR: UBT ERROR: Failed to produce item:
C:\dev\projects\ue4\FarkleFriends\Binaries\Win32\FarkleFriends.exe
Total build time: 20.26 seconds (Local executor: 0.00 seconds)

```

**EDIT Part 2**
When I try to run the command

```
C:\dev\UnrealEngine\UE_4.16\Engine\Binaries\DotNET\UnrealBuildTool.exe FarkleFriends Win32 Development -Project=C:\dev\projects\ue4\FarkleFriends\FarkleFriends.uproject  C:\dev\projects\ue4\FarkleFriends\FarkleFriends.uproject -NoUBTMakefiles  -remoteini="C:\dev\projects\ue4\FarkleFriends" -noxge -NoHotReload -ignorejunk

```

in the cmd prompt I get a Windows error:

# Answer
> 0 votes
Check your system's configuration, check wether it is 32-bit, or 64-bit. Then check the configuration your engine is set to, and if you are using certain development libraries or assets, check theirs to. If **ANY** one of them does not match the others, there'll be confusing consequences.

This is an example of a common configuration-conflict error in Unreal Engine 4:

```
Error DBG4045: Application configuration (x64) conflicts with library configuration (x86)

```

Keep these points in mind and you'll be able to fix this mess.

**Fix for Edit III**

Place all your required '\*.dll' files (including mspdb140.dll) with your Unreal 4 project files.

---
Tags: unreal-4
---


# Question
Title: How to determine if the player between two points?
I'm making a skating game and I'm having trouble figuring out how to snap the player onto grinds and rails in between multiple points. My plan was to snap the player onto a point in between the two points using lerp, check which direction the player is facing using the dot product to compare direction of the rail from its first point to second and its second point to first and move them in direction that they are closer to.

But I'm having trouble with the first step. If the rail is more than two points how do I determine which two points do I use for lerping?

# Answer
You must find the grind segment that's closest to the player.

The first thing you need is a function to find the **closest point on a segment** as an **interpolation value** of 2 points we'll call `i`.

```
// return interpolant value "between" segment_point1 (0.0f) and segment_point2 (1.0f)
// values go outside this range when past the end of a segment
float ClosestPointOnLine(Vector3 player, Vector3 segment_point1, Vector3 segment_point2)
{
  Vector3 segment_vector = (segment_point2 - segment_point1);

  float length_squared = DotProduct(segment_vector, segment_vector);

  return DotProduct(player - segment_point1, segment_vector) / length_squared;
}

```

Note: You may want to check if length\_squared is zero but we're assuming your level does not have any zero-length segments.

If the value returned is \< 0 the player is before `segment_point1`, if \> 1 then the player is past `segment_point2`.

You can then find the exact point on the segment by doing `Lerp(segment_point1, segment_point2, i);` where `i` is the returned value of the above function (in red on the image).

But what we really want is **the point on the segment clamped between 0 and 1** (in yellow), this is why the above function returns an interpolation value and not an actual point.

```
float i = ClosestPointOnLine(player, segment[s].first, segment[s].second);
Vector3 point_on_segment = Lerp(segment_point1, segment_point2, Clamp(i, 0, 1));

```

What you then do is calculate the **distance** between the **point on the segment** and the **player** for **every segment (grinding edge)** in the area and **find the closest one**.

Then if the closest distance is less than a **grind distance threshold**, you can snap to that edge.

In this image, we'd snap to the B segment. (In gray is the extended segment A to show how `i` is outside of 0..1 for that segment before clamping)

That's it.

Additionally for movement on the rails:

* Use `i` to move the player along that segment rather than in 3D.
* Use the **segment length** to adjust the speed by dividing it by the segment length (`i` is relative to the segment, not world space).
* Use the `DotProduct` of the segment direction `(segment.second-segment.first)` and the player's movement direction to figure out in which direction and speed to move `i` on the segment.
* When `i` moves out of the (0..1) range **switch** to the previous \<0 or next \>1 **grind segment**
* snap off and back in 3D if it's the last one (either ends) in the chain

Outside of this question: You need to build grind segment chains to know which segment comes next when grinding and use some way to limit the search for grind segment chains such as an octree or other method to avoid going over the \>10000 segments in the entire level.
> 1 votes

# Answer
Make all of the points of any grindable rail part of their own array.

Use collision detection to see if a player is touching the rail (initiating grind).

Retreive the array and loop through each of its points to find the 2 points closest to the players point of contact, a simple distance check should suffice (keep in mind that circular grinds could create problems, depending on the distance between each point).

Use the characters speed and direction to do the rest, the path can be determined by the points in the array.

Hope it helped!
> 0 votes

# Answer
you can check the distances between the points in the rail compared to your skater, then whichever is greater than playerVector but closest is the next point, and whatever is lesser than it but least distance is the previous point
> 0 votes

# Answer
You will want to test if the player collides with the rail; and if so, snap the player onto the rail.

### 2D Illustration

Here, the blue line represents the rail; the red circle represents the original position of the player (the circle could be any shape); the maroon circle represents the position of the player after being snapped to the rail; and the purple line represents the direction of translation/movement. This line is perpendicular to the rail, so the player is snapped to the closest point possible. As the illustration demonstrates, *the player must move to the center of the rail in one direction, while staying centered on the line of translation.* This could be calculated using the following pseudocode:

```
// form equation of line of the rail
float rail_slope = rail_dir.y / rail_dir.x;
// y - y1 = m*(x - x1) => y = m*x + (m*-x1 + y1)
//                        y = m*x +       b
float rail_y_int = rail_slope * -a_point_on_rail.x + a_point_on_rail.y;  // y-intercept, or |b|

// form equation of line of translation
float translation_slope = - 1 / rail_slope;   // a perpendicular line's slope is the opposite reciprocal
// the player will always be on the line of translation
float translation_y_int = translation_slope * -player_pos.x + player_pos.y;

// now find the intersection between the two lines, which is the new location of the player
// f(x) = m1*x + b1; g(x) = m1*x + b1;
// intersection: m1*x + b1 = m2*x + b2 => m1*x - m2*x = b2 - b1
// => x (m1 - m2) = b2 - b1 => x = (b2 - b1) / (m1 - m2);
// y = m1*x
float snapped_x = (translation_y_int - rail_y_int) / (rail_slope - translation_slope);
float snapped_y = rail_slope * snapped_x;
player_pos = new Vector2(snapped_x, snapped_y);

```

---

### 3D Illustration

The player before being snapped to the rail:

The player after being snapped to the rail, with the plane of translation:

As the illustration demonstrates, *the player must move to the center of the rail, while staying on the plane of translation*. I don't know 3D geometry as of now, so I cannot provide the pseudocode for 3D.
> 0 votes

---
Tags: vector, linear-algebra
---


# Question
Title: Is it worth to implement game mechanics/rules separately from the main code?
Not sure whether it fits the scope of this community, or should go to Stackoverflow instead.

Let's suppose that I want my game be easily extendable in its core, i.e. I want that a lot of people, even without decent programming knowledge, would be able to not only tweak existing rules, but even add totally new game mechanics into it. I'm not good programmer myself, but I'm ready to learn, I'm just need some directions and assurance it can be done.

What I've thought about is whether it's possible/feasible to somehow implement game mechanics **separately** from the main utility code? I mean, for tabletop games we have those rulebooks which don't contain actual algorithms of all actions, but rather describe some protocols and limits, referencing context of each such item heavily. Is it possible to do something similar for PC game, like, describe all the rules in some very high-level, easily readable (and changeable) by a human programming language, which is then "consumed" and parsed by the utility code into a working instance of game mechanics?

That really seems like I need to write my own language and a compiler for it )) Which I won't be able to do, of course. But may be there is an easier approach to the problem?

FYI: my language of choice for the utility code will be Python 3.x

# Answer
> 34 votes
Generally speaking, the ease with which any system can be extended is dependant upon the degree to which its subsystems are tightly or loosely coupled. Usually, the more loosely coupled the subsystems are, the easier it is to modify them as they are isolated & don't necessarily require a complete understanding of the system as a whole.

Nothing is free though - such system typically require more resources (various combinations of time, money & skill) to build. The degree of extensibility you've described strikes me as being directly at odds with the level of skill you've attributed to yourself. It could be done, but crafting software as you've described it is a very challenging undertaking.

The closest existing things I'm aware of is Vassal (which is far more programmatic than you've described), or making a mod for Tabletop Simulator (which mostly depends human interaction to interpret & enforce any game rules).

# Answer
> 18 votes
> What I've thought about is whether it's possible/feasible to somehow implement game mechanics separately from the main utility code?

It is absolutely possible. One way used often in gaming is Lua scripting.

From the linked article:

> Lua was originally designed in 1993 as a language for extending software applications to meet the increasing demand for customization at the time.

Many games use Lua. (I would link but new-user reputation is limiting my link count.)

Lua scripts can be compiled at run-time. This means they can (for example) be text files sitting in your game's "scripts" directory, easily editable by a modder. Your game loads them up and runs them.

I've seen Lua scripts define the properties of in-game units. Here is a random example from TA Spring.

But you want to "describe all the rules". That's possible in theory, as Lua is a full language, but the trouble is you have to be prescient enough to have the core game code know to look for scripts to extend its behaviour.

For instance you might develop a card game that knows to look for cards in a "scripts/cards" directory. That's great for adding new cards, or editing existing ones. But if you later want to expand your game to include miniatures on a grid you're going to have to edit the core code -- no amount of Lua fiddling is going to get you there on its own.

Please note: I bring up Lua because I know it's commonly used both in gaming and in software for customisation. I'm not suggesting it is the only solution, nor the best for the questioner's needs.

# Answer
> 3 votes
There is a continuum of approaches and whether any particular one of them is worth it will depend on exactly what you are trying to do. Specifically, how much control do you want to offer the tweaker?

On the extreme end of control, you can simply let the tweaker modify the code of the entire game. At that point you would essentially be publishing the utility code and at least one example of how to use it. A tweaker could use as much or as little of the code as they want.

An approach that offers a little less control would be to somehow "freeze" your utility code (say by compiling it beforehand) and only let tweakers fill out specific functions (callbacks), restricting what they can do. Depending on what you want to do, this approach can take many forms. A common method would be to put all the display part in the utility/main code and all the mechanics in the tweakable portion. Or, you may want to keep some mechanics in the "frozen" part because players are unlikely to want to change them, or making them changeable is too complicated.

On the low-control end of the continuum is only letting tweakers change values within a fixed range. A data file which let you select the colours of things within the game would be an example. You could, however use this approach and still offer a lot of customization. It would be possible to define a selection of functions and allow tweakers to compose them to create the callbacks from the previous approach, but not allowing them to define new ones. Or maybe you skip the composition part and just offer a finite selection.

The details of all these approaches and which one fits your use case depends on what kind of base game you want to make and how much control you want to give up. Note that commercial games generally use only the second and third methods because the first allows players to make entirely separate games, which introduces complicated licensing issues. Note that as these approaches form a continuum, the second approach may introduce these issues as well.

# Answer
> 2 votes
It is absolutely possible to separate the rules of the system from the code that applies those rules. I prefer to structure my code that way for complex projects, as it makes it easier to add new rules or change the rules later without introducing bugs into the underlying system. And bugs in a rules engine get found faster than bugs in a system where the rules and other code are mixed together higgledy-piggledy, because the same rules engine gets used over and over by every rule.

Whether it is worth it depends on the complexity of the system. Like I wouldn't bother for Pac-Man, but I couldn't imagine writing Dwarf Fortress any other way.

# Answer
> 2 votes
It's definitely feasible. If it's worth it depends on your goals.

You don't have to invent your own language or write a compiler to make this work.

If you want your game to be easily extendable, it's probably a good idea to go for it.

It's probably more work for you, at least short term, to create understandable systems and make things easy to modify.

One game that does this is Rimworld (I have no affiliation) and you might be able to see & learn from how they did, basically putting a lot of game data and mechanics in XML files that are in the game folders for anyone to see and modify. The core/engine of the game was made using Unity.

There is also the possibility of extending the game further/deeper by actual coding, I know less about that but you can learn by looking at the mods forum.

The possibility of modding makes the game more interesting to a lot of people and I think it has contributed a lot to its success. It also allows the developers to bring in any mod content they want into the core game and in a way, that speeds up development and improves the game since they get assistance from a lot of people, and they can decide to take in things based on what is popular, what seems to work, etc.

And of course, especially for a small independent studio, they have hundreds of people coming up with ideas and testing them for them, which is a lot of work they couldn't do themselves, nor probably hire people to do.

# Answer
> 1 votes
You might want to look into **Object-Oriented Design**. Python has good support for that.

Thick books are written about this which can be scary when you are new, but the main principles are fairly easy.

The main point is just that you identify what kind of objects you are working with. You don't say what kind of game you are thinking about, but things like Player, Monster, Item, Equipment, Weapon, Armour and so on are typical objects.

If you want different game types, you will probably want a Game object that takes care of victory condition and such. Perhaps a Map object too?

Sometimes it is not clear if something deserves to be an object or not, e.g. damage. If you don't make damage an object the code will be simpler, but making it an object makes it easier to customize.

*Subclassing:* Both Weapons and Armours are Equipment. Equipments are Items. There are probably other types of Items. You will probably find it useful to define a class Combatant that both Players and Monsters are subclasses of.

The idea is that for example Weapons will have many things in common with all other types of Items, they have a weight, size and other properties like that.

So, subclassing gives you a way of saying that "Weapons are like other Items, but in addition you can wield them, they affect the damage you do, etc etc."

**Subclassing also lets your mod builders say "My new type of weapon is just like the standard weapons except that ..."**

Then you have to decide which object is responsible for what. This is not as easy as it seems and you should do some thinking about it. Making the wrong choices will not affect the basic game much, but will make it harder to customize.

As long as you are just tinkering on your own you can change things around but **the moment you release something to the public, making changes becomes much harder!** People will make mods that depend on things being just like they are now. Even bugs. People will write mods that depends on bugs staying in the code. If you change things, those mods will break and lynch mobs will appear at your house.

For example:

A Player wielding a Weapon attacks a Monster wearing multiple Armours. This takes place in a particular Game mode and on a certain Map.

Both Combatant may have Skills like Critical Hit and Dodge.

Now, which object is responsible for what?

There is not one right answer to this. A lot depends on what kind of customization you want to allow.

If you never call an object (e.g. the Map), that object cannot change the attack in any way.

After making all these decisions, **document them**. Write a "Modders manual" that lists exactly what moddable methods each object has, what parameters they take, what they should return, and so on and on and on...

Good luck!

# Answer
> 1 votes
A simple way to get some basic support for this would be to separate most numerical values into one or more separate text files to allow interested individuals to tweak them into oblivion.

For example, you mentioned tabletop games; if you had a game based on D&D you might have a `weapon_damage` file containing lines like `Battleaxe: 1d12`. Your utility code would read that file and whenever damage was dealt by a `Battleaxe` your code would `generate a number from 1-12, 1 time(s)` and add them. Tweaking the line to read `Battleaxe: 4d6` would instead `generate a number from 1-6, 4 time(s)` and add them. Similarly, you could have a folder `Creatures` and inside you have a file for each creature, including lines like `AC: 12`; then adding new files to that folder would create new creatures. It could even be done for character classes, terrain types, a ton of things.

This style of non-code customization can still be very powerful and cover a lot of pieces of your game. However, this doesn't really allow a user to make changes that you didn't explicitly specify. For example, you might enable `Sneak Attack: [damage]` to be given to any Creature or Class to add `[damage]` to any attack that meets the conditions for a Sneak Attack. You could even provide ways to change what the conditions are, such as "whenever you attack from stealth" or "whenever you are flanking" or "whenever you have advantage". However, if a user decides that they want sneak attacks to be "When you make an attack roll, you can also roll stealth against the target's perception. If both rolls succeed, then add the Sneak Attack damage" then the user is out of luck unless you predicted that exact scenario.

If you wanted a user to be able to add completely new behavior to the game without needing coding skills at the same level as the developer, then as people mentioned you're looking at essentially creating either a game engine or a separate programming language. For modifications that don't require coding knowledge, text-based data files and folder structures can still provide a lot of options. If you want users to modify more than that then you'll need to ask them to learn or know a programming language.

# Answer
> 0 votes
\[I'm a decades-long software developer, but with no game development experience, so maybe the games industry takes different approaches, maybe for good reasons...\]

Your approach absolutely makes sense to me. The core gives the basic functionalities that mechanics and rules build upon, so it's an API that is to be used by the higher-level components.

And when designing an API, my favorite guideline is to create the language that you want to express your higher level code in (of course, withing the syntax limitations of your programming language).

So, a good approach would be to write some hypothetical rules and mechanics just the way you'd like them to be expressed (withing Python's syntax, of course), thus finding out what you want the core API to provide to the rules and mechanics layers.

And of course, I'd recommend to have a look at the scripting facilities of existing games to get an idea what they do.

---
Tags: game-mechanics
---


title: Pointer reference to a nullptr?

text:
# Question
Title: Pointer reference to a nullptr?
I think this question should have been posted on Stack Overflow, but as I am using all of this stuff to make a video game, I decided to post it here.

So, suppose you have an integer value called '*firstgid*' declared:

```
int firstgid;

```

And I'm not telling the program what value `firstgid` equals to, like I'm not saying that `int firstgid = 5;` or something.

And then somewhere else in the program, I say:

```
SDL_Texture* tex(graphics, &firstgid);

```

Notice the `&firstgid` here. I am not telling the program what `firstgid` is, and still I am making a reference to it using the ampersand (`&`) symbol.

So, if I do that, will the program crash and display this breakpoint error on the output screen?:

```
Unhandled exception thrown. Read access violation:
  **this** was nullptr

```

A good folk just told me that the `**this** was nullptr` breakpoint error is triggered when we are calling a *function* on an unknown *value* or stuff.

What do you guys think about it? Thank you for your kind assistance.

# Answer
> 2 votes
In C++, pointers are a very important concept. In this case, they get a bit confusing because they're pointing to an unspecified integer, so let's get the rules about unspecified values out of the way.

The specific line from the specification is section 8.5.11:

> If no initializer is specified for an object, the object is default-initialized; if no initialization is performed, an **object with automatic or dynamic storage duration has indeterminate value**.

What that last bit means is that your integer, `firstgid`, has an unspecified value because you did not assign one. It might be 0. It might be 1. It might be -1195716. It might even be different each time you run the program. It is *legal* to access this value, it's just not specified what its value will be. *If* it were a pointer, it would be a pointer to an unspecified memory address, so *dereferencing* it would be illegal, but `firstgid` is not a pointer, it's an `int`.

A key thing to note is that you can *always* assign a value to a variable that previously had an unspecified value. If you were to later write `firstgid = 1`, that would be completely valid *and* `firstgid` would have a defined value from that point on (it's value would be `1`).

Now for the pointers. The `&` operator is known as the "address of" operator. It takes any variable and returns the address of that variable as a pointer. In your case, because `firstgid` is an `int`, `&firstgid` will be an `int*`. The value of this pointer (the address) is defined, even if the value of the integer it is pointing at is not. The important thing here is that the pointer is valid, and we can dereference it. For example:

```
int firstgid; // an int with an unspecified value
int* ptr = &firstgid; // a pointer with a specified value (pointing at firstgid)

int temp1 = *ptr; // dereferencing the pointer to an unspecified value is valid,
                 // but the value of temp itself is unspecified
*ptr = 1; // assigning a value to the int that ptr points to
int temp2 = firstgid; // temp2 is now 1

```

So, in this case, you can pass `&firstgid` to `tex()`, as long as `tex()` operates correctly if the pointer is a pointer to an unspecified value.

The specific error you mention is what happens when you try to call a method on an object that you got by derefereincing a null pointer:

```
MyObject* objPtr = nullptr; // create a new pointer, not pointing at anything
objPtr->foo(); // ERROR!  **this** was nullptr

```

The difference between your first case and this second one is that, in the first case, you had a perfectly valid pointer, it was just pointing to an object with an unspecified value. In the second case, we're actually calling a member function from a null pointer. Pointers must be pointing at a valid object if you want to use them to call member functions on the object they point at. However, this is fine:

```
MyObject* objPtr = nullptr;
someFunction(objPtr);

```

In this case, all we did was pass a null pointer to `someFunction`, which is legal, as long as `someFunction` is ready for it. For example, it might have some code like:

```
void someFunction(MyObject* obj)
{
    // If the user does not provide an object, use the default one
    if (obj == nullptr)
        obj = sDefaultObject;
    ...
}

```

In this case, objPtr will not change (because the *pointer* to the object was copied as part of the function call), but clearly `someFunction` will operate on some other object.

# Answer
> 1 votes
As long as you don't **access**/**use** `firstgid` before initializing it, there's no problem at all with that. Check if the function which is receiving a reference to it is not using it.

By using it I mean calling a function on the object, using its value (which is not necessarily bad, the only problem is that you don't know what value it holds) or trying to dereference it if it were a pointer.

---
Tags: c++
---


title: Setup sub platforms inside Unity

text:
# Question
Title: Setup sub platforms inside Unity
I want to automate some of my Unity build process. I know that setting up automatic builds for platforms is relatively easy, just start Unity headless and tell it to build platform X!

This is fine for most things however I have some platform specific things for a given platform. For example I have achievements for Steam, GoG and my own thing if you are running truly standalone. I can easy switch between them by setting `#define STEAM_BUILD` to make a build with steam features enabled. This is setup for each platform that I support.

At the moment I have to change the script manually and re-build every time. I want to make a build server do this all for me but **how do I tell Unity to build my PC version with a certain `#define X` set?**

# Answer
Use `Application.RuntimePlatform` to determine in code which platform you're on.

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

You can also specify a build target on the commandline, which will set the appropriate `#define` for the target in question.

`-buildTarget <name>`

https://docs.unity3d.com/Manual/CommandLineArguments.html

The `#defines` are listed here:

https://docs.unity3d.com/Manual/PlatformDependentCompilation.html

If you need seperate builds for Windows and Windows with Steam, then you can set other preprocessor definitions in a text asset:

> You can define your own preprocessor directives to control which code gets included when compiling. To do this you must add a text file with the extra directives to the Assets folder. The name of the file depends on the language you are using. The extension is .rsp: C# (player and editor scripts) /Assets/mcs.rsp UnityScript /Assets/us.rsp
>
> As an example, if you include the single line -define:UNITY\_DEBUG in your mcs.rsp file, the #define directive UNITY\_DEBUG exists as a global #define for C# scripts, except for Editor scripts.
>
> Every time you make changes to .rsp files, you need to recompile in order for them to be effective. You can do this by updating or reimporting a single script (.js or .cs) file.

https://docs.unity3d.com/Manual/PlatformDependentCompilation.html
> 2 votes

---
Tags: unity, build-process, automation
---


# Question
Title: How to make player instantly move to the right or left when entering a box collider
I have a box collider and right now when I walk into it it says "you can't go there yet" I would like it for it to also move the player like 3 steps to the right or something. How would I do thatr?

# Answer
> 0 votes
You have not provided enough info, but I may have a solution.

You may have a `void Player::playAnimation` function in your 'player.cs' file for your PLAYER gameObject.

Go to the file where your controls for the player are. Read and understand the code. It should have this:

```
If (Input.GetKey(KeyCode.Right) == true) {
  player.moveRight;
}

```

Now, `moveRight` is a function that moves the player right. This is perhaps the code for it:

```
void Player::moveRight() {
  animator.SetBool("MoveRight", true);
  GameObject.move(Vector3.right);
  _facing = RIGHT;
}

```

Now, you can simply apply this `playAnimation` logic here in your box gameObject (tagged here as 'box1'):

```
void OnCollisionEnter2D (Collision2D coll) {
  string tag = coll.collider.gameObject.tag;
  if (tag == "box1") {
    player.moveRight;
    }
  }

```

Hope that helped.

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


# Question
Title: How to change the color of an invalid texture?
In openGL, when I don't bind a texture, or I bind a texture that was loaded incorrectly, any calls to texture2D/texelFetch in the shader will return vec4(0, 0, 0, 1), is there a way to change this to return vec4(1, 1, 1, 1) instead?

Initially I looked for a way to test if the sampler2D was valid, and when I couldn't find that I tried using glColor4f, but that doesn't seem to work either--although that could be the amdgpu driver, it seems to have some trouble with the old pipeline calls generally.

Is there someway to change what this default return color is?

# Answer
> 1 votes
There is no way to change that.

For incomplete textures the color is vec4(0, 0, 0, 1) as required by the OpenGL specification for float textures.

Integer textures return undefined values.

Shadow samplers return 0.

---
Tags: opengl, c++
---


# Question
Title: Organizing Setup(), Update() and Draw() function in a game engine
I'm creating my first game engine and I want help with organizing the Setup(), Update() and Draw() functions in the correct way.

Here is how my main() function looks like

```
/* BEGIN main() Function */
int main(int argc, char *argv[])
{
    prepareSetting(&settings);

    initEngine();

    setup();

    // Main loop

    while (!done)
    {
        update();
        draw();
    }

    SDL_Quit();
    return 0;
} /* END main()*/

```

The above approach requires me to declare the shared variables as global, which I think is not a good thing to do.

I was thinking about creating a ENGINE class which contains the setup(), update() and draw() functions and inheriting it. libcinder use this kind of approach. So should I use classes or leave them as it is. What is the best way to organize those functions?

What approach is used by professionals in the industry?

# Answer
> 1 votes
Look into Entity component system ( https://en.wikipedia.org/wiki/Entity\_component\_system ) and similar Object Oriented Programming paradigms.

This can be done in C++, C, assembly, or just about any languages. I've included an example in plain C further down showing one way how OOP & **virtual functions** can be done in C, but C++ was designed to do this stuff for you.

The idea as applied to your situation is you have a list of objects and each object has a creation (setup/constructor) function, an update function, a draw function, and a destroy function (destructor).

And your main loop calls the update and draw functions of all active objects in the list.

So you have a base class / struct which declares the virtual functions (or function pointers in C) :

```
class EntityBase
{
public:
  virtual ~EntityBase() {}
  virtual void Update() {}
  virtual void Draw() {}
};

```

And then derived classes which override those functions:

```
class Bob : public EntityBase
{
public:
  // bob variables here
  int energy;

  void Bob() {
      energy = 10;
  }

  void ~Bob() {
    // clean up
  }
  void Update() {
    // update bob
  }
  void Draw() {
    // draw bob
  }
};

```

And your main loop can call the Draw & Update functions of all your objects as EntityBase without knowing the details.

---

in plain C it would be something like:

```
typedef struct EntityBase_ {
    void (*Destroy)(struct EntityBase_ *me);
    void (*Update)(struct EntityBase_ *me);
    void (*Draw)(struct EntityBase_ *me);
} EntityBase;

```

and creating an object Bob would be like:

```
typedef struct Bob_ {
    EntityBase base;

    // bob variables here
} Bob;

void Bob_Destroy(struct EntityBase_ *me){
    Bob *bob = (Bob *)me;
    // clean up code here

    free(me);
}

void Bob_Update(struct EntityBase_ *me){
    Bob *bob = (Bob *)me;

    // update bob here
}

void Bob_Draw(struct EntityBase_ *me){
    Bob *bob = (Bob *)me;

    // draw bob here
}

EntityBase *CreateBob()
{
    Bob *bob = (Bob *)malloc(sizeof(Bob));
    bob->base.Destroy = &Bob_Destroy;
    bob->base.Draw = &Bob_Draw;
    bob->base.Update = &Bob_Update;

    // initialize bob variables here

    return &(bob->base);
}

```

the main loop in C would do something like:

```
EntityBase *eb = entity_pointer_array[i];
eb->base.Update(eb);
eb->base.Draw(eb);

```

# Answer
> 0 votes
Well, I would modify the main loop as follows:

```
while(!done)
{
    update();
    draw();
    present();
}

```

The "present" method is so the main loop synchronizes with the display's refresh rate. In that way, your game is optimal. Otherwise, you could be drawing frames that will never be seen by the player, which is a waste of CPU and GPU cycles.

An added benefit is that your game will run at a 60 fps.

That is what I did when I created my game engine.

---
Tags: architecture, game-loop, oop, entities
---


title: Quaternion Translation

text:
# Question
Title: Quaternion Translation
I am writing a small game and I need some help with my quaternions.

If I have an object at rotation A (quaternion)

And I need it to be at rotation B (quaternion) in 10 steps how would I work out the step change?

For normal vectors I would do C = (B - A) / 10 And then each step simply add C to my position to move from A to B in 10 steps. I don't believe this would work for quaternions so how do I do this?

Also there would be an infinite number of routes that could be taken to get from A to B, so I would like to calculate this for the shortest route.

I did find this http://wasted.nz/posts.php?topic=82629 But if this is correct then how do you apply the difference to the current rotation? and could this difference be divided by 10 to get the step difference?

If it helps I am using C++, DirectX 11 and Bullet Physics

# Answer
Given this operation

```
q' = q.inverseQuaternion() * q2

```

q' is a quaternion holding the rotation from q2 to q1.

For the stepping part, you should search for **LERP** or **SLERP**
> 1 votes

---
Tags: 3d, rotation, directx11, quaternion
---


title: Top Down 2D Collision C#

text:
# Question
Title: Top Down 2D Collision C#
I know this has been asked before, but I don't understand why my code isn't working.

I'm doing top-down collision with no gravity.

Here is my code :

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

public class TankBodyControls : MonoBehaviour {

public KeyCode Foward = KeyCode.W;
public KeyCode Backward = KeyCode.S;
public KeyCode TurnLeft = KeyCode.A;
public KeyCode TurnRight = KeyCode.D;

public const float MaxSpeed = 6.0f;
public const float RotSpeed = 4.0f;

private Rigidbody2D TankBody;

void Start () {
    TankBody = GetComponent<Rigidbody2D>();
}

void OnCollisionEnter2D(Collision2D coll)
{
    print("called");
    if(coll.collider.CompareTag("wall"))
    {
        print("collided!");
        var P = transform.position;
        P.x -= TankBody.velocity.x;
        P.y -= TankBody.velocity.y;

        transform.Translate(P);
    }
}

private void MoveTank()
{
    var Vel = TankBody.velocity;

    if(Input.GetKey(Foward)||Input.GetKey(Backward))
    {
        float VelMag = (Input.GetKey(Foward) ? MaxSpeed : -1.0f * MaxSpeed/2.0f);
        float VelAngle = transform.eulerAngles.z * ((float)Math.PI / 180f);
        Vel = new Vector2((float)Math.Cos(VelAngle), (float)Math.Sin(VelAngle));
        Vel *= VelMag;

        var rot = TankBody.rotation;

        if (Input.GetKey(TurnRight))
        {
            rot -= RotSpeed;
        }

        if(Input.GetKey(TurnLeft))
        {
            rot += RotSpeed;
        }

        TankBody.rotation = rot;
    }
    else
    {
        Vel = Vector2.zero;
    }

    TankBody.velocity = Vel;
}

void Update ()
{
    MoveTank();
}
}

```

The idea was : if I detect a collision, shift the player out of the wall, the distance (velocity) they intersected it. My problem right now is, the OnCollisionEnter2D function doesn't even get called when they intersect (hence not console prints). Any idea what I'm doing incorrectly?

# Answer
> 1 votes
It's because your `Rigidbody2D`'s `Body Type` is set to `Kinematic`. It should be `Dynamic` body type.

`Kinematic` body type will ignore force, joints, collisions. So what are you looking for is `Dynamic` body type.

Read Body Types here and Kinematic here.

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


# Question
Title: How do I iterate over map tiles visible within a rectangular portion of an isometric view?
I have an isometric map broken up into terrain tiles. the area of the map on-screen is given by a rectangle rotated 45 degrees (in red below).

Given the position of the corners of the visible rectangle, how would I go about iterating over all visible tiles (shaded), such that no tile down or to the right of tile A is iterated upon before tile A

# Answer
> 0 votes
Assuming the top right side of that diamond is the top (row 0) of your array...

You're still walking top to bottom (+y) as in the unrotated array, but you are also stepping -1 in Y each time you step +1 in X. Where N is the width (and height) of your square grid:

```
for (int y = 0; y < N; y++)  //row in untransformed space
{
    for (int x = 0; x < N; x++) //col in untransformed space
    {
        yt = y - x;
        if (yt >= 0) //we haven't hit the right/top edge of the rotated map
        {
            ProcessTile(x, y);
        }
        else break; //exit the x loop and return to the y loop
    }
}

```

Next, we limit to the red rectangle. I do this by isometric row and column, min and max. You already have the row `yt` above, the column `xt` would be `x + (N - y)`. Thus, those 3 darkened squares on the left of your diagram being `[0,4]`, `[1,5]`, `[2,6]` would be `0 + (8-4) - 1 = 3`, `1 + (8-5) - 1 = 3`, `2 + (8-6) - 1 = 3`. So this is column 3 i.e. the 4th column as you count from the leftmost edge (first column is 0).

Then you just need to check whether you're within the min and max *transformed* row and column, and it will process only those cells outlined by the rect.

```
for (int y = 0; y < N; y++)  //row in untransformed space
{
    for (int x = 0; x < N; x++) //col in untransformed space
    {
        yt = y - x;
        xt = x + (N - y);
        if (yt >= 0) //we haven't hit the right/top edge of the rotated map
        {
            if (yt >= minRow && yt <= maxRow) //inclusive
            if (xt >= minCol && xt <= maxCol) //inclusive
                ProcessTile(x, y);
        }
        else break; //exit the x loop and return to the y loop
    }
}

```

P.S. It's left to you to get the minRow / maxRow / minCol / maxCol from screen corners.

---
Tags: tiles, maps, isometric
---


# Question
Title: Unity, Detect the last GameObject in the hierarchy of a given list of GameObjects
I have a list of GameObject , and I need to know which one is the last in the hierarchy ( This is for a UI system, So is kind of 'which one is showing up')

I have a cursor managed by GamePad , and I use Raycast to see if he clicked something, It give me an array of Gameobjects but I need to know which one is showing up(on top of the others) to click on it

Example this is my full hierarchy:

```
GameObject A
        GameObject B
        GameObject C
GameObject D
        GameObject E
        GameObject F
GameObject G
          GameObject H
               GameObject I
           GameObject J

```

The list of raycast contain 'GameObject D','GameObject A','GameObject I'

How I cand find that 'GameObject I' is the last one? they don't have a common root

# Answer
> 2 votes
Here is a script I've made to determine which Transform is the "front most" **according to the hierarchy**. But be careful, if one of the "candidates" has a higher `z` value, the function will return the wrong result :

```
// Call this function by giving an array of transforms
public Transform GetFrontMost( Transform[] transforms )
{
    List<List<int>> siblingIndices = new List<List<int>>();

    for ( int i = 0 ; i < transforms.Length ; i++ )
    {
        siblingIndices.Add( GetSiblingIndices( transforms[i] ) );
    }

    Transform frontMost = null;
    int depth = 0;
    bool conflict = true;
    int maxSibling = -1;

    while ( conflict )
    {
        conflict = false;
        maxSibling = -1;

        for ( int transformIndex = 0 ; transformIndex < siblingIndices.Count ; transformIndex++ )
        {
            if ( depth < siblingIndices[transformIndex].Count )
            {
                if ( siblingIndices[transformIndex][depth] > maxSibling )
                {
                    conflict = false;
                    maxSibling = siblingIndices[transformIndex][depth];
                    frontMost = transforms[transformIndex];
                }
                else if ( siblingIndices[transformIndex][depth] == maxSibling )
                {
                    conflict = true;
                    frontMost = null;
                }
            }
        }

        depth++;
    }

    return frontMost;
}

private List<int> GetSiblingIndices( Transform t )
{
    if ( t.parent == null )
        return new List<int>() { t.GetSiblingIndex() };
    else
    {
        List<int> list = GetSiblingIndices( t.parent );
        list.Add( t.GetSiblingIndex() );
        return list;
    }
}

```

Supposing you have a hierarchy as below, if you give 'GameObject D','GameObject A','GameObject I', the function should return 'GameObject I'.

```
GameObject A
        GameObject B
        GameObject C
GameObject D
        GameObject E
        GameObject F
GameObject G
          GameObject H
               GameObject I
           GameObject J

```

In the code above :

1. For each "candidates", you get an array containing the sibling indices of all its parent
2. You compare the indices, candidate by candidate. If you find one candidate with a higher sibling index for a given depth, you have found the frontmost element
3. Else, you go deeper in the hierarchy to make the comparisons

---
Tags: unity, gameobject, hierarchy
---


# Question
Title: C++11 & Efficient Networking Client<->Server<->"Zone(s)"
I am building both an engine and a networked game at once because I'm completely insane. The original design/plan was to use internal Unix sockets for each "zone" for server\<-\>zone communication, with UDP for server\<-\>client(s) communication.

My conundrum is this: It seems like there are a variety of ways to handle getting packets from a client to the intended "zone", not none of them seem particularly efficient.

1. Simply move data from a singular queue to the intended zone server, via data objects within code. (**Pro**: Simple // **Con**: Potentially slow as molasses in a Canadian winter.)
2. (Somehow) Allow Server and Zones to communicate via Unix sockets, with a networking class/wrapper to pass packets into a "pool" for redistribution to Zones. (**Pro**: Unix sockets, from my reading, tend to be fairly quick. // **Con**: Need to re-evaluate how I am currently handling packets and the redistribution of packets makes it too similar to #1 for my liking.)
3. Use the underlying messages system on Linux. Ref (Pro: Crazy fast for large objects. // Con: No idea how to implement at the moment.)

Additionally, if there is a specific text, document, or book(s) that I should be hitting instead of harassing everyone here, PLEASE let me know! Not at all afraid to spend a week tearing through a 200+ page tome.

Thank You!

# Answer
> 0 votes
Thanks to Quentin's question, I believe my path to success is actually to utilize each "zone" as a separate process, not embedded into the main game. This means I can use Unix sockets (Berkeley Sockets) to communicate between the world server and the zone servers. While the builtin message queue looks promising, the numerous mentions of it being less than ideal for simple/small packets (i.e. movement update with 2 floats, 1 uint32, and 1 string could actually be slower than a simple Unix-socket sent datagram/payload).

@Quentin, thank you again!

---
Tags: opengl, c++, networking, sdl2, linux
---


# Question
Title: Where is better to do shaders, vfx, uv-mapping and coloring?
Well i understand that 3DS-Max is mainly for modeling and Unity is mainly for programming and logic, but where is it better to do shaders, vfx, uv-mapping/painting and coloring?

for example i worked a little bit in Blender and it has modifiers, but also Unity has materials and similar stuff.

What let's say "imade a model in 3ds max, now where should i do the art and texturing, should i continue with 3ds or should i do it in blender? OR it doesn't matter where?"

# Answer
Modelling, uv unwrapping, texturing, and skinning should all be done in your content generation tools (eg. 3DS Max, Blender, Photoshop, etc...)

Your final shader & material setup should generally be done in your game engine. Unless you're using a specific material creation tool that promises 1:1 consistency when imported into your engine, you'll usually find that the engine's rendering pipeline is substantially different than your source tools, and material settings/shaders will not translate between them exactly.

Unity's built-in tools for modelling/unwrapping/painting are basically limited to terrain, so sticking to what your source tools create here is usually your best bet. If you need to iterate on levels once they're assembled in Unity (eg. blocking out a placeholder asset, or blending models into their surroundings), custom tools & add-ons are available to help.
> 1 votes

---
Tags: art, 3d-modeling
---


title: Strange gpu glitch

text:
# Question
Title: Strange gpu glitch
I've recently tried to run my game in a new hardware (arm a17 processor, Mali-T760) and the result is quite bad, as you can see in the images below seems that the polygon's coordinates are clamped to infinite values. **The game runs ok and at a good framerate on PC and on another arm-a20 based tablet**. **This is how it should be**:

**And this is what I get (ignore the color change):**

Another detail is when I zoom in into this area it disappears, same as a near/far plane clip issue, but can't find the error.

My game uses Ogre3D (OpenGL ES 2.0). Any ideas of what this glitch could be about?

**EDIT**: Code that I use to initialize entity's material:

```
Ogre::TextureManager* tmgr = Ogre::TextureManager::getSingletonPtr();
Ogre::TexturePtr ptr = tmgr->createManual(mColorMapTextureName,                             Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
                               Ogre::TEX_TYPE_2D,
                               16,  // Width
                               4,    // Height
                               1, // Depth
                               0,

                               Ogre::PF_A8B8G8R8,

                               Ogre::TU_AUTOMIPMAP | Ogre::TU_DYNAMIC);

        ptr->createInternalResources();
        ptr->load();
    }

    Ogre::MaterialManager* mmgr = Ogre::MaterialManager::getSingletonPtr();
mMaterialName = uniqueMaterialName("Ground");
mMaterial = mmgr->create(mMaterialName, "General");

Ogre::Technique* tec = mMaterial->getTechnique(0);
tec->setSchemeName("ShaderGeneratorDefaultScheme");
Ogre::Pass* pass = tec->getPass(0);
pass->setDepthBias(mDepthBias);
pass->setVertexProgram("Ground/vs", false);
pass->setFragmentProgram("Ground/fs", false);
pass->setDepthWriteEnabled(false);
pass->setDepthFunction(Ogre::CMPF_LESS);
pass->setCullingMode(Ogre::CULL_NONE);
pass->setColourWriteEnabled(true);
pass->setLightingEnabled(true);
pass->setSceneBlending(Ogre::SBT_TRANSPARENT_ALPHA);
Ogre::TextureUnitState* tus = pass->createTextureUnitState();
tus->setTextureFiltering(Ogre::TFO_NONE);
tus->setTextureAddressingMode(Ogre::TextureUnitState::TAM_CLAMP, Ogre::TextureUnitState::TAM_CLAMP, Ogre::TextureUnitState::TAM_CLAMP);
tus->setTexture(tmgr->getByName(mColorMapTextureName));

mMaterial->prepare();
mMaterial->load();

```

Fragment shader:

```
#version 130
precision mediump float;

uniform sampler2D colormaps;
uniform float alpha;

varying vec2 texCoord;

void main()
{
    vec4 color = texture2D(colormaps, texCoord);
    gl_FragColor = vec4(color.xyz, color.a * alpha);
}

```

Vertex shader:

```
#version 130

precision mediump float;

uniform mat4 mvp_matrix;
uniform float activeView;
uniform vec2 colormapsScale;

attribute vec4 vertex;
attribute vec3 normal;

varying vec2 texCoord;

void main()
{
    gl_Position = mvp_matrix * vertex;

    float slot = 1.0;

    texCoord.x = (slot + 0.5)       * colormapsScale.s;
    texCoord.y = (activeView + 0.5) * colormapsScale.t;
}

```

Then to update entity's mesh I simply call the mesh method addTriangle() with the new triangle vertex coordinates as arguments.

# Answer
Luckily the fix was quite simple: increase shader precision. On both shader files I changed the line

```
precision mediump float;

```

by this one

```
precision highp float;

```

And everything was drawn correctly on screen.
> 1 votes

---
Tags: shaders, opengl-es2, ogre, hardware
---


# Question
Title: How to add the iPhone X screen dimensions to the mix of different iPhone screen sizes
Generally for Unity I design all my artwork in Illustrator. So I start off with 1440x1920 (for portrait games) and outline a red frame of 1080x1920. So everything that fits well within the 1080x1920 usually covers the family of iOS devices for me. Then I set the Pixels Per Unit to 192 for all my images. This approach has really served me well. Now that the iPhone X is in the mix, how can I cater for it in a similar way?

# Answer
> 1 votes
Even without taking the X into account you had to support 3 screen ratios for iOS:

* 3:4 for iPads
* 2:3 for older iPhones
* 9:16 for newer iPhones

So presumably you already take that into account in the display of the game? Or maybe you let Unity place bands?

In any case, the way to do it is to specify an area that will fit inside all the target devices then add padding/background/etc on the sides. If you look at Clash Royale screenshot on iPad for instance, you can see that you see a lot more of the sides of the arenas.

Then you set your Canvases and Camera's projection to target a specific height of a screen and let Unity scale as needed.

---
Tags: unity, ios, iphone
---