# Question
Title: Matrix transformations vs manipulating vertex data directly
I was wondering whats more efficient to do if you want to transform a mesh.
1) Transforming a matrix and pass that to a shader or
2) Manipulate the meshs vertex data directly

I was wondering because LibGDX is using the second option to transform sprites. And calculating the translation, rotation and scaling for every mesh every frame seems a bit too much, since you have to change the vertex data every frame too.

# Answer
> 2 votes
It's usually faster to use matrices and keep the vertices the same for multiple reasons:

* The GPU makes optimizations based on the fact, that the vertices don't change. There are ways to make OpenGL expect changes in the vertex list (like using GL\_DYNAMIC\_DRAW), but these methods are still slow.
* You usually don't need to update every matrix every frame, but if any one of them changes, you'd need to update the vertices. For example the projection matrix hardly changes if at all.
* The CPU is good at doing complex stuff, but slowly (relatively) and the GPU is good at doing basic stuff, but fast. This means, that the GPU is very fast at matrix multiplications.
* Calculating matrices is very fast. it's mostly just setting some values to constant or easily calculateable values. The most complex is the rotational matrix, and it only requires calculating the cosinus and sinus of 3 angles.
* Even if every matrix has to get updated, you only need to load 48 values to the GPU. This could only be faster, if you only need to update less than 16 vertices.

---
Tags: opengl, libgdx, matrix, vertex
---


# Question
Title: Löve2d: How can i select object with mouse if it's overlap?
I have already some code but i can't solved this. How can i select one object with mouse if the objects are overlap? It's looks like solitaire game. I wish you can understand me...

For example my code;

```
function love.load()

    love.graphics.setBackgroundColor(245, 255, 255)
    --1
    carda = {}
    carda.x       = 110
    carda.y       = 5
    carda.width   = 100
    carda.height  = 150
    carda.dragged = false
    carda.dropped = false
    --3
    cardb = {}
    cardb.x       = 110
    cardb.y       = 20
    cardb.width   = 100
    cardb.height  = 150
    cardb.dragged = false
    cardb.dropped = false
end
function love.draw()
    love.graphics.setColor(255, 255, 255)
    love.graphics.rectangle("fill", carda.x, carda.y, carda.width, carda.height)
    love.graphics.setColor(255, 128, 128)
    love.graphics.rectangle("line", carda.x, carda.y, carda.width, carda.height)
    love.graphics.setColor(0, 0, 100)
    love.graphics.print("Card\nA", carda.x + 5, carda.y + 5)
    --2
    love.graphics.setColor(215, 255, 225)
    love.graphics.rectangle("fill", cardb.x, cardb.y, cardb.width, cardb.height)
    love.graphics.setColor(255, 128, 128)
    love.graphics.rectangle("line", cardb.x, cardb.y, cardb.width, cardb.height)
    love.graphics.setColor(0, 0, 100)
    love.graphics.print("Card\nB", cardb.x + 5, cardb.y + 5)
end
function love.keypressed(key)
    if key=="escape" then
        love.event.quit()
    end
end
function love.mousepressed(x, y, button)
    if button == 1 and x >= carda.x and x <= carda.x + carda.width and y >= carda.y and y <= carda.y + carda.height then
        carda.dragged = true
    end
    --2
    if button == 1 and x >= cardb.x and x <= cardb.x + cardb.width and y >= cardb.y and y <= cardb.y + cardb.height then
        cardb.dragged = true
    end
end
function love.mousemoved(x, y, dx, dy)
    if carda.dragged then
        carda.x = carda.x + dx
        carda.y = carda.y + dy
    end
    --2
    if cardb.dragged then
        cardb.x = cardb.x + dx
        cardb.y = cardb.y + dy
    end
end
function love.mousereleased(x, y)
    carda.dragged = false
    --2
    cardb.dragged = false
end

```

# Answer
If I understand your question correctly, you are asking when the two cards are on top of eachother how do you decide which gets grabbed? I guess you would chose whichever one is on top visually right? So in your draw function look which one is drawn last. I believe that one should be on top. If that is carda for example: set up your if statements as if else instead of seperate statements with carda first. Like this:

```
if button == 1 and x >= carda.x and x <= carda.x + carda.width and y >= carda.y and y <= carda.y + carda.height then
    carda.dragged = true
else if button == 1 and x >= cardb.x and x <= cardb.x + cardb.width and y >= cardb.y and y <= cardb.y + cardb.height then
    cardb.dragged = true
end

```

make sure in your draw function that carda is being drawn after cardb
> 1 votes

---
Tags: lua, love2d
---


title: Managing complicated RPG character data

text:
# Question
Title: Managing complicated RPG character data
For a detailed survival RPG, the data that needs to be managed can easily become overwhelming if approached in an ad hoc manner.

First, you may want to do away with HP and instead have a system of wounds, where various body parts can be specifically injured and each injury requires individual attention. Attacks can be targeted and the effect of an injury depends on its location and how well it is treated.

The next obvious step is to manage clothing so that each piece of clothing covers particular body parts and provides particular armor values to each part. We also need to keep track of clothing conflicts, where two pieces of clothing try to cover the same area and so they can't be worn together, except when they are designed to be worn under or over other clothing.

In addition, there could be magical effects on certain body parts, or perhaps claws or spikes could be added. Perhaps various limbs could be replaced by cyborg parts, or magical parts. Even worse, perhaps there are creatures alternate body plans with more or fewer than the usual limbs.

Each limb can be divided into parts, so for example a leg consists of a thigh, a knee, a lower leg, and a foot. We want to manage those parts individually, but we also want to remember that together they represent a leg. We might need this so that targeted attacks aren't forced to be overly specific and we can provide players with notifications that doesn't give excessive detail.

For example, in the game "Slaves to Armok" you can sometimes get messages about some particular toe, finger, or ear being hit. This is clearly too much detail for the middle of battle. We wouldn't want be forced to give that sort of detail because we're not storing the fact that these detailed parts add up to a greater whole. At the same time, a strict hierarchy of parts wouldn't be right, because two arms together make up "the arms" of a character, yet each arm individually is part of either the "the left side" or "the right side" of the character, and we'd want to keep track of these relationships so we can provide appropriate messages to the player.

We'd also want all this data to be stored sparsely. For example, if you're facing twenty goblins, there's no point in individually storing every limb and detail for each goblin when they are all identical. We want to store a prototypical goblin in one place, then each individual goblin can be represented only by how it differs from the prototype. Further, the prototype goblin could be represented by how it differs from the prototype human. This is not just to save memory, but also to allow the game to know what makes each character special so it can give the player relevant messages. The game could mention "the goblin with the head wound" or "the goblin with the spiked glove" because that's exactly how those goblins are represented in memory.

Obviously one shouldn't jump blindly into designing such a game, solving each problem as it arises. This level of complicated data needs a database-style system to keep all the details organized, yet a simple relational database doesn't provide an obvious solution. Could something like an Entity System be the right approach?

Is there a known strategy for managing this sort of data that experienced game developers would always use for making this sort of game?

# Answer
This is not a complete answer since as others here have noted, this question is rather broad. But I just wanted to give you some pointers.

`body parts` / `clothing` / enhancements

This is the core of your system. I think what you want here is a nice hierarchical message dispatch system that tells "owning" parts that a subpart is damaged, e.g. maybe you cannot raise a hammer if one or more fingers are broken. This also allows dispatch from finger up through hand through arm through shoulder to main body. The main body can dispatch to larger game controllers to say, "look, this guy can't attack (because he has a broken finger)". You can also shut down any actions on the subparts by deactivating the larger part, so if actor's arm is in a sling, they're probably not going to be using any fingers anyway. I strongly recommend you implement *hierarchies of control*.

The clothing exclusion system is really just one of breaking the down the body into all areas e.g. arm, leg but also including boundary areas e.g. cuff, waist, collar, and ensuring on any attempt to don new gear, that none of these are conflicting. Bitflags/bitfields/bitmasks would be a fast way to check what's wearable, in one(?) op.

Grouping right and left arm into "arms" is a just a layer you write over the top of all this.

`We'd also want all this data to be stored sparsely.`

The best you can do then is have one instance of each, and ref these using pointers, which tend to be either 32- or 64-bit (4-8 bytes) depending on platform. Actually, you can do slightly better: You can set up an 8- or 16-bit keyed array (256 or 16384 elements) which you then key into with an `unsigned byte` or a `unsigned short`. This keeps your index size down, allowing you to store more indices per CPU word. You will probably also want all the originals to be contiguous in memory.

See also composition of singleton objects that act as prototypes (more on composition below).

`For example, if you're facing twenty goblins, there's no point in individually storing every limb and detail for each goblin when they are all identical. We want to store a prototypical goblin in one place`

So compose your prototypes and keep them aside. See more below.

`Further, the prototype goblin could be represented by how it differs from the prototype human.`

Even though superclass/subclass might seem the right relationship here, *don't* do that as you will lock yourself into a corner later on. Rather compose your prototypal objects and diff them: assign a numeric (or string) ID to each body part, then take a hash over the whole body's collection of parts. That hash allows you to compare actor species; if hash/species differs, you can thereafter numerically compare individual body parts which is very fast, especially with vectorised code.

It could actually be very informative for you to study JavaScript's prototypal inheritance system for what you're trying to do here. It's an almost-perfect fit. It is fairly trivial to implement similar in another language, provided you understand the concept.

`Obviously one shouldn't jump blindly into designing such a game`

No, but you'd be hard put to know exactly what the most efficient approach is until you've tested several options extensively! That's exactly why you should follow others' advice and get prototyping. It's impossible for anyone here to give you a best-fit architectural approach, because that would rely on how all the different aspects of your design come together - which can only be garnered by extensive experimentation. Start simple and don't worry about efficiency yet.

---

**(clear) "Hierachies of control"**

A pattern so common I'm not sure it's really named. It ensures control flows remains sane / avoids spaghetti. You have a series of control classes, say, Game, Body, Arm, Hand, Finger (increasingly fine-grained). Game has functions that calls Body's functions; same for Body and Arm, etc,. down the line; it may not be `update`, but other named functions e.g. Arm might call `Hand.wield`. The hierarchy is respected in the sense that you try only to have direct parents (or at least ancestors) speak to children, and children back up to their direct parents (sometimes using loose coupling so there are no direct refs to parents). You can have children speaking to grandparents and/or vice versa, but that makes the control flow harder to follow since you are skipping levels of the tree. You also want to make sure that communications for the system as a whole come out of the top of the tree, which in this case is Body; *don't* have e.g. Hand dispatching messages out to supersystems.

Basically, Body is the interface to the outside world through which you are channelling all outgoing information, thus making it easy to keep a strict eye on what's going on with actors. Ultimately though, where and whether you skip levels is up to developer discretion, since it does cause mirroring of function definitions at higher levels if you are rigourous with this approach throughout.
> 3 votes

---
Tags: architecture, rpg, data-structure, character
---


# Question
Title: Unity fails to effectively split spritesheet
I'm very new to game development and I find it very difficult to split the spritesheets available at opengameart.org. All of them are kind of jumbled together without any fixed grid.

The resource I learned from always used neatly assembled sprite sheets and Unity would have no trouble in automatically splitting them. But almost all are randomly placed and Unity cannot split them.

For example:

And below is the automatic splitting in unity:

How do you guys get the sprites from such spritesheets in unity? Some guidance would be appreciated.

Thank you

# Answer
> 1 votes
When there are no transparent pixels between two sprites, Unity can not detect where one sprite ends and another sprite begins.

But your spritesheet uses a fixed grid of 16x16px, so you can use the "Grid By Cell Size" slicing mode:

This will nicely slice up the 1-cell character sprites and the map tiles, but also slice up some multi-cell sprites which you might want to keep together, like the vehicles in the center-left. If you want to use those as oversized sprites, you will have to fix that by hand for each object by deleting all of the bounding boxes which cover it but one and enlarge the remaining one.

---
Tags: unity, 2d, sprites, spritesheet
---


# Question
Title: Ground texture comes up blurry using the UV Rect Tool
Im trying to recreate the ground as this sample sprite sheet: https://opengameart.org/content/post-apocalyptic-expansion

I downloaded the sprite sheet and extracted the top left block and saved it separately and added it as a default object not Sprite/UI. I then added a UI \> Raw Image to my scene, added the imported texture. But as I expand it, it becomes blurry, even the UV rect does not seem to help. I though the UV rect was supposed to repeat the texture.

Am I doing this wrong?

# Answer
> 1 votes
you can set the 'Tiling' inside the material section of the inspector (im assuming you are using Unity from the how you've asked this question). The tiling part is just under wherre you set the colour etc and it defaults as 1 , but you can make it 10 for example in the X and Y and that will be 10x the detail

---
Tags: unity, 2d, textures, image
---


title: Very large terrains in Unreal-4

text:
# Question
Title: Very large terrains in Unreal-4
I was watching some YouTube tutorials on making terrains in UE4 and in each one they mention that the larger the terrain the worse the performance gets. I was wondering what you would do if you wanted to create a map like in skyrim or WOW. Is the terrain made of one massive terrain or is it made up out of a series of terrains in a grid? And is there any optimisation that you can do or is it all handled by UE4?

# Answer
> -1 votes
This link should help. Although it's about satellite maps, it still answers your question: **UE4 has support for importing tilesets, which is your giant terrain broken up into pieces.**

You could also look here to find UE4's World Composition tool, which makes it incredibly easier to use a large terrain in your game. (So, to answer the other part of your question, it *is*, in fact, handled by Unreal.

---
Tags: terrain, unreal-4
---


# Question
Title: Struggling to implement A* pathfinding execution
So I've implemented pathfinding to my game which works well with a tile based map. All tiles have an x & y integer coordinate for example the tile on the top left would be 0,0 the adjecent tiles would we 0,1; 1,0 and 1,1. My pathfinding returns a path based on these coordinates.

My game however is using float coordinates. So that an entity is basically able to stand on or between two tiles at the same time. For that the tile coordinates are multiplied by 32 (the size of one tile). That means the first tile would be 32,32 and the adjecent tiles 64,32; 32,64; 64,64

My approach was to get a target X and Y from my pathfinding to calculate the next step and multiply it by 32. So if the entity is supposed to move to the top left for example the targetX and Y would be 1\*32, 1\*32.

After the targetX & targetY is set i'll increase or decrease the coordination of moving entity by its movementspeed, when it's reached its targetX & targetY i'll get the next step and to the same until no steps are left.

However I'm encountering various problems because it's not really possible to set an entity to a certain field because its possible to stand on two tiles at the same time and entities only have float coordinates. Especially when an entity is supposed to move around a narrow corner its getting stuck because of the offset between the pathfinding and the float coordinates of the entity.

I hope my problem became more or less clear, how could I deal with that or how is dealt with that problematic in general? I'm glad about any advices.

Edit: No diagonal movement is intended.

# Answer
A\* is inherently an integer process, a tile is either travelled through or not. However your world is a floating point one; you can stand at 0.3,0.4 if you like. As such you need to convert from the A\* output to a set of way points in your coordinate system. Personally I would make each tile of size 1 and allow floating point numbers. As such you would add 0.5,0.5 to each of the A\* positions to get your waypoints; the centres of the tiles travelled. You appear to have chosen to make each tile 32 by 32. In this case you should multiply by 32 **after** adding 0.5 to each A\* value to get the tile centres. If you have your waypoints at the top left of each tile as I believe you have you will inevitable clip the tile above and to the left of the character
> 3 votes

# Answer
This has to do with the pathfinding algorithm itself, not with the float coordinates. You'd encounter the same problem even if the tiles were integer based and the entities were larger than one tile in radius. What this has to do with the pathfinding algorithm is, when you check if a tile is valid to move to, you have to make sure the entity can stand there. Check all the surrounding tiles (in floats) and make sure the entity can stand there. If it can, then it'll be a valid path. Here's an example if the entity's radius was `3` units:

```
public boolean isValid(TileBasedMap map, int x, int y)
{
    if(x >= 3 && x < map.width - 3 && y >= 3 && y < map.height - 3)
    {
        for(int i = -3; i <= 3; i++)
        {
            for(int j = -3; j <= 3; j++)
            {
                if(!map.getTile(x + i, y + j).isEmpty())
                    return false;
            }
        }
        return true;
    }
    else return false;
}

```

In summary, this applies to your problem because you convert the coordinates from 0-1 to 0-32 because of your floating point coordinates. This makes the entities much bigger than they actually are. They're now 32 units large (in theory) so you have to account for that in your pathfinding.
> 0 votes

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


title: Percentage based half circle filling

text:
# Question
Title: Percentage based half circle filling
I am trying to re-create this:

So what I did is, made an half-circle image, filled with red, and set a `TextureRegion`, and used `setRegionHeight` for given percentage:

```
public void setDamage(int d) {
    int height = damage.getTexture().getHeight();

    double val = (double) d / 100;
    damage.setRegionHeight((int) Math.round(val * height));
}

```

I did the same for the water one

And called after creating:

```
water.flip(false, true);
bilge.flip(false, true);
setDamage(70);
setWater(30);

```

I had to flip it aswell y-wise.

And it looks like this:

Doesn't look right, because it fills in a straight line, like I guess it would.

What methods can I use to create that filling look? I know I can use `ShapeRenderer` but I am not sure how, maybe use the circle equation and use half circle and fill lines at each degree based on the percentage set on damage? I would be happy to get some ideas

# Answer
> 3 votes
You can indeed use the `ShapeRenderer` to get something that is close to what the first image depicts.

The only part of drawing that that requires any math is the portions of red and blue, which if you use the `arc` method on `ShapeRenderer` is fairly simple.

`arc` takes a start point in degrees, so for the blue part it's trivial at 270 (at the bottom), but since `arc` does not use *from* and *to* but rather *from* and *length* for it's arguments the red one needs to start at `90 + 180 * (1 - amountOfRed)`, where `amountOfRed` is normalized to lie in the range \[0 - 1\].

I knocked up an example of this that produces something that looks like this

The full code for that is:

```
package com.bornander.sandbox;

import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType;
import com.badlogic.gdx.math.Interpolation;

public class SandboxGame extends ApplicationAdapter {
    private OrthographicCamera camera;
    private ShapeRenderer shapeRenderer;

    private float red = 0;
    private float blue = 0;
    private float elapsed = 0;

    public void create() {
        shapeRenderer = new ShapeRenderer();

        float aspectRatio = (float)Gdx.graphics.getWidth() / (float)Gdx.graphics.getHeight();
        float w = 800;
        float h = w / aspectRatio;

        camera = new OrthographicCamera(w, h);
    }

    @Override
    public void render () {
        Gdx.gl.glClearColor(0.2f, 0.2f, 0.4f, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        camera.update();

        /*
        // Create some neat-looking values for red and blue, this part is not important
        elapsed += Gdx.graphics.getDeltaTime();

        float a1 = Math.min(1.0f, elapsed / 4.0f);
        float a2 = Math.min(1.0f, elapsed / 3.0f);

        red = Interpolation.bounceOut.apply(0, 1, a1);
        blue = Interpolation.bounceOut.apply(0, 1, a2);
        */

        // The values for damage and water are hard-coded here, they
        // should come from your code
        float damage = 250.0f;
        float water = 340.0f;

        float maxDamage = 500.0f; // This is the constant that is the maximum amount of damage in your game
        float maxWater = 400.0f; // This is the constant that is the maximum amount of damage in your game

        // this is the method that does all the work
        // dividing by the max values normalizes the values to the [0-1] range
        drawTheCircleThingy(damage / maxDamage, water / maxWater);
    }

    // redStuff and blueStuff should be normalized to fit into the range [0 - 1]
    private void drawTheCircleThingy(float redStuff, float blueStuff) {
        shapeRenderer.setProjectionMatrix(camera.combined);

        float x = 0;
        float y = 0;

        float size = 200;
        float borderWidth = 10;

        float redStart = 90.0f + 180.0f * (1.0f - redStuff);
        float redLength = 180.0f * redStuff;

        float blueStart = 270.0f;
        float blueLength = 180.0f * blueStuff;

        float centerBarHeight = (size - borderWidth) * 2;
        float centerBarLeft = x - borderWidth / 2.0f;
        float centerBarRight = x + borderWidth / 2.0f;
        float centerBarTop = y + centerBarHeight / 2.0f;
        float centerBarBottom = y - centerBarHeight / 2.0f;

        // Draw the filled bits
        shapeRenderer.begin(ShapeType.Filled);

        shapeRenderer.setColor(Color.YELLOW);
        shapeRenderer.circle(x, y, size);

        shapeRenderer.setColor(Color.TEAL);
        shapeRenderer.circle(x, y, size - borderWidth);

        shapeRenderer.setColor(Color.RED);
        shapeRenderer.arc(x, y, size - borderWidth, redStart, redLength);

        shapeRenderer.setColor(Color.BLUE);
        shapeRenderer.arc(x, y, size - borderWidth, blueStart, blueLength);

        shapeRenderer.setColor(Color.YELLOW);
        shapeRenderer.rect(x - borderWidth / 2, y - centerBarHeight / 2, borderWidth, centerBarHeight);

        shapeRenderer.end();

        // Draw the black borders
        shapeRenderer.begin(ShapeType.Line);
        shapeRenderer.setColor(Color.BLACK);

        shapeRenderer.circle(0, 0, size);
        shapeRenderer.circle(0, 0, size - borderWidth);

        shapeRenderer.line(centerBarLeft, centerBarBottom, centerBarLeft, centerBarTop);
        shapeRenderer.line(centerBarRight, centerBarBottom, centerBarRight, centerBarTop);
        shapeRenderer.end();
    }
}

```

---
Tags: java, libgdx, graphics
---


title: Way to structure items in code?

text:
# Question
Title: Way to structure items in code?
I have an "Item" class here that is used to create items.

```
public class Item {
    private String name;
    private int id;
    private int worth;

    //constructor
    Item(String _name, int _id, int _worth) {
        name = _name;
        id = _id;
        worth = _worth;
    }

    public String getName() {
        return name;
    }
}

```

This works fine and dandy.. but I don't know how to give them unique ID's, I thought about using

```
private static Item[] items;

```

and then when they're created add them to this array, but is that the only way? Also where do I put my code to initialize all the various items in the game? Should it be in the main method, or have a loader of some sort, or have them declared straight away in the Item class using

```
private static Item apple = new Item("Apple",0,3);

```

?

# Answer
Most games don't hardcode things like item data. They instead put all the game data into files. At game start those files are read, parsed and used to generate all the item objects. The unique ID's would be part of those game data files.

This has a lot of advantages. It allows non-programmers to add content without having to make code changes, it makes your content updates much leaner, it makes the game more modding friendly, it allows you to create external tools to edit your item database, it makes code reuse easier etc. etc..

> I thought about using `private static Item[] items;`and then when they're created add them to this array, but is that the only way?

There is **never** only one way to do something in programming. What you could do instead:

* Use an `ArrayList<Item>`. ArrayList is an object-oriented wrapper around arrays. One of its biggest advantages is that you can create one without having to state a fixed size (it grows automatically when you `.add` items by internally re-allocating the content to larger and larger arrays).
* Use a `HashMap<Integer, Item>`. This class is a bit slower, but doesn't waste any space when you have unused ID numbers. You can also use a different key than an integer. A `HashMap<String, Item>`, for example, allows you to use human-readable names instead of numbers as item ID's.

There is no best solution. Only the best solution for your game.
> 2 votes

# Answer
Since it looks like you wouldn't have any trouble making this ID to be auto incremented, the solution for this post should do the job for you.

Regarding to where to put your items, we would need more info to give you some advice. However and as a general rule, things hold on some kind of manager and factory pattern are usually the way to go.
> 0 votes

# Answer
Building on Philipp's correct answer, here's a generally simple way of doing it.
(Similar to how Minecraft does it)

```
public class Item
{
    public final String name;
    public final int id;

    public Item(String name, int id)
    {
        this.name = name;
        this.id = id;
    }
}

```

This is the class that all the items will extend or use.

```
public class Items
{
    private Items() {}

    public static final Item APPLE = new Item("Apple", 0);
    public static final Item PEAR = new Item("Pear", 1);
    public static final Item BANANA = new ItemBanana();
}

```

This will contain all the items in the whole game.

```
public class ItemStack
{
    public final Item item;
    public int stackSize;

    public ItemStack(Item item)
    {
        this(item, 1);
    }

    public ItemStack(Item item, int stackSize)
    {
        this.item = item;
        this.stackSize = stackSize;
    }
}

```

This is what you'll have the array of in your inventory classes. Like the player class will have an array of `ItemStack`s. Here's an example:

```
private final ItemStack[] stacks = new ItemStack[10];

```

This is how Minecraft does it and how countless other games do it as well. Some games even have the ItemStack extend `Comparable<?>` and have the inventories auto-sort as items are added, etc.
> 0 votes

---
Tags: java
---


# Question
Title: How to find the ideal path done inside a given shape in LibGDX?
I'm trying to make an android/libgdx game in which for every level you have a different shape as a png, and you have to drag your finger inside the shape and try to be as close as the ideal path created after the shape. At the end of the level the game will show you in a percentage how close you were from the ideal path.

My question is how can I find the ideal way that the player has to follow? Is there any function that i can use to find out the array of points created after the shape?

My problem is that the shape width is different along the way, so I can't use the pixels path. I already have an algorithm which gives me the array of points from the path of the player so I have to compare it with the ideal one.

If you have any ideas of any algorithm or functions that can help please let me know. Any answer will be helpful.

# Answer
This is much harder than you think. It's extremely difficult. But before you render the shape, you can keep track of the shape that's being drawn in vertices. What I mean by this is, suppose the shape is a triangle. What would happen is you'd keep track of the three coordinate points needed to draw the triangle. Then just calculate the distance from the line at each point the user's finger is on the screen. This'll take some simple formulas and algorithms to calculate the distance from a point and a line. Here's an example of the distance formula.

At rendering time, draw lines from vertex to vertex with a thickness of some. I hope this made sense. because as I'm typing this, it sounds like it's not explaining too much.
> 1 votes

---
Tags: java, libgdx, android, path-finding
---


# Question
Title: how to slide pieces for a slide puzzle game for android(libgdx)
I want to make a small one-screen game in which the player has to slide pieces of an image until the image is completed. I used texture regions to create the pieces from an image

```
int numOfTiles_Horizontal = 5;
int numOfTiles_Vertical = 5;

float tile_width = img.getWidth() / numOfTiles_Horizontal;
float tile_height = img.getHeight() / numOfTiles_Vertical;

TextureRegion[][] tiles = new TextureRegion[numOfTiles_Horizontal][numOfTiles_Vertical];
for(int col = 0; col < numOfTiles_Horizontal; col++) {
    for(int row = 0; row < numOfTiles_Vertical; row++){
        tiles[col][row] = new TextureRegion(img, col * tile_width, row * tile_height, tile_width, tile_height);
    }
}

```

, but I'm unsure about how to allow the player to move the tiles into a blank space as well as making a "blank space" to allow tiles to move.

The game would look like this:

I followed some tutorials for libgdx but cannot find much on achieving this.

I am new to the engine and Android development so any help is appreciated.

# Answer
> 1 votes
Add an `InputProcessor` using `Gdx.input.setInputProcesser(...)` and check if where the mouse was clicked is in bounds of the grid map. If it is, try moving the piece in the spot to the empty spot near it. I didn't wanna add code but who cares. Here's an example in

```
public boolean touchDown(int screenX, int screenY, int pointer, int button)
{
    label1:
    for(int i = 0; i < widthInTiles; i++)
    {
        for(int j = 0; j < heightInTiles; j++)
        {
            int tx = i * tileSize;
            int ty = j * tileSize;
            if(screenX >= tx && screenX <= tx + tileSize && screenY >= ty && screenY <= ty + tileSize )
            {
                tryMovingTile(i, j);
                break label1;
            }
        }
    }
    return true;
}

```

---
Tags: java, android, android-studio
---


title: Google Play beta testing

text:
# Question
Title: Google Play beta testing
I made a game I wish to upload to Google Play and I faced the options

* Production
* Beta testing
* Alpha testing

I made the game all alone and I think it is complete, was tested on multiple physical as well as virtual devices, all well and good.

As I'm alone and would consider the game finished, does it make sense to upload beta instead of production? I'm not in connection with anybody, so I don't think anyone would try and play the game (apart from meself). Or would some testers employed by Google test the apps if they are submitted to open beta?

# Answer
The *alpha* and *beta* test stages only make sense to use if you plan to do any testing in them, Google will not do any testing for you on your application just because it goes through those stages.

Note that this does not mean you need to have staff or employed people testing your application, both *alpha* and *beta* can be run as open testing, i.e. people can download and run the application from Play just like any other app if the stage is open, but the download page comes with a notice saying the application is still in testing.
> 1 votes

---
Tags: google-play, testing
---


# Question
Title: How is a Mesh Collider "performance expensive"?
* Do Mesh Colliders slow down performance simply by existing or only when they are colliding?
* Do they directly impact FPS or do they slow down the in-game physics?

# Answer
> 15 votes
A moving body near a meshcollider needs to check for collisions against potentially *every* triangular face of the mesh. So for a detailed or non-convex mesh, or lots of bodies, this can get expensive. And of course, if you have a meshcollider moving near another meshcollider, you pay this cost combinatorically.

These costs hit during the physics update step, as part of its collision resolution. The physics engine doesn't know where to position things for the next frame until it's worked out which objects need to bounce or stop due to these collisions. So in extreme cases, this can make the physics update process take longer and delay rendering of the next frame, impacting the game's frames per second rate.

If your frame runs extremely slow, past the maximum allowed timestep configured in the Time Manager then Unity will start dropping physics steps to try to keep things moving. Only if that happens will your physics slow down relative to realtime, otherwise Unity's decoupled fixed timestep will keep your physics moving consistently even if the rendered FPS drops.

When the meshcollider is not moving, the physics engine can put it to sleep, and only check it when another body comes close enough to potentially hit it, saving quite a lot of computation.

So the cost isn't fixed every frame, it will vary based on the complexity of the physics interactions that need to be checked & resolved in that frame.

To manage this cost, your best bets are:

* Favour simpler collider types for dynamic objects, or terrain colliders for environments
* Minimize the number of faces in meshes used for collision
* When possible, make mesh colliders convex, or break them into convex pieces

(convex meshcolliders can use faster algorithms than an exhaustive face-by-face check, though the worst-case complexity still grows with the face count in the mesh)
* Avoid moving big mesh colliders — see if you can keep them static and move things *relative to them* to create a sense of motion for big environmental collision shapes like a boat/spaceship

# Answer
> 5 votes
Unity first uses Axis-Alligned Bounding Boxes (AABB) to check which colliders actually have a chance to collide. Checking two AABB's for intersection is a very cheap operation. Only then does Unity check if the collider-geometries also collide.

That means a mesh-collider only consumes CPU cycles when its bounding box intersects that of another collider. As long as nothing is near it, the collider type doesn't matter much for collision detection performance. Another operation which can cost lots of CPU cycles is rotating, because whenever you rotate an object the engine needs to recalculate the size of its bounding box. By the way, the Unity API exposes the bounding boxes of colliders.

# Answer
> 4 votes
A **Mesh Collider** will have to figure out the collisions for every single face of the whole mesh, Therefore It would take ***Longer (No significant difference most of the time)*** and would consume more ***Hardware Resources*** which would also slow down the performance.

**Q -)** Do they reduce performance simply by existing or Colliding ?

**A -)** No they don't reduce performance by just existing, The performance gets a hit when they are colliding.

**Q -)** Do they directly impact FPS or do they slow down the in-game physics?

**A -)** Essentially in a Mesh Collider. The more the triangles, The more the performance hit and So on. Most developers actually spend too much time trying to optimize uncritical parts of their projects and This sometimes leads to the poor optimization of the actual critical parts. However to only answer Your question, Yes mesh colliders do actually Impact Fps if they have a lot of faces.

---
Tags: unity, meshcollider, collider
---


# Question
Title: Unity - Manually sync location of players from server to client
I am new to Unity networking. I've set up my scene with NetworkManager and the Player prefab having NetworkIdentity. I originally had my players set up to sync with a NetworkTransform. This worked, but the objects were very choppy whenever they were children of a moving object.

In order to fix this issue, I've replaced NetworkTransform with a class extending NetworkBehavior, using UnityEngine.Networking, and containing the following code to sync localPosition:

```
void Update () {
    CmdSyncPos (transform.localPosition, transform.localRotation);
}

[Command]
protected void CmdSyncPos (Vector3 localPos, Quaternion localRotation) {
    transform.localPosition = localPos;
    transform.localRotation = localRotation;
}

```

This works really well! The only problem is that this is one-way, the server now has the updated position of all clients but the clients only have the updated versions of themselves.

How can I do this in reverse: Manually sync the location of non-local players from server to client?

# Answer
I ended up designing my code with help from /u/Cell-i-Zenit on Reddit. Final code:

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

public class SyncPosition : NetworkBehaviour {

    private GameObject playerBody;
    private Rigidbody physicsRoot;

    void Start () {
        playerBody = transform.GetChild (0).gameObject;
        physicsRoot = GetComponent<Rigidbody> ();
    }

    void Update () {
        if (isLocalPlayer) {
            CmdSyncPos (transform.localPosition, transform.localRotation, playerBody.transform.localRotation, physicsRoot.velocity, transform.parent.name);
        }
    }

    // Send position to the server and run the RPC for everyone, including the server.
    [Command]
    protected void CmdSyncPos (Vector3 localPosition, Quaternion localRotation, Quaternion bodyRotation, Vector3 velocity, string parentName) {
        RpcSyncPos (localPosition, localRotation, bodyRotation, velocity, parentName);
    }

    // For each player, transfer the position from the server to the client, and set it as long as it's not the local player.
    [ClientRpc]
    void RpcSyncPos (Vector3 localPosition, Quaternion localRotation, Quaternion bodyRotation, Vector3 velocity, string parentName) {
        if (playerBody == null) {
            return;
        }
        if (!isLocalPlayer) {
            transform.localPosition = localPosition;
            transform.localRotation = localRotation;
            playerBody.transform.localRotation = bodyRotation;
            physicsRoot.velocity = velocity;

            if (!transform.parent.name.Equals(parentName)) {
                transform.parent = GameObject.Find (parentName).transform;
            }
        }
    }
}

```
> 1 votes

# Answer
Edit:

You could use ClientRPCs:

```
[ClientRpc]
public void RpcSyncedPos(Vector3 syncedPos, Quaternion syncedRotation)
{
    transform.position = syncedPos;
    transform.rotation = syncedRotation;
}

[Server]
private void UpdateClientsPos()
{
  RpcSyncedPos(transform.position, transform.rotation);
}

void Update()
{
   UpdateClientsPos();
}

```

The method with the \[ClientRpc\] attribute is only invoking on client side, but it's important to write it correctly, because it's invoking by reflection: Rpc\_____

The \[Server\] attribute ensure that the method below is only called/invoked by the server. You could also do that in the Update loop by simply write a if statement to check whether this is a server: `if(server) { UpdateClientsPos(); }`

The workflow is the following:

The Client Alise calls your command to send his pos and rot to the server. The server calls the UpdateClientsPos()-method, which is a ClientRpc, to invoke the method on all other clients to send the synced pos and rot from the server to the other clients, f.e. client Bob.

This attributes and methods only work if you are using the unet high level api.

Ref: https://docs.unity3d.com/ScriptReference/Networking.ClientRpcAttribute.html

You can also use SyncVars, but then there is no need for Commands and ClientRPCs.

Take a look: https://docs.unity3d.com/Manual/UNetUsingHLAPI.html and it's subtitles.
> 0 votes

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


# Question
Title: In Unity how can I know which direction is the screen auto-rotated?
From the `Screen.orientation` description I get

> If the value is set to `ScreenOrientation.AutoRotation` then the screen will select \[...\] automatically as the device orientation changes.

This seems to imply that if the screen *does* auto-rotate, *then* `Screen.orientation` has been set to `ScreenOrientation.AutoRotation`.

If that's so, how can I know in which direction it has been auto-rotated?

Disabling the auto-rotation doesn't count (obviously), and I need to distinguish between `LandscapeLeft` and `LandscapeRight`, so checking height and width doesn't work either.

This should be cross-platform, without including any kind of non-C# plugin.

*(the answer, given this documentation, seems to be "you can't", but maybe I'm missing something)*

# Answer
It should be easy to distinguish between portrait and landscape by checking `Screen.height > Screen.width`.

From a display perspective you are unable to distinguish between `Portrait`/`PortraitUpsideDown` and `LandscapeLeft`/`LandscapeRight`.

However it is possible to disable any of these by setting any of the following to `false`:

* `autorotateToLandscapeLeft`
* `autorotateToLandscapeRight`
* `autorotateToPortrait`
* `autorotateToPortraitUpsideDown`

Some coverage of these display issues is here for Android and here for iOS.

However you can determine the device orientation via Input.deviceOrientation
> 1 votes

# Answer
I can think of some method, that will return ScreenOrientation from Input.deviceOrientation. But because sometimes deviceOrientation can't be distinguished (e.g. diagonal or parallel to ground) that method will return null in that case:

```
private ScreenOrientation? DeviceOrientationToScreenOrientation(DeviceOrientation deviceOrientation)
        {
            switch (deviceOrientation)
            {
                case DeviceOrientation.Portrait:
                    if (Screen.autorotateToPortrait)
                    {
                        return ScreenOrientation.Portrait;
                    }
                    break;
                case DeviceOrientation.PortraitUpsideDown:
                    if (Screen.autorotateToPortraitUpsideDown)
                    {
                        return ScreenOrientation.PortraitUpsideDown;
                    }
                    break;
                case DeviceOrientation.LandscapeLeft:
                    if (Screen.autorotateToLandscapeLeft)
                    {
                        return ScreenOrientation.LandscapeLeft;
                    }
                    break;
                case DeviceOrientation.LandscapeRight:
                    if (Screen.autorotateToLandscapeRight)
                    {
                        return ScreenOrientation.LandscapeRight;
                    }
                    break;
            }
            return null;
        }

```

So we need to wait, until Input.deviceOrientation will return something, we can distinguish. In my game I need to freeze screen from flipping between landscapeLeft & landscapeRight when in game, but allow when in menu. So I start checking for Input.deviceOrientation each half-second after hiding menu. That's how it can be implemented using UniRx:

```
private void OnEnable()
{
Observable.Interval(TimeSpan.FromMilliseconds(500))
                .Select(_ => DeviceOrientationToScreenOrientation(Input.deviceOrientation))
                .First(orientation => orientation.HasValue)
                .SubscribeUntilDisable(this, orientation =>
                {
                    Screen.orientation = orientation.Value;
                });
}

```
> 0 votes

---
Tags: unity, mobile, screen
---


# Question
Title: Basic equation for pure metallic reflectance
I'm working on a live wallpaper that shows a pure metallic object. Since it's a live wallpaper, I can make a ton of approximations...this isn't a full blown scene in a game world. My shader only has to support this one material. People won't expect extreme detail, etc. So, for example, I don't even bother with diffuse since a pure conductive material barely has any.

So I'm trying to implement a reflective conductive surface that pulls the reflection from a cubemap representing the lighting environment. On a very basic level it looks like this:

```
vec3 fresnelSchlick (vec3 f0, float cosTheta)
{
    return mix(f0, vec3(1.0), pow(1.0 - cosTheta, 5.0));
}

//...
float NdV = dot(normal, viewDir);
vec2 brdf = texture2D(u_brdf, vec2(u_roughness, NdV)).rg; // from a LUT

vec3 reflection = textureCube(u_cubemap, reflect(viewDir, normal));
gl_FragColor = reflection * (fresnelSchlick(materialColor, NdV) * brdf.x + brdf.y);

```

The problem with my simple math here is that the range of possible final pixel colors does not produce a proper-looking range of hues. Suppose my material color is #0050ff and the environment is monochrome white. Then all of the possible colors that could be seen are:

This doesn't allow for bright looking reflections at the light sources in the envmap. I found this example material render for comparison. The cubemap in the example here is close to monochrome white. But at the bright areas of the reflection, there is a lot of red component in the color.

With my limited range of colors, my object looks dull and lifeless. Can anyone point out what I'm missing in my equation?

# Answer
This is a dirty little secret for metallic lighting: **it's all about the reflections**. Every good looking metallic render is actually reflecting from a complex environment. This goes for other reflective materials too, like glass and water.

> From http://www.pauldebevec.com/Probes/

Take for example the above scene. The reflective spheres all use the same environment map (shown inset above-left), which is a room with natural lighting coming through large windows, which can be plainly seen in the reflections. The environment can be most clearly seen in the fully-reflective sphere in the back.

This makes sense if you think about it; a perfectly reflective object would have its appearance almost entirely determined by its environment (and its shape). So of course, if you have a simple, monochrome environment, your reflective object will look similarly boring.

This is why most reflective materials are showcased in a certain environment. It could be an outdoor or indoor scene or an artificial one but with distinctive lighting sources.
> 1 votes

---
Tags: shaders, rendering, glsl, pbr, specular
---


# Question
Title: Learning how to make imposters manually in Unity - how to render an object to a texture not what camera sees?
I am trying to learn the most performant way to make an imposter in Unity manually - not using pre-fabricated solutions.

My first guess is that it should be achieved by using RenderTexture and a second camera and then taking different "snapshots" of different angles of the objec. If there are better alternatives in terms of performance (even if more difficult to implement), I would love to hear about.

In case that is the only path, then I have learned how to render from a camera to a texture via script, but I still couldn't figure it out how do the following, which is what I need to do first: how to render-to-texture a specific object without the background of the camera (i.e. with rest of texture being transparent) in a performant manner?

Pointers, suggestions or at least link recommendation will be great.

Thanks in advance.

# Answer
> 3 votes
There are a variety of different imposter techniques.

Level of detail is probably the easiest to achieve, but has two main drawbacks. The noticeable 'pop' effect when you swap between low and high resolution models, solved by gradual transitions between LODs. The second problem is that it's MUCH more work for the artist to generate LODs for every single model. There's a GDC talk which about an automated way to generate LODS - "Automated Level of Detail Generation for HALO: REACH"

A simpler technique would be billboarding, where you use only a flat polygon, instead of a low resolution mesh. This polygon faces the camera, and is textured from a render of your model. This method requires having multiple different views of your object, much like how the enemies in doom. You could prerender all your views to a texture atlas. Modern games use this approach, like Far Cry 3 https://www.youtube.com/watch?v=9P3EI17kHaI

You could also have several different static billboards, and combine them like in this unity package https://forum.unity3d.com/threads/abi-automatic-3d-billboard-imposters-released.204579/

But the best way (which I think you want) is dynamically rendering your billboards, like in this gamasutra article. http://www.gamasutra.com/view/feature/130911/dynamic\_2d\_imposters\_a\_simple\_.php This was first done by Jurrassic Park: Trespasser in 1998, so it's not a new technique. Check out the code review here http://fabiensanglard.net/trespasser/index.php Scroll down to the section on wavelets to see their imposters.

Except the standard LOD approach, your first step would probably to find a render texture tutorial. The orientation of the renderTexture camera must be the same as your main camera, but cropped around the gameObject for efficency. You will need to isolate the gameObject(s) you want to render with a culling mask. And set the camera's clear flags so that you get a transparent background. Then render an imposter billboard in place of the original object.

---
Tags: rendering, unity, texture-atlas, billboarding, rendertexture
---


# Question
Title: Rotate object such that a child object is facing a target (3D)
Given a parent object **A** and a child object **B**, how do I find the rotation of **A** such that **B** is pointing toward the position of a target **C**.

This is a simplified way of solving 'what angle does the torso need to be so that the hand is aiming a weapon at a target?'.

I can solve easily in 2D by iteratively checking how much **B** needs to turn to look at **C** and then applying that rotation delta to **A**, but in 3D this method seems to breaks down.

Does this problem have a known name, and what types of algorithms should I be researching in order to solve it?

Initial state

Desired state

# Answer
Think about the problem backwards, how would we rotate C around A so that it lines up with B. If we can solve this problem, we just need to rotate A by the same amount, but in the opposite direction.

If you're familiar with linear algebra, this should be pretty straight forward. If you're not, I can try and write up some pseudo-code to complement this answer.

From the above diagram, we can see that B (the gun) forms a line if sight (green), a straight line (2D or 3D), we know that we want C somewhere along this line. Since we're rotating around A, the distance (d) between A and C will remain the same, so we just need to find the 2 points (x1 and x2) along the line which satisfy this. Construct a right angle triangle (A x3 x2), where x3 is the point on the line closest to A. Using the Pythagorean theorem, we can get y. And from y we can get both x1 and x2. Choose the point which point is in front of the gun, not behind. Finally we can get the axis of rotation, and the angle of rotation (theta). The axis can be obtained by the cross product between the vectors (x2-A)x(C-A). The angle (theta) can be found by taking the inverse cosine of the dot product between the same vectors after normalization.

That should give you the inverse rotation, so just rotate A by negative theta, around the same axis.

I haven't walked through the math myself, but is should simplify into a fairly short algorithm.

Note: in 2D there is only 1 solution, but in 3D there are infinite rotations that satisfy your problem. My solution will find the smallest rotation, which may not be the most natural looking for a guy aiming a gun.
> 4 votes

---
Tags: mathematics, rotation, transformation, aiming
---


# Question
Title: What are Layout Qualifier in GLSL used for?
So I'm reading up on GLSL 4.0 standard and I see things like **"layout (location = 0) in vec3...."**

I understand they dictate where certain values are placed but...

1. Do particular locations hold special meaning (as in the index #s)?
2. Since I'm sending data by getting that attribute/uniform location by name, what advantage does it provide me?
3. What are some use cases / tricks done by using it?

**On a side note:** I see gl\_FragColor is depricated, is gl\_position deprecated too? Is there a particular name for the frag. shader output or is any vec4 output considered the final result?

# Answer
1. For the vertex shader the in are the vertex attributes. The number will be the location The net effect is the same as calling glBindAttribLocation with matching name/location before linking but instead it's now encoded inside the shader.
2. it lets you reuse the location numbers for different programs so you don't have to keep a mapping per program.
3. see #2

No gl\_Position is still the required output from the vertex shader. The fragment shader outputs can be bound to specific color attachments in the framebuffer. If you only have a single output then you don't really have to worry about it.
> 1 votes

---
Tags: opengl, glsl
---


# Question
Title: LWJGL—How to Animate and Render Characters Using a Sprite Sheet
I'm making an RPG similar to Super Nintendo RPGs in the early '90s. I'm handling movement much like Squaresoft's *Final Fantasy IV*.

Notice that the player never actually **changes his x and y positions on screen**. What I'm asking, to be precise, is how could I, in LWJGL through user input (say, the arrow keys), take the **sprite sheet I have of my character's movement animations** and render them in a \[partially\] fluid animation like above?

I've been perusing the internet for hours, and I've not found a surefire way to do this. I don't have any code as of yet; I'm more or less looking for a guideline or some pointers in the right direction concerning how I might tackle this.

And, to note, this'll be a rather large game, so I want to focus partially on speed and efficiency—that meaning that I don't want to dive into Slick2D and libGDX unless absolutely necessary.

# Answer
> 3 votes
It's much easier than you think. In your shader you need to have a uniform containing the size of one sprite and the position of the current sprite (in a normalized coordinate system, where `(0; 0)` is the upper left corner and `(1; 1)` is the lower right corner). Then you simply need to multiply the texture coordinates with the size of one sprite and add the position of the sprite to it:

```
in vec2 a_textureCoords;

uniform sampler2D u_sampler;
uniform vec2 u_spriteSize;
uniform vec2 u_spritePosition;

out vec4 color;

void main(void) {
    color = texture(u_sampler, a_textureCoords * u_spriteSize + u_spritePosition;
}

```

Loading in the uniforms is also very easy. If you have a variable `delay` storing the amount of milliseconds between the two sprites, then you can do

```
if (!playerMoving) {
    // Load in the position of the standing sprite
} else {
    if (System.currentTimeMillis() % (2 * delay) < delay) {
        // Load in the position of the first walking sprite
    } else {
        // Load in the position of the second walking sprite
    }
}

```

if you have more than 2 walking sprites, then you should store the sprite position in an array and load them dynamically:

```
private Vector2[] positions = new Vector2[] {
    new Vector2(0.5, 0),
    new Vector2(0, 0.5),
    new Vector2(0.5, 0.5)
};

    if (!playerMoving) {
    // Load in the position of the standing sprite
} else {
    int currentPos = System.currentTimeMillis() % (positions.length * delay) / positions.length;
    Vector2 pos = positions[currentPos];
    // Load in pos
}

```

---
Tags: java, animation, sprites, lwjgl, rpg
---


# Question
Title: How can I block Copy/Paste from Input Fields in Unity?
I don't want the user to write a text by copying and then pasting the content to an Input Field, how can I do that?

# Answer
> 1 votes
I haven't tested the following script, but I guess you can detect whether the paste keys are pressed when the value of the input changes.

```
using UnityEngine;
using System.Collections;

public class Example : MonoBehaviour
{
    public UnityEngine.UI.InputField mainInputField;
    private string inputValue;

    public void Start()
    {
        inputValue = mainInputField.text;
        mainInputField.onValueChanged.AddListener(OnInputValueChanged);
    }

    // Invoked when the value of the text field changes.
    public void OnInputValueChanged(string newValue)
    {
        if ((Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.RightControl)) && (Input.GetKey(KeyCode.V) || Input.GetKeyUp(KeyCode.V)))
        {
            Debug.LogError("Not allowed");
            mainInputField.onValueChanged.RemoveListener(OnInputValueChanged);
            mainInputField.text = inputValue;
            mainInputField.onValueChanged.AddListener(OnInputValueChanged);
        }
        else
        {
            inputValue = mainInputField.text;
        }
    }
}

```

EDIT : After testing this code (which works), you will have as many "Not allowed" errors as you have characters in the copied string. My solution may not be the best I guess.

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


# Question
Title: How can i change the camera view when clicking a button?
I added enum with all the views options. But when i click/press on V nothing happen with the game is running.

```
using UnityEngine;

public class FollowTargetCamera : MonoBehaviour
{
    public enum Views
    {
        Forward, Backward, Left, Right
    }

    public Transform Target;
    public float PositionFolowForce = 5f;
    public float RotationFolowForce = 5f;

    public Views views;

    void Start()
    {

    }

    void FixedUpdate()
    {
        Vector3 vector = new Vector3(0, 0, 0);
        Vector3 dir = new Vector3(0, 0, 0);

        if (Input.GetKeyDown(KeyCode.V))
        {
            switch (views)
            {
                case Views.Backward:
                    vector = Vector3.back;
                    dir = Target.rotation * Vector3.back;
                    break;
                case Views.Forward:
                    vector = Vector3.forward;
                    dir = Target.rotation * Vector3.forward;
                    break;
                case Views.Left:
                    vector = Vector3.left;
                    dir = Target.rotation * Vector3.left;
                    break;
                case Views.Right:
                    vector = Vector3.right;
                    dir = Target.rotation * Vector3.right;
                    break;
            }
        }
        dir.y = 0f;
        if (dir.magnitude > 0f) vector = dir / dir.magnitude;

        transform.position = Vector3.Lerp(transform.position, Target.position, PositionFolowForce * Time.deltaTime);
        transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(vector), RotationFolowForce * Time.deltaTime);
    }
}

```

# Answer
You don't change the value of variable `views` anywhere (in the given code), that's why it doesn't change.

It will be Views.Backward all the time, for example.

If you want it to be looping through all the views, you could try something like

```
if (views < 3 ) ++views
else views = 0

```

This can be achieved in more optimal ways, but check if that simply works.
> 1 votes

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


# Question
Title: Move Camera After Player Moves Certain Distance
I've got a 3D mobile game with the player centered in the middle of the screen, and a camera looking down on top of the player. The player is controller by an on-screen joystick. Currently when the joystick is touched to move the player, the camera instantly moves along with the player. This is okay, but what I want to have happen is to allow the player to move in a small circular area freely without the camera moving. Once the player reaches the edge of the pre-defined area, I'd like the camera to start moving with the player again. If the player starts moving back towards the camera location (x,y) then I'd like the camera to stop moving and allow the player to roam freely again.

I've got this sort of working with the following code using `LateUpdate`, but as I move the player near the edge of the max distance from the camera the movements get jumpy.

```
public class CameraController {
    const float MAX_DISTANCE = 5f;

    void LateUpdate()
    {
        if (Joystick.IsTouched)
        {
            // This properly shows the distance the player is from the camera
            float distance = GetPlayerDistance();

            if (distance > MAX_DISTANCE)
            {
                // Move camera the same way the player is being moved.
                // This works and moves the camera and player properly in sync.

                // This causes jerky and unsmooth movement when the distance
                // is close (above/below/equal) to the max in subsequent frames.
            }
        }
        else if (transform.position.x != player.position.x || transform.position.y != player.position.y)
        {
            // Lerp the camera position back to be directly above the player
            // when the joystick is let go and the camera and players' x or
            // y position don't match. This works great.
        }
    }
}

```

I am having trouble figuring out how to get this working properly. I can't seem to come up with a way to determine when the player should be allowed to move freely after they have already hit the max distance from the camera. When it first starts, the player can move freely fine, and when letting go of the joystick, the camera animates back properly. The issue arises once the max distance is hit.

I've also tried parenting the player to the camera to have them move in sync when the threshold is hit, but I am unable to determine when to un-parent them because the ship can't move freely to get closer to the camera. Any thoughts on this approach? It works perfect except I can't figure out when to un-parent the two game objects.

Thanks in advance for any help/thoughts!

# Answer
> 1 votes
I don't know if it's really what you are looking for, but try this script I've made :

```
using UnityEngine;
using System.Collections;

public class CameraController : MonoBehaviour {
    const float MAX_DISTANCE = 5f;

    public Transform target; // Specify the player
    public float speed = 1 ;
    private Vector3 destination;
    private Vector3 projection;

    void Start () {
        destination = transform.position;
        projection = target.position;
    }

    void LateUpdate () {
        if ((target.position - projection).magnitude > MAX_DISTANCE )
        {
            projection = Vector3.MoveTowards(projection, target.position, Time.deltaTime * speed);
            destination = projection;
            destination.y = transform.position.y;
            transform.position = destination;
        }
    }
}

```

Here, I've supposed the camera is looking straight down, and the player moves on the XZ plane only.

The script makes the camera follow the player when the latter is outside a circle of `MAX_DISTANCE` radius. The center of the circle is the center of the screen. While the player stays inside this circle, the camera does not move.

---
Tags: unity, camera, movement
---


# Question
Title: Buggy behavior on basic hinge joint (pinball flipper)
I'm trying to make a pinball flipper, but before I begin working on the script to incorporate user controls, I want to get the rotational movement working. Basically it rotates in a circle around the left-most point.

Clearly one option is to make half the flipper invisible. This is the easiest way but it leaves me still not really understanding how to work with rotation. For example:

```
<======o======>

```

where o is the midpoint.

I want it to rotate along the same axis, but without the left half of the shape:

```
       o======>

```

I have tried watching this video a couple times but am coming short of understanding how the hinge joint works. I attached one my left flipper and set the axis to 0,1,0 so it rotates along the y axis (remaining parallel to the playfield). I also moved the anchor to the leftmost position. I have left the rest of the hinge joint at its default configuration. Here is some evidence:

1. the placement of the hinge joint (it's the little yellow arrow at the left of the flipper)
2. the hinge joint config
3. The buggy behavior
4. The left paddle's rigid body (it is locked on all position and all rotation except y)

What I'm really trying to do is have the flipper rotate from it's leftmost point as the origin. I just want it to free-rotate when the ball hits it.

# Answer
> 0 votes
I think I figured this out, I needed to remove all constraints on the flipper rigid body. The hinge joint already handles the constraints in effect. If it's pointing up (0,1,0) then that prevents rotation on x and z. Also, position constraints have to be removed because otherwise they will override the hinge's effects (essentially making movement around the hinge impossible).

Here is the proof:

---
Tags: unity
---


# Question
Title: How can I implement dynamic button size?
I'm on the process of planing a sort of a 2D/2.5D, pixel-art multilingual game, while I learn about game development. I have a pretty solid background at programming, but when it comes to game design, I don't know too much. My particular question is about how is the proper/better way of creating and implementing a game text button, but I suppose it can be applied to other GUI elements. What I have found so far, while "googleing"/looking for this specific question, is how to deal with engines or frameworks which have their own way of doing it, but I would like to do it by my own. So to make things clearer, let me expose my vision of potential approaches.

1. Fixed text in a fixed-size texture

* This is an easy way of implementing a text button, as all I have to do is loading and positioning a texture. However, it could be painful to change my .psd files all the time, as I'm working with a multilingual game.
2. Variable text and fixed-size texture

* I could use a texture as a button model and overlap it with all kinds of text of different languages, reading the texts from .xml files. The problem is that a word in a language can exceed its equivalent of another language. A workaround for this could be switching between different font sizes, i.e., a text in a language would be smaller or larger than in another, but this would look ugly.
3. Variable text and splitted texture

* This approach would divide a button texture into 3 different parts: left, middle and right. Then, I would read a text from a .xml file, measure its length in pixels and increase ("multiply") the "middle" part of the texture so that the text could fit on it. This looks fine when working with a pixel-art game GUI, but sounds not fine when working with vectorized images.
4. Dynamically-generated GUI

* I could use OpenGL to render rectangles and use them as buttons, but this would produce quite basic shapes. At most, I would have shaded rectangles with a basic border and some text rendered on it; it would look like a HTML/CSS GUI, which is a way far from a game GUI.

These approaches are just my guesses, as I've never worked in the game industry; I assume that someone experienced can correct me if I deduced something wrong. Another thing is that I think these approaches can work diffently depending of the texture type (e.g. pixel-art and vectorized textures), so you'll be welcome for answering why an approach is better for a texture type or another. There's also a possibility of me being a bad thinker and all of this being a "bullshit", and if it is the case, I hope you share your technique with me.

Moreover, as I said before, this question is specific for a text button, but I think with some adjustments it could cover more GUI elements which have related properties (such as window, text input and the like), so if you include it as part of your answer, it'll be helpful.

# Answer
> 0 votes
I'm no expert in GUI, but I think I could help you get in the right direction. I'm assuming that you want to avoid manually setting button sizes for each language, so this will discuss how to procedurally generate a GUI.

Depending on how you are rendering your fonts, there should be a way to get the width and height of a string. For instance, if you are using the Java swing library, this is how you could get the pixel dimensions of your text. Obviously, if you are using a different API, you will have to find this method on your own, or if you are writing your font rendering from scratch, you will have to implement this on your own. This shouldn't be too difficult so I won't get into the details of it. If you are concerned about a language's translation being really long and taking up too much screen space, here is where you could write some code that will check "Is this string length excessively long?" If so, shrink the font size.

The next step is to write a "procedural design" system. This basically takes the dimensions of the string from the previous step and then creates a button object based on that. Depending on how complex your game's GUI is, this could be either really easy or really difficult. Assuming you are using OpenGL, you can create a button of custom size by procedurally generating a VBO like this:

```
    /* Top Left */
    // Pos
    vertices[0] = -dimensions.x;
    vertices[1] = dimensions.y;
    // TexCoord
    vertices[2] = 0;
    vertices[3] = 0;

    /* Top Right */
    // Pos
    vertices[4] = dimensions.x;
    vertices[5] = dimensions.y;
    // TexCoord
    vertices[6] = 1;
    vertices[7] = 0;

    /* Bottom Right */
    // Pos
    vertices[8] = dimensions.x;
    vertices[9] = -dimensions.y;
    // TexCoord
    vertices[10] = 1;
    vertices[11] = 1;

    /* Bottom Left */
    // Pos
    vertices[12] = -dimensions.x;
    vertices[13] = -dimensions.y;
    // TexCoord
    vertices[14] = 0;
    vertices[15] = 1;

    elements[] = { 0, 1, 2, 2, 3, 0 };

```

Note: This assumes you are using glDrawElements(GL\_TRIANGLES).

If you are concerned about getting the button to look interesting, remember that because of how texture coordinates work in OpenGL, the image will stretch to the size of the button. This usually works for when the buttons don't end up stretching too much, so the visual artifacts aren't very visible. However, if this produces too obvious of an effect, you can implement a more complicated texturing system so that you repeat the texture rather than stretching it. Or even make it so that you repeat the middle of the texture (the body of the button) but don't tile the ends of the button. This would probably produce the most natural effect, however it may not be necessary depending on the requirements of your GUI.

You can probably use similar code/techniques in applying this to other parts of your GUI system, but you will probably have to change how you calculate the dimensions if you are not making a button with text on it. Additionally, if you want a GUI element that changes size dynamically (eg a text box that expands as the player types), keep in mind you will have to dynamically rewrite the gui's vbo. Make sure you use GL\_DYNAMIC\_DRAW for dynamic elements.

Good Luck! Have fun coding and learning!

---
Tags: gui
---


# Question
Title: How can i play animationclip from array of AnimationClip?
The original goal is to switch and play each time animation from the Animator. But not sure if it's possible so i'm trying to play it as animation clips.

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

public class SwitchAnimations : MonoBehaviour
{
    private Animator animator;
    private int index = 0;

    static UnityEditor.Animations.AnimatorController controller;

    // Use this for initialization
    void Start ()
    {
        animator = GetComponent<Animator>();

        GetStateNames(animator);

    }

    // Update is called once per frame
    void Update ()
    {
        if (Input.GetKeyDown(KeyCode.A))
        {
            if (++index == controller.animationClips.Length)
                index = 0;
            Animation clip = controller.animationClips[index];

        }
    }

    private static UnityEditor.Animations.AnimatorState[] GetStateNames(Animator animator)
    {
        controller = animator ? animator.runtimeAnimatorController as UnityEditor.Animations.AnimatorController : null;
        return controller == null ? null : controller.layers.SelectMany(l => l.stateMachine.states).Select(s => s.state).ToArray();
    }
}

```

What i want is to switch between the animation and each time i switch by pressing A it will play the current animation clip.

I'm getting error on the line:

```
controller.animationClips[index];

```

Cannot implicitly convert type 'UnityEngine.AnimationClip' to 'UnityEngine.Animation'

---

Update this is how i'm playing the Animator States:

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

public class SwitchAnimations : MonoBehaviour
{
    private Animator animator;
    private List<AnimationClip> myAnimationComponent = new List<AnimationClip>();
    private int index = 0;
    private static UnityEditor.Animations.AnimatorController controller;
    private UnityEditor.Animations.AnimatorState[] an;

    // Use this for initialization
    void Start()
    {
        animator = GetComponent<Animator>();
        myAnimationComponent = new List<AnimationClip>();

        an = GetStateNames(animator);

        for (int i = 0; i < controller.animationClips.Length; i++)
        {
            myAnimationComponent.Add(controller.animationClips[i]);
        }
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.A))
        {
            animator.Play(an[index].name);
            if (++index == an.Length)
                index = 0;
        }
    }

    private static UnityEditor.Animations.AnimatorState[] GetStateNames(Animator animator)
    {
        controller = animator ? animator.runtimeAnimatorController as UnityEditor.Animations.AnimatorController : null;
        return controller == null ? null : controller.layers.SelectMany(l => l.stateMachine.states).Select(s => s.state).ToArray();
    }
}

```

# Answer
I would use GetKeyUp when cycling the anims. If you don't want to use the controller in the animation tab you can assign the clips from a array using `anim.Play(ac[index].name);`

```
public AnimationClip[] ac;
Animator anim;
int index = 0;
void Start () {
    anim = GetComponent<Animator>();
}
void Update () {
    if(Input.GetKeyUp(KeyCode.A))
    {
        anim.Play(ac[index].name);
        if (++index == ac.Length)
            index = 0;
    }
}

```
> 1 votes

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


# Question
Title: How feasible is it to integrate a personality system such as the MBTI into a game?
Specifically, how difficult would it be for an indie developer to implement a system similar to the MBTI so that the player character's dialogue, actions, and choices will change, according to the assigned MBTI type?

This may be limited to the snarkiness of the player character's responses, the character being more reluctant to go to a social event, how well the character will respond to criticism, etc.

It would help to reference games that have done this or something similar.

EDIT: For those that don't know, the Meyers Briggs Type Indicator is a way of measuring someone's personality based on 5 variables, (the last of which is usually ignored) in order to get 16 (or 32, including the last variable) different archetypes.

**E**xtraversion vs. **I**ntroversion determines if you 'regain energy' by interacting with others, being the centre of attention, etc. or by being alone, doing such activities as walking, reading, and introspection.

**S**ensing vs. i**N**tuition determines if you prefer to absorb new information by focusing on facts, statistics, and details, preferring ideas with practical applications, or imagining the possibilities, exploring concepts for their own sake, and looking at deeper meaning.

**T**hinking vs. **F**eeling determines if you make decisions using logic, value justice, enjoy finding flaws and playing devil's advocate, or base decisions on personal values, and are more about how things *should* be.

**J**udging vs. **Perceiving** determines if you use **T**/**F** attributes to interact with the world around you, or **S**/**I** attributes.

Perception tends to make people want to keep their options open, and make external dealing decisions on the spot, rather than in advance, while Judging tends to be linked to making a plan and sticking with it.

Then, there's **A**ssertive vs. **T**urbulent, which determines confidence in decisions. Assertive individuals supposedly are less affected by stress, which has the side effect of it not affecting their performance that much, whereas Turbulence is related to perfectionism, completionism, and panicking.

People cannot be fitted neatly into 32 different categories, as many people are near the centre for some of the variables, and it is therefore better to consider these archetypes than actual categories that everyone falls into. If as well as left and right there was also a 'middle ground' classification, instead of 32 personalities, there would be 243.

The personality system in question would not have to be the Meyers Briggs, and indeed it probably should deviate from it in a few areas for copyright reasons. The purpose of giving the PC an in-game personality is so that the player can relate to them, not so they can emulate the player, so the Forer effect actually works in the Game Designer's favour.

How feasible is it, therefore, to integrate a system such as this into a game such as an RPG?

# Answer
Firstly, you should know that the Myers-Briggs Type Indicator is a proprietary system - if you wanted to use exactly this system in your game you'd need to license it from the foundation that commercializes it. (It's also, in terms of scientific validity, kind of bunk \- it's popular mainly due to effective promotion and application in flashy motivation programs, rather than for any accuracy or even internal consistency).

Other, open/non-commercial, and better-vetted models of personality exist, with some already being applied in game development.

The broader idea of establishing a personality type for the player / their character through early choices in the game and using that to steer future outcomes is certainly viable.

In Interactive Fiction games and those that focus on branching narrative, this is called the "sorting hat" choice structure, with the initial choices often referred to as a "personality quiz," establishing internal variables called "personality stats" to control branching down the line. Choice of Games' style and their ChoiceScript format emphasize this use of stats.

Tooling around the IF links above, you'll find tons of advice for choosing effective personality stats, setting them, and using them for interesting branching structures and variability in your game.

Silent Hill: Shattered Memories is one example I know of a larger-scope game using this approach. There, the player goes through a literal psychological exam, answering a therapist's questions and filling in a questionnaire, which ultimately determines what they'll encounter later in the game. Morality & alignment systems common in RPGs like Neverwinter Nights could also be considered a simple form of personality metric, with actions your character takes shifting their position on a scale that can be used to selectively offer / hide particular dialogue & quest options or change NPC reactions toward you.

The MBTI example illustrates a helpful bias we have as humans, called the Forer effect: when we are told that a particular outcome was tailored specifically for us based on our individual responses, we tend to read into it the things we identify with, and subjectively rate it as much more personally accurate than if we'd seen exactly the same outcome but without this framing. So, you don't need to get carried away with extremely granular choices and thousands of varied outcomes - as long as you do a good job conveying the *idea* of an individually personalized character, your underlying model can be relatively simplistic and still deliver a compelling positive player experience.
> 35 votes

# Answer
As DMGregory pointed out, the Myers-Briggs Type Indicator system has some problems both legally and scientifically. But my answer should be applicable to any personality system which uses two or more axis' to categorize people. Whether or not such systems have merit would be a topic for cogsci.SE. But we game developers always oversimplify complex real-world systems into simplified models so we can build comprehensible game mechanics around them. So let's roll with it.

---

To make the players MBTI category affect their responses, you simply have a set of responses for each situation and a bunch of if-statements to decide which one to use. It might be difficult to come up with 16 different phrases for every possible situation, so in some situation you might only decide based on one or two of the four different cognitive learning styles mentioned by Myers and Briggs.

However, keep in mind that most games are about making decisions during the game, not making one decision at the beginning and then seeing how it plays out. That's why many RPGs which have some character personality mechanic use a different approach:

* Don't start with a defined character personality. Form it over the course of the game, based on the player's choices during decisions. For example, when the player chooses the answer "Would you like to join me?" they get +1 Extroverted. When the say "I prefer to go alone" they get +1 Introverted. Those scores then later affect their character's abilities and/or the story of the game.
* Have the character's personality affect what options they have over the course of the game. For example, when the player picked the character type "INTJ" and they have to make a decision, you give the player one option which represents introversion, one which represents intuition, one which represents thinking and one which represents judging. That means you need at most 8 options per decision.

Pillars of Eternity combines those two mechanics. Choosing personality-specific dialog options gives you points in that personality-direction, and having a lot of those points later in the game unlocks special dialog choices which might have more beneficial (or at least more interesting) results than the neutral options.

Now the hard part is dealing with the explosive combination of so many options. If you have 4 possible options per decision, and you let the player make 10 such choices, you end up with 4 to the power of 10 = over a million possible combinations. The number of possible outcomes increases exponentially with the number of decisions to make. Writing an unique story for each leaf of this huge decision tree is impossible. To keep the development scope bearable, you have to prune some of these branches. These are some techniques you can use:

* Localize the effect of decisions. Have a choice affect one future event, and then never mention it again.
* Fake it. Have multiple options result in the same effect. A decision might have 3 options which turn out as "yes" and 5 which turn out as "no" and then only take into account if the player picked a "yes" or a "no" option. You can even have decisions which do not actually affect the story at all and serve no purpose but to give the player the illusion of a meaningful decision. Bethesda does this a lot in the 3d Fallout Games. Whenever the player-character is about to say *anything*, the player has to pick between exactly 4 options. But more often than not they do not even affect the next sentence by the NPC (and sometimes not even the sentence spoken by the PC).
* Aggregate decisions. Use a points system where points are added or subtracted based on choices during multiple decision and then later branch the story based on the total score. This can be how much the player is following a specific personality archetype, but can also be entirely separated from it, like how much an NPC likes the PC.
> 3 votes

# Answer
Instead of issuing a test, why not present a chart of stereotypical characters to choose from, and let the user play as that character with that personality set? It can be presented like these charts:

https://www.google.com/search?tbm=isch&q=mbti%20characters&tbs=imgo:1#imgrc=\_

With your characters, or it can have several well-known archetypes for each category. However I would recommend the 4 major functions to keep it simple: SJ, SP, NT, NF.

I've created psychometric personality tests before (specifically for Big5). If you really want a test, for MBTI, you will need 4 scales (E/I, N/S, T/F, P/J) and a bunch of questions which measure a score on that scale. For example, 10 questions for E/I like "Do you like parties?"; "Do you get energy from large crowds?"; etc. Add up the scores, 1=YES, 0=NO, and you will get a 0-10 sum for each scale. If they score 7, then round to Extrovert category (5+). That is how to create a test. (If you need more stringent validity you can mix in true/false questions that everyone answers the same to filter random choice, and you can randomize the questions also.)
> 0 votes

---
Tags: ai, character
---


# Question
Title: How to make my Diamond-Square-algorithm less 'random'?
I'm currently writing a world generator for a Tilemap-Engine in C++. But there is a little problem concerning the Water to Land ratio. My DiamondSquare-class returns a field of random float-values between 0 and 1, and my condition to let my tilemap-class generate a Land-Tile on the given spot, is that the returned value is bigger than 0.5. The problem is, that the amount of values bigger or smaller than 0.5 fluctuates with every call of my float-field-generation function, so that i often only have a few little Islands/a few little lakes on my map. How could i manipulate my code, so that a 50/50 distibution is more likeley to happen?

```
include "DiamondSquare.h"
include <Windows.h>
pragma comment (lib, "winmm.lib")
floatfield /*typedef floatfield is std::vector<std::vector<float>>*/ DiamondSquare::generate(int n, float randomness) {

// Initializing stuff
srand(timeGetTime());
fieldSize = pow(2,n)+1;
randField.resize(fieldSize);
for (int i=0; i<fieldSize; i++)
{
    randField[i].resize(fieldSize);
    for (int j=0; j<fieldSize; j++)
    {
        randField[i][j] = 0;
    }
}
stepDist = pow(2, n-1);
m_randomness = randomness;

// Setting corner point values
randField[0][0] = (float)(rand()%1001)/1000;
randField[fieldSize-1][0] = (float)(rand()%1001)/1000;
randField[0][fieldSize-1] = (float)(rand()%1001)/1000;
randField[fieldSize-1][fieldSize-1] = (float)(rand()%1001)/1000;

// Core Algorithm
for (int i=0; i<n; i++)
{
    for (int k=0; k<pow(2,i); k++)
    {
        for (int l=0; l<pow(2,i); l++)
        {
            // Getting position of current tile
            int xPos = k*2*stepDist+stepDist;
            int yPos = l*2*stepDist+stepDist;
            // Getting Average of sorrounding tiles
            randField[xPos][yPos] = (randField[xPos-stepDist][yPos-stepDist]+randField[xPos+stepDist][yPos-stepDist]+
                                      randField[xPos+stepDist][yPos+stepDist]+randField[xPos-stepDist][yPos+stepDist])/4;
            // Random displacement
            if (rand()%2 == 1)
                randField[xPos][yPos] += (float)(rand()%1001)/1000/pow(randomness,i+1);
            else randField[xPos][yPos] -= (float)(rand()%1001)/1000/pow(randomness,i+1);

            // Doing the same for the Square-Step tiles left of and above     the current tile
            squareAvg(xPos-stepDist, yPos, i);
            squareAvg(xPos, yPos-stepDist, i);

            // If diamond-step-tile is part of the right side row
            if (k == pow(2,i)-1)
                squareAvg(xPos+stepDist, yPos, i);
            // If diamond-step tile is part of the bottom row
            if (l == pow(2,i)-1)
                squareAvg(xPos, yPos+stepDist, i);
        }
    }
    stepDist /= 2; // Self explanatory
}
return randField; // Return random field.
[![Often, insted of maps like this, there is stuff like 10% water or 10% land][1]][1]}

void DiamondSquare::squareAvg(int x, int y, int i) {
// Testing if square-Tile lies at on of the sides of the map, if so, adding         0 (i tried implementing wrapping, but this option generated better looking     landscapes)
randField[x][y] = (x!=0) ? randField[x-stepDist][y] : 0;
randField[x][y] += (x!=fieldSize-1) ? randField[x+stepDist][y] : 0;
randField[x][y] += (y!=0) ? randField[x][y-stepDist] : 0;
randField[x][y] += (y!=fieldSize-1) ? randField[x][y+stepDist] : 0;
// If 4 values were added /= 4, otherwise /=3.
if (x!=0 && x!=fieldSize-1 && y!=0 && y!=fieldSize-1)
    randField[x][y] /= 4;
else randField[x][y] /= 3;
// Displacement
if (rand()%2 == 1)
    randField[x][y] += (float)(rand()%1001)/1000/pow(m_randomness,i+1);
else randField[x][y] -= (float)(rand()%1001)/1000/pow(m_randomness,i+1);
}

```

Is it maybe even possible to preciseley control n\<0.5 to n\>0.5 ratio ? That would be ideal. I just don't know how and where to manipulate the code. That's about it.

# Answer
While creating the height values, calculatevthe average of them, this can be done in two ways: either save them in an array, get their sum and divide it with the count or simply have an average and every time you get a new height value add `value / count` to the average.

The average should be the water level, this is the closest you can get to 50-50%
> 1 votes

# Answer
When I want to adjust the proportions of different terrain types that occurs in a fractal I use this function:

```
    List<float> getCutOffLevels(float[,] map, float[] levels)
    {
        float[] mapValues = new float[map.Length];
        System.Buffer.BlockCopy(map, 0, mapValues, 0, sizeof(float)*map.Length);
        Array.Sort(mapValues);
        float levelSum = 0;
        foreach(float a in levels){
            levelSum+=a;
        }
        List<float> cutOffLevels = new List<float>();
        float t = 0;
        for (int i=0;i< levels.Length-1;i++)
        {
            cutOffLevels.Add(mapValues[(int)Math.Floor(mapValues.Length * t / levelSum)]);
            t += levels[i];
        }
        return cutOffLevels;
    }

```

The function takes the fractal as input in addition to an array containing the proportions of the different terrain types. Say, for example you want two regions at an 2:1 ratio, you input an array with values 2 and 1. The output is a list containing the values of the of the fractal at the border between regions. The first region has values greater than than the first item in the list, the second region greater than second value, and so forth.
> 0 votes

# Answer
You can subtract .5 and then divide your outcome by something to decrease the spread and then add .5
> -1 votes

---
Tags: algorithm, procedural-generation, tilemap, maps, content-generation
---


title: Limit the grid fill

text:
# Question
Title: Limit the grid fill
I'm doing some grid snapping and I wanted to fill out my grid on the gameObject surface. However I can't figure out the math on how to limit the grid fill. Here's the snippet:

```
private void Values()
{
    sizePlace.y = baseGrid.transform.localScale.y / sizeGridX;
    sizePlace.z = baseGrid.transform.localScale.z / sizeGridZ;
    sizePlace.x = baseGrid.gameObject.GetComponent<MeshRenderer>().bounds.size.x*1.6f;

    gridPosition.y = (baseGrid.transform.localScale.y / 2) - (sizePlace.y / 2);
    gridPosition.z = (baseGrid.transform.localScale.z / 2) - (sizePlace.z / 2);
    gridPosition.x = baseGrid.transform.position.x;

    startGridPosition = gridPosition;
}

```

baseGrid is the gameObject surface and Place is basically a flat cube where I made it as a grid. The picture below illustrate my problem.

No matter how many grids in the game, the grid will resize itself and they will always spawned exceeded the wall size. I'm not very good at math and stuff so if someone could guide me, I would be glad. Thanks thanks thanks!

UPDATE: Ok I managed to limit the fill but I don't know why they won't cover all the area of the wall. ((

Here's the updated code:

```
sizePlace.y = baseGrid.gameObject.GetComponent<MeshRenderer>().bounds.size.y / sizeGridX;
    sizePlace.z = baseGrid.gameObject.GetComponent<MeshRenderer>().bounds.size.y / sizeGridZ;
    sizePlace.x = baseGrid.gameObject.GetComponent<MeshRenderer>().bounds.size.x*1.6f;

    gridPosition.y = (baseGrid.gameObject.GetComponent<MeshRenderer>().bounds.size.y / 2) - (sizePlace.y / 2);
    gridPosition.z = (baseGrid.gameObject.GetComponent<MeshRenderer>().bounds.size.z / 2) - (sizePlace.z / 2);
    gridPosition.x = baseGrid.transform.position.x;

    startGridPosition = gridPosition;

```

# Answer
Ok what a silly mistake I did, my sizePlace.z is calculated using `baseGrid bound.size.y` instead of `bound.size.z`. Problem solved.

```
sizePlace.z = baseGrid.gameObject.GetComponent<MeshRenderer>().bounds.size.z / sizeGridZ;

```
> 1 votes

---
Tags: unity, c#, transformation, grid
---


# Question
Title: Switching from one solution to another in visual sudio
I have been able to bring a number of projects together like this:

But now, whenever I try to switch from "Bitmap Loading and Drawing" sln(do realize bold letters) to another sln, I am unable to do so.

I even tried to click on another sln's file. It does come out but if I try to build the latter sln file... the former sln gets built.

what is the correct way to switch from one solution to another?

Thanks in advance.

# Answer
> 1 votes
To "switch" between projects in vs right click the project you want to switch to and choose the "Set as start up project" option

The project you are currently in or the one which will be built if you "start" is the one that is highlighted bold in the project explorer.

---
Tags: visual-studio
---


# Question
Title: MonoGame - Scale Texture2D from 16x16 to 64x64
I need to scale a Texture2D (let's say it's 16x16) to 64x64.

I tried scaling it in the SpriteBatch#Draw method, but it doesn't look like pixel art as soon as it's drawn, more like a lot of anti-aliasing happened.

I chose 64x64 because 16x16 is pretty small, and I thought I could just scale every pixel by 4 (1x1 pixel in 16x16 could be 4x4 pixels in 64x64), basically I don't want MonoGame to anti-alias when I draw the scaled Texture.

Thank you!

# Answer
You'll want to use SamplerState.PointClamp in the SpriteBatch.Begin call.

To quote this answer:

> You need to set the sampler state. The default for SpriteBatch is SamplerState.LinearClamp (ie: linear interpolation - the smooth/blurry one).
>
> Choose one of the SpriteBatch.Begin calls that takes a SamplerState and pass in SamplerState.PointClamp (selects the pixel at that precice "point").
> 1 votes

---
Tags: c#, monogame
---