title: How to make a layered health bar in GML

text:
# Question
Title: How to make a layered health bar in GML
I am currently working on a game in Game Maker Studio 2 where the player character is capable of increasing their maximum health beyond a starting value of 30, by increments of 10. I want to represent this graphically by adding a different-colored overlay to the character's health bar for each additional 10 points added, with the last layer added diminishing before the ones behind it, proportional to how much of the last "extra" 10 points remains.

If you are familiar with the Mega Man Zero games, and how some bosses in that game had extra health represented in "layered" health bars that decremented independently of and sequentially to each other, I am basically trying to make that, just using a different health increment for all layers beyond the first.

So far I can get the first layer to work out just fine:

```
draw_sprite_ext(sprite931, -1,0,0,(min(30, hp_current)/30),1,0,c_white,1);

```

but I am having some difficulty calculating the *xscale* argument for the layers representing `hp_current` values 31-40, 41-50, 51-60, etc. without causing visual glitches.

To summarize, I need the gauge to remain full if the player's current HP is equal or greater than its respective range's maximum, be empty if it is less than its increment range's minimum, and scale between empty and full proportional to where `hp_current` lies between said layer's maximum and minimum values. I am having trouble figuring out how to make each layer do this independently of each other. Does anyone else have experience with making something similar to this work?

# Answer
> 1 votes
Nevermind, I already found a crude but effective solution that serves my purposes nicely:

```
draw_sprite_ext(sprite931, 0,0,0,(min(30, global.hp_current)/30),1,0,c_white,1);
if(global.hp_max > 30)
    draw_sprite_ext(sprite931, 1,0,0,(min(10, global.hp_current - 30)/10),1,0,c_white,1);
if(global.hp_max > 40)
    draw_sprite_ext(sprite931, 2,0,0,(min(10, global.hp_current - 40)/10),1,0,c_white,1);
if(global.hp_max > 50)
    draw_sprite_ext(sprite931, 3,0,0,(min(10, global.hp_current - 50)/10),1,0,c_white,1);
if(global.hp_max > 60)
    draw_sprite_ext(sprite931, 4,0,0,(min(10, global.hp_current - 60)/10),1,0,c_white,1);
if(global.hp_max > 70)
    draw_sprite_ext(sprite931, 5,0,0,(min(10, global.hp_current - 70)/10),1,0,c_white,1);
if(global.hp_max > 80)
    draw_sprite_ext(sprite931, 6,0,0,(min(10, global.hp_current - 80)/10),1,0,c_white,1);

```

I used different frames of the same sprite to represent the different-colored layers of the health bar, just to clarify.

# Answer
> 1 votes
**TL;DR**
Sample code solution is the very last one at the bottom of this answer. Here is a small in-depth explanation of such code.

---

I've worked on a personal project in which I implemented exactly what you are looking for. In my scenario, I had to draw a bar representing the player character's shield points (instead of HP), and the shield was capable of reloading and even increase over the normal maximum, in a Halo-like way.

My strategy was simple: the variable in charge of storing HP value was one only to keep the game logic simple, while the *Draw Event* code drew overlayed healthbars of different colors for each base quantity a full gauge could represent.

**Simple solution**
Let `hp_gauge` be the amount of HP a full healthbar can represent, 30 in our case − using a *constant* or a local variable rather than hard-coded values is slight better practice and more convenient. Since each bar represents intervals, we can draw each bar by telling them how much wide they must be related to their assigned interval:

```
// Support value
var hp_gauge = 30;
// First bar (interval 0-30)
draw_sprite_ext(sprite931,-1,0,0,(clamp(hp_current-2*hp_gauge,0,hp_gauge)/hp_gauge),1,0,c_red,1);
// Second bar (interval 31-60)
draw_sprite_ext(sprite931,-1,0,0,(clamp(hp_current-hp_gauge,0,hp_gauge)/hp_gauge),1,0,c_yellow,1);
// Third bar (interval 61-90)
draw_sprite_ext(sprite931,-1,0,0,(clamp(hp_current,0,hp_gauge)/hp_gauge),1,0,c_green,1);

```

When subtracting `hp_gauge` once or twice, we are telling each bar to draw their amount *assuming* the rest of HP will be drawn later by other functions. E.g. if HP is 70, we'll draw a full red bar, then a full yellow bar, finally a foreground green bar scaled at 33%. Also, the function `clamp()` forces the returned value between 0 and 30 for us.

However this method forces us to code the drawing functions for every single gauge that can be drawn − this very snippet assumes maximum HP can be 90. Also, we may draw two or more full bars on top of each other, seeing only the last one while the others would be overdrawn and not visible, and thus wasting CPU time and resources.

**Some optimization ideas**
Instead of drawing every single healthbar, we can work this out in another way; first, we can find two useful values by using `mod` and `div` expressions:

* Number of full gauges that can be completely filled by the current health value:

`var bars = hp_current div hp_gauge;`

* Amount of HP that should be represented with a partial (not full) healthbar:

`var hp_partial = hp_current mod hp_gauge;`

For example, if the player's HP is 70, the previous values will be: `bars` = 70 `div` 30 = 2; and `hp_partial` = 70 `mod` 30 = 10. This means there are two full healthbars to be drawn (2 * 30 = 60 total HP), plus a third bar scaled to represent the remaining 10 HP.

The meaning of `hp_partial` is obvious, these are the points the top scaled bar must represent:

```
// Foreground bar (unknown intervals)
draw_sprite_ext(sprite931,-1,0,0,(hp_partial/hp_gauge),1,0,c_white,1);

```

Note that here the `xscale` value depends on the value of `hp_partial`. On the other hand, `bars` tells us how many healthbars virtually lie below our front partial bar (and we need to draw just one bar only):

```
// Background bar (unknown intervals)
if (bars>0)
    draw_sprite_ext(sprite931,-1,0,0,1,1,0,c_white,1);

```

Note that here `xscale` is 1 because we *know* this bar must be drawn entirely, since `hp_current` is greater than `hp_gauge`. Of course, the background bar must be drawn **before** the foreground one.

Now that we can draw our bars, how can we deal with colors to give the player an idea of the amount of remaining health? We can solve this issue by using an array to store the colors we want to use for our gauges:

```
// Colors
barColor[0] = c_red;
barColor[1] = c_yellow;
barColor[2] = c_green;

```

If `bars` is 0, we draw only the scaled bar, whose color may be red for example. If `bars` is 1, we have an extra HP gauge, so the bottom one will be red and the top one yellow (respectively indexed as `bars-1` and `bars`). With this last trick, we can draw our healthbars as follows:

```
// Healthbar colors
barColor[0] = c_red;
barColor[1] = c_yellow;
barColor[..] = ...;    // this array is up to you
// Background bar
if (bars>0)
    draw_sprite_ext(sprite931,-1,0,0,1,1,0,barColor[bars-1],1);
// Foreground bar
draw_sprite_ext(sprite931,-1,0,0,(hp_partial/hp_gauge),1,0,barColor[bars],1);

```

This way you can use as many colors as you wish for different health levels, or even change the code to use the `[merge_color()][3]` function for fancier visual effects, although you must care about `bars` as an array index not to be out of bounds.

**Alternative to using the `barColor[]` array**
Since `bars` tells us what color the healthbar must be, we can get rid of the `barColor[]` variable and using a multi-frame sprite, each frame colorized as needed (e.g. frame 0 is red, frame 1 is yellow, ...); finally, we choose what frame to draw instead of picking a color:

```
// No healthbar colors here
// Background bar
if (bars>0)
    draw_sprite_ext(sprite931,barColor[bars-1],0,0,1,1,0,c_white,1);
// Foreground bar
draw_sprite_ext(sprite931,barColor[bars],0,0,(hp_partial/hp_gauge),1,0,c_white,1);

```

Hope this answer helps, sorry if too long.

---
Tags: mathematics, gui, game-maker
---


# Question
Title: Having trouble with foreach loop affecting anything past the first object found
I have been trying to disable `isTrigger` in unity c# script on all GameObjects containing a certain tag. Currently my code works and disables the isTrigger part of the box collider, but it only does this for the first object with the tag I am looking for do this for all objects.

Here is the code:

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

public class DefenseCollisionTrigger : MonoBehaviour {

    public static Rigidbody rb;
    public bool CanBePlaced;
    public GameObject[] defenseTriggers;

    void Start ()
    {
        CanBePlaced = true;
        defenseTriggers = GameObject.FindGameObjectsWithTag("Defense");
    }

    public void OnTriggerEnter (Collider other)
    {
        if (other.tag == "Defense")
        {
            CanBePlaced = false;
        }
    }

    public void OnTriggerExit(Collider other)
    {
        if (other.tag == "Defense")
        {
            CanBePlaced = true;
        }
    }

    public void IsTriggerFalse()
    {
        foreach (Object dt in defenseTriggers)
        {
            Debug.Log("working on it");
            GetComponent<Collider>().isTrigger = false;
        }
    }
}

```

That is what is currently looks like. The `public void IsTriggerFalse()` is called on each time I go to instantiate an object with my mouse button. The Debug.Log is working and printing to the console. This is the closest I have came to making it work, but it only works for the first object. I have searched for hours and watched videos/looked at unity docs on foreach statements with no luck to my issue. I have also tried `using foreach (GameObject dt in defenseTriggers)` instead of just Object.

Anyone know how to solve my issue?

# Answer
> 0 votes
Well, I found the Answer. Not sure how good this is for performance or if it is advised against, but it is working for me!

I had to put the line

```
defenseTriggers = GameObject.FindGameObjectsWithTag("Defense");

```

into my IsTriggerFalse(); area so that it checks for the objects that were being instantiated. Thank you Byte56 for showing me that they weren't being recognized since they were not there at the time of the Start() call.

# Answer
> 1 votes
It's actually only working on the Object that's calling the code.

```
foreach (Object dt in defenseTriggers)
{
    Debug.Log("working on it");
    GetComponent<Collider>().isTrigger = false;
}

```

Is the same as:

```
foreach (Object dt in defenseTriggers)
{
    Debug.Log("working on it");
    this.GetComponent<Collider>().isTrigger = false;
}

```

Notice the `this.`. Meaning, for each object, you're getting the collider on the **current object** and setting it's `isTrigger` to false.

What you really want is something like this:

```
foreach (GameObject dt in defenseTriggers)
{
    Debug.Log("working on it");
    dt.GetComponent<Collider>().isTrigger = false;
}

```

# Answer
> 0 votes
Well I think you forgot to reference the ***dt*** Object in core operation.

```
public void IsTriggerFalse() {
    foreach (Object dt in defenseTriggers) {
        Debug.Log("working on it");
        dt.GetComponent<Collider>().isTrigger = false;
    }
}

```

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


title: How to import the Sanford Midi Library?

text:
# Question
Title: How to import the Sanford Midi Library?
I am trying to parse a MIDI file using the Sanford MIDI Toolkit. How do I use this toolkit? I found this link on Github:

https://github.com/tebjan/Sanford.Multimedia.Midi

I downloaded the .zip file and saved it on my desktop. Afterwards, how should I proceed? This may be a beginner question, but how do I start using this library?

Do I need to save it in a particular location in my computer? Ultimately I just want to be able to have access to the functions, properties, etc. of this library.

# Answer
> 0 votes
After some trial and error, I figured it out.

In order to expose the methods and properties of the library, I copied the DLL file found in Sanford.Multimedia.Midi-master/Source/bin/Debug to the GAC folder and then added a reference to the DLL in my project.

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


# Question
Title: how to check a condition for too many objects in a list that you dont know count of them
I'm working on a defense game that I need a way of knowing if every enemy in a wave is dead. I wanted to use a counter for it:

```
foreach (GameObject g in group1)
{
    if(g == dead) {
        deadCount++;
    }
}
if(deadCount == allEnemiesInWave)
{
    goToNextWave();
}

```

but I think it's not a safe or accurate way. Is there any better way?

Edit: This question is not like Check if all gameobjects are destroyed. In my question, I wanted to make a condition on many objects, in the other one, OP wanted to check if such objects existed.

# Answer
> 3 votes
If you don't need to count them, don't count them. Although it does not hurt to count them and compare with the size of the list, you can achieve the same thing with a boolean variable (pseudo-code):

```
bool areAllDead = true;
foreach (GameObject g in group1)
{
  if (g != dead)
  {
    areAllDead = false;
    break;
  }
}

if (areAllDead)
{
  goToNextWave();
}

```

This code is a bit more explicit with it's intention.

In either cases, this will be unsafe if the code within the loop changes the size of your `group1`.

---
Tags: unity
---


# Question
Title: Using 2D std::vector for map and collision
Hello to anyone reading this. I am having trouble on how to use std::vector. From what I know, std::vector is a flexible version of an array and iterator is used to go through each individual element within a vector.

```
std::vector<std::vector<int>> row;
std::vector<int> column;
//This is equivalent to... (?)
int array[i][j];

```

So what if I wanted to use a 2D std::vector for a tilemap?

```
std::vector<std::vector<int>> row;
std::vector<int> column;

for (int i = 0; i < row.size(); ++i) {
    for (int j = 0; j < row[i].size(); ++j) {
    //something with map
    }
}

for (itr = row.begin; != row.end(); ++itr) {
    //something with each block of the map?
}

```

Sorry if the code is incomplete or wrong. I can't seem to understand the standard format of std::vector and using an iterator.

Thank you to those willing to help.

# Answer
The 'equivalent' of a 2d array for a vector of vector is something like this:

```
std::vector<std::vector<int>> mTileMap;

```

You can add values to it like this:

```
int numRows = 4;
int numCols = 6;

for ( int y = 0; y < numRows; ++y ){
  mTileMap.push_back( std::vector<int>() );
  for ( int x = 0; x < numCols; ++x ){
    mTileMap[y].push_back( /* your tile will be added here*/ );
  }
}

```

You can use that method if all the values for the map are different.

A simpler way to only allocate your map would be to tell it the sizes at construction:

```
int defaultTileValue = 0;

std::vector<std::vector<int>> mTileMap( numRows,
  std::vector<int>( numCols, defaultTileValue ) );

```

or

```
mTileMap = std::vector<std::vector<int>>( numRows,
  std::vector<int>( numCols, defaultTileValue ) );

```

With that method, you lose the possibility to set a specific value for each tile. You can use the iteration methods described below to do that.

And you access it this way:

```
for ( int y = 0; y < mTileMap.size(); ++y ) {
  for ( int x = 0; x < mTileMap[y].size(); ++x ) {
    std::cout <<
      "TileMap value at row " << y <<
      " column " << x <<
      " is " << mTileMap[y][x] << "\n";
    }
}

```

If you want to use iterators, you can get go through each element like this:

```
for ( auto& itRow : mTileMap  )
{
    for ( auto& itCol : itRow )
    {
        std::cout << "TileMap value is " << itCol << "\n";
    }
}

```

The iterator version allows you to go through each element, but you lose the concept of 'index' for your x and y. It's ok for some situations, but for some other situations, an iterator won't do and you'll have to use the first version.

---

Note that the above is a very naive way to create and use a 2d vector. It works and it is easy to understand, but it's not very efficient, specially if the data is to be used and iterated over often.

You might be interested in a single vector that contains all your data.

```
// In header
const int numRows = 4;
const int numCols = 6;

int getFlatVectorIndex( int aIndexX, int aIndexY ) { return ( numCols * aIndexY ) + aIndexX;}

std::vector<int> mTileMap;

// This is the initialization code:
mTileMap.resize( numRows * numCols );

for ( int y = 0; y < numRows; ++y ){
  for ( int x = 0; x < numCols; ++x ){
    mTileMap[getFlatVectorIndex( x, y )] = /* your tile will be set or accessed here */;
  }
}

```

The reason why this implementation is better is because all your data are close together in memory, allowing you to benefit from Data Locality.

---

*Disclaimer: I don't have access to my compiler to make sure this works for now.*
> 2 votes

---
Tags: c++, sfml
---


# Question
Title: How to avoid hard coding in game engines
My question isn't a coding question; it applies to all of game engine design in general.

How do you avoid hard coding?

This question is a lot deeper than it seems. Say, if you want to run a game that loads the files necessary for operation, how do you avoid saying something like `load specificfile.wad` in the engine's code? Also, when the file is loaded, how do you avoid saying `load aspecificmap in specificfile.wad`?

This question applies to pretty much all of engine design, and as little as possible of the engine should be hard coded. What is the best way to achieve that?

# Answer
**Data-driven coding**

Every thing you mention is something that can be specified in data. Why are you loading `aspecificmap` ? Because the game configuration says that is first level when a player starts a new game, or because that's the name of the current save point in the player's save file they just loaded, etc.

How do you find `aspecificmap` ? Because it's in a data file that lists map ids and their on-disk resources.

There need only be a particularly small set of "core" resources which are legitimately hard or impossible to avoid hard-coding. With a bit of work, this can be limited to a single hard-coded *default* asset name like `main.wad` or the like. This file can potentially be changed at runtime by passing a command-line argument to the game, aka `game.exe -wad mymain.wad`.

Writing data-driven code relies on a few other principles. For instance, one can avoid having systems or modules ask for a particular resource and instead invert those dependencies. That is, don't make `DebugDrawer` load up `debug.font` in its initialization code; instead, have `DebugDrawer` take a resource handle in its initialization code. That handle might be loaded from the main game configuration file.

As a concrete examples from our codebase, we have a "global data" object that is loaded from the resource database (which itself is by default the `./resources` folder but can be overloaded with a command line argument). The resource databse ID of this global data is the only necessary hard-coded resource name in the codebase (we have others because sometimes programmers get lazy, but we generally end up fixing/removing those eventually). This global data object is full of components whose sole purpose is to provide configuration data. One of the component is the UI Global Data component which contains resource handles to all the main UI resources (fonts, Flash files, icons, localization data, etc.) among a number of other configuration items. When a UI developer decides to rename the main UI asset from `/ui/mainmenu.swf` to `/ui/lobby.swf` they just update that global data reference; no engine code needs to change at all.

We use this global data for everything. All the playable characters, all the levels, UI, audio, core assets, network configuration, everything. (well, not *everything*, but those other things are bugs to be fixed.)

This approach has a lot of other advantages. For one, it makes resource packing and bundling integral to the whole process. Hard-coding paths in the engine also tends to be mean that those same paths have to be hard-coded in whatever scripts or tools package up game assets, and those paths can then get out of sync. Relying instead on a single core asset and reference chains from there, we can build an asset bundle with a single command like `bundle.exe -root config.data -out main.wad` and know that it will include all the assets we require. Further, since the bundler would just be following resource references, we know that it will include *only* the assets that we require and skip all the left-over fluff that inevitably accumulates over the life of a project (plus we can automatically generate lists of that fluff for pruning).

A tricky corner case of this whole thing is in scripts. Making the engine data-driven is easy conceptually, but I've seen so very many projects (hobby to AAA) where scripts are considered data and hence are "allowed" to just use resource paths indiscriminately. Don't do that. If a Lua file needs a resource and it just calls a function like `textures.lua("/path/to/texture.png")` then the asset pipeline is going to have a lot of trouble knowing that the script requires `/path/to/texture.png` to operate correctly and might consider that texture to be unused and unnecessary. Scripts should be treated like any other code: any data they need including resources or tables should be specified in a configuration entry that the engine and resource pipeline can inspect for dependencies. The data that says "load script `foo.lua`" instead should say "load `foo.lua` and give it these parameters" where the parameters include any resources necessary. If a script randomly spawns enemies for example, pass the list of possible enemies into the script from that configuration file. The engine can then pre-load the enemies with the level (since it knows the complete list of possible spawns) and the resource pipeline knows to bundle all the enemies with the game (since they're definitively referenced by configuration data). If the scripts generates strings of path names and just calls a `load` function then neither the engine nor resource pipeline have any way of knowing specifically which assets the script might try to load.
> 42 votes

# Answer
The same way you avoid hardcoding in general functions.

**You pass parameters and you keep your information in configuration files.**

In that situation, there is absolutely no difference in software engineering between writing an engine and writing a class.

```
MgrAssets
public:
  errorCode loadAssetFromDisk( filePath )
  errorCode getMap( mapName, map& )

private:
  maps[name, map]

```

Then your client code reads a "master" configuration file (*this one* is either hard coded or passed as a command line argument) which contains the information that tells where the assets files are and what map they contain.

From there, everything is driven by the "master" configuration file.
> 11 votes

# Answer
I like the other answers so I'm going to be a little bit contrary. ;)

You can't avoid coding knowledge about your data into your engine. Wherever the information comes from, the engine must know to look for it. However, you can avoid encoding the actual information itself into your engine.

A "pure" data driven approach would have you start the executable with the command line parameter(s) necessary for it to load the initial configuration but the engine will have to be coded to know how to interpret that information. E.g. if your configuration files are JSON, you need to hard code the variables you look for, e.g. the engine will have to know to look for `"intro_movies"` and `"level_list"` and so forth.

However, a "well-constructed" engine can work for many different games just by swapping out the configuration data and the data that it references.

So the mantra isn't so much to avoid hard coding as it is to ensure that you can make changes with the least amount of effort possible.

To contrast against the data files approach (which I wholeheartedly support), it may be that you're ok compiling the data into your engine. If the "cost" of doing so is lower, then there's no real harm; if you're the only one working on it then you can defer filehandling for a later date and not necessarily screw yourself. My first few game projects had big tables of data hardcoded into the game itself, e.g. a list of weapons and their assorted data:

```
struct Weapon
{
    enum IconID icon;
    enum ModelID model;
    int damage;
    int rateOfFire;
    // etc...
};

const struct Weapon g_weapons[] =
{
    { ICON_PISTOL, MODEL_PISTOL, 5, 6 },
    { ICON_RIFLE, MODEL_RIFLE, 10, 20 },
    // etc...
};

```

So you put this data somewhere easy to reference and it's easy to edit as necessary. The ideal would be to put this stuff into a config file of some sort but then you need to do parsing and translation and all of that jazz, plus hooking up inter-structure references might become an additional pain that you really don't want to deal with.
> 3 votes

---
Tags: architecture, cross-platform, file-format
---


title: Hand cards auto arrangement

text:
# Question
Title: Hand cards auto arrangement
I'm making a card game with libgdx scene2d and what I'm trying to achieve is auto arrange the cards in a way the all fit the screen. This is what it looks now when the hand is full:

I have done that using a horizontalGroup and puting a -1/3 cardWidth space between the cards. I want the cards to spread evenly when some are removed. I think I have to change the space between the cards whenever a card is removed or added but I don't know how much.

This is my code:

```
    CardActor[] cards = new CardActor[14];
    HorizontalGroup hand = new HorizontalGroup();
    int width = Gdx.graphics.getWidth()/10;
    int height = width * 2;
    hand.setBounds(width/2, -height/4, stage.getWidth()-width, height);
    hand.space(width / -3f);
    hand.align(Align.bottom | Align.center);
    for (int i = 0; i < cards.length; i++) {
        cards[i] = new CardActor(new Card(MathUtils.random(3), MathUtils.random(3, 10)));
        hand.addActor(cards[i]);
    }
    stage.addActor(hand);`

```

And this is the CardActor:

```
public class CardActor extends ImageButton {

public CardActor(Card card) {
    super(new TextureRegionDrawable(CardTextures
            .getTexture(card.getType(), card.getRank())));

    int width = Gdx.graphics.getWidth()/10;
    int height = width*2;
    getImageCell().prefSize(width, height);
    setBounds(getX(), getY(), getWidth(), getHeight());
    addListener(new ChangeListener() {
        @Override
        public void changed(ChangeEvent event, Actor actor) {
            onSelected();
        }
    });
}

```

# Answer
> 0 votes
I did this once, you want to start by creating a *startX* variable so that the first card is centred in the centre of the screen at any given y value (*screenWidth* / 2 - *cardWidth* / 2).

Then for each other card it's x value on screen is the \[*startX* \+ *cardWidth* / 2\] (overlapping the previous card by half, giving the desired effect).

But for each card \> 1 the *startX* must move to the left by half a card (*startXOffset* = *cardWidth* / 2 * *totalCards*. To keep the entire hand of cards centred. So the *startX* must negate the *startXOffset*.

As you add and remove cards just recalculate.

If the hand does get larger than what can fit on the screen, you will need to change the *cardWidth* overlap to be a fraction of the *totalCards* rather than just / 2 (gets smaller with each card).

**For example:**

```
for (int i = 0; i < totalCards; i++) {
       cards[i] = new CardActor(new Card(MathUtils.random(3), MathUtils.random(3, 10)));
       hand.addActor(cards[i]);
       cards[i].setX(startX - startXoffset * (totalCards - i));
}

```

Then have a method in the hand class called reorganise or something that loops through all the cards (if they are still there) and resets their X values.

I honestly don't know how I would actually implement it but its just something to give you an idea, I am not good with Java graphics so I can't provide much more.

# Answer
> 1 votes
I would comment on Daedrics answer but I don't have enough rep. His detailed explanation is great and is pretty much already handled by LibGdx's `HorizontalGroup()` widget, most of the actual layout calculations are already taken care of using the `.center()` and `.space()` methods.

What you need to do:

* Create a `HorizontalGroup()` to hold the cards in your `hand`
* Add the `CardActors` to the `HorizontalGroup hand`, by default they are just positioned at the 0,0 location of the `HorizontalGroup (bottom-left)`
* Simply call `hand.center()` to have all of the cards aligned to the center of the `HorizontalGroup`
* Now they will be centered, but not overlapping at all.
* If you set the `hand.space()` as some negative width like you already have, you will see that they overlap.

I'm not sure of the details of your game, but the static space in between may be enough, if not you can always keep a reference to your `hand` and update the `.space()` whenever you need to.

Using a static space - In your example picture, removing the left most 8 wouldn't change the spacing, but the positions of the cards in the group would be moved to the left by a half a card(all of them). If you only had 1 card, it would be in the center.

_ _ _ _ _ *C* _ _ _ _ _ .

If you had 2 cards they would be grouped in the center. (the left card will be slightly to the left of center now)

_ _ _ _ _ C C _ _ _ _ _

Using a dynamic space - In your example picture, removing the left most 8 would cause the 3 to take its place. The rightmost card 9, wouldn't move. All of the cards in between are all moved left by different amounts. So if you had 1 card in your hand it would be in the center like the previous example,

_ _ _ _ _ *C* _ _ _ _ \_,

but if you had 2 cards depending on how you calculate your spacing it may look like

_ _ C _ _ _ _ _ _ C _ _

C _ _ _ _ _ _ _ _ _ _ C

If you want to work with a static space, but are worried about when the width of the `hand` would be greater than the width of the screen, you can always tell set set `.wrap(true)` on your `hand`, and then depending on how you want them to look, change `.wrapSpace()` to your liking. * note that when you use `wrap(true)` you need to set a `width` for the `HorizontalGroup()`

So you'll have a couple of options here. Good news is the `HorizontalGroup()` makes things pretty simple

---
Tags: libgdx, card-game, scene2d
---


title: Reduce texture switches in UI

text:
# Question
Title: Reduce texture switches in UI
I'm working on game which uses LibGDX's Stage2d for GUI.

All textures for UI are packed into one texture atlas.

Fonts (BitmapFont) are generated in runtime by gdx-freetype for different locales and font sizes (at least 6 locales and 4 font sizes for each locale) and then placed into separate texture.

Game UI contains much different elements (strategy game with lots of numbers) - buttons, icons, text labels, which usually alternate between each other and trigger many texture switches when drawn. I wonder if there's any way to reduce the number of texture switches as it sometimes takes up to 5ms per frame for stage.draw().

The only way I see is to draw fonts only when all UI textures are drawn, when it is possible, but it will produce awful code and will harm the hierarchy of elements in stage.

I didn't merge textures (but thought of it), because:

1. Textures use different filtering (MipMapLinearNearest for UI textures, Linear for fonts) and it will require manual texture filtering switches or mess with stage2d overriden Label class.
2. UI texture already has a size of 2048x2048px, and I can't add all font size textures to it as it will require higher texture sizes, which are not supported by many old devices.

Is there any good way of solving this issue?

# Answer
First thing is to use distance field font rendering and pack every glyph into a single texture using all 4 channels as individual gray-scale textures. This allows you to use only 1 font size in your atlas.

It looks like this inside the texture when tightly packed:

You can pack a ridiculous amount of characters at very low resolution and they still look great when scaled up. You can see the little distortions around the corners:

The font in the atlas in the above example is only 24 pixels high.

This gives you space for over 20,000 glyphs (or ~10,000 Asian glyphs as they need a bit more definition) in a single 2048x2048x32bpp texture.

This eliminates the need for multiple sizes of the same font in the font atlas texture.

---

The next step is to assign **ALL** your UI textures atlases to a single pixel shader that will sample all texture atlases but only effectively use 1 texture / texture plane out of all the textures.

You can use a UV encoding to let the pixel shader know which textures to throw out and which to use: eg: U range \[-2..-1), \[-1..0), \[0..1), and so on..

Make sure you sample all the textures: conditional/dependent texture sampling hurts GPU performance more than sampling excessively (within reason)

```
// sample all the textures at the same time
vec4 glyph_combined = texture(glyph_texture, uv.xy);
vec4 ui_graphics1 = texture(ui_graphics_texture1, uv.xy);
vec4 ui_graphics2 = texture(ui_graphics_texture2, uv.xy);
vec4 ui_graphics3 = texture(ui_graphics_texture3, uv.xy);

// DecodeDistanceFieldMagic is outside the scope of this question
// look up distance field font rendering linked at the top of the answer
vec4 glyph = DecodeDistanceFieldMagic(glyph_combined);

// uv.x < 1 selects glyph, uv.x >= 1 selects gfx 1
vec4 glyph_or_gfx1 = mix(glyph, ui_graphics1, step(1.0, uv.x));

// uv.x < 3 selects gfx 2, uv.x >= 3 selects gfx 3
vec4 gfx2_or_gfx3 = mix(ui_graphics2, ui_graphics3, step(3.0, uv.x));

// uv.x < 2 selects first "pair", uv.x >= 2 selects second "pair"
vec4 last_selection = mix(glyph_or_gfx1, gfx2_or_gfx3, step(2.0, uv.x));

output = last_selection * vertex_color;

```

Make sure to set all your textures to repeat.

With this method each individual texture can still have their own filtering.

If the graphic card supports GL\_TEXTURE\_2D\_ARRAY you can do part of the selection in the vertex shader by passing to the vertex shader which texture in the array to use which will reduce the texture sampling in the pixel shader but all textures in the array must share the same filtering setting.

On current GPUs you can have 16 or 32 textures bound at once (Depending on your definition of current GPU). You still want to minimize this for performance reasons by using atlases.
> 1 votes

---
Tags: opengl, java, libgdx, gui, texture-atlas
---


# Question
Title: OpenGL - Drawing quad with 4 position coordinates
Im developing a graphically very simple program (Does not require any 3D) in opengl. The main issue is that the default float positions for vertices are based on percentages of the screen.

Basicly what I want is to be able to pass 4 coordinates: x1, y1, x2, y2 and draw a quad based on those coordinates. For example if it was (0, 0, 10, 10) It would draw a 10px by 10px box in the top left.

So far shaders for transformations like pos and scale have been implemented. But they do not provide enough fine control on the quad and access to window width, height and other variables.

I don't need actual code, pseudo code is more than enough. But if you are curious im using lwjgl 3 with java in the programmable pipeline.

Is there any way of doing this with shaders? Or should I be using a completely different method?

# Answer
You need to set your projection matrix to be orthographic and to scale the range 0-1 to fit into a single pixel. You can do this in your vertex shaders by changing the projection matrix.

I'm not familiar with lwjgl, but would assume it has some sort of matrix library. I've used the C++ library glm, and it has a method `ortho` for creating a 2D orthographic projection matrix. I would bet that lwjgl has a similar method. If not, you can do it by hand. Here is Wikipedia's article on how to create one.
> 0 votes

---
Tags: opengl, java
---


# Question
Title: Unity player movement, rotation breaks the movement
I'm new on unity and I developed a script to move a player cube:

```
        var moveSpeed = 5.0f;

        var x = moveSpeed * Input.GetAxis("Horizontal") * Time.deltaTime;
        var z = moveSpeed * Input.GetAxis("Vertical") * Time.deltaTime;

        transform.Translate(
            x,
            0f,
            z
        );

```

This works fine, the cube moves around the plane.

Then I wanted to make the cube rotate to face the movement, I mean, if the cube is moving to the right, face the right, etc.

the problem is when I change the transform.rotation with the direction position, there is a strange behaviour.

The movement is like WASD (the camera doesn't rotate, but I want to use Input.GetAxis("Horizontal"))

Any idea?

Thanks

# Answer
> 1 votes
```
void Update()
{
    var moveSpeed = 5.0f;

    //move relative to world space (so rotation doesn't affect movement)
    var x = moveSpeed * Input.GetAxis("Horizontal") * Time.deltaTime;
    var z = moveSpeed * Input.GetAxis("Vertical") * Time.deltaTime;
    transform.Translate(x, 0f, z, Space.World);

    //work out angle using atan 2
    float angle = Mathf.Atan2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical")) * Mathf.Rad2Deg;

    // prevent cube snapping to angle if there is no movement
    if(Input.GetAxis("Horizontal") != 0f || Input.GetAxis("Vertical") != 0f)
        transform.rotation =  Quaternion.Euler(0f, angle, 0f);
}

```

Atan2 is used to work out the rotation as it will take XY values and generate an angle in radians. So all we have to do is convert the radians to degrees via `angle * Mathf.Rad2Deg` and set it to the transform.

---
Tags: unity, movement
---


# Question
Title: Synchronization problem with Visual Studio 2017 and Unity 2017.1.1f
Sometimes I need to change a lot of files and Clean and Rebuild the Solution to get the changes on Unity, am I missing some configuration on Visual Studio or Unity? I uninstalled everything and make a clean install and few days later I'm getting the same problems.

Sometimes if I create a stardard MonoBehaviour script from Unity and I try to attack it to a gameObject I get the error: "Can't add script component XXXXXX because the script class can't be found"(see image: screenshot). The class name and file name are the same, with no syntax errors.

Some times opening a file with an external editor changing the encoding, cleaning and rebuilding the project solves the problem, but just sometimes and I'm tired of do that for test any change, now I have a lot of Debug.Log just to check if Unity is getting my code changes.

Any suggestion will be very greatful

# Answer
There's no configuration that I can think of but I fix this problem by creating and deleting my scripts inside of visual studio. If you have your VS working with Unity then you should be able to create a "MonoBehaviour" script within the IDE itself.
> 0 votes

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


# Question
Title: How to optimize pathfinding on a very large dynamic 2d grid?
I have a large 2d tilemap, ranging anywhere from hundreds to thousands in size. The map is formed by 8x8 chunks. I am currently using A\* but it isn't quite efficient because I may have as many as a hundred objects pathfinding simultaneously. The path doesn't have to be the absolute shortest, but a certain degree of shortness is expected.

I've looked here and saw that HPA\* might work for me since my map is broken into smaller chunks. However, because the map is highly dynamic (let's assume that *at least* two chunks are modified per second) it seems there may be better alternatives.

Also, D\*/Lite (mentioned in the link) might work, but how can it be optimized for a chunk based grid?

My question isn't particularly about HPA\* or D\*, but rather about finding an optimal algorithm for a large and dynamic, chunk-based, tilemap.

**EDIT:** The chunks contain procedurally generated content. Most of the time this will mean that the chunk is empty except for about 10-20% of its tiles, however sometimes this number can go up to 90% (that is in the case of generated "blobs"). The chunks will contain near-arbitrary data, and two chunks will rarely be the same.

Furthermore, each agent will have an independent path, however because the map is dynamic, it may contain man-made corridors and long passage ways that might result in them being shared often by many agents.

Most goals will be arbitrarily located, however there will be some predefined goals (locations) as well. For those predefined locations, I am considering using a vector field (sort of like a heat map) that can be used to approach it. However, doing this for every goal would be terribly inefficient especially since I would use the generated field only once (or in better cases, maybe a few times).

# Answer
Since every unit has a unique endpoint, you best bet will likely be HPA\*.

When a chunk changes, you'll need to update its node at every layer in the hierarchy, then rerun pathfinding on each unit *(if a wall was added, you can skip units whose best-path didn't go through that node)*. Since the graph changes so often, I'd recommend only running the path-finding at the highest layer, then only drilling down when necessary. The top-layer has few nodes, so this will be super-fast.

At that point, profile. If you determine you need to make your pathfinding faster, you could look into things like JPS *(for the bottom-most layers)*, DynamicSWSF-FP *(for the higher layers)*, etc. You could also cache the most common queries at each layer. Another good optimization would be to only recalculate the path for some units each frame.
> 1 votes

# Answer
Hundred objects doing pathfinding constitutes a "crowd" I think. For this, you should look into Continuum Crowds by University of Washington.

What you do, is solve the pathfinding from anywhere on the map, to a goal. Then every agent that shares that goal can use it.

This works well if you have many agents, but only a few different goals.

I've used this in my pyramid building sim which can do thousands of agents doing pathfinding at 60Hz.

It comes down to solving for the entire map: what is the distance from here to the goal. From that map, calculate a gradient, and follow that gradient.

It comes with some nifty features, as "automatic lane forming" if two streams (with different goals) collide with each other. The agents will then form lanes, as moving against the predominant flow is more expensive than going with it.

The image below shows this "potential field" (distance to a particular goal) visualized as a colour, and then a gradient vector field superimposed.
> 1 votes

# Answer
You likely do not want to run a full path-finding algorithm PER unit: this is probably where you're finding the inefficiency. Instead you would create a shortest-path-to-goal map per goal location. So if multiple units are headed to one goal, they would simply lookup in this map which tile is the next closest tile to move to.

Such a map would be a separate grid that's computed based on the main grid you're working with. But more than just walls, any "open" tiles would contain numbers that are precomputed as shortest distance to the goal from that spot.

An example computed map would look like (X denotes a wall, 0 denotes the goal)

```
6 5 4 3 2 3
7 X 3 2 1 2
8 X 2 1 0 1
X X X X X 2

```

Any unit headed towards the goal (the 0) would simply follow the numbers in this grid downwards. Any change to the grid would force you to recompute this map (and how you make this efficient depends on your particular algorithm). A simple approach to create such a map would be to use a a Breadth First traversal from the goal location.

The main idea is that you can have hundreds of units using the same path map to find their way to a goal without computing a separate path for each of them.
> 0 votes

---
Tags: algorithm, path-finding
---


title: Performance issue in a simple game loop

text:
# Question
Title: Performance issue in a simple game loop
I have a problem with a simple game loop. As my rendering and iteration functions together take 10 ms, the time between update and swapBuffers measuers around 140 ms. What is causing this. Is there a straightforward way to fix this.

Could it be related to the fact that each rect() (in a for loop) calls glDrawElements() and it somehow ques the whole process.

```
void game::startup()
{
    startup();
    glfwSwapInterval(1);
}

void game::render(double currentTime)
{
    static const GLfloat green[] = { 0.0f, 0.25f, 0.0f, 1.0f };
    static const GLfloat one = 1.0f;

    glClearBufferfv(GL_COLOR, 0, green);
    glClearBufferfv(GL_DEPTH, 0, &one);

    auto t1 = std::chrono::high_resolution_clock::now();

    for (size_t y = 0; y < game_board.getWorldHeight(); ++y) {
        for (size_t x = 0; x < golf_board.getWorldWidth(); ++x) {
            rect(x * cell_size, y * cell_size, cell_size, cell_size, game_board.get_state(y * game_board.getWorldWidth() + x));
        }
    }

    auto t2 = std::chrono::high_resolution_clock::now();
    game_board.iterate(1);
    auto t3 = std::chrono::high_resolution_clock::now();

    float rendertime = std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1).count() / 1000.0f;
    float generatetime = std::chrono::duration_cast<std::chrono::microseconds>(t3 - t2).count() / 1000.0f;

    std::chrono::milliseconds ms_perframe(1000 / 60);  // About 60 fps
    auto cur_time = std::chrono::high_resolution_clock::now();
    float sleep_time = std::chrono::duration_cast<std::chrono::microseconds>(t1 + ms_perframe - t2).count() / 1000.0f;

    std::this_thread::sleep_for(t1 + ms_perframe - t3);

    cout << "render time (ms)" << rendertime <<"\n"
         << "generate time (ms)" <<generatetime << "\n"
         << "sleeping time (ms)" << sleep_time << "\n";
}

```

Output (board size: 256 x 128 = 32768 rectangles drawn per frame):

```
render time (ms) 8.1
generate time (ms) 1.3
sleeping time (ms) 6.6
SWAP TIME (ms) 146

```

application run function rendering part:

```
startup();

do
{
    render(glfwGetTime());

    auto t1 = std::chrono::high_resolution_clock::now();
    glfwSwapBuffers(window);
    auto t2 = std::chrono::high_resolution_clock::now();
    float  swap_time =
    std::chrono::duration_cast<std::chrono::microseconds>(t2-t1).count() / 1000.0f;
    std::cout << "SWAP TIME (ms)" << swap_time << "\n";

    glfwPollEvents();

    running &= (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_RELEASE);
    running &= (glfwWindowShouldClose(window) != GL_TRUE);

} while (running);

shutdown();

glfwDestroyWindow(window);
glfwTerminate();

```

rectangle draw function:

```
rect(int x, int y, int w, int h, int state) {
// input is top left corner of rectangle, width and height of rectange
and the state of unit

GLfloat fstate = (float)state * 0.5f;
GLfloat vertices[] = {
    x,  y,      fstate,         // Top-left
    x + w,  y,  fstate,         // Top-right
    x + w,  y + h,   fstate,    // Bottom-right
    x, y + h,    fstate          // Bottom-left
};

glBufferSubData(GL_ARRAY_BUFFER,0, sizeof(vertices),vertices);
glUseProgram(shaderProgram);

glUniformMatrix4fv(mvp_location, 1, GL_FALSE, mvp);

glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
}

```

# Answer
Currently you modify the buffer for each rectangle you draw. This is a very bad way to draw rectangles, because it's very slow.

Create instead a 1 unit by 1 unit square, and use a scale matrix to make it the appropariate size.
> 1 votes

# Answer
Also remember when you have two loops. Always traverse in row major as it increases spatial locality and increases cache coherency. Edit: In your case you are doing it right I overlooked it.

You could also use instancing to send geometry of one rect and mutiple matrices and draw using instancing .

Also correct way to major time taken by rendering loop is as follows

```
Loop
{
  Call glFinish()
  Start timer

  Do rendering
  Call swap buffers.
  Call glFinish()
  End timer.
  Get difference in start and end
}

```

This is important as opengl calls are not synchronised to your application.
> 0 votes

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


title: OpenGL NDC initial values

text:
# Question
Title: OpenGL NDC initial values
I have a set of vertex locations to create a plane:

```
this->Vertices = {
    // position         // color          // texture
    -0.5f,  0.5f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f,
     0.5f,  0.5f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
     0.5f, -0.5f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f,
    -0.5f, -0.5f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f
};

```

Everything is fine, but I can't grasp how I should input these values at the very beginning. I used to give exact locations for vertices in DirectX in pixel unit, but here in OpenGL I should give vertex locations in normalized coordinates.

If I wanted to create a plane say 200px by 200px how should I deal with that when I set vertex data. I know I can transform my plane with coordinate matrices through model space and view space and etc. I just don't know what I should be giving for the initial vertex location values.

# Answer
In whatever coordinate system you want. It doesn't matter for OpenGL, it only needs to receive them in NDC at the end. For example, if you want an ortographic projection, where 1 unit equals 1 pixel on the screen, then you can use the

matrix with the arguments `r = 0, l = width, t = 0, b = height, f = 100, n = -100`. You need to pass this matrix to the shaders and multiply the vertex coordinates with it.
> 2 votes

# Answer
I think you can keep your original co-ordinates as they are . Because I see they are always in NDC space or OpenGL i.e \[-1.0,1.\]. So just pass this vertices as it is to shader. So you Vertex Shader should look like this

VS

layout(location = 0) in vec3 pos;

`void main(void)
{
 gl_Position = vec3(pos,1.0);
}`

FS

out vec4 color;

`void main(void)
{
 color = vec4(1.0,0.0,0.0,1.0);
}`

This should draw your plane in red color. If you want to transform this plane some how then

with using following function transform your NDC space co-ordinates to world space w.r.t model and view and projection matrix you want.

You can do this in shader also as you will just need to pass model view projection matrices to shaders along with NDC co-ordinates of plane. Convert them to world co-ordinates apply model view projection to them to get transformed coordinates in NDC. and pass them along.

```
void unproject(float x, float y, float z)
{
 vec4 in;
 vec4 out;
 mat4 m;
 mat4 A;
 vec4 world_coord;
 vec3 object_coordinate;

A = mvp_matrix;

m = inverse(A);

//in the sample i was following, theres a bit of code to convert screen coords to NDC
//i just set in equal to my parameters which are already in NDC
in = vec4(x,y,z,1.0);

out = m * in;

out[3]=1.0/out[3];

world_coord[0] = out[0]*out[3];
world_coord[1] = out[1]*out[3];
world_coord[2] = out[2]*out[3];
 }

```
> 0 votes

---
Tags: opengl, coordinates, vertex
---


# Question
Title: How can i change transform position only on the x each time by gap of 50?
Global variable gap:

```
public int gap = 10;

```

Then:

```
clone.position = new Vector3(transform.position.x, 0,0);

```

clone is Transform

I want to use the gap variable to make spaces between each clone:

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

public class ClickOnKeys : MonoBehaviour
{
    public GameObject[] prefabs;
    public int gap = 10;

    private GameObject go;

    void Start()
    {
        prefabs = Resources.LoadAll("Prefabs", typeof(GameObject)).Cast<GameObject>().ToArray();

        foreach (GameObject prefab in prefabs)
        {
            if (prefab.name == "Test")
            {
                go = prefab;
            }
        }
    }

    void Update()
    {
        if (Input.anyKey)
        {
            foreach (Transform child in go.transform)
            {
                if (Input.inputString == child.name)
                {
                    Transform clone = Instantiate(child);
                    clone.parent = transform;
                    clone.position = new Vector3(transform.position.x + gap += 50, 0,0);
                }
            }
        }
    }
}

```

I tried to make:

```
clone.position = new Vector3(transform.position.x + gap += 50, 0,0);

```

But getting error on the part: transform.position.x + gap

The left-hand side of an assignment must be a variable, property or indexer The

This is what i tried now:

```
Transform clone = Instantiate(child);
clone.parent = transform;
gap += 50;
clone.position = new Vector3(transform.position.x - gap, 0, 0);

```

But the result is that the space/gap between the clones is not equal and also it seems the clones that each one is a letter looks rotated like mirror:

Each clone present a letter so it should show the word Hello But the letter e is on the H and the gap/space between the first l and second l not equal and the l is on the o:

# Answer
> 1 votes
That's not valid C#. You probably want to do something like this instead:

```
clone.position = new Vector3(transform.position.x + gap, 0,0);
gap += 50;

```

This will give you a gap of 10 units between the first and second clone, and 50 units between the second and the third, and the third and the fourth, and so on.

So if you don't want that, you might want to use two variables instead, one containing the offset and one (constant) storing the difference. So something like

```
offset += gapSize;
clone.position = new Vector3(transform.position.x + offset, 0,0);

```

where `offset` is initialized to `0`, and `gapSize` is set to `50`.

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


title: How to set up borders in snake game

text:
# Question
Title: How to set up borders in snake game
I have a snake game set up in Java and I wanted to be able to toggle between the ability to go through the sides and pop out the opposite side and the classic version where you die when you hit the border. The problem is that my snake keeps going one spot after the border; how do I fix this?

This is one of the parts of my code, that acts when the right arrow key is pressed:

```
if(right) {
    for(int i = lengthofsnake - 1; i >= 0; i--) {
        snakeylength[i+1] = snakeylength[i];
    }

    for(int i = lengthofsnake; i >= 0; i--) {
        if(i == 0) {
            snakexlength[i] = snakexlength[i] + 25;
        }
        else {
            snakexlength[i] = snakexlength[i-1];
        }

        if(!borderGameplay) {
            if(snakexlength[i] > 850) {
                snakexlength[i] = 25;
            }
        }
        else {
            if(snakexlength[i] > 850) {
                borderDead = true;
            }
        }
    }

    repaint();
}

```

`borderGameplay` is the variable that you can toggle to have borders on and off, and `borderDead` is used in this `if` statement:

```
if(borderDead) {
    if(score > highScore) {
        highScore = score;
    }
    playing = false;
    dead();
    deadGraphic(g);
}

```

This is my `deadGraphic(g)`: public void deadGraphic(Graphics g) { g.setColor(Color.WHITE); g.setFont(new Font("arial", Font.BOLD, 50)); g.drawString("Game Over", 300, 300); g.setFont(new Font("arial", Font.BOLD, 20)); g.drawString("Press \\"Space\\" To Restart And \\"Enter\\" To Toggle Borders", 160, 340);

```
    if(borderGameplay) {
        g.drawString("Borders ON", 370, 380);
    }
    else {
        g.drawString("Borders OFF", 365, 380);
    }
 }

```

This is my `dead()`:

```
public void dead() {
    right = false;
    left = false;
    up = false;
    down = false;
    dead = true;
    score = 0;
    moves = 0;
}

```

And finally, my JFrame:

```
JFrame obj = new JFrame("Snake");
gameplay Gameplay = new gameplay();
obj.setBounds(10, 10, 905, 700);
obj.setBackground(Color.DARK_GRAY);
obj.setResizable(false);
obj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
obj.add(Gameplay);
obj.setVisible(true);

```

If you need to see other parts of my code, please tell me; this question is already really long, and my total code is 550 lines.

# Answer
I understand your problem to be that the snake, before it dies, can go one block into the boundary, or wall.

From the looks of it, your right boundary is at **850px** on the X axis, and spans the Y axis indefinitely, giving us a nice wall.

Well, your snake travels **25 pixels** per frame per second (25px/FPS); if this is wrong, I apologize, do correct me as this is what I was able to understand from your code.

When the snake reaches 850px, the IF statement does not equal true, because your operator is set as **greater than**. It's only that once your snake reaches 875px (after moving 25px at a time) that the IF statement is true and the snake dies while in the boundary.

Here's my suggested solution: make sure the user isn't already at the pre-defined barrier before you move them right anymore. This way, before they get the chance to move inside the of the barrier, they die instead.
> 1 votes

---
Tags: java
---


title: 3D model rendered in halftone

text:
# Question
Title: 3D model rendered in halftone
I am writing a 3D renderer that would render 3D models as if they had been drawn in halftone. Feature-wise I need nothing fancy - no colors, just pure 3D geometry and basic lighting like here: Image credit: https://blenderartists.org/forum/showthread.php?438820-Suzanne-Sketch

**Notes:**

* *I have written a basic 3D renderer in the past, however, I am really inexperienced when it comes to shaders (again, I do know basics) and I have absolutely no idea where to start with this.*
* The example image has been created in Blender, but I am writing my custom renderer.
* This is not a duplicate of "How can I make a shader effect that looks like a lightly shaded pencil drawing?", as my input is a 3D model, whereas the OP in the linked question used an image.

# Answer
> 1 votes
I would write a two-pass renderer. The first pass renders the geometry to a 2D texture. In a second pass the texture is uploaded to the GPU. Use a different shader for the second pass. This shader then uses the fragment position to decide which part of the crosses it is rendering (whitespace or line). The brightness or thickness of the cross can be obtained by sampling the brightness of the surrounding pixels values from the texture.

Maybe you can get some good results without multi-sampling. Then it is possible to render this in one step by directly calculating the brightness

---
Tags: opengl, c++, shaders, rendering, glsl
---


title: Set Layer of UI Object being Dragged

text:
# Question
Title: Set Layer of UI Object being Dragged
In my game, I have an inventory system with slots and images in those slots. The images are by default disabled, but when an item is added to the slot, the image component becomes enabled. I have implemented a very simple drag and drop system for moving objects around in the inventory using IBeginDragHandler, IDragHandler, and IEndDragHandler. As I am dragging an item from one slot to another, I want the item image to be rendered in front of the slots and the rest of the inventory. Currently, when dragging an item image, it renders behind the empty slots.

I don't want to use hierarchy order to organize the layers of these slots because moving items around is very dynamic and the hierarchy order of the slots changes seemingly randomly when I press play. Is there another way to ensure that the item image being dragged is "closer to the camera" or in front of the rest of the inventory? Thanks.

# Answer
> 1 votes
Decided to manipulate hierarchy order after all and it's working pretty well.

I added

```
for (int i = 0; i < numRows; i++)
{
    inventoryRows[i].transform.SetSiblingIndex(i);
}

```

to a slot manager script to remove the random ordering upon pressing play.

Then, in my DragHandler script, I added the following to OnBeginDrag()

```
slotStartingSiblingIndex = transform.parent.GetSiblingIndex();
rowStartingSiblingIndex = transform.parent.parent.GetSiblingIndex();
transform.parent.SetAsLastSibling();
transform.parent.parent.SetAsLastSibling();

```

and the following to OnEndDrag()

```
transform.parent.SetSiblingIndex(slotStartingSiblingIndex);
transform.parent.parent.SetSiblingIndex(rowStartingSiblingIndex);

```

This gives pretty good control of hierarchy order, and thus, of rendering layers.

---
Tags: unity
---


# Question
Title: How can i create 700,000 cubes, memory usage get to 91% and above it?
```
var key = thisKv.Key;
                foreach (var thisValue in thisKv.Value)
                {
                    GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
                    cube.transform.parent = emptygameobject.transform;
                    var renderer = cube.GetComponent<MeshRenderer>();
                    renderer.material = textMaterial;
                    cube.transform.position = new Vector3(-thisValue.Y, 0, thisValue.X);
                }

```

thisKv.Value Value contain over 700000 And then when it's creating the cubes:

```
GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);

```

And make the loop very fast my memory usage of the pc get to 91% and more and i need to shut down the unity editor.

Is there any other way to handle so much cubes ?

# Answer
You should definitely not create a separate entity for each block in the terrain. Entities have a huge overhead in terms of memory. Instead, use something more compact, like a bunch of bytes, shorts or integers (depending on how many types of blocks you have, you could also use a struct if you need to keep some additional data) in a multi dimensional array (or a single dimensional one if you really need to save memory).

So, you'd basically have chunk objects, each containing an array of values. From here you can go in 2 different directions.

* If the chunks don't change that much, then you should generate a single mesh out of the cubes where you remove the invisible faces and you only need to update this mesh if the blocks change.
* If the chunks change frequently, then you should use instancing to render the cubes. This way you don't need to change a mesh every time the blocks change. You should try to avoid rendering invisible cubes and possibly faces, but the latter one wouldn't help too much over the former if the terrain's mostly solid.

If you did all that, but you still hit the memory cap (I doubt it though), then try a different method instead. Create a 3d texture containing the terrain information and render it using a geometry shader. This way you only use the VRAM instead of the RAM, but it's going to be slower to update the terrain.
> 1 votes

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


# Question
Title: Is there a way to make GUI.SelectionGrid expand horizontally
I am working on an inventory system, And I want to be able to make a Selection Gird that expands horizontally rather than vertically, is there an easy way to do this? Or will I have to create my own version of SelectionGrid?

# Answer
> 1 votes
I found out the answer 1) there is no such thing in unity (which is not that big of a surprise). However there are two methods that once can use to create a selection grid like button system. The most efficient of which (cuz GUILayout is slow) is done using plain old GUI.Functionality;

```
for (int x = 0; x < 3; ++x) {
 for (int y = 0; y < 3; ++y) {
  if (GUI.Button (new Rect (m_BackPack.x + x*32, m_BackPack.y + y*32, 32, 32), m_EmptyInventorySlot, inventorySlotStyle)) {
   m_BackPackButton = y + x * 3;
   Debug.Log (m_BackPackButton);
    }
  }
}
```

This will create a selection grid like structure, that changes the value of m\_BackPackButton to the location of the pressed button, this snippet expands horizontally, and the x,y position of any button is given by m\_BackPackButton/(num horizontal buttons), m\_BackPackButton%(num vertical buttons).

I think this is how selectionGrid is created internally.

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


# Question
Title: 2D UI - Image with 1px border randomly gets different thickness
I created a test image that is 60 x 60 px, which has a 1px border. I then drop that into Unity as a UI sprite image set to the same size, however the 1px border on a few sides can appear to be thicker, and this ruins the look I am going for especially when there are multiple of them.

I've tested in the editor and creating builds (testing resolutions), and the same issue in all cases.

It's easier to explain this with images.

The left screen shot is the actual size of the image in the game view. The zoomed in image is another case where the borders change thickness, but zoomed in to make it more clearer.

I've tried various settings, always the same issue.

How can I get the image to appear exactly as it should with no changes to the borders?

# Answer
> 3 votes
There are a couple of points you need to take into account to solve this.

First you'll want to switch your sprite's Mesh Mode in its texture import settings to Full Rect so you can **enable 9-slice scaling** on it as described in the Unity docs.

This lets you select either the Sliced or Tiled modes on your Sprite or Image components, which will ensure borders of your sprite stay the same thickness in the game world/canvas when the sprite is enlarged - they'll be spaced out or tiled instead of stretched to fit.

**For a non-UI sprite,** the size of the border in actual display pixels will depend on how your camera sees it. This includes your pixels per unit setting, the size of your orthographic camera, and the resolution of the display viewport. You can work out the result using these formulas:

```
world thickness = (1 pixel of texture) ÷ (pixels per unit)

vertical screen fraction = (world thickness) ÷ (camera height * 2)

display pixels = (vertical screen fraction) * (pixel height of display viewport)

```

(For perspective cameras you also need to factor in the depth of the sprite from the camera)

You'll want to carefully choose your pixel per unit and camera settings to keep this at an integer value. Otherwise you can get one border drawn thicker than the other if one border rounds the fraction differently.

**For an Image component displayed as part of your UI**, this is a bit easier to manage. Set up your Canvas with a CanvasScaler set to Constant Pixel Size, with the Reference Pixels per Unit value the same as the one you used to import your sprites, or an integer multiple of it if you want to upscale the art (Don't forget to switch your textures to Point filtering if you're upscaling pixel art).

Then enable the Pixel Perfect box in the Canvas component, which turns off anti-aliasing on UI so you get exactly the pixels of your sprite.

# Answer
> 0 votes
In the settings for the sprite use **Filter Mode** of "point" instead of Bilinear.

---
Tags: unity, image
---


# Question
Title: How do I calculate NDC coordinates in a fragment shader?
I have some weird problem going on in my openGL shader.

First,, I pass the viewspace position from the vertex shader to the fragment shader like this:

```
vec4 view_pos = V * M * vec4(world_position.xyz, 1.0);

```

Then, in the fragment shader, I do this:

```
vec4 clip_pos = P * view_pos;
vec2 ndc_xy = clip_pos.xy / clip_pos.w
vec2 ndc_fragcoord = 2.0 * gl_FragCoord.xy / viewport_wh - 1.0

```

I would expect that `ndc_xy` is the same as `ndc_fragcoord`; however, when rendering them to textures, they are not nearly the same:

Can someone explain to me the differences? How can I get the same result in `ndc_fragcoord` by using view space position or vice versa?

This is important information for me for a later stage, when reconstructing the view space position from the depth. I have already been sitting on this the whole day, and am close to despair.

# Answer
It looks like you are rendering point primitives. The vertex shader only operates on the center points of each primitive and the varying will hold the same value for all fragments on the primitive. That's why your first image looks the way it does.

I do not know of any way to get the NDC for point primitives other than calculating them from `gl_FragCoords`.
> 1 votes

# Answer
Not an open GL guy but it looks like its not getting interpolation over the vertex, I was just going to make a comment but to low on the points.

Not sure I know how to fix it in open GL but in dx I would make sure it gets passed from vertex shader to pixel shader with TEXCOORD\[n\] so it gets interpolation.

Again I just wanted to comment, sorry if I'm wrong.
> 0 votes

# Answer
move the projection multiplication in the vertex shader:

```
vec4 view_pos = P * V * M * vec4(world_position.xyz, 1.0);

```

and in fragment shader:

```
vec4 clip_pos = view_pos;
vec2 ndc_xy = clip_pos.xy / clip_pos.w

```

It is better to stick with gl\_FragCoord because you avoid the need to have a varying that you have to calculate.
> 0 votes

# Answer
`gluProject` does exactly what you want i.e. it maps a vertex from object space to the window space.

Lets take the formula for X from its spec:

> winX = viewportLeft + ((viewportWidth * (ndc.x + 1)) / 2)

You've stopped just after calculating NDC coordinates, but this step is also needed to get the same result as `gl_FragCoord`.
> 0 votes

---
Tags: opengl, coordinates, fragment-shader
---


# Question
Title: High-resolution VR with tethered smartphone display
I have an Android SmartPhone with a fairly high resolution + USB-C port, a USB-C-to-USB-A cable, and a Google Cardboard headset.

Is it possible to develop a VR app running on a PC game engine (such as Unreal) but stream the output to the Cardboard headset by using the phone as a display? (rather than running the app entirely on the phone). For instance, if I wanted to render using a beefy NVIDIA GPU and stream the graphics over USB.

What are the options here? I'm aware of this guide, which seems reasonable: https://uploadvr.com/budget-vr-101-get-pc-vr-streaming-phone/

Is this a use case supported by any Game Engines like Unreal/Unity?

# Answer
> 1 votes
Found a workable solution: developing a Daydream/Cardboard App using Instant Preview (https://developers.google.com/vr/tools/instant-preview) allows Unity / Unreal Applications to be rendered locally on the desktop and be streamed over to the smartphone. This is good enough for prototyping.

---
Tags: unreal-4, virtual-reality, google-cardboard
---


# Question
Title: How to manage instances of (placed) cards and decks in card games?
This question sounds quite specific, but I mean in general, how do you manage something like a card game when it comes to decks (one for player1, one for player2, ...) and placed cards focused on instances of *a* `Card`-object?

Specifically in my case - using Java - I got a few cards with static data (image, values displayed on them, ...) and some data, depending on who has the card in their deck or where it lies on the board, for each type of card.

Now I got instances of those cards with their values like

```
Card DOG = new Card(image, a, b, ...);
Card SHEEP = new Card(image, a, b, ...);
Card PIG = new Card(image, a, b, ...);

```

statically in `Card`. Maybe this is already the wrong way to do it?

How do I manage decks and stuff now, because I need specific instances after those blueprints, but fitted to their use, be it the deck where it is in or if it is on hand or on board, ...

The first thought I got was having something like `Card.createInstance` but is this something that is done?

I'm more or less asking for a best practice on doing something like this.

# Answer
There is never one "right" or "wrong" way to do something in programming. Just ways which do or do not work for you, your team and your project. So don't worry about doing things the right way, worry about writing a program you can still understand, change and extend later.

The pattern from the question has some implications for later maintainability. When each card is a `static`, they seem more like card-*types* to me than actual instances of cards. This conceptual difference might not matter much when each card only exists once in the game, but will matter when you allow multiple cards of the same type.

With this pattern, you can write code like `if (lastCard == Card.PIG) sayOink();`. But because the `==`-operator only checks if both references point to the same object, this only works when lastCard is a reference to `Card.PIG`. There might be multiple pig-cards in the game, but they are all represented by references to the one `Card.PIG` object. That means if `Card.PIG` has any internal state, that state will be shared by all pig-cards in the game.

When your game doesn't have state for individual cards, that's fine.

But if you have some mechanics where cards have a state (like counters on cards, a "tapping" mechanic like in some trading card games, etc...) or when you want cards themselves to be aware of their current location in the game (in the deck, in a player's hand, on the table), this is not going to work. You will then need an instantiated object for each card.

If you want to follow that architecture, you have two different classes `Card` and `CardType`. When there are 7 pig-cards in the game, you would have one `CardType PIG` and 7 instances of `Card` which each have a reference to `PIG` which you can pass to it in its constructor. Your code to initialize your deck of cards could look something like this:

```
static CardType DOG = new CardType(image, a, b, ...);
static CardType SHEEP = new CardType(image, a, b, ...);
static CardType PIG = new CardType(image, a, b, ...);

static int NUM_DOG_CARDS_PER_DECK = 3;
static int NUM_PIG_CARDS_PER_DECK = 7;
static int NUM_SHEEP_CARDS_PER_DECK = 7;

[...]

int i = 0;

for (i = 0; i < NUM_DOG_CARDS_PER_DECK; i++) {
     deck.add(new Card(DOG));
}
for (i = 0; i < NUM_PIG_CARDS_PER_DECK; i++) {
     deck.add(new Card(PIG));
}
for (i = 0; i < NUM_SHEEP_CARDS_PER_DECK; i++) {
     deck.add(new Card(SHEEP));
}

```

But there is always more than one way. Instead of having a `CardType` class, you could implement each card type as a separate class which inherits from `Card`. Then your code would look like this:

```
for (i = 0; i < NUM_DOG_CARDS_PER_DECK; i++) {
     deck.add(new DogCard());
}
for (i = 0; i < NUM_PIG_CARDS_PER_DECK; i++) {
     deck.add(new PigCard());
}
for (i = 0; i < NUM_SHEEP_CARDS_PER_DECK; i++) {
     deck.add(new SheepCard());
}

```

The differences between different card types (like their names and images) would then be implemented in `DogCard`, `SheepCard` etc.. This architecture would be most appropriate if your card types don't just differ by the values of their variables, but also have some mechanical differences which require card-specific code. That code would then belong into those sub-classes.
> 2 votes

---
Tags: java, state, instancing, refactoring
---


# Question
Title: Unity: How to make an array of video clips and play them?
I have 26 video files which I have to put in an array and play for different objects. So far I have written this from what I know:

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

public class videomanager : MonoBehaviour {

    public VideoClip[] vids;

    private VideoPlayer vp;

    // Use this for initialization
    void Start () {

        vids = new VideoClip[25];
        vp = gameObject.GetComponent<VideoPlayer> ();
    }

    // Update is called once per frame
    void Update () {

    }
}

```

I have attached this script on a plane on which I am playing the video.

Before that, I had 26 different planes, one for each different video, but I think it would be better if I could play them on a single plane and change the video according to logic.

I am not sure how I should load them into my player and play them.

# Answer
This is a pretty simple application of the `clip` property and `Play()` method described in the Unity VideoPlayer docs.

Have you had any difficulty doing something like this?

```
// This script won't work without a VideoPlayer present,
// so let's ask Unity to enforce that relationship for us.
[RequireComponent(typeof(VideoPlayer))]

// The C# convention for class names is PascalCase.
public class VideoManager : MonoBehaviour {

    // Don't create/size the Array in Start() - that makes an empty
    // array, discarding the clips you assigned in the Inspector.
    public VideoClip[] vids = new VideoClip[26];

    private VideoPlayer vp;

    void Start () {
        vp = gameObject.GetComponent<VideoPlayer> ();
    }

    // Call this method when it's time to play a particular video.
    // Pass a number from 0 to 25 inclusive to choose which video.
    public PlayVideo(int id) {
        // To be safe, let's bounds-check the ID
        // and throw a descriptive error to catch bugs.
        if(id < 0 || id >= vids.Length) {
            Debug.LogErrorFormat(
               "Cannot play video #{0}. The array contains {1} video(s)",
                                   id,                 vids.Length);
            return;
        }

        // If we get here, we know the ID is safe.
        // So we assign the (id+1)th entry of the vids array as our clip.
        vp.clip = vids[id];

        vp.Play();
    }
}

```
> 1 votes

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


# Question
Title: How to rotate several game objects without rotating individual objects
I have a some game objects that are a unit away from the center. They are all contained in a parent object, see the image below.

When I rotate the parent object by 60°, the game objects individually rotate, as below.

Below is the script attached to the parent object that I use to rotate the parent object.

```
    IEnumerator RotateSquaresParent(Vector3 byAngles, float duration)
{
    Quaternion fromAngle = gameObject.transform.rotation ;
    Quaternion toAngle = Quaternion.Euler (transform.eulerAngles);
    toAngle = Quaternion.Euler (gameObject.transform.eulerAngles - byAngles);

    for(float t = 0f ; t <= 1f ; t += Time.deltaTime/duration)
    {
        gameObject.transform.rotation = Quaternion.Lerp(fromAngle, toAngle, t) ;
        yield return null ;

    }
    gameObject.transform.rotation = Quaternion.Lerp(fromAngle, toAngle, 1);

}

```

How can I rotate the parent object containing these square game objects without rotating them individually?

**UPDATE**

The squares represent enemy objects that would be shooting projectiles (yet to work on that) in my game. Thats why they'd have to be straight. As a player approaches a given child square (enemy), I would want to rotate individual child squares based on proximity and other conditions to possibly face the player object.

# Answer
Try the following script :

```
IEnumerator RotateSquares( Vector3 byAngles, float duration )
{
    int childCount           = transform.childCount;
    Vector3[] localPositions = new Vector3[childCount];
    Quaternion startRotation = Quaternion.identity;
    Quaternion endRotation   = Quaternion.Euler( byAngles );
    int childIndex           = 0;

    // Store the local positions of the children
    for ( childIndex = 0 ; childIndex < childCount ; ++childIndex )
    {
        localPositions[childIndex] = transform.GetChild( childIndex ).localPosition;
    }

    // Lerp position of children
    for ( float t = 0f ; t <= 1f ; t += Time.deltaTime / duration )
    {
        for ( childIndex = 0 ; childIndex < childCount ; ++childIndex )
        {
            Transform child = transform.GetChild( childIndex );
            Quaternion rotation = Quaternion.Slerp( startRotation, endRotation, t);
            child.position = transform.position + rotation * localPositions[childIndex];
        }
        yield return null;
    }

    // Final position of the children
    for ( childIndex = 0 ; childIndex < childCount ; ++childIndex )
    {
        Transform child = transform.GetChild( childIndex );
        child.position = transform.position + endRotation * localPositions[childIndex];
    }
}

```

---

# INITIAL ANSWER :

I would save the rotation of the children and re-apply the initial rotation while rotating the parent.

```
    IEnumerator RotateSquaresParent( Vector3 byAngles, float duration )
    {
        int childCount = gameObject.transform.childCount;
        Quaternion[] childRotations = new Quaternion[childCount];
        Quaternion fromAngle = gameObject.transform.rotation ;
        Quaternion toAngle = Quaternion.Euler( gameObject.transform.eulerAngles - byAngles );
        int childIndex = 0;

        for ( childIndex = 0 ; childIndex < childCount ; ++childIndex  )
        {
            childRotations[childIndex] = gameObject.transform.GetChild( childIndex ).rotation;
        }

        for ( float t = 0f ; t <= 1f ; t += Time.deltaTime / duration )
        {
            gameObject.transform.rotation = Quaternion.Lerp( fromAngle, toAngle, t );

            for ( childIndex = 0 ; childIndex < childCount ; ++childIndex )
            {
                gameObject.transform.GetChild( childIndex ).rotation = childRotations[childIndex];
            }
            yield return null;

        }
        gameObject.transform.rotation = toAngle;
    }

```

Otherwise, you may find a trick with the `RotateAround` function called on every child, and providing `gameObject.transform.position` as first argument
> 1 votes

# Answer
You cannot do this by applying a single transformation to the parent object because the desired end shape is not an affine transformation of the parent object.

I see the following options:

1. Rotate the parent object by X degrees around its center, and then rotate each child object by -X degrees around its center.
2. Discard the parent object, calculate the rotated position of child objects' centers and move the objects according to the change in their positions.
> 0 votes

---
Tags: unity
---


# Question
Title: How to wrap a components position using angles (i.e horizontal compass)
I'm trying to make a horizontal compass. The compass is made up of UI components: panel (with mask), with a child UI Image (the compass image).

Here is the compass from Fallout:

As you turn around, so does the compass. I want to move the child based on the rotation of the player. I want to move the child by using transform.position so that any child components will also move (i.e way points).

I found some code on the Unity forum. I got it to kinda work, however when it wraps around, it doesn't wrap to the correct position. See GIF. When I approach the South rotation, it wraps but not to the correct position. The compass image and code can be found here.

I've made sure that the image is native size, and also tried various values in the "numberOfPixelsNorthToNorth" property.

```
using UnityEngine;
using UnityEngine.UI;

using System.Collections;

public class CompassHandler : MonoBehaviour {
    public float numberOfPixelsNorthToNorth;
    public GameObject target;
    Vector3 startPosition;
    float rationAngleToPixel;

    void Start(){
        startPosition = transform.position;
        rationAngleToPixel = numberOfPixelsNorthToNorth / 360f;
    }

    void Update (){
        Vector3 perp = Vector3.Cross(Vector3.forward, target.transform.forward);
        float dir = Vector3.Dot(perp, Vector3.up);
        transform.position = startPosition + (new Vector3(Vector3.Angle(target.transform.forward, Vector3.forward) * Mathf.Sign(dir) * rationAngleToPixel, 0, 0));
    }
}

```

I don't really understand how the code works in the Update method, as my Math knowledge is pretty poor. I looked up the methods used, but still was clueless. So I can't work out how to solve it.

I would like to understand what is going on in the Update, but if that is too much, can anyone help fix the issue that is seen in the GIF?

Edit: Here is a GIF using the accepted solution.

# Answer
I'd junk this code and do it in a simpler way. ;)

```
// Get an arrow pointing to the marked object in the player's local frame of reference
Vector3 offset = playerTransform.InverseTransformPoint(markedObjectTransform.position);

// Get an angle that's 0 when the object is directly ahead,
// and ranges -pi...pi for objects to the left/right.
float angle = Mathf.Atan2(offset.x, offset.z);

// Let's put these markers in a container parent object
// whose center is where you want the middle of the compass.
// Then each marker only needs to worry about its x position relative to this.
compassMarker.localPosition = Vector3.right * compassWidth * angle/(2f * Mathf.PI);

```
> 1 votes

---
Tags: unity, mathematics, angles
---


# Question
Title: How to convey that a cutscene is about to end?
I'm currently developing a 3rd person game with dynamic cutscenes (using in-game objects instead of a pre-rendered video). During some playtesting of my game I noticed that some of my playtesters would have trouble identifying when a cutscene would end, sometimes killing them because they didn't react in time. For example:

1. Player walks into hallway
2. Cutscene start
    1. Camera pans to look behind player
    2. Monster drops down from the ceiling behind player
    3. Player character starts running by itself
3. Cutscene end
4. Player expected to keep running, but doesn't know cutscene has ended so doesn't respond in time and gets killed.

---

**My playtesters comments:**

* They can realize when a cutscene starts because something out of the ordinary happens (e.g. camera view changes).
* They sometimes don't realize when a cutscene ends because the out of the ordinary thing doesn't change back (e.g. camera view doesn't revert to normal).

---

**What I've tried:**

To try and teach players that it's common for I used popups during the tutorial stage of the game:

1. Cutscene end.
2. Display message *"Hey! Did you know you can **ACTION** by pressing `KEY`?"*

I've also tried to give them examples during the tutorial where you have to be quick after a cutscene by pausing the game after the cutscene and displaying a popup, giving them time to react:

1. Cutscene end.
2. Game pauses.
3. Displays popup: *"You're being hunted! **RUN** by holding `SHIFT`!"*

Both of these methods makes the user realize (at that time) that the cutscene has ended, yet it doesn't seem to successfully *teach* them that this will happen in the future and they are still confused about if a cutscene has ended. I don't want to have these popups after the tutorial stage since it sort of defeats the point of tense moments.

So my question is: **How can I more clearly convey to the players that my cutscene is about to end without explicitly telling them?**

# Answer
In my experience, such integrated cutscenes (that is, using the in-game renderer) tend to use camera angles & perspectives that differ from the game play. For instance, if the game is played in 1st person mode, the camera shifts to a 3rd person view for the cut-scene.

You could adjust the display to use letterboxing, pillarboxing or windowboxing during the cutscene & then switch back for regular play. Less commonly, I've also seen filters used (for instance sepia tone, black & white filter or 'vintage film' overlays) to indicate cutscenes, but these are usually for flashbacks or other special purpose cutscenes.

If the nature of the game permits, you could also reinforce the transition via game dialog. Here's a questionable example (maybe hire a better writer than I did):

> NPC: Player, when I say give the signal, you need to \[game action\] as fast as you can to the exit.
>
> Player: No, NPC I can't, I \[emotion\] you too much to do that.
>
> NPC: There's no time! You must \[game action\]! Go!!

You could put some sort of cutscene timer indicator on the screen. Given what you've already tried, I'm skeptical it will give you the desired result. On the other hand, it's also easy to implement. It also might create a sense of tension - if the plot of the cutscene feels unresolved & the timer is almost done, it might foster an "edge of the seat, how's this going to play out" feeling.

Lastly, if you have the luxury of testing in a way that allows for it, asking your player base might help. Maybe they're all expecting something that we're not imagining here. You'll need to apply you developer's intuition as to if their suggestions are any good - I think Jesse Schell observed that players are good at spotting when things are off, but not necessarily so good at knowing how to fix them.
> 7 votes

# Answer
Is it possible for your cut scenes to end at a place/time in which the player feels a sense of urgency or need to move, shoot/block/defend? One of the things I liked about the Last of Us is that it was really good at integrating cut scenes pretty seamlessly into the game. Generally they would all end at a time when you needed to run, shoot, duck, or otherwise take some kind of action. They would also have the focus of the cut scene disappear once it was over (ie giraffe eating a leaf then it turns and runs off). So for your scenario, just remove #3 from the equation and the player will take action as the monster is closing in on them.

I also have seen people take a zoomed in approach, where your field of view seems to narrow during a cut scene and then when it's over you tend to zoom back out to your regular field of view. Then you don't have to do so much changing of perspectives with the camera.
> 7 votes

# Answer
If your cutscenes are skippable, have the key to do so on-screen during the cutscene. Then, remove the key (and option!) to do so several seconds before the cutscene ends. The prompt disappearing is the cue for the cutscene nearly ending.
> 3 votes

---
Tags: game-design, user-experience, playtesting, cutscene
---


title: Friction on a rolling ball

text:
# Question
Title: Friction on a rolling ball
How long will a ball, say a billiard ball, stop rolling on a flat surface for a given coefficient of friction? What is the formula for the ball's decreasing velocity?

# Answer
> 3 votes
```
 Time to stop is  initial_speed/(mu * g)

```

Derivation below.

Assume the ball is moving to the right, then the free body diagram is

The equation of motion is $$ m\ddot{x} = -\mu N $$ But \\$ N = mg \\$ hence $$ \ddot{x} = -\mu g $$ Using the constant acceleration kinematic equation $$ \dot{x}\_{final} = \dot{x}\_{initial} + \ddot{x}t = \dot{x}\_{initial} - \mu gt$$ Then, by letting final speed be zero, we solve for the time for the ball to stop. $$ t= \frac{\dot{x}\_{initial}}{\mu g}$$ For example, using coefficient of friction \\$ \mu = 0.15 \\$, initial speed of \\$ \dot{x} = 15 \\$ meters per second and earth's gravity \\$ g=9.81 \\$, then the time to stop is $$ t = \frac{15}{(0.15)(9.81)} = 10.2 s$$

---
Tags: physics
---


# Question
Title: How can i make my soldier to patrol over the space stationin random?
I mean i want to bake all the places in the space station and make the soldier to move automatic around the spaceship to random places.

What i did so far is placing the soldier at a start point. Added a camera as child to the soldier. Added a nav mesh agent component to the soldier.

Attached a script to the soldier: It's not my script. I don't want the soldier for now to chase only to walk randomly around the space station.

I didn't change any of the setting on the Nav Mesh Agent component in the inspector and i didn't

Should i change anything in the nav mesh agent component and if so what ?

How do select or set what areas to bake so the character will know to walk to this areas or if i want to select all the areas ?

How do i tell the character when to turn right or left in case there is a wall ? Could be also random to turn left or right. Depending if there is left and right ways or maybe there is also straight way so that's 3 possible ways to move to.

clicked the Bake button yet.

I didn't write yet the script.

```
using UnityEngine;
using System.Collections;

public class SoldiersPatrol : MonoBehaviour
{

}

```

# Answer
I show you with like a psudo code:

```
system.random rnd = new system.random();
GameObject[]  points;
// assume you have 5 possible points that you can go
int moveIndex;
void update()
{

transform.position= vector3.movetowards(transform.position,points[moveIndex].transform.position,speed);
if(vector3.distance(transform.position,points[moveIndex].transform.position)<1)
{
moveIndex= rnd.next(1,6);
}

}

```
> 0 votes

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


# Question
Title: Reasonable amount of garbage collection for mobiles games?
I'm making a 2D game for mobile and I noticed that my GC seemed to spike during attack. My normal GC is 40b but during attack it could spike to 2.2kb. I think this is really high specially when I saw a 3D game with only 8b GC. I would love to hear your thoughts about what's a reasonable amount of GC for mobile(e.g device with 512ram). I know I'm supposed to keep the GC as low as possible however I want to have a value I could compare to.

# Answer
> 2 votes
There's no real rule on what's reasonable. If your game performs ok, then don't worry about it. If you're having problems and you're sure it's GC, then consider pooling objects. Also check this article:

https://unity3d.com/learn/tutorials/topics/performance-optimization/optimizing-garbage-collection-unity-games

---
Tags: unity, optimization, mobile
---


# Question
Title: Unity Android Project Settings.gradle file
I am trying to debug Android project after building it with Unity Editor

The project i want to include is an External Project.

the usual way is Adding to settings.gradle

```
:include (':common')
:project (':common') as File(...)

```

and build.gradle

```
compile project(':common')

```

1.Its doesn't seems to work since i have no idea (if possible) place the settings.gradle for usage. Any1 manage to fix it?

2.maybe there is another way to fix this?

Thank you

# Answer
> 0 votes
Issue Fix.. Posting Answer for Future Reference.

Export Project using Unity. include the exported project to your external Project in the Settings.gradle

```
include ':project'
project (":project").projectDir = new File('project path')

```

Build external project run and you can Debug.

---
Tags: unity, android
---


# Question
Title: How to rotate an object around its own roll axis
I have a 2-dimensional image of smiley face in a 3-dimensional space. I want it to rotate like a fan, so the smiley would look as if it's rolling like a wheel in place. Since the smiley is placed in a 3D space it can face any direction, but I always want it to rotate around like a wheel.

**I use Minecraft** so the Z and Y have the opposite jobs. (Y is the height).

I use these 3 functions for rotating around the x, y and z axis.

```
public static final Vector rotateAroundAxisX(Vector v, double angle) {
    double y, z, cos, sin;
    cos = Math.cos(angle);
    sin = Math.sin(angle);
    y = v.getY() * cos - v.getZ() * sin;
    z = v.getY() * sin + v.getZ() * cos;
    return v.setY(y).setZ(z);
}

public static final Vector rotateAroundAxisY(Vector v, double angle) {
    double x, z, cos, sin;
    cos = Math.cos(angle);
    sin = Math.sin(angle);
    x = v.getX() * cos + v.getZ() * sin;
    z = v.getX() * -sin + v.getZ() * cos;
    return v.setX(x).setZ(z);
}

public static final Vector rotateAroundAxisZ(Vector v, double angle) {
    double x, y, cos, sin;
    cos = Math.cos(angle);
    sin = Math.sin(angle);
    x = v.getX() * cos - v.getY() * sin;
    y = v.getX() * sin + v.getY() * cos;
    return v.setX(x).setY(y);
}

```

Sometimes I spawn the smiley facing the negative/positive X direction so to make it look like a wheel I have to rotate it around the X axis. But sometimes I spawn the smiley facing the negative/positive Z direction so I have to rotate it around the Z axis.

I searched online and found a term for an object's axes, and the one I was looking for is called "Roll".

Is there any way to rotate this smiley like a wheel **regardless of where it's facing**? a.k.a rotate it around its own "roll axis"?

# Answer
> 1 votes
I got you. Classic dynamics question right here. The three types are called 'roll', 'pitch', and 'yaw', corresponding to rotation about the x-y-z axes (respectively).
First, some vocabulary:

1. Frame - same thing as a coordinate system, but it doesn't have to be located at the origin, so it has both an orientation and a position (also called a 'transform'). Ex: 2 frame system
2. Directional Cosine Matrix (DCM) - 3x3 matrix describing how to transform vectors between frames.

What you want to do is place a frame at the base of the fan, with the x-axis pointed toward the front of the fan (such that rotation about the fan's x-axis, 'roll', forms the desired motion).

A frame is defined by a DCM (orientation) and a position vector.
Let's say you have a vector which defines the location of a point in the global frame. To express this vector in the 'fan' frame you must multiply by the frame's orientation, and subtract the frame's position.
`f_A_b = frame.orientation`
`v_f = f_A_b * v_b - frame.position`
My notation means this: `v_f` is the vector 'v' expressed in the 'f' frame (for fan). Uppercase letters are matrices. `f_A_b` is the DCM, 'A', which transforms from the 'b' frame to the 'f' frame.

By transposing the DCM, we get the opposite transform.
`f_A_b = frame.orientation`
`b_A_f = (f_A_b)^T`
`v_b = b_A_f * v_f + frame.position`
Check out this python source that shows how rotation about a frame's own x-axis is performed: link

So what you need to do is define the DCM for your fan (can be created from 3 rotations about the base coordinates and multiplied together - found here), and then update the fan frame during your game tick. Then, you can write a 'fromFanToBase' function to get your vector in the base frame.

---
Tags: java, physics, rotation
---


title: Adding Color to button after cloning

text:
# Question
Title: Adding Color to button after cloning
```
public GameObject button;

public void Start()
{
       GameObject button1 = Instantiate(button) as GameObject;
       button1.transform.SetParent(canvas.transform, false);
       button1.transform.position = new Vector3(7, 0, 2);
}

```

I have cloned the button game object now want to add color to that game object how can i do it ?

# Answer
> 0 votes
Just retrieve the Button component and apply the new color to the target graphic.

```
public void Start()
{
   GameObject button1 = Instantiate(button) as GameObject;
   button1.transform.SetParent(canvas.transform, false);
   button1.transform.position = new Vector3(7, 0, 2);
   UnityEngine.UI.Button buttonComponent = button1.GetComponentInChildren<UnityEngine.UI.Button>();
   buttonComponent.targetGraphic.color = new Color32(r,g,b);
}

```

---
Tags: unity
---