# Question
Title: Resource protection in cocos2d-x 2 and 3
I am developing a game in **cocos2d-x 2.2.3** and I want to protect my resources from being extracted. Is there any way I can do this?

I don't know much about encryption.

# Answer
> 1 votes
There's honestly not a lot you can do here in terms of absolute protection.

No matter how strong a vault you lock your resources inside, ultimately your game needs to know the code to open that vault so that it can use/display/play the resources in-game.

That means anyone who has a copy of your game also has a copy of the code or procedure to read those protected assets. A dedicated adversary will *always* be able to extract the resources given these tools.

All you can really do technologically is make it incrementally harder to do so, to the point where most people won't care enough to put in that time.

But that's time you're sinking into complex features that don't make your game play any better, fighting against a potential adversary you can never fully defeat anyway. I wouldn't recommend it as a valuable use of your time.

So rather than solving the issue with technology, you may want to consider a legal protection instead. Creative works like game assets (illustrations, music, 3D sculptures....) are automatically protected by copyright in many jurisdictions. If someone is using or distributing your resources in a way that you have not authorized, you'd have grounds for a legal case against them.

It's not practical to try to stop every homebrew tinkerer this way, but if someone is systematically trying to redistribute/resell your assets or use them in their own competing game, this gives you some recourse that they can't as easily hack their way around.

---
Tags: cocos2d-x, encryption
---


# Question
Title: Why there are more games in windows than linux?
I cannot comprehend why there are so many games available for windows and so few for linux in comparison. Why is the main reason, is it a technical or business reason ?

Are Windows libraries (directx) better or is it because of the driver support ? Linux have some great libraries like Allegro , SDL and LibGlut. And Android is Linux after all.

Given all that Why are more games in windows than linux ?.

# Answer
Windows has tranditionally been, and still is, highly attractive for Game developers while Linux (except for mobile phones) is highly unattractive.

Love Windows or hate it, but Windows has the advantage that it (well, mostly, if you manage its quirks) *just works*, and it works the same (well, mostly) regardless of what install you have. I'm running some 12-14 year old AAA titles on my present-day Windows computer, no workarounds or compatibility mode hacks needed. Say what you will, but this is darn awesome.

I'm about to go a bit hyperbole now (please bear with me), but still there's a grain of truth in it... Linux is *so much better* in theory, but in practice, no two distributions are compatible, and not even different versions of the same distro are compatible with each other. Also, everything is generally designed with "open" and "accountable" in mind whereas game developers generally prefer "obscure". To the typical Linux person, words like DRM and content protection stink whereas the typical big-studio person will likely say they have a fragrance of roses.

Add to that the fact that although Microsoft provides you with arguably the world's worst compiler suite, this is paired with the most bloated, yet most awesome development environment (with IHVs integrating tools) that money can buy. And, um... for free.

Under Windows, you get a new graphics card generation *built for* the newest DX features to come, with a *just works* DX installer. They're even called *DX-nn class* hardware. Under Linux, you get the features as vendor-specific GL or Vulkan extensions if you are lucky, after some time. And maybe, after an even longer time, as ARB extensions which are subtly different and require you to rewrite a lot of code. If you have stable drivers, that is, and if you are able to decipher the gibberish in the otherwise undocumented extension specification.
Under Windows, you and your customers can buy cheap whatever-it-is hardware and plug it in, and it (usually) just works with the well-supported, well-documented API. Under Linux, who knows. Maybe you're lucky and your manufacturer bothered to supply a driver, or maybe a generic one works. Maybe you find a hack that works, maybe you don't.

Yes, the situation has greatly improved since Steam went Linux, but still Linux is definitively a second-class citizen.

Which isn't surprising because the market share is like 2% and to make things worse from an economic point of view, not few Linux users expect software to be free. Which isn't bad *per se*, but it's not a great incentive for someone who wants to fill his pockets with money.

All in all, it's not very attractive to spend a six-digit amount of money for making a properly working Linux port (which properly works on one distro and skims maybe 0.5% of the market), or a seven-digit amount of money for making a Linux-only AAA game. It's not attractive to write drivers *and offer support* (which is more expensive than the actual drivers!) for a small minority from whom you can't expect to make much money. It's not attractive to document the intentionally-obscure details of your hardware implementation so everybody including your competitors knows, just so you *maybe* get another 1% of sales.

Sad, yes, but that's just what it is.
> 2 votes

# Answer
> 81.76% of worldwide computers run Windows
>
> 13.49% of worldwide computers run macOS
>
> 1.68% of worldwide computers run Linux
>
> 3.07% - Other/ChromeOS

Take a guess why developers prefer Windows and Mac over other operating systems... Even if Linux was some super OS with magic powers it still doesn't help that less than 2% of the population uses it.

Source: https://en.wikipedia.org/wiki/Usage\_share\_of\_operating\_systems
> 3 votes

# Answer
Yes, Android uses a kernel based on Linux. But from the perspective of an application developer, Desktop Linux and Android have very little in common. Android apps don't communicate directly with the OS kernel like Linux programs do. They run in a sandboxed runtime environment which has an own API. Programming for that API has absolutely nothing in common with regular Linux programming. They are even more different than Linux and Windows. So porting an Android game to run on a Desktop Linux distribution is anything but trivial.

Besides the fact that Windows is still the king of the Desktop operating systems by distribution (with MacOS being the most serious contender at the moment), the Linux desktop community also has a certain property which makes them a bad market segment for games. A lot of Linux users use Linux because they believe in open source software.

Unfortunately open source is not a viable business model for game developers. Open source development is usually funded by companies who either invest their own development resources into it in order to improve a software they use themselves or who pay good money for support contracts. Neither is an option for games. The two standard ways to monetize a game do not work in an open source ecosystem. Pay-by-copy doesn't work because customers are allowed to redistribute your game and microtransactions don't work because open source games can easily be patched to make those items available for free.

What's left are enthusiast free-time volunteers and donations. Creating a high quality game that way is next to impossible. I am speaking from experience here. I was a contributor to an open source game for years which didn't really get anywhere due to the lack of dedicated full-time developers.

But there is hope for Linux as a gaming platform. Steam for Linux was made available a few years ago and game engines like Unreal and Unity make it relatively easy to create a Linux port of a game. The increased availability of high-quality commercial games on Linux might lead to a higher acceptance among the hard-core Linux crowd for proprietary games and also make Linux more attractive for the "average" gamer who doesn't care as much about all their software being open source. But we are still far away from the market situation where it makes any commercial sense to develop a Linux-exclusive AAA title.
> 0 votes

---
Tags: windows, linux, business
---


# Question
Title: Replacement for glDrawElementsBaseVertex in OpenGL ES?
I am porting my game engine(c++) to Emscripten, which unfortunately only supports OpenGL ES 3.(Not 3.2) Therefore I don't have access to glDrawElementsBaseVertex, which is needed by my renderer(Canvas2D Renderer). It is needed because this way I can combine all my triangles in one draw call, instead of multiple hundred draw calls. So I need something that does the same. I can't just use normal draw calls, because it would be horribly slow and would require redesigning my Canvas2D class.

The reason I need so many draw calls is because the user can use a Canvas2D to draw single/multiple 2D triangles on the screen, which are then combined into one array. Because the user can also send multiple triangle set's, the indexes need an offset to work correct, which is why I need glDrawElementsBaseVertex.

Does anyone know how to replace glDrawElementsBaseVertex with something that does the same?

Thanks!

# Answer
> 0 votes
If there was something that did the same thing, why would OpenGL have even had that as a separate function?

The only thing you can do is pre-offset the indices you're assembling in your index buffer.

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


title: Diegetic UI in a game set in the past

text:
# Question
Title: Diegetic UI in a game set in the past
Recently I've been putting together an in-game UI for a passion project I'm working on, but I absolutely hate the UI meta at the moment.

I love Morrowind's UI, in that it is central and easy to access. For this reason, when opening inventory nearly everything is instantly visible. The difference is that I find those kind of UIs break the flow of the game and immersion, so I used a diegetic UI element for this. Other UI elements I've succeeded in making diegetic include a basic map, compass, and journal.

I also love Dead Space's UI, and it's impossible to mention diegetic UI without mentioning it. Other diegetic UI's such as those in some Metroid series entries are similar, though I prefer Dead Space's for its simplicity.

My own game is a third-person action adventure RPG, so immersion in the environment is important to me. It has its own magic system that plays a lot on the way health works. Magic overuse can kill the user, making it very important for me to telegraph HP and magic reserves to the player.

These goals make UI hard though. I don't want a cluttered UI, but I can't use sci-fi or futuristic elements to display information like the examples I listed due to the context of the story and the time period it is based in. I can use animation based things like limping, slouching and so on, but I feel those are too hard to recognise in the heat of a fight and could use some complementary system. Are there any fantasy games that don't use futuristic elements or gamey UIs successfully? Is it possible and has it been done before?

# Answer
How do you signal to the player that they are about to cast a spell?

The Elder Scrolls series, for example, shows some "magic stuff" in the player-characters hand:

In TES, the look of that "magic stuff" symbolizes the kind of spell. But what you could do in addition to that is use size and intensity of that effect to communicate how much mana the character has left.

* Large flame: You have plenty of mana left.
* Small flame: You are about to run out.
* No flame at all: You are out of mana. Hope you got a plan B.
> 0 votes

# Answer
Something of a zen koan you're asking. What does it "look" like to be low on mana or full mana from the point of view of a spellcaster, given that spell casting isnt real? I cant think of a game that does this without some form of non-diegetic scroll bar. You could maybe play with shaders. Maybe the world is more colorful the more mana someone has, approaching black and white when nearing empty. Lots of games do something in the vein of having the screen turn red (and more so at the edges of the screen, i.e. a vignette) as the health is low.
> 0 votes

---
Tags: ui-design, user-experience
---


# Question
Title: How can I monetize with AdMobs a libGDX game made with AIDE?
I have created a libGDX game with the AIDE IDE Android app. The game is working fine so I will be uploading it to the Play Store to make money.

I'd like to use AdMob ads, how would I integrate it?

# Answer
> 1 votes
According to Linux Journal, you need to purchase the premium version of AIDE.

*"AIDE is distributed under a freemium model. The free version allows you to develop, compile and run your code. It also allows you to install to the device on which AIDE is running. However, if you want to generate APK files that can be used to install onto other devices, you need to purchase the full version."*

Next, you need to abide to the Apache 2 License of libGDX, which doesn't require much, if anything. I don't see a NOTICE text file in the libGDX source, and giving credit is non-mandatory.

So to me it appears that, yes, you can publish commercial apps, and monetize it the way you see fit, once you comply with these two. But you need to verify this yourself.

---
Tags: monetization
---


# Question
Title: When I open an image from Unity in preview it's blank?
Ok, I need to know why this is and don't have the .png anywhere else. I have a texture in Unity that I need to edit in Photoshop, yet when I Reveal the image in Finder then open it in preview or photoshop, the whole thing is blank.

It is clearly not a blank image, and other images are not doing this:

What is wrong here?

# Answer
> 1 votes
Open photoshop and do layer mask from transparency, then disable the mask.

---
Tags: unity, textures, image
---


title: How OpenGL running without GPU?

text:
# Question
Title: How OpenGL running without GPU?
Every tutorial on OpenGL mentions that,

> OpenGL codes are commands executed by the GPU.

Few days ago, my GPU cashed and I removed it from my computer. But the same OpenGL programs are still running without any additional change! What is happening?

# Answer
**How do you know your programs are running if you can't see anything on your screen?**

Or to put it another way - you still have a GPU of some description in your computer, because in addition to executing OpenGL (or Direct3D, or Vulkan, etc) commands, your GPU is also responsible for displaying images on your screen. The fact that images are displaying on your screen (otherwise you wouldn't know if your programs were running) confirms that you have a GPU.

So what this tells me is that your computer actually had **TWO** GPUs, one which was most likely an Intel integrated on the motherboard, the other which was an NVIDIA or AMD and which was the one that you removed. This is quite a common configuration.
> 2 votes

---
Tags: opengl, gpu
---


# Question
Title: Unreal installation and storage space requirement
I am a new user of Unreal. I installed the program on Windows 7, and after using it for awhile I noticed that the C:/ partition was filling up very fast as I worked on my projects. I store my projects on a storage device different than the one with Windows- does Unreal nevertheless write files related to a project to C:/ and if it does, can such a setting be changed?

I am upgrading to Windows 10. Is there any difference in the behavior explained above between the two Windows versions? Is there any rule of thumb about how much there should be free space on the C:/ partition for Unreal to work with, regardless of where projects are stored?

# Answer
> 2 votes
What I found is that there was several gigs of data being stored in my **App Data Derived Data Cache**.

```
"C:\Users\yourusername\AppData\Local\UnrealEngine\Common\DerivedDataCache"

```

These are all just cached textures but are way larger than they should be. It is completely safe to delete this derived data cache from your app data (to see this folder you must enable "view hidden options" in your file explorer. When you reopen your project all of your textures will be reset to he default checkered grey but after a while it will recompile them all and that folder will be hopefully be much smaller than what is was before.

This eliminated around 60 gigs off my ssd when I cleared it.

Hopefully this clears up some storage for you.

---

**NOTE**

Reference the unreal guide online to find more info about automatically storing these textures on a external drive as they do explain how to go about doing that on there.

---
Tags: unreal
---


title: Wrong angles given by atan2

text:
# Question
Title: Wrong angles given by atan2
I have a method to calculate angle between two vectors, but it is giving wrong values.

here is the code :

```
float Vector2_Dot(Vector2 a, Vector2 b)
{
    return a.x * b.x + a.y * b.y;
}

float Vector2_Cross(Vector2 a, Vector2 b)
{
    return a.x * b.y - a.y * b.x;
}

float Vector2_Angle(Vector2 a, Vector2 b)
{
    return atan2f(Vector2_Cross(a, b), Vector2_Dot(a, b));
}

```

As you can see in the image bellow the angle is slightly wrong.

I'm giving the two positions marked by a black cross. is the code correct or Do I have a problema elsewhere?

Here's is where I do my transformation matrix calculation:

```
float Transform_GetLocalAngle(DeadTransform *transform)
{
    if (transform->parent != NULL)
        return transform->parent->angle - transform->angle;
    else
        return transform->angle;
}
void Transform_Update(DeadTransform *transform, GLfloat depth)
{
    float angle     = Transform_GetLocalAngle(transform);
    Vector2 position    = Transform_GetLocalPosition(transform);
    Vector2 scale       = Transform_GetLocalScale(transform);

    GLfloat data[16] = {(GLfloat)cosf(angle) * scale.x,     (GLfloat)(-sinf(angle)) * scale.y,  0.0f,   position.x / 1000,
                        (GLfloat)(sinf(angle)) * scale.x,   (GLfloat)cosf(angle) * scale.y,     0.0f,   position.y / 1000,
                        0.0f,                               0.0f,                               1.0f,   depth,
                        0.0f,                               0.0f,                               0,      1.0f};
    Matrix_SetData(transform->transformationMatrix, data);
}

```

This is where I create the road:

```
direction = Vector2_Subtract(*tile->top->transform->position, *tile->topLeft->transform->position);
            pos.x = tile->top->transform->position->x + direction.x / 2;
            pos.y = tile->top->transform->position->y - direction.y / 2;

            float angle = Vector2_Angle(*tile->top->transform->position, *tile->topLeft->transform->position);

            CreateConnection(application, pos.x, pos.y, angle);

void CreateConnection(struct Application *application, float x, float y, float angle)
{
    DeadGameObject *zone = GameObject_Create("Connection");
    zone->transform->position->x = x;
    zone->transform->position->y = y;
    zone->transform->angle = angle;
    zone->transform->scale->x = 64;
    zone->transform->scale->y = 6;
    DeadRenderer *renderer = Renderer_Create(Texture2D_Create("Images/Connection.png", GL_CLAMP, GL_LINEAR));
    Renderer_SetDepth(renderer, -2);
    GameObject_AddComponent(zone, renderer, Type_Renderer);

    Application_Instantiate(application, zone);
}

```

# Answer
After some research I found the answer:

```
float Vector2_Angle(Vector2 a, Vector2 b)
{
    Vector2 c = Vector2_Subtract(a, b);

    return atan2f(c.y, -c.x);
}

```

this is the right formula.
> 1 votes

---
Tags: opengl, mathematics, c
---


# Question
Title: What's a good way of implementing traits/promotions/buffs?
I basically need something that modifies existing code without the need to go back and change it. So for instance, if I have a game where the player or NPS can eat food to gain health back, and eating a banana gives five health, how can I make a trait that will make the banana gives ten health instead of five without going back into the original code that makes the banana award five health? Thanks.

# Answer
> 0 votes
I would suggest adding a conditional to the action, so if the player has that trait it would raise a flag, and every time the character eats a banana it would check using a if else and if the user has that trait it would heal the 10 instead of 5, hope that helps.

---
Tags: c#
---


title: SDL Sliding Collision

text:
# Question
Title: SDL Sliding Collision
I'm working on a 2D SDL C++ project, and I'm having a bit of trouble with collision detection. Currently the player collides with the edges of the level and with the SDL\_Rect objects in the level, however it's not reacting how I want it to. This is the code I've got so far:

```
void CollisionManager::playerCollision(float xVelocity, float yVelocity, float* xNewPos, float* yNewPos, SDL_Rect currentPos)
{
    // --- Test collision with level boundaries. ---
    if (((*xNewPos) < 0) || ((*xNewPos) + currentPos.w > currWorldWidth))
        (*xNewPos) -= xVelocity;

    if (((*yNewPos) < 0) || ((*yNewPos) + currentPos.h > currWorldHeight))
        (*yNewPos) -= yVelocity;

    SDL_Rect currentRect;
    bool collisionX, collisionY;

    // --- Test collision with game objects. ---
    for (std::vector<Shape>::iterator it = cObjects->begin(); it != cObjects->end(); ++it)
    {
        currentRect = it->GetRect();

        // X-Axis collision
        collisionX = ((*xNewPos) + currentPos.w > currentRect.x) && (currentRect.x + currentRect.w > (*xNewPos));

        // Y-Axis collision
        collisionY = ((*yNewPos) + currentPos.h > currentRect.y) && (currentRect.y + currentRect.h > (*yNewPos));

        if (collisionX && collisionY)
        {
            (*xNewPos) -= xVelocity;
            (*yNewPos) -= yVelocity;
        }
    }
}

```

First it tests the player against the level boundaries. If it detects collision on the X-axis, it subtracts xVelocity from the new X position, and likewise with the Y-Axis and Y position. This way when the player collides with the level boundaries, it slides along the edges.

When testing collision with the level objects, I have to test both axis at the same time to test for a collision, but this way if for example, the top of the player is colliding with the bottom of the object, and I'm pressing Up and Left, the player won't move until I let go of the Up button. I can't test for collision with just one axis as before, because I might be colliding with several other objects on the screen on the same Y-axis, but on the other side of the screen.

I'm thinking what I need to do is find out which side of the object I'm on by testing the intersection depth of the two SDL\_Rect objects, then only revert the position on that axis back to what it was, so if I'm colliding on the left or right side, set xNewPos back to its old position, and if it's colliding on the top or bottom, set yNewPos back to its old position. I'm having trouble getting my head around how to do this though, especially if I'm colliding with two objects at once. Can anyone give me any ideas, or if there's a better way of doing this?

Edit - Okay, I think I've made progress. I've replaced the two lines of code in the if (collisionX && collosionY) statement with this:

```
objWidth = currentRect.x + currentRect.w;
            objHeight = currentRect.y + currentRect.h;

            // Collision from top or bottom
            if (((playerHeight > currentRect.y) || (currentPos.y < objHeight)) &&
                (currentPos.x > currentRect.x && currentPos.x < objWidth)
                || (playerWidth > currentRect.x && playerWidth < objWidth))
                    (*yNewPos) -= yVelocity;

            // Collision from side
            if (((playerWidth > currentRect.x) || (currentPos.x < objWidth)) &&
                (currentPos.y > currentRect.y && currentPos.y < objHeight)
                || (playerHeight > currentRect.y && playerHeight < objHeight))
                    (*xNewPos) -= xVelocity;

```

It seems to be working for the most part. If I collide with one of the objects, the player slides along the edges instead of just stopping. However when I'm sliding up the right side, the player gets stuck on the top right corner. It looks like it happens when the bottom of the player reaches the top of the rectangle. The same thing happens if I'm sliding along the bottom towards the left. When the player reaches the bottom left corner, it gets stuck, just as the right side of the player reaches the corner. I'm looking at this now, but can anyone see any immediate problems with my code?

Edit - Got it. This code gives me the results I'm after:

```
if (collisionX && collisionY)
        {
            objWidth = currentRect.x + currentRect.w;
            objHeight = currentRect.y + currentRect.h;

            // Collision from side
            if (
                (currentPos.x <= objWidth || playerWidth >= currentRect.x)
                && (currentPos.y > currentRect.y && currentPos.y < objHeight)
                || (playerHeight >= currentRect.y && playerHeight < objHeight)
                )
                verticalColl = true;

            // Collision from top or bottom
            if (
                (currentPos.y <= objHeight || playerHeight >= currentRect.y)
                && (currentPos.x > currentRect.x && currentPos.x < objWidth)
                || (playerWidth >= currentRect.x && playerWidth < objWidth)
                )
                horizontalColl = true;

            if (horizontalColl)
                (*yNewPos) -= yVelocity;

            if (verticalColl)
                (*xNewPos) -= xVelocity;
        }

```

I also had to make sure I was testing for \>= rather than just \> or \<.

# Answer
> 1 votes
Got it. This code gives me the results I'm after:

```
if (collisionX && collisionY)
        {
            objWidth = currentRect.x + currentRect.w;
            objHeight = currentRect.y + currentRect.h;

            // Collision from side
            if (
                (currentPos.x <= objWidth || playerWidth >= currentRect.x)
                && (currentPos.y > currentRect.y && currentPos.y < objHeight)
                || (playerHeight >= currentRect.y && playerHeight < objHeight)
                )
                verticalColl = true;

            // Collision from top or bottom
            if (
                (currentPos.y <= objHeight || playerHeight >= currentRect.y)
                && (currentPos.x > currentRect.x && currentPos.x < objWidth)
                || (playerWidth >= currentRect.x && playerWidth < objWidth)
                )
                horizontalColl = true;

            if (horizontalColl)
                (*yNewPos) -= yVelocity;

            if (verticalColl)
                (*xNewPos) -= xVelocity;
        }

```

I also had to make sure I was testing for \>= rather than just \> or \<. This is working for me, but does anyone have any other/better ways of doing this for future reference?

---
Tags: c++, collision-detection, sdl
---


# Question
Title: 2D converting absolute top-down coordinates into relative third-person coordinates
I'm working on 2D top down zombie game. I started working on it as having a static 2D map and on every tick you update the coordinates of every object, including the player itself **relative to the static map**. Every object has x, y and angle against x axis `x, y, theta`.

But I would like to also provide a way to see it as a kinda third-person shooter (still top down 2d just different center of coordinates), where **camera and coordinates are connected to the moving player object**. So the player would always have the `0, 0, 0` coordinates and every other object transformed `xT, yT, thetaT` coordinates.

What approach should be used in such cases? Should I still keep the static coordinates and simulate the world over a static map, and then transform the coordinates of every object into relative coordinates? So every tick there will be two transformations - world simulation and static -\> relative coordinate transformation?

# Answer
You should keep everything in the static world frame and only transform them into the player's coordinate frame when necessary. This will reduce many headaches along the way because your static reference frame will be independent of the player's position and velocity.

That makes it possible to reference objects w.r.t fixed coordinates or regions in the level which never have to be changed. For example "is this monster inside this door?" becomes a simple box vs. box check and requires no reference frame transformation. It also allows you to cache the coordinates of every non-moving object.

As for "transforming into the player's reference frame every tick," yes, you do this but **not on the CPU**. Just set up your game's rendering system to appropriately adjust the World and View matrices so that the GPU takes care of that for you at draw time. The standard pratice would be to set up an orthographic perspective matrix and a view matrix centered on your player.

Aside from that, there are a few times you'll want to transform coordinates into the player's reference frame -- but I suspect they're fewer than you anticipate. It won't have to be for every object, and it certainly won't have to be for every tick.
> 1 votes

---
Tags: coordinates, linear-algebra
---


title: Chunked A* Pathfinding Issues

text:
# Question
Title: Chunked A* Pathfinding Issues
I've run into an issue with A\* pathfinding in a chunked world.

This is my current setup:

* The world is designed in Tiled and exported as a .json file.
* I wrote a little program that converts the .json file into objects that are serialized into binary files the main game loads.
* Each chunk is stored in it's own file (`-2_-1.cnk` for example).
* Chunks contain an `x`, `y`, `width`, `height`, `int[,]` for tile ids and a `bool[,]` for solid flags.
* The GameWorld contains a `Dictionary<Point, Chunk>` to store the chunks.
* When the game needs to know which tile id exist at `(x,y)`, the world first checks to see if the chunk is loaded. If not it is loaded from disk and stored in memory until it's unloaded.
* The pathfinder does not know about chunks, an `IGrid` interface is passed when FindPath is called, `IGrid` contains an `IsWalkable(x, y)` method.
* The GameWorld implements 'IGrid' and contains an implemented `IsWalkable` method.
* When `IsWalkable` is called by the pathfinder, the world calls `GetChunk(x, y` but does not load a chunk from disk if isn't not already in memory. If a chunk is found, the `bool[,]` is checked to see if the tile is solid or not. If a chunk is not found, the tile is considered solid.

Pathfinding runs fine, search time range between 0.3ms - 9ms; though I have noticed that there are some corners that take ~40ms to search.

But as for my issue. Say I have a valid, accessible tile that a path can be found for, only it's close to the border of a chunk and can only be reached by leaving the current chunk and moving into an adjacent chunk. This image should be a better representation:

The red lines are the chunk borders, the yellow circle is the goal, the pink circle is the start and the blue line is the path.

For this example, pretend everything ABOVE the red chunk is an unloaded chunk, below the red line is loaded, and the player CAN SEE the goal tile. Diagonal movement is allowed, but not when moving next to a solid tile, so slipping between the trees diagonally is not allowed.

The pathfinder will keep searching the loaded chunk until it reaches the border, the chunk above is not loaded, so any tiles outside the current chunk are 'solid'. The pathfinder will continue to search available tiles in the loaded chunks until it's checked them all and decided a path could not be found.

A work around for this is to allow the pathfinder to load chunks when it reaches chunk borders, but this doesn't seem like a very clean solution.

Is there any way around this? The map is static and will not change, so I can pre-compute 'something' when I convert the map from the .json file.

One solution might be to flood fill each accessible 'region' in each chunk, only allowing paths with goals in the same region the player is standing in. But that would break if the player is standing on the boundary of two chunks, they would have different regions.

Or I'm just way over thinking this and I should just increase the chunks loaded distance so there's more overlap with the on screen and off screen chunks. Then just limit the pathfinding to have a `max_search_length` limit and stop when it's searched for too long.

Any thoughts?

# Answer
> 1 votes
Store PF information in a different struct/object (since you said it never changes). You only need 1 bit for every tile anyway, or 1 byte if you want to handle different tile speeds, it should't take too much memory. This might come handy for circunstances where the PF actually needs to skip several chunks in order to reach a goal.

# Answer
> 1 votes
* The binary data of whether or not a tile is occupied is much smaller than the rest of the map. You can store this in your json data as a binary string. For a 1024 x 1024 chunk, that's just 131 kilobytes, which should be very easy to load.
* If just loading the binary metadata is unpalatable to you, you could modify A\* in the following way: assume every unloaded tile is passable. If later any cell along your path is loaded and found to be unpassable, you replan the path. This sounds like a dumb algorithm but it's actually not that bad. If you want something that's optimal, you can use D\*, which is actually not that different from just replanning.

# Answer
> 0 votes
When you are near the edge of your loaded chunks, you should be loading more (in the background), and that will reduce the lag time as you travel long distances.

One option is to instead of considering unloaded chunks to be `unwalkable` consider them `unknown`. In a first pass you consider them as `unwalkable` tiles, when path finding fails in that case you can do a second pass where you actually load those chunks.

You can also use a bidirectional A\*. That way, if one side ends in a dead end in the first pass, you can skip the second pass.

Also, if it's a pregenerated map it should be possible to load the walk-able state separately (which will be cheaper to load and keep in memory) and even keep the entire map's walk-able state loaded as a bitmap.

---
Tags: 2d, path-finding, terrain
---


# Question
Title: How to program smooth player 2D movements
I am writing a simple 2D game in Rust, having access to the following dependencies:

The genre is Metroidvania, the game features a single map *Super Mario* style, where the player can only move backwards and forwards and jump (and throw attacks). Modern games, such as Hollow Knight just to give an example, allow the player the same type of movements and they are very smooth.

I have never developed a game with these features, and from my first attempts now it looks like developing these smooth movements is harder than I thought it would be.

I have thought of several alternatives in order to move the player, but I am not sure which of these approaches is the best one or if there are others that are even better:

* Do not rely on the physics engine at all and implement the movements just by changing the position of the graphics (shapes/sprites...). I personally didn't try this one because it sounds like a lot of work that does not guarantee good results.
* Implement the movements by setting the velocity of the player through the physics engine.
* Implement the movements by applying a force to the player through the physics engine.

I guess the answer would also depend on how to handle the user inputs properly and link them to the player movements, since they are very strictly related to each other.

# Answer
You should use forces to play nice with your physics engine, but you've got to be careful about how to apply them.

One point I'd like to make is that if you do use forces, you should do so to **servo to a desired velocity**, rather than applying a constant force. What the player expects in a platformer that their character will move at a constant velocity in the direction they desire (maybe with very slight delays). They don't expect the character to get faster and faster. They also don't expect the character to have a lot of inertia when stopping.

So, each time you get input from the player, interpet it as a *desired velocity*. Compare this to your current velocity, and apply a correcting force proportional to the difference between the two. You can then adjust how "smooth" the change in velocity is by filtering or clamping the forces.
> 1 votes

# Answer
Unfortunately, **smooth** and **responsive** are kind of opposites on a spectrum.

For the smoothest control, you set force, which leads to acceleration, which leads to velocity change which leads to position change.

Setting forces will also be a lot friendlier to your physics engine. If you start setting positions or velocities, the physics engine will get confused. At the very least, you'll be very prone to setting the objects into a colliding state.

This indirect steering via forces, will make feel the control less responsive to the player, though.

If the player presses JUMP, he wants to jump *now*, and not wait for acceleration to play out.

But if you go for maximum realism, forces are the way to go. And you do have the option to use very high forces too, to hide the inertia of your game objects.

In conclusion, it kind of depends on your game genre. A game like PONG would definitely require setting of positions for optimum responsiveness. A racing game should only use forces, otherwise the physics will look very fake.
> 0 votes

---
Tags: 2d, physics, game-design, movement
---


# Question
Title: Interstitial Ads Not Showing in 1st Scene
I want to show interstitial ads in my game's 1st scene. Whenever game is opened, ads should show inside it.

When I use the Play Button ads work ok, but it's showing on the next scene.

```
using UnityEngine;
using System.Collections;
using GoogleMobileAds.Api;
using System;

public class Admob : MonoBehaviour
{
    InterstitialAd interstitial;

    public string InterstitialId;

    // Use this for initialization
    void Start()
    {
        //Request Ads
        //RequestBanner();
        RequestInterstitial();
    }

    public void showInterstitialAd()
    {
        //Show Ad
        if (interstitial.IsLoaded())
        {
            interstitial.Show();
        }
    }

    private void RequestInterstitial()
    {
#if UNITY_ANDROID
        string adUnitId = InterstitialId;
#elif UNITY_IPHONE
        string adUnitId = "INSERT_IOS_INTERSTITIAL_AD_UNIT_ID_HERE";
#else
        string adUnitId = "unexpected_platform";
#endif

        // Initialize an InterstitialAd.
        interstitial = new InterstitialAd(adUnitId);
        // Create an empty ad request.
        AdRequest request = new AdRequest.Builder().Build();
        // Load the interstitial with the request.
        interstitial.LoadAd(request);
    }
}

```

# Answer
> 1 votes
We don't have a lot of information about where you call this method, but based on what we can see I'd suspect your problem may be here:

```
public void showInterstitialAd()
{
    //Show Ad
    if (interstitial.IsLoaded())
    {
        interstitial.Show();
    }
}

```

This tries exactly once to show the ad. If the ad hasn't loaded yet (because the game just started up and it hasn't had time to process the request & download the ad in its entirety), then it gives up and never shows the ad.

You can make this more robust like this...

```
Coroutine pendingAd;

IEnumerator ShowIntersitialAdWhenReady() {
    // As long as the ad hasn't leaded, let the game keep running.
    while(interstitial.IsLoaded() == false)
        yield return null;

    // Now the ad has loaded - show it.
    interstitial.Show();

    // Clear out our "pending" state.
    pendingAd = null;
}

```

Now your show method can look like this:

```
public void ShowInterstitialAd()
{
    if (pendingAd == null)
        pendingAd = StartCoroutine(ShowInterstitialAdWhenReady());
}

```

If the ad isn't ready when you first try to show it, then we'll buffer the request and show it as soon as we can.

You can use the `pendingAd` variable to make sure you don't accidentally try to show the same ad twice, and can cancel the ad show request if you change states while it's still pending.

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


# Question
Title: How to import character package in Unity
I recently made a game in Unity 3D and I tried to import the FPS Controller package as the tutorial I was following said, but when I clicked Assets/Import Package the only thing I saw was a button saying 'Custom Package'

How do I get the character option when I click 'Import Package'?

# Answer
It looks like when you installed Unity, you might have skipped installing the Standard Assets package. You can download it for free from the Unity Asset Store here.
> 1 votes

---
Tags: unity, first-person-shooter, importing
---


# Question
Title: pygame KEYUP KEYDOWN events only once per frame?
I've been playing around with pygame, and I ran into a bit of an odd issue with input on the pygame event queue. Consider the following test code:

```
import pygame as pg

def main():
    pg.init()
    pg.display.set_mode([640,480])
    clock = pg.time.Clock()
    while True:
        clock.tick(1)
        events = pg.event.get()
        print("There are %d events in the queue." % len(events))
        for event in events:
            print(event)
        print()

if __name__ == "__main__":
    main()

```

Here I'm intentionally running the game loop just once per second. What I observe is that the pygame event queue can easily receive dozens of mouse-related events per frame, but only ever **a single** KEYDOWN **or** KEYUP event at a time.

This is the output after pressing four keys simultaneously and quickly pressing the left mouse button a few times at the same time:

```
There are 0 events in the queue.

There are 1 events in the queue.
<Event(5-MouseButtonDown {'pos': (494, 392), 'button': 1})>

There are 8 events in the queue.
<Event(2-KeyDown {'unicode': 'f', 'key': 102, 'mod': 0, 'scancode': 41})>
<Event(6-MouseButtonUp {'pos': (494, 392), 'button': 1})>
<Event(5-MouseButtonDown {'pos': (494, 392), 'button': 1})>
<Event(6-MouseButtonUp {'pos': (494, 392), 'button': 1})>
<Event(5-MouseButtonDown {'pos': (494, 392), 'button': 1})>
<Event(6-MouseButtonUp {'pos': (494, 392), 'button': 1})>
<Event(5-MouseButtonDown {'pos': (494, 392), 'button': 1})>
<Event(6-MouseButtonUp {'pos': (494, 392), 'button': 1})>

There are 3 events in the queue.
<Event(2-KeyDown {'unicode': 'q', 'key': 113, 'mod': 0, 'scancode': 24})>
<Event(5-MouseButtonDown {'pos': (494, 392), 'button': 1})>
<Event(6-MouseButtonUp {'pos': (494, 392), 'button': 1})>

There are 1 events in the queue.
<Event(2-KeyDown {'unicode': 'e', 'key': 101, 'mod': 0, 'scancode': 26})>

There are 1 events in the queue.
<Event(2-KeyDown {'unicode': 'w', 'key': 119, 'mod': 0, 'scancode': 25})>

There are 1 events in the queue.
<Event(3-KeyUp {'key': 119, 'mod': 0, 'scancode': 25})>

There are 1 events in the queue.
<Event(3-KeyUp {'key': 113, 'mod': 0, 'scancode': 24})>

There are 1 events in the queue.
<Event(3-KeyUp {'key': 101, 'mod': 0, 'scancode': 26})>

There are 1 events in the queue.
<Event(3-KeyUp {'key': 102, 'mod': 0, 'scancode': 41})>

There are 0 events in the queue.

```

At 1 FPS, it takes pygame 8 seconds to process just 4 keypresses, one for each KEYUP and KEYDOWN signal. Is this intended behavior? Am I missing something here? It seems odd to me that pygame cannot register multiple keypresses per frame. I'm a bit of a newbie when it comes to gamedev, so I'm not sure where this is coming from.

# Answer
Please use the function pygame.key.set\_repeat(delay, interval) once before starting the infinite while loop. I use as delay 1 and an interval of 25.

From the docs: pygame.key module

> The delay is the number of milliseconds before the first repeated pygame.KEYDOWN will be sent. After that another pygame.KEYDOWN will be sent every interval milliseconds. When pygame is initialized the key repeat is disabled.

This is the equivalent of for example a key pressed event in Game Maker
> 1 votes

---
Tags: input, python, pygame, keyboard
---


# Question
Title: Any way to interface methods in objects?
Say I have object A, which has children B, C and D.

In OOP I would have A be an interface containing method `action()`, then I would have B, C and D *implement* A and, in their class definition, I would define the method in each of them in extremely different ways (as intended).

Is there a way to do something similar in GML? So far I can only think of making a script with an chain of if statements for every kind of action based on `object_is_ancestor()` which feels messy and unorganized to say the least.

Thank you for the help.

# Answer
Yes, you can by using function pointers (or script indexes as game maker calls them).

You already know that you can have an object be a child object type of some other parent. You want parent A to have a general method "action()" that can be called in B, C, and D and have varying behavior. This can be done via function pointers, and is precisely the same way that the internals of most OOP languages do so. The reason you have to do this yourself is that game maker is an **event oriented language** (or at least that's how I have heard it phrased). Hence, objects don't have methods they have *events* and those are predefined or addable with triggers.

So how do you do function pointers in game maker? Suppose you have a few versions of the method written as scripts:

action()

actionB()

actionC()

etc.

Then just give the parent A and each of the children a variable called action\_pointer. For A set action\_pointer = action, and do similarly for each of the children. Then use the function script\_execute to call the stored index.

You will have to make the methods separate from the objects and written as scripts (unless you wish to use the forbidden execute\_string function which I highly recommend not using), but that can be done with simple organization and folders for different objects. The nice thing here is that if you do all this in the create event and call the parent's event before doing the sub-objects initialization within a create event then you get the effect of hierarchical behavior as an interface. I haven't had a particular use for it in game maker but it sounds like what you are wanting.

See here for more details on the script\_execute function: http://gamemaker.info/en/manual/409\_06\_scripts
> 1 votes

# Answer
Game Maker doesn't support anything resembling OOP interfaces. On the other hand, you can use inheritance to override/overload actions defined in parent objects' events.

Also, you don't need to use `object_is_ancestor()` continuously, as long as you design your game object in a good way. You may create generic or ad-hoc scripts for different objects, or make a reference to a common user-defined event, and place your custom code in there as if you were implementing an interface method.
> 0 votes

---
Tags: game-maker
---


# Question
Title: How to create walking animations in Gamemaker 8
We are learning how to use Gamemaker 8.1 in my game design class, and I wanted to experiment with it, and try to make my own game. I have run into a problem when trying to animate an object walking. I've looked all over google for how to animate the walking, but the only tutorials I can use what looks like a different kind of Gamemaker where you code everything.

To specify, I am using the version of Gamemaker where you drag and drop different actions into events. You can add code, but I would prefer not to use it.

I would like to know a way to either import a sprite sheet or a gif and have a walking animation play while the character is moving whenever you use the arrow keys.

# Answer
FYI, the version of game maker you saw was Game Maker: Studio which was a rewrite and the version immediately proceeding 8.1. It does have drag and drop. The people writing tutorials just aren't using them is all that is going on there.

Now as for how to do the walking animation:

Use one sprite for each movement direction.

For each press event for the arrow keys set the sprite to the appropriate direction.

For each release event set the image\_speed to 0.

Adjust the logic accordingly if your movement system differs.

Basically just change the sprite whenever you tell your object to change a movement direction, and set the image\_speed to 0 (pause the animation) whenever you make the motion stop. Since I don't know all the complexities of your motion system and exactly how the game is designed to respond to multiple buttons pressed simultaneously this philosophy and way of thinking will serve you better. It is also preferable for any future developers reading this question.
> 1 votes

---
Tags: game-maker
---


# Question
Title: How can I make relative movement in GameMaker studio?
I know I can change the `hspeed` and `vspeed` properties on my object. Assume I do it for the directional diamond in a squared-style movement game (not necesarily snapping to tiles, but it could). So the following scenarios apply (for any constant K) for my `obj_Hero` object:

* Pressing UP: vspeed is -K, hspeed is 0
* Pressing DOWN: vspeed is K, hspeed is 0
* Pressing LEFT: vspeed is 0, hspeed is -K
* Pressing RIGHT: vspeed is 0, hspeed is +K
* Otherwis: vspeed and hspeed are 0
* Only one directional arrow at the same time will be considered (the last pressed).

My player starts from position of an `obj_Start` object, and wins when reaching (colliding) an `obj_End` object. In the meantime, an `obj_Enemy` will be chasing the player using a *step avoid* strategy to avoid the player. The player loses if the enemy collides with him. Assuming I can correctly select the enemy current direction sprite, I'm done.

So far, so good.

Now assume some parts of my game have moving platforms. They have a specific platform speed vector (PSH, PSV), assuming I have such constants.

I know I could always condition my player movement speed to be:

* `(K + PSH, PSV)` for player moving right
* `(-K + PSH, PSV)` for player moving left
* `(PSH, K + PSV)` for player moving down
* `(PSH, -K + PSV)` for player moving up
* `(PSH, PSV)` for player not moving

But... How do I alter (relative to the platform movement, as I do with the player) the enemy movement when it is actually generated by the *step avoiding* strategy?

# Answer
> 0 votes
When an enemy is standing on the platform add dx and dy to the enemy's position each frame where dx and dy are the change in the platforms position. Do it manually through gml in addition to the step avoid code. It should work just fine.

---
Tags: game-maker
---


# Question
Title: GameMaker - Sprite will not stop moving backwards
I am very new to game development, and I am using GameMaker Studio as my first engine. I was following along with a tutorial to create an Asteroids-like game from scratch, but right now I am trying to create my own coding. There are small problems, but I believe it may just be my coding. The coding language is GML, its proprietary language.

The first problem is that I cannot get my sprite to stop moving backwards:

```
motion_add(image_angle,-0.2);
if (speed < 0) speed = 0;

```

It seems okay, since I am trying to force the sprite to have a motion of zero if the speed starts going negative.

Another thing is that I cannot seem to get the bullets to fire from my ship. The code is under the event "Press \<Space\>":

```
bullet = instance_create(x,y,obj_bullet);
bullet.speed = 15;
bullet.direction = image_angle;

```

The bullet literally just doesn't appear, at all. I know it isn't invisible because firing at an asteroid will not destroy the asteroid.

Thanks for the help everyone!

# Answer
For your first question, does motion\_add move the object or add speed? I'm guessing what's happening is the object has no speed, but you're still moving it with move\_add.

What you probably want to do is something like:

```
if(speed > 0) motion.add()
else if(speed < 0) speed = 0

```

This way we only add motion if the speed is positive.

Even better would be to first calculate speed and then calculate position:

```
speed = speed + acceleration
if(speed < 0) speed = 0
position = position + speed

```

I have never worked with Gamemaker, so I apologize if I've suggested something it doesn't allow you to do.

---

For your second question (again, haven't used Gamemaker, so forgive me if these are moot), a few things to check: \- Are x and y where you expect them to be? EG, is the bullet being created, just off screen? \- Are you sure press is getting called at all? EG, do you have to map it to a key?

If Gamemaker allows you to debug at all, adding a breakpoint on the first line would answer both of these questions (if it breaks, you know the code is being entered, and you can check the values of x and y).
> 1 votes

# Answer
According to the game maker studio documentation:

> speed has no direction associated it with it as this is governed by the direction value of the instance, but it can have a negative value, in which case the instance will travel in the opposite direction to that set by the direction function (ie: direction - 180°).

This means that most likely the direction rotated by 180 which is why the object keeps moving.

As for the object not spawning that is a separate question and should be posted as a new question. Please do not ask more than one question in a post.

Source: https://docs.yoyogames.com/
> 0 votes

---
Tags: game-maker
---


# Question
Title: Issue with variables in GameMaker Studio
I am having issues coding a game, in terms of variables in objects. Whgen running i get this error

```
FATAL ERROR in
action number 1
of  Step Event0
for object obj_text_demo_player:

Variable obj_gameManager.<unknown variable>(100020, -2147483648) not set before reading it.
at gml_Object_obj_text_demo_player_StepNormalEvent_1 (line 1) - if  (obj_gameManager.ammo == 0)

```

and i have no clue hope to fix this, this is where the code is used.

**obj\_player (player - where the issue seems to be - STEP EVENT)**

```
if (obj_gameManager.ammo == 0)
{
     obj_gameManager.weapon = "MachineGun";
    obj_gameManager.ammo = 50000;
};

```

**obj\_pickup (pickup object - COLLISION /W PLAYER OBJECT)**

```
obj_gameManager.weapon = "Tri-Shooter";
obj_gameManager.ammo = 900;

```

**Obj\_gameManager (object variables are from - DRAW EVENT)**

```
global.health = 100;
global.weapon = "MachineGun";
global.ammo = 50000;

draw_healthbar(787,181,1073,231,health,c_white,c_red,c_green,0,true,true);

draw_set_colour(c_blue);
draw_set_font(fnt_speach_new);
draw_text(780, 300, global.weapon );
draw_text(780, 375, global.ammo );

```

Any help would be massively appreciated, as I'm new to Game Maker Studio. If you need any more info I'm happy to add it.

# Answer
It seems to me that you didn't declare the variables in the Create event, since it says `<unknown variable>`. In the Create event of obj\_gamemanager you need to setup like

```
this.ammo = 0;

```

And do that every single variable that you have, otherwise they won't exist.
> 1 votes

# Answer
In global game settings click "set uninitialized variables to 0".

This isn't recommended all the time in programming practices to assume undefined variables have initialized values, but if that is what you wish to do then so be it.
> 0 votes

---
Tags: game-maker
---


# Question
Title: Workflow for creating spherical heightmaps
I'm wondering how I can create a spherical heightmap.

In my ideal workflow, you'd see a 3D sphere that you can edit using procedural terrain techniques (like World Creator) and that spherical terrain can be exported into six seamless images based on what layout you want your images to fold up into a cube in-game to create your planet.

Another option would be if you can at least tell the program you want specific images to tile with other images, such as the designated 'front, right, back, left' images tile with each other and the 'up, down' images seamlessly.

Specifically, I'm making planets for a game that wraps six images into a cube and 'inflates' them into a planetary terrain.

I've made a few basic heightmap sets in a program called Scape, and flipped them so at least four of the images mirror each other, then I edited the interior of those maps to all be different so the landscape isn't repetitive. However, manually editing the top and bottom maps is very daunting to get perfect, and I'm creating a dozen or more planets.

I'd like to know how to make 'front, right, back, left' images tile with 'up and down' images and I can edit the interiors of the images in a 3D program of choice. I've been directed to this site from search queries many times, but I'm a newbie to all things code so I have no clue how to use things such as the Diamond-Square method or any algorithms to achieve seamless textures (what program do you actually use, literally a python script you write in Notepad++ or something?).

# Answer
When solving this problem in the past, we used an out-of-the-box terrain sculpting tool like World Machine together with a custom terrain merging tool created by our technical artist (in C# I believe).

We used the stock sculpting tool to create highly detailed, non-tiling, flat terrains, roughly twice as long as they were wide. We'd make two such terrains for each planet: one representing the equatorial to tropical regions, and one representing a "cap" over each of the north & south poles.

After exporting the terrain maps (height, material info, etc), we'd load them into our custom-built tool. This would wrap the first map around the planet in latitude-longitude form (equirectangular mapping), and blend-out the seam. Then it would cross-fade to the cap maps at the poles.

The tool had a 3D preview pane so you could orbit around the planet and inspect the merged result before saving, and exposed sliders to control the rotation/scaling of each patch being blended and the sharpness of the blending between them.

This workflow successfully shipped 7 unique planets, though I'm still leery about the distortion we get from the particular map projections we chose. I kind of wanted to explore using the Peirce Quincuncial projection, which tiles through simple rotation.

> I have no clue how to use things such as the Diamond-Square method or any algorithms to achieve seamless textures

If you have questions about these algorithms, feel free to post those specific questions here and we can try to help you out. Just be sure you've searched for previous Q&A on the topic first so you're up to speed on what's already been covered. A couple off the top of my head:

> (what program do you actually use, literally a python script you write in Notepad++ or something?)

Usually custom procedural generation algorithms are implemented as part of the game's code if you need runtime procedural content (eg. Minecraft, roguelikes). If you only need procedural generation offline, as in the example above, it can sometimes pay to implement it as a standalone tool program written in the language of your choice, in the IDE or text editor you prefer working in. Since it doesn't need to run with the game, you can be a bit more loose with performance or other factors, and prioritize languages/UI frameworks that help you speed up development, even if they have performance costs.
> 1 votes

---
Tags: procedural-generation, terrain, heightmap, planet, workflow
---


# Question
Title: Button mapping of an Xbox 360 controller for windows
I can't get a clear answer on the rest of the internet. What are the joystick buttons for left and right triggers?

I'm on Windows, if it matters.

# Answer
* Go to "Devices and Printers" in the system settings (this is found at different places in different versions of Windows)
* Right-click on the gamepad and select "Game Controller Settings"
* Click "Properties"

Now press the buttons on the gamepad. You will see the icon with the corresponding number light up in the "testing" window. The same window can also be used to identify any axial inputs of the controller.
> -1 votes

# Answer
Below is a helpful image guide, provided by the Unify Community Wiki article on the Xbox 360 controller.

## Make sure you use Axis

The triggers are represented as axis, as opposed to buttons. This is because the triggers output a value based on *how far down* they have been pressed. A trigger can output a value of `0.5` if only half-way pressed, while a button can only interpret "on" or "off" - `0` or `1`.

For this reason, the triggers are referenced as "axis", and not as "buttons". Apart from the terminology difference, this means that you **must** set them up using `InputManager`, as opposed to having the additional option of calling them through `Input.GetKey(KeyCode)`.

### Using both triggers for a single axis

As you can see, the triggers are associated with "3rd axis". This means that if you set up an axis in your `InputManager` to use "3rd Axis (Joysticks and Scrollwheel)" for its `Axis` and set the `Type` to "Joystick Axis", the axis will output `1` when you hold the left trigger down, and output `-1` when you hold the right trigger down1.

### Using individual axis to represent each trigger

The previously mentioned Wiki page also points us in the direction of using individual axis to represent the two triggers. You could alternativley use the above setup with "9th Axis" to represent the left trigger, and "10th Axis" to represent the right trigger. Both axis will output `1` when you press the trigger down.

## Operating system *does* make a substantial difference

You mention using Windows, but in effort to make this answer more useful to other users, its worth mentioning that the controller references are unique to the *driver* being used. Given that Microsoft made both Windows and Xbox 360, it is not surprising that the controllers are "plug and play". However, you might find the need to download a specific driver for use on a Mac or Linux operating system. Below are two more additional image guides provided by the Unify Community Wiki detailing the changes on these alternate operating systems.

If you find yourself using either of these operating systems, I implore you to read more on the page, as there are slight differences in how they interpret the controller. For example, Mac OSX interprets triggers differently, and Linux interprets the D pad differently depending on whether your using a wireless controller or a wired controller.

### Mac OSX

### Linux

1 You would probably expect left to be +1 and right to be -1, but thats how it outputs to the debug when I tested the default axis setup.
> 7 votes

# Answer
The left and right tigers are not buttons, they are axis. You need to poll them regularly, probably once a frame, to see when they are moved/pressed. In Unity you needed to check when the axis hits whatever threshold you want it to be. You need to figure out what axis the triggers are in Unity and use Input.GetAxis()

https://docs.unity3d.com/ScriptReference/Input.GetAxis.html

It returns a float between 0 and 1, or -1 and 1. Figure out what value in that range works for you, and then trigger input off of that threshold.
> 0 votes

---
Tags: unity, controllers, joystick
---


# Question
Title: Name doesn't exist in current context in Unity
I'm currently making a collectible heart in unity, the kind that updates your health bar when you collide with it, and I made two scripts:

This one is called 'healthmonitor':

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

public class healthmonitor : MonoBehaviour {

public static int HealthValue;
public int InternalHealth;
public GameObject Heart1;
public GameObject Heart2;
public GameObject Heart3;

void Start () {
    HealthValue = 1;
}

void Update () {
    InternalHealth = HealthValue;

    if (HealthValue == 1) {
        Heart1.SetActive (true);
    }
    if (HealthValue == 2) {
        Heart2.SetActive (true);
    }
    if (HealthValue == 3) {
        Heart3.SetActive (true);
    }

}
}

```

This one is called 'hearstscript':

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

 public class heartscript : MonoBehaviour {

public int Rotatespeed;
public AudioSource CollectSound;
public GameObject thisheart;

void Update () {
    Rotatespeed =10;
    transform.Rotate(0, Rotatespeed, 0, Space.World);
}

void OnTriggerEnter () {
    CollectSound.Play ();
    HealthMonitor.HealthValue += 1;
    thisheart.SetActive (false);
}
}

```

Here is a picture of my UI:

I made an empty game object and named it HealthMonitor and applied the healthmonitor script to it. Here's a picture of the inspector panel:

The problem is that with heartscript I get the following error;

> Name "HealthMonitor" doesn't exist in current context.

I believe it relates to this line:

```
HealthMonitor.HealthValue += 1;

```

P.S. I am trying to refer to the empty game object, not the script.

# Answer
> 2 votes
Just like the error message says,

> Name "HealthMonitor" doesn't exist in current context.

ie. "You haven't told me anywhere in this script what the word `HealthMonitor` is supposed to mean"

If you want it to refer to the `healthmonitor` class, then you need to use the class's name exactly, all lowercase the way you've defined it.

But don't do that - making the `HealthValue` `static` is not a good solution to this problem, as it limits you to only ever having one instance of this health, and you'll have to refactor if you ever add multiplayer / NPCs with health / etc.

If you want it to refer to a particular instance of the `healthmonitor` script, (and get rid of the `static` on `HealthValue` so it lives on that instance), then you need to tell the compiler/runtime that's what you want.

First, by defining a member variable with the name you want to use, at the top of your `heartscript` class where the other public member variables are defined:

```
// This tells the compiler "I'm going to use the name HealthMonitor
// to refer to an instance of the healthmonitor script. And I want this
// variable to be public so I can set the instance in the inspector.
public healthmonitor HealthMonitor;

```

Then, you need to assign a reference to it. The easiest/most reliable & flexible way to do this is via the inspector. You can just drag the object containing the `healthmonitor` script from the hierarchy window into the `HealthMonitor` variable in the `heartscript` component's inspector. Or click the little circle next to the variable to select it from a list. Note that both instances need to exist inside the same scene or the same prefab for this to work as desired.

If you need to wire up the reference at runtime, you can do it like this if you have just one `healthmonitor` in your scene:

```
void Start() {
    HealthMonitor = FindObjectOfType<healthmonitor>();
}

```

As an aside, I'd recommend following Unity coding conventions where the names of types (like classes / structs) follow PascalCase (capitalize every word, including the first), and the names of member variables follow camelCase (capitalize every word after the first).

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


# Question
Title: How to resolve this problem with an object's collider?
In my game there is an **obj\_maze**:

The width of the maze is 10 pixels in all its extension.

In the game, the goal is to get the obj\_Cube through the maze.

**obj\_Cube**:

The obj\_Cube is wider than the maze on purpose, to get a pixel exceeding all sides as the object runs.

There are also obj\_Tubes. They are responsible for defining what position the obj\_Cube should go in the intersections that exist in the maze.

The obj\_Tubes also have an extra pixel to stand out from the maze.

I made this whole explanation, to make it easier to understand my problem.

When obj\_Cube collides with obj\_TubeX, its new direction will be defined by what you can imagine.

It turns out that this is done wrongly, detection happens early in the collision, as expected.

Stirring in the bounding box, I was able to correct the problem.

By doing this I get the obj\_Cube go right or left correctly.

Now and when the obj\_Cube does not come from below, but from the right or from the left? This collision certainly did not happen properly.

Here is an example of the obj\_Cube from the right, with the bounding box I used earlier:

The collision is neither detected.

Believe me, I've tested numerous bounding box possibilities for both obj\_TubeX and obj\_Cube, so that all cases are resolved, but it's physically impossible.

(At least the way I'm trying)...

I also thought about having three equal sprites from each tube with different bounding boxes, but that would be extremely harder and coarser, making my game weigh a lot more.

Sorry for the bad English, I'm not English speaker. I had to use google translator to translate everything.

**Thank you in advance!!!**

# Answer
The solution I found to this problem was as follows:

Starting with **obj\_TubeX** =\> I've changed your collision box:

I also modified the obj\_Cube collision box (I passed the collision box to the bottom of obj\_Cube.):

In order for the collision to happen correctly, whatever direction the obj\_Cube comes from, just modify the obj\_Cube rotation before it collides with the obj\_TubeX. See below:

You can change the rotation of obj\_Cube by adding an object that makes this change in rotation in the path between obj\_Cube and obj\_TubeX.
> 1 votes

# Answer
There is a much cleaner solution. Instead of editing bounding boxes, you can detect a collision with the tube and wait before it turns.

At 1, the box sets a timer for x frames. At 2, the timer runs out and the box turns.
> 1 votes

# Answer
In the collision event add the following code as a wrapper for the turning code:

`if (box.x == other.x && box.y == other.y)//other is the tube being collided against
{
 //insert turning code here
}`

Adjust offsets accordingly.

Basically your issue is that you wanted collision to be a replacement for detecting position, and that will only be the case when you make the collision for both exactly one pixel. You could do that, but I wouldn't recommend it.
> 1 votes

---
Tags: collision-detection, game-maker
---


title: pyglet how to disable image smoothing?

text:
# Question
Title: pyglet how to disable image smoothing?
I'm using sprites made up of very few pixels. When scaling the sprite gets blurry, so how do I disable this smoothing? I couldn't find anything in the docs or elsewhere online

Sprite:

In pyglet, scaled 8:

# Answer
Found a solution at Scaling window contents in Pyglet?

```
from pyglet.gl import *

```

then add

```
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)

```

to on\_draw()
> 1 votes

---
Tags: pyglet
---


# Question
Title: Game development with Unity option is Unavailable
When I am trying to download"Game development with Unity" from the visual studio 2017 the option says it's"Unavailable".. How to download this? So question is : Ques. : How to select the option which says "Unavailable" in the "visual studio installer"?

# Answer
> 1 votes
I'm sorry but I don't know how to help you in downloading Unity from Visual Studio 2017. But I have another idea:

Why download Unity from Visual Studio 2017? You don't need it, you can download it from the Unity page, it's very simple. Even more, if you download it from Visual Studio you might download an older version of Unity (I have understood that Visual Studio takes some time to update it).

If you only want to download a single version of Unity you can do it from this link. If you instead plant to have several Unity versions (for compatibility with older projects) you can download the Unity HUB (a program which "manages" your Unity versions) from the same link, in the `Unity HUB` button.

In order to use Visual Studio 2017 to edit your Unity Script simply go to `Unity preferences` \> `External tools` \> `External script editor` and choose `Visual Studio`. Easy, right? The same instructions can be found in Unity documentation.

I know this answer isn't exactly an answer to your question, but I hope it helps. If you aren't agree with this post, I will delete it.

---
Tags: unity, visual-studio
---


# Question
Title: How to get depth of vertex in 0 - 1 range
I want to get the depth of vertex in 0 to 1 range(like it done in the shader) and I do it like this

```
    D3DXVec3TransformCoord(&vertex, &vertex, &wvp);

depth = vertex.z;

```

It works(sometimes wrong) but when I write This

```
    if (depth > 1.0f || depth < 0.0f)return false;

```

Sometimes it returns false. How can I get correct depth for vertex in 0 to 1 range??

I want to compare two vertexes and select the nearest

EDIT

```
    wvp = worldmatrix*viewmatrix*projectionmatrix;

```

It works wrong when I zoom in

# Answer
> 1 votes
You are missing the normalization step, which requires a **W component**.

Hence, you should be calling D3DXVec4Transform and not D3DXVec3TransformCoord.

You need to feed this your vertex, with the last component (W) set to a 1.0 value.

The output vertex will have W set in the last component, and you need to divide by that:

```
v_in[3] = 1.0;

D3DXVec4Transform
(
    &v_out,
    &v_in,
    &wvp
);

v_out[0] = v_out[0] / v_out[3];
v_out[1] = v_out[1] / v_out[3];
v_out[2] = v_out[2] / v_out[3];

```

Now you can use `v_out[2]` as the depth value, but beware: **it ranges from -1 to 1**, and not from 0 to 1 as you assumed.

# Answer
> 0 votes
Matrix multiplication is not commutative. You need to do `projection * view * model`

---
Tags: directx, depth
---


# Question
Title: How do I play a particle system when moving?
I have a car that I move with a Physics-based movement (`AddForce()`, `AddTorque()`, etc...) and I have a simple particle system attached behind the car as follows:

I'd like to play this ParticleSystem whenever the car moves; I tried checking if the car's rigidbody's velocity was greater than 0:

```
if(m_Rigidbody.velocity.z > 0)
   m_ParticleSystem.Play();

if(m_Rigidbody.velocity.z == 0 && m_ParticleSystem.isPlaying) // velocity.z == 0 is unreliable, verified with Debug.Log
   m_ParticleSystem.Stop();

```

I then tried using Input:

```
if(Input.GetAxis("Vertical") > 0) // the car is moving along the positive z axis
    m_ParticleSystem.Play();
if(Input.GetAxis("Vertical") == 0 && m_ParticleSystem.isPlaying)
    m_ParticleSystem.Stop();

```

These two methods don't work, I'm probably making assumptions on how `Rigidbody.velocity` behaves (when you stop the car for example, it becomes negative, so the particle system would keep playing until it reaches 0);

# Answer
> 0 votes
Using a range and selectively stopping emission seemed to work fine in my tests:

```
if (Input.GetAxis("Vertical") > 0.1f) {
    if (!particles.isEmitting)
        particles.Play();
} else if(particles.isEmitting) {
    particles.Stop(true, ParticleSystemStopBehavior.StopEmitting);
}

```

---
Tags: unity
---


# Question
Title: Shadow artifacts/acne on block intersections
This is using the default shader and depth shader from LibGdx. It creates lines at the blocks intersections.

This is what I use to create the blocks models for now:

```
private Model createModel(Color color) {
    Model model = modelBuilder.createBox(
            cellSize, cellSize, cellSize,
            new Material(ColorAttribute.createDiffuse(color)),
            Usage.Position | Usage.Normal);
    return model;
}
...
for(int x = 0; x < data.models.length; x++) {
    for(int y = 0; y < data.models[x].length; y++) {
        int z = data.getElevation(x, y);
        ModelInstance instance = new ModelInstance(model);
        instance.transform.setTranslation(new Vector3(cellSize * x + cellSize/2, cellSize * y + cellSize/2, z * cellSize - cellSize/2));
        getWorld().addToCache(instance);
    }
}

```

This sets the environment lights:

```
getEnvironment().set(new ColorAttribute(ColorAttribute.AmbientLight, getAmbiantBrightness(), getAmbiantBrightness(), getAmbiantBrightness() , 1f));
getEnvironment().set(new ColorAttribute(ColorAttribute.Specular, getAmbiantBrightness(), getAmbiantBrightness(), getAmbiantBrightness() , 1f));
getEnvironment().add((shadowLight = new DirectionalShadowLight(1024*4, 1024*4, 600f, 600f, 0.1f, 100f)).set(db, db, db, dx, dy, dz));
getEnvironment().shadowMap = shadowLight;

```

This is how I render:

```
@Override
public void render(float delta) {
    getWorld().buildCache();
    clearScreen();
    renderShadows(delta);
    controls.update(delta);
    renderWorld(delta);
    renderHud(delta);
}
public void clearScreen() {
    Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
    Gdx.gl.glClearColor(getBGColor().r, getBGColor().g, getBGColor().b, getBGColor().a);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
}

protected void renderShadows(float delta) {
    shadowLight.begin(Vector3.Zero, getCam().direction);
    shadowBatch.begin(shadowLight.getCamera());
    shadowBatch.render(world.cache, env);
    getWorld().tempModels.forEach(m -> shadowBatch.render(m, env));
    shadowBatch.end();
    shadowLight.end();
}

protected void renderWorld(float delta) {
    getBatch().begin(getCam());
    // render the cached models
    getBatch().render(getWorld().cache, getEnvironment());
    // render the temp models
    getWorld().tempModels.forEach(m -> getBatch().render(m, getEnvironment()));
    getBatch().end();
}

```

I tried to copy the default fragment and vertex shader and edit the PCFoffset with random values, but the result wasn't better.

```
float getShadow()
{

    float pcfOffset = 0.0f;
    return (//getShadowness(vec2(0,0)) +
            getShadowness(vec2(pcfOffset, pcfOffset)) +
            getShadowness(vec2(-pcfOffset, pcfOffset)) +
            getShadowness(vec2(pcfOffset, -pcfOffset)) +
            getShadowness(vec2(-pcfOffset, -pcfOffset))) * 0.25;
}

```

Should I code the lights/shadows myself using Lwjgl instead of using LibGdx defaults? Seems like a lot of work for something I expected to be included.

# Answer
> 1 votes
Ok, there is a simple fix to shadow acne that I found here https://lwjglgamedev.gitbooks.io/3d-game-development-with-lwjgl/content/chapter18/chapter18.html

```
float bias = 0.05;
if ( projCoords.z - bias < texture(shadowMap, projCoords.xy).r )
{
    // Current fragment is not in shade
    shadowFactor = 0;
}

```

And I found how to apply it to LibGdx's default fragment shader :

```
float getShadowness(vec2 offset)
{
    const vec4 bitShifts = vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0);

    // EDIT
    float bias = 0.0005f;

    return step(v_shadowMapUv.z - bias, dot(texture2D(u_shadowTexture, v_shadowMapUv.xy + offset), bitShifts));//+(1.0/255.0));
}

```

This gets rid of the shadow acne very cleanly.

Unfortunately, I still have some problems with white/black lines showing on intersections because, as I just realized, the wrong vertex gets rendered on top of the other. I.e. if I look in the same direction as the directional light, I get white lines and if I look in the opposite direction (towards the light source), I get black lines. Perhaps I can fix this with a noise filter.

Edit :

Final solution : I found out that the seams indeed came from the unculled side faces of the blocks which can ocasionnaly render on top of the "top" faces of the blocks. The problem is hard to explain by text, but the solution is simple. I found out about greedy meshing, which merges all possible quads. Here are the resources I used :

I ended up not using Robert O'Leary's implementation as I had problems with winding/indexing with it. So I implemented Mikola Lysenko's code in java myself which also gave me a better understanding of the algorithm and let me arrive to this result. Extremely clean mesh which produces no seams :

The only problem with Mikola Lysenko's original code is that it doesn't include the actual quad mesh generation and vertex winding. So one has to add backface management by himself to know if a face's normal must be positive or negative, and adjust the winding accordingly.

---
Tags: java, libgdx, glsl, shadows, shadow-mapping
---


title: How to build a better game save?

text:
# Question
Title: How to build a better game save?
I am making a roguelike card game like dream quest, and I want to improve my dungeon/level save method.

Here's what my levels look like:

I checked dream quest saves but I don't like their method because it uses a simple text file for all the information. it's also really messy, repetitive and not extendable.

I used the format below for the first couple of months:

```
[
  [
    "Wall",
    "Wall",
    "Room",
    "Room",
    "Room",
    "Merchant",
    "Room",
    "Room",
    "Wall",
    "Wall",
  ],
  [
    "Wall",
    "Wall",
    ...
  ]
]

```

But at the time I did not have multiple enemies, merchants, items. I simply read the file by using an enum which matched the strings used in the save format (item, enemy, merchant etc.) then passed them into an array to create the board.

As I started to create different kinds of enemies, items, and merchants, my current game wouldn't support this. I don't want to create an enum like `enemy1, enemy2, enemy3 ...`

How can I improve the scalability & legibility of this save game format, so I don't have to keep adding new enum categories for each variety of content?

# Answer
Your game save is already in JSON form, as a two dimensional array, but it is the most verbose possible way of representing the data. Some notes:

* You are looking to make your format more concise, which means trying to make the data more readable / parseable by omitting data and restructuring. To do that you need to consider frequency of the values in your data.
* If one value is by far more common than others (e.g. wall or empty space, most likely), then restructure the format to make that value implicit. I.e. "if not specified, the value for the cell is empty space."
* Consider splitting out the data into parts that don't change (e.g. rooms and walls) and parts that do (e.g. items, enemies and merchants) into separate sections in your save format. This is especially important when you come need to store two values in the same cell (e.g. what type of room cell it is, plus the item present in that cell.)
* 2D grid data is often easily stored as an image/bitmap (where the colour of the pixel maps to a particular cell value). However this is not particularly extensible or readable for storing dynamic data like where the enemies are stored. Nothing stops you from using both methods (image for walls/rooms, JSON for spawnable entities.)
* If you have "sparse" entities, do not attempt to store them in a 2D array of values, instead store them as dictionaries which contain a co-ordinate plus any additional information about the item (e.g. `{ x: 2, y, 5, type: "sword"}`
* Even if you store entities in the 2D array, you can take advantage of JSON type flexibility and store *either* a simple cell value or a dictionary. E.g.:

```
[
  [
    "Wall",
    "Room",
    { type: "enemy", id: "enemy1", health: 50 },
    "Room",
    "Wall"
  ],
  [
    "Wall",
    "Room",
    "Room",
    { type: "item", id: "sword1", wear: 80 },
    "Wall"
  ]
]

```
* Then at load time you check the cell, if it is a string interpret it as a simple cell type, and if it is a dictionary interpret it by looking at the contents of the dictionary.
* Finally, as has been pointed out in other answers, don't store anything you can easily recreate; if using randomness to general levels, use a fixed seed and store only that seed, making sure that your level generation is predictable and repeatable. If your seed is used to generate initial positions and IDs for enemies, only do that process on the initial generation, on subsequent loads simply discard that information from the generation process and load the information on dynamic entities from your save state.
> 3 votes

# Answer
I would suggest using JSON.

Basically everything you create is either an object `{}`, an array `[]` or a data type (string, integer, float etc).

Here is an example of how you can implement this. **Please note**, I've used a `#` to represent a comment, so it is easier to understand what every symbol means, JSON does **not** support comments.

```
{ # an object representing a stage

    "name": "The name of my stage",

    # these are the tiles of your map. For the sake of this example, 0's represent a wall, and 1's represent empty (walkable) space.
    "map": [ 0, 1, 0, 0,
             0, 1, 1, 0,
             0, 0, 1, 0,
             0, 0, 1, 0],

    "enemies": [ # enemies is an array, so if you want to add a new enemy, just put a comma

        { # enemies[0]
            "positionX": 0,
            "positionY": 0,
            "positionZ": 0
        },

        { # enemies[1]
            "positionX": 0,
            "positionY": 0,
            "positionZ": 0
        }

    ]

    # here you can add more information about your stage

}

```

The last question is, how do you parse that the easy way? That's hard to answer without knowing what language you are working on, but there are plenty of JSON parsing libraries for most languages out there. The only reason I recommend it, is that its easy, simple, and scalable.

Depending on the languages, you can have a variable `stage` that saved the parsed data, and do something like `stage.enemies[0]` to access the first enemy, `stage.enemies[1]` for the second enemy etc. This way you can also iterate through the whole array, so as you keep adding new enemies, you won't have to edit your code.
> 1 votes

# Answer
Don't save the world you are procedurally generating.

Instead, save the random seed, then regenerate it.

That way, you only need to save the dynamic positions, such as the players and NPCs.

EDIT: Based on your comments, I suggest you read https://stats.stackexchange.com/q/354373/106928 and/or https://en.m.wikipedia.org/wiki/Random\_seed to learn what is a random seed.
> 0 votes

---
Tags: procedural-generation, software-engineering, design-patterns, level-design, savegame
---


# Question
Title: Why is drawing good lines in Unity so hard?
With the new Renderer Pipelines, the OnPostRender-callback is gone, which means GL.Lines is gone.

LineRenderer looks terrible (aliases really badly, and scales with distance from camera).

How do I draw UI lines (similar to the editor "grid", solid color, preferably with controllable width)?

# Answer
> 1 votes
GL.Lines are not gone, if using the Scriptable Render Pipeline you can use your GL methods in this event: RenderPipeline.beginCameraRender

```
void Start(){
  RenderPipeline.beginCameraRendering = OnPostProcess(yourCamera);
}

void OnPostProcess(Camera camera){
  OnLineRender(Material mat, Vector3 startPos, Vector3 endPos, Color color);
}

public void OnLineRender(Material mat, Vector3 startPos, Vector3 endPos, Color color)
{
   RenderPipeline.beginCameraRendering = OnPostProcess(yourCamera)
   GL.PushMatrix();
   GL.LoadProjectionMatrix(Camera.main.projectionMatrix);
   GL.modelview = Camera.main.worldToCameraMatrix;

   mat.SetPass(0);

   GL.Begin(GL.LINES);
   GL.Color(color);
   GL.Vertex3(startPos.x, startPos.y, startPos.z);
   GL.Vertex3(endPos.x, endPos.y, endPos.z);
   GL.End();

   GL.PopMatrix();
}

```

---
Tags: unity
---


# Question
Title: How to randomly rotate a D20 Dice in Unity?
I'm working on a Dice Application in Unity that involves randomly rotating a dice model on instantiation and then dropping it. But in order for this application to be useful I need to guarantee that the Dice Roll is close enough to random to be used for a live tabletop game. The problem I'm getting is that after some testing the dice rolls are not random at all.

Here's some pictures of a a D20 I'm working with as it looks at instantiation.

Bottom view:

Top view:

Side view 1:

Side view 2:

Side view 3:

My first attempt at randomizing the dice rolls was to use this code:

```
m_Instance.transform.Rotate(UnityEngine.Random.Range(0.0f, 360.0f), UnityEngine.Random.Range(0.0f, 360.0f), UnityEngine.Random.Range(0.0f, 360.0f));

```

But after 250,000 test rolls, the data shows that it's almost twice as likely to land on a side face than it is the top or bottom faces

After doing some digging, I found a recommendation to use this code instead:

```
m_Instance.transform.rotation = Quaternion.Euler(UnityEngine.Random.Range(0.0f, 360.0f), UnityEngine.Random.Range(0.0f, 360.0f), UnityEngine.Random.Range(0.0f, 360.0f));

```

Which gave me the exact opposite results, where faces on the top and bottom of the dice were suddenly twice as likely as those on the sides.

So my mad-scientist approach to this problem currently is to randomly pick between the two rotation methods. So that way it's randomly decided if one face will be twice as likely as another.

```
int randomRange = UnityEngine.Random.Range(0, 2);
    if (randomRange == 1)
    {
        m_Instance.transform.Rotate(UnityEngine.Random.Range(0.0f, 360.0f), UnityEngine.Random.Range(0.0f, 360.0f), UnityEngine.Random.Range(0.0f, 360.0f));
    }
    else
    {
        m_Instance.transform.rotation = Quaternion.Euler(UnityEngine.Random.Range(0.0f, 360.0f), UnityEngine.Random.Range(0.0f, 360.0f), UnityEngine.Random.Range(0.0f, 360.0f));
    }

```

Which is getting me close, but not quite perfect.

But it's not quite close enough for my liking as some faces like 10 seem favored by both methods. So my question is: is there something wrong with my code that's making the rolls not as random as I'm imagining? And if not, is there a way of rotating a dice in Unity such that the result of the rotation is suitably random enough to be used in a potentially professional setting?

EDIT: Thanks for the response DMGregory! That's definitely looking better, but I'm still seeing that 10 and 11 are favored sides after a million test rolls. with both getting a \> '5.8' percent chance of landing there. Perhaps there's something wrong with my implementation of your code?

```
public void RandomizeDice()
{
    m_Instance.transform.rotation = UniformRandomRotation();
}

Quaternion UniformRandomRotation()
{
    float x0 = UnityEngine.Random.value;
    float theta1 = UnityEngine.Random.Range(0f, Mathf.PI * 2f);
    float theta2 = UnityEngine.Random.Range(0f, Mathf.PI * 2f);
    // Make this theta2 in the range (0, PI * 1) if you want w > 0

    float r1 = Mathf.Sqrt(1f - x0);
    float r2 = Mathf.Sqrt(x0);

    return new Quaternion(
        Mathf.Cos(theta2) * r2,
        Mathf.Sin(theta1) * r1,
        Mathf.Cos(theta1) * r1,
        Mathf.Sin(theta2) * r2);
}

public void UnRandomizeDice()
{
    m_Instance.transform.rotation = Quaternion.Euler(270, 270, 270);
}

```

# Answer
I recommend developing a healthy distrust of Euler angles. ;)

They're great for *printing* a particular rotation in a reasonably human-readable way. They're terrible for *computing* arbitrary rotations in a controlled way. Their parameters are not globally orthogonal, and as you've discovered, they don't uniformly cover the space of all rotations.

For any kind of computed rotation, you'll almost always have an easier time working in quaternions (though an argument an be made for yaw-pitch for camera rotatations where you only want a small,controlled slice of the space of all rotations)

Unfortunately Unity's built-in quaternion method `Random.rotation` is not uniform (something I'd never spotted before trying to roll dice with it, so thank you for this illuminating test case!), but we can make our own with its helper methods, or a little math.

For something quick and dirty, we can use:

```
 transform.rotation = Quaternion.LookRotation(Random.onUnitSphere, Random.onUnitSphere);

```

This forms a rotation that points the local z axis somewhere randomly in 3 dimensional space, and twists the local y axis randomly about that axis.

If you want to do the math yourself, we can sample a uniform random quaternion using the technique presented by Ken Shoemake in the Graphical Gems III chapter Uniform Random Rotations:

```
Quaternion UniformRandomRotation() {
    float x0 = Random.value;
    float theta1 = Random.Range(0f, Mathf.PI * 2f);
    float theta2 = Random.Range(0f, Mathf.PI * 2f);
    // Make this theta2 in the range (0, PI * 1) if you want w > 0

    float r1 = Mathf.Sqrt(1f - x0);
    float r2 = Mathf.Sqrt(x0);

    return new Quaternion(
        Mathf.Cos(theta2) * r2,
        Mathf.Sin(theta1) * r1,
        Mathf.Cos(theta1) * r1,
        Mathf.Sin(theta2) * r2);
}

```

I get the expected 5% probability for all 20 sides, plus or minus about 0.015% and falling as the trial count climbs.
> 4 votes

# Answer
## Short answer

As of Unity version 2017.1 (maybe earlier), use Random.rotationUniform instead, as it is designed to provide a more uniform distribution.

## Use-case answer

You don't have to perfectly simulate real, physical dice, so you are free to separate the dramatic player-feel from the mundane random-calculation.

I'd suggest running a dice-rolling animation, maybe with randomized parameters for spin time, travel distance, and number of bounces. Store the correct rotations to display each outcome/face, then calculate the result based on plain-old Random.Range. Set the final rotation to display the appropriate face, possibly using an Animation Event as a trigger.

Juice it up with some cool sound effects (different sounds for different surface & dice-material combos?), and *maybe* some subtle camera shake, and there you go.
> 1 votes

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


title: unity emission map bleeds (bug?)

text:
# Question
Title: unity emission map bleeds (bug?)
I have a material with a spritesheet texture (albedo) and an emission map. The spritesheet has 32x32 squares. The emission has a 32x32 square that is an emission for the magma-looking square.

It works well on the magma, however, the glow also spreads to the sand, grass, planks, and snow\_grass textures. You can clearly see it spread on the sand (bottom-rightmost opaque texture) in the right because it isn't directly touching the magma. Here is another picture where it is attached

You can still see the spreading of glow if you look closely. Now, you can definitely see it glow here

How do you stop that from happening? That artifact is really weird and i really need it to go away. I've tried decreasing the size of the square in the emission map but it still was there. Please help.

Thanks.

**EDIT 1** Here is how I apply uv

\` public static Dictionary textureMap = new Dictionary();

```
public static void Initialize(string texturePath, Texture texture)
{
    Sprite[] sprites = Resources.LoadAll<Sprite>(texturePath);

    foreach (Sprite s in sprites)
    {
        Vector2[] uvs = new Vector2[4];
        uvs[0] = new Vector2(s.rect.xMin / texture.width, s.rect.yMin / texture.height);
        uvs[1] = new Vector2(s.rect.xMax / texture.width, s.rect.yMin / texture.height);
        uvs[2] = new Vector2(s.rect.xMin / texture.width, s.rect.yMax / texture.height);
        uvs[3] = new Vector2(s.rect.xMax / texture.width, s.rect.yMax / texture.height);
        //Debug.Log(s.name);

        if (!textureMap.ContainsKey(s.name))
        {
            textureMap.Add(s.name, uvs);
        }
    }

}

public static bool AddTextures (Block block, Direction direction, int index, Vector2[] uvs)
{
    string key = FastGetKey(block, direction);

    Vector2[] text;
    if (textureMap.TryGetValue(key, out text))
    {
        //Debug.Log(key);
        uvs[index] = text[0];
        uvs[index + 1] = text[1];
        uvs[index + 2] = text[2];
        uvs[index + 3] = text[3];
        return true;

    }

    text = textureMap["Default"];

    uvs[index] = text[0];
    uvs[index + 1] = text[1];
    uvs[index + 2] = text[2];
    uvs[index + 3] = text[3];

    return false;
}

```

\`

Where Direction is a direction (example north) and Block is a short. Index is the vertex index of the mesh. Texture is the sprite texture (.png)

# Answer
So I figured out a solution. (I "disobeyed" DMGregory) If ever you have an emission map that can become a power-of-two image due to transparency, you need to check if unity made it one. Check it under Advanced \> None Power of 2. Set it to none. I did this to mine and it worked. Also just change it to point filter.
> 1 votes

---
Tags: unity, spritesheet, bug, glow
---


# Question
Title: Any advantage of having chunks with sizes by the power of two?
With my past experience of having my little game lag because of the size of the world, I have decided that in whatever next project I might choose to create, I will split said world into chunks. Now here comes my question : *Should the chunk's width, height and depth be a power of two?*

For example, in a little game called *Minecraft*, chunks have a height of 256 and width,depth of 16. Both numbers a power of two. Is there any advantage over having the chunk simply be 100x100x100?

Minecraft was written in Java, but I'm working in Lua. Just pointing that out in case it has any relevance.

# Answer
> 3 votes
The main advantage of power-of-two sizes is that division by a power of 2 (on an integer) is just a bit shift, and modding is just a mask. Both of these operations are blazingly fast to do on gobs of numbers, while division by an arbitrary value can be substantially slower.

So if I want to quickly find which cell of which chunk a particular point is in, I can write something like this for each axis:

```
rounded = RoundToInt(axisValue);

cell = rounded & 0xFF;
chunk = rounded >> 8;

```

If you're using image tiles for each chunk anywhere (like hightmap / splatmap / biome encoding...), GPUs also like to work with power-of-two-sized images, and this might let you use built-in mipmapping hardware for diminishing the level of detail in the distance, without extra padding/adjustments.

In some cases you might also get better alignment of your data in memory to 32-byte / page boundaries when using power-of-two sized chunks, but this is likely to be a much more minor effect.

# Answer
> 1 votes
What I think the primary reason why tile based games like power of 2 is due to the fact that they store world data in octrees and quadtrees.

Using a 2D example, spatial partitioning techniques such as quadtrees will allow for highly optimized collision and raytracing checks. Quadtrees essentially divide each chunk into 4 equal quadrant each time, and items that lie entirely in each quadrant is guaranteed to not be able to collide with items in other quadrants at all, thus significantly cutting down on the amount of collision checks you need to perform.

Octrees are an extension of the 2D example in 3D space, except that each cube is divided into 8 parts.

---
Tags: lua, memory-efficiency, memory
---