# Question
Title: Unity WebGL Build: Why it shows only Empty Folder?
i'm trying to built my game, made in Unity 2018.3, and i'm trying to built it in WebGL, but the problem is this: built was succeeded, but the Folder is still Empty, and here is the problem occured:

This was never happened to me before. anybody know how to fix it?

# Answer
Try these things:

(a) Uncheck the "Strip Engine Code" from project settings -\> other settings

(b) Try to build your project outside the current Unity project

More info: https://docs.unity3d.com/Manual/webgl-building.html
> 1 votes

# Answer
Change the Company Name and Product Name to **"ProductName"**. You can do this by:

Edit =\> Project Settings =\> Player

Both of the fields will be on top of the inspector.

I do not know why this is the case, but this surely fixed my issue, and hopefully yours would too!

Cheers!
> 0 votes

---
Tags: unity, webgl
---


title: Dialogue trees voiceover

text:
# Question
Title: Dialogue trees voiceover
I am planning to get my game dialogue trees voiced. Something like this:

However I am not sure how can I hand in the dialogue scripts in any understandable format for both me and the voice actor.

The image example from above is probably done by hand in photoshop and I dont have the time to bother with all of that. The plugin I am using does not have the full text in the separate boxes and even if it did the only way to show that to the actor is to make multiple screenshots and then combine them to one big image.

I have found a few separate programs for this, but they would require the various voice actors to install some unknown software to their machines... and I dont think any of them would want to risk that.

So to my question... What is the professional way of doing this ? I would prefer an online tool that doesn't require any installation or if I can convert all the dialogue boxes to one big image.

# Answer
> 4 votes
The professional way of doing that is to give the voice actor a script. A simple text document with all the lines you want them to say. You might also want to use this as an opportunity for adding some stage directions to the script (how they are supposed to say things) as that might not always be obvious from context.

The voice actor will then either give you one audio file per line or a single audio file with the whole script as you wrote it. Cutting that audio file into separate clips is then your job.

How do you generate that script file from your dialogue tree assets? In a comment you mentioned you are using this asset. I haven't used it myself (and I am not going to pay €37.96 to find out), but one of the bullet points in the feature list reads "Export screenplay format, voiceover asset list, CSV, Chat Mapper, and more". That's the option you might want to find and try out.

# Answer
> 1 votes
According to their documentation, the plugin supports exporting dialog in a variety of formats. For something you can hand off to voice actors, you probably want to look at the Screenplay Format.

> **Exporting Screenplay Format**
>
> conversations in standard screenplay format for interactive dialogue. For maximum flexibility, it exports one text file per language and uses tabs to ident properly.

---
Tags: unity, voice, dialogue-tree
---


# Question
Title: How do I create a weighted collection and then pick a random element from it?
I have a loot box that I want to fill with a random item. But I want each item to have a different chance of being picked. For example:

* 5% chance of 10 gold
* 20% chance of sword
* 45% chance of shield
* 20% chance of armor
* 10% chance of potion

How can I make it so that I select exactly one of the items above, where those percentages are the respective chances of getting the loot?

# Answer
> 41 votes
# The Soft-coded Probabilities Solution

The hardcoded probability solution has the disadvantage that you need to set the probabilities in your code. You can't determine them at runtime. It is also hard to maintain.

Here is a dynamic version of the same algorithm.

1. Create an array of pairs of actual items and weight of each item
2. When you add an item, the weight of the item needs to be its own weight **plus** the sum of the weights of all items already in the array. So you should track the sum separately. Especially because you will need it for the next step.
3. To retrieve an object, generate a random number between 0 and the sum of the weights of all items
4. iterate the array from start to finish until you found an entry with a weight larger or equal than the random number

Here is a sample implementation in **Java** in form of a template class which you can instantiate for any object your game uses. You can then add objects with the method `.addEntry(object, relativeWeight)` and pick one of the entries you added previously with `.get()`

```
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class WeightedRandomBag<T extends Object> {

    private class Entry {
        double accumulatedWeight;
        T object;
    }

    private List<Entry> entries = new ArrayList<>();
    private double accumulatedWeight;
    private Random rand = new Random();

    public void addEntry(T object, double weight) {
        accumulatedWeight += weight;
        Entry e = new Entry();
        e.object = object;
        e.accumulatedWeight = accumulatedWeight;
        entries.add(e);
    }

    public T getRandom() {
        double r = rand.nextDouble() * accumulatedWeight;

        for (Entry entry: entries) {
            if (entry.accumulatedWeight >= r) {
                return entry.object;
            }
        }
        return null; //should only happen when there are no entries
    }
}

```

Usage:

```
WeightedRandomBag<String> itemDrops = new WeightedRandomBag<>();

// Setup - a real game would read this information from a configuration file or database
itemDrops.addEntry("10 Gold",  5.0);
itemDrops.addEntry("Sword",   20.0);
itemDrops.addEntry("Shield",  45.0);
itemDrops.addEntry("Armor",   20.0);
itemDrops.addEntry("Potion",  10.0);

// drawing random entries from it
for (int i = 0; i < 20; i++) {
    System.out.println(itemDrops.getRandom());
}

```

---

Here is the same class implemented in **C#** for your Unity, XNA or MonoGame project:

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

class WeightedRandomBag<T>  {

    private struct Entry {
        public double accumulatedWeight;
        public T item;
    }

    private List<Entry> entries = new List<Entry>();
    private double accumulatedWeight;
    private Random rand = new Random();

    public void AddEntry(T item, double weight) {
        accumulatedWeight += weight;
        entries.Add(new Entry { item = item, accumulatedWeight = accumulatedWeight });
    }

    public T GetRandom() {
        double r = rand.NextDouble() * accumulatedWeight;

        foreach (Entry entry in entries) {
            if (entry.accumulatedWeight >= r) {
                return entry.item;
            }
        }
        return default(T); //should only happen when there are no entries
    }
}

```

---

And here is one in **JavaScript**:

```
var WeightedRandomBag = function() {

    var entries = [];
    var accumulatedWeight = 0.0;

    this.addEntry = function(object, weight) {
        accumulatedWeight += weight;
        entries.push( { object: object, accumulatedWeight: accumulatedWeight });
    }

    this.getRandom = function() {
        var r = Math.random() * accumulatedWeight;
        return entries.find(function(entry) {
            return entry.accumulatedWeight >= r;
        }).object;
    }
}

```

**Pro:**

* Can handle any weight ratios. You can have items with astronomically small probability in the set if you want to. The weights also don't need to add up to 100.
* You can read the items and weights at runtime
* Memory usage proportional to the number of items in the array

**Contra:**

* Requires some more programming to get right
* In the worst case, you might have to iterate the whole array (`O(n)` runtime complexity). So when you have a very large set of items and draw very often, it might become slow. A simple optimization is to put the most probable items first so the algorithm terminates early in most cases. A more complex optimization you can do is to exploit the fact that the array is sorted and do a bisection search. This only takes `O(log n)` time.
* You need to build the list in memory before you can use it (although you can easily add items at runtime. Removing items could also be added, but that would require to update the accumulated weights of all items which come after the removed entry, which again has `O(n)` worst case runtime)

# Answer
> 29 votes
*Note: I created a C# library for this exact problem*

The other solutions are fine if you only have a small number of items and your probabilities never change. However, with lots of items or changing probabilities *(ex. removing items after selecting them)*, you'll want something more powerful.

Here are the two most common solutions *(both of which are included in the above library)*

# Walker's Alias Method

A clever solution that's *extremely* fast *(`O(1)`!)* if your probabilities are constant. In essence, the algorithm creates a 2D dartboard ("alias table") out of your probabilities and throws a dart at it.

There are plenty of articles online about how it works if you'd like to learn more.

The only issue is that if your probabilities change, you need to regenerate the alias table, which is slow. Thus, if you need to remove items after they're picked, this is not the solution for you.

# Tree-based solution

The other common solution is to make an array where each item stores the sum of its probability and all the items before it. Then just generate a random number from \[0,1) and do a binary search for where that number lands in the list.

This solution is very easy to code/understand, but making a selection is slower than Walker's Alias Method, and changing the probabilities is still `O(n)`. We can improve it by turning the array into a binary-search tree, where each node keeps track of the sum-of-probabilities in all the items in its subtree. Then when we generate the number from \[0,1), we can just walk down the tree to find the item it represents.

This gives us `O(log n)` to pick an item *and* to change the probabilities! This makes `NextWithRemoval()` extremely fast!

**The results**

Here are some quick benchmarks from the above library, comparing these two approaches

```
         WeightedRandomizer Benchmarks                  |    Tree    |    Table
-----------------------------------------------------------------------------------
Add()x10000 + NextWithReplacement()x10:                 |    4 ms    |      2 ms
Add()x10000 + NextWithReplacement()x10000:              |    7 ms    |      4 ms
Add()x10000 + NextWithReplacement()x100000:             |   35 ms    |     28 ms
( Add() + NextWithReplacement() )x10000 (interleaved)   |    8 ms    |   5403 ms
Add()x10000 + NextWithRemoval()x10000:                  |   10 ms    |   5948 ms

```

So as you can see, for the special case of static (non-changing) probabilities, Walker's Alias method is about 50-100% faster. But in the more dynamic cases, the tree is several *orders of magnitude faster*!

# Answer
> 20 votes
## The Wheel of Fortune solution

You can use this method when the probabilities in your item pool have a rather large common denominator and you need to draw from it very often.

Create an array of options. But put each element into it multiple times, with the number of duplicates of each element proportional to its chance of appearing. For the example above, all elements have probabilities which are multipliers of 5%, so you can create an array of 20 elements like this:

```
10 gold
sword
sword
sword
sword
shield
shield
shield
shield
shield
shield
shield
armor
armor
armor
armor
potion
potion

```

Then simply pick a random element of that list by generating one random integer between 0 and the length of the array - 1.

**Disadvantages:**

* You need to build the array the first time you want to generate an item.
* When one of your elements is supposed to have a very low probability, you end up with a really large array, which can require a lot of memory.

**Advantages:**

* When you already have the array and want to draw from it multiple times, then it is very fast. Just one random integer and one array access.

# Answer
> 7 votes
## The Hard-coded Probabilities Solution

The most simple way find a random item from a weighted collection is to traverse down a chain of if-else statements, where each if-else increases in probably, as the previous one does not hit.

```
int rand = random(100); //Random number between 1 and 100 (inclusive)
if(rand <= 5) //5% chance
{
    print("You found 10 gold!");
}
else if(rand <= 25) //20% chance
{
    print("You found a sword!");
}
else if(rand <= 70) //45% chance
{
    print("You found a shield!");
}
else if(rand <= 90) //20% chance
{
    print("You found armor!");
}
else //10% chance
{
    print("You found a potion!");
}

```

The reason the conditionals are equal to its chance plus all of the previous conditionals chances is because the previous conditionals have already eliminated the possibility of it being those items. So for the shield's conditional `else if(rand <= 70)`, 70 is equal to the 45% chance of the shield, plus the 5% chance of the gold and 20% chance of the sword.

**Advantages:**

* Easy to program, because it requires no data structures.

**Disadvantages:**

* Hard to maintain, because you need to maintain your drop-rates in your code. You can't determine them at runtime. So if you want something more future proof, you should check the other answers.

# Answer
> 2 votes
In C# you could use a Linq scan to run your accumulator to check against a random number in the range 0 to 100.0f and .First() to get. So like one line of code.

So something like:

```
var item = a.Select(x =>
{
    sum += x.prob;
    if (rand < sum)
        return x.item;
    else
        return null;
 }).FirstOrDefault());

```

`sum` is a zero initialized integer and `a` is a list of prob/item structs/tuples/instances. `rand` is a previously generated random number in the range.

This simply accumulates the sum over the list of ranges until it exceeds the previously selected random number, and returns either the item or null, where null would be returned if the random number range (e.g. 100) is less than the total weighting range by mistake, and the random number selected is outside the total weighting range.

However, you will notice that weights in OP closely match a normal distribution (Bell Curve). I think in general you will not want specific ranges, you will tend to want a distribution that tapers off either around a bell curve or just on a decreasing exponential curve (for example). In this case you could just use a mathematical formula to generate an index into an array of items, sorted in order of preferred probability. A good example is CDF in normal distribution

Also an example here.

Another example is that you could take a random value from 90 degrees to 180 degrees to get the lower right quadrant of a circle, take the x component using cos(r) and use that to index into a prioritized list.

With different formulae you could have a general approach where you just input a prioritized list of any length (e.g. N) and map the outcome of the formula (e.g.: cos(x) is 0 to 1) by multiplication (e.g.: Ncos(x) = 0 to N) to get the index.

# Answer
> 1 votes
Probabilities don’t need to be hard-coded. The items and the thresholds can be together in an array.

```
for X in items’range loop
  If items (X).threshold < random() then
     Announce (items(X).name)
     Exit loop
  End if
End loop

```

You do have to accumulate the thresholds still, but you can do it when creating a parameter file instead of coding it.

# Answer
> 1 votes
Not really a new answer, but modifications to two of the answers above with:

1. Adjusted for removal of objects from the pool.
2. Added Supplier for easy stream construction (`static <T> Stream<T> generate(Supplier<T> s)`), if needed.
3. Not thread safe, so you may want to synchronize methods.
4. Java 16+

```
/**
 * Remove items from a pool, with probability proportionate to a (positive) item weight.
 * @param <T>
 */
public class WeightedRandomBag<T> implements Supplier<T> {

    private static record Entry<T>(double weight, T object) {}

    final private List<Entry<T>> entries = new ArrayList<>();
    private double accumulatedWeight;
    final private Random rand = new Random();

    public void addEntry(T object, double weight) {
        if (weight < 0) throw new IllegalArgumentException("weight cannot be negative");
        accumulatedWeight += weight;
        entries.add(new Entry<>(weight, object));
    }

    /**
     * This operation also removes the entry from the pool!
     */
    @Override
    public T get() {
        double r = rand.nextDouble() * accumulatedWeight;
        double currentAccumulatedWeight = 0;
        for (int i = 0; i < entries.size(); i++) {
            var entry = entries.get(i);
            currentAccumulatedWeight += entry.weight;
            if (currentAccumulatedWeight >= r) {
                accumulatedWeight -= entry.weight;
                return entries.remove(i).object;
            }
        }
        return null;
    }

}

```

<pre><code>/**
 * Remove items from a pool, with probability proportionate to a (positive) item priority.
 * @param <T>
 */
public class WheelOfFortune<T> implements Supplier<T> {

    final private ArrayList<T> entries = new ArrayList<>();

    public void add(T object, int priority) {
        if (priority <= 0) throw new IllegalArgumentException("priority must be >1");
        for (int i = 0; i < priority; i++) entries.add(object);
    }

    /**
     * This operation also removes the entry from the pool!
     */
    @Override
    public T get() {
        if (entries.isEmpty()) return null;
        int i = (int) (Math.random() * entries.size());
        return entries.remove(i);
    }

}
```
</code></pre>

# Answer
> 0 votes
I done this function: https://github.com/thewheelmaker/GDscript\_Weighted\_Random Now! in your case you can use it like this:

```
on_normal_case([5,20,45,20,10],0)

```

It gives just a number between 0 to 4 but you can put it in array where you got the items.

```
item_array[on_normal_case([5,20,45,20,10],0)]

```

Or in function:

```
item_function(on_normal_case([5,20,45,20,10],0))

```

Here is the code. I made it on GDscript, you can, but it can alter other language, also check for logic errors:

```
func on_normal_case(arrayy,transformm):
    var random_num=0
    var sum=0
    var summatut=0
    #func sumarrays_inarray(array):
    for i in range(arrayy.size()):
        sum=sum+arrayy[i]
#func no_fixu_random_num(here_range,start_from):
    random_num=randi()%sum+1
#Randomies be pressed down
#first start from zero
    if 0<=random_num and random_num<=arrayy[0]:
        #print(random_num)
        #print(array[0])
        return 0+ transformm
    summatut=summatut+arrayy[0]
    for i in range(arrayy.size()-1):
        #they must pluss together
        #if array[i]<=random_num and random_num<array[i+1]:
        if summatut<random_num and random_num<=summatut+arrayy[i+1]:
            #return i+1+transform
            #print(random_num)
            #print(summatut)
            return i+1+ transformm

        summatut=summatut+arrayy[i+1]
    pass

```

It works like this: on\_normal\_case(\[50,50\],0) This gives 0 or 1, it has same probability both.

on\_normal\_case(\[50,50\],1) This gives 1 or 2, it has same probability both.

on\_normal\_case(\[20,80\],1) This gives 1 or 2, it has bigger change to get two.

on\_normal\_case(\[20,80,20,20,30\],1) This give random numbers range 1-5 and bigger numbers are more likely than smaller numbers.

on\_normal\_case(\[20,80,0,0,20,20,30,0,0,0,0,33\],45) This throw dices between numbers 45,46,49,50,51,56 you see when there is zero it never occure.

So it function returns just one random number that depends lenght of that arrayy array and transformm number, and ints in the array are probability weights that a number might occure, where that number is location on the array, pluss transformm number.

---
Tags: random
---


# Question
Title: How to randomly spawn prefabs on the X axis?
I created an infinite runner game.

I need to make random spawning obstacles in 3D.

How do I randomly spawn prefabs on the X axis using a C# script?

# Answer
Modified from the unity docs:

```
//creates a position between -10 to 10 on the x-axis
float randomRange = Random.Range(-10.0f, 10.0f);
Vector3 randomPosition = new Vector3(randomRange, 0, 0);

var alexsObstacle = Instantiate(
AlexsObstaclePrefab,
randomPosition,
Quaternion.identity);

```
> 1 votes

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


# Question
Title: How can I get Steam username and avatar image from leaderboard?
After I downloaded leaderboard data (using the Steamworks.NET API), I couldn't find any related info about the user's name and the avatar picture. The only thing I can get is a `CSteamID`.

I saw some games implement a Steam Leaderboard, displaying their name and avatar images, and I'm trying to achieve the same thing. However, I've searched on the Steamworks documentation and on Google for almost a day, but couldn't find any related information.

The only thing I found was an API with SteamFriends, there were some API's that retrieved the user's name and avatar image.

Here's the code I'm trying:

```
private CallResult<LeaderboardScoresDownloaded_t> m_DownloadResult = new CallResult<LeaderboardScoresDownloaded_t>();

...

SteamAPICall_t hSteamAPICall = SteamUserStats.DownloadLeaderboardEntries(
    m_CurrentLeaderboard,
    ELeaderboardDataRequest.k_ELeaderboardDataRequestGlobalAroundUser,
    -4,
    5
);
m_DownloadResult.Set(hSteamAPICall, OnLeaderboardDownloadScore);

...

void OnLeaderboardDownloadScore(LeaderboardScoresDownloaded_t pCallback, bool failure) {
    Debug.Log("Failure: " + failure);

    if (!failure) {
        int count = pCallback.m_cEntryCount;

        for (int i = 0; i < count; i++) {
            LeaderboardEntry_t leaderboardEntry;

            SteamUserStats.GetDownloadedLeaderboardEntry(
                pCallback.m_hSteamLeaderboardEntries,
                i,
                out leaderboardEntry,
                null,
            0);

            CSteamID user = leaderboardEntry.m_steamIDUser;

            Debug.Log("Rank" + i);
            Debug.Log("User Name: " + leaderboardEntry.    // how to get user name and avatar?
            Debug.Log(leaderboardEntry.m_nScore);

            Debug.Log("===========================");
        }
    }
}

```

In `LeaderboardEntry`, I can only get the `score` and `CSteamID`. In `SteamUser` and `SteamUserStat` classes, there was no API that can get the user's name and avatar image.

# Answer
> 2 votes
You're looking for ISteamFriends.

Code for use with Steamworks.NET's isteamfriends.cs:

```
public static string GetFriendlyName(CSteamID id)
{
    return SteamFriends.GetFriendPersonaName(id);
}

public static Texture2D GetAvatar(CSteamID id)
{
    // See docs for when this is valid. Also for other sizes.
    int avatar_id = SteamFriends.GetMediumFriendAvatar(id);
    Texture2D avatar = null;
    if (!SteamUtils.GetImageSize(avatar_id, out uint width, out uint height)
            && width > 0
            && height > 0)
    {
        var image = new byte[width * height * 4];
        SteamUtils.GetImageRGBA(avatar_id, image, (int)(width * height * 4));
        avatar = new Texture2D((int)width, (int)height, TextureFormat.RGBA32, false, true);
        avatar.LoadRawTextureData(image);
        // Unity expects texture data to start from "bottom", so avatar
        // will be upside down. You could change the pixels here to fix it.

        avatar.Apply();
    }
    return avatar;
}

```

But you may want to consider using Facepunch.Steamworks which is more C#-friendly (async/await instead of callbacks, enumerables, etc). From their examples:

```
foreach ( var friend in SteamFriends.GetFriends() )
{
    Console.WriteLine( $"{friend.Id}: {friend.Name}" );
    Console.WriteLine( $"{friend.IsOnline} / {friend.SteamLevel}" );

    friend.SendMessage( "Hello Friend" );
}

var image = await SteamFriends.GetLargeAvatarAsync( steamid );
if ( !image.HasValue ) return DefaultImage;
return MakeTextureFromRGBA( image.Value.Data, image.Value.Width, image.Value.Height );

```

# Answer
> 1 votes
`SteamFriends.GetFriendPersonaName(leaderboardEntry.m_steamIDUser)`

---
Tags: unity, c#, steam, steamworks
---


# Question
Title: Building an LWJGL jar file - java.lang.NoClassDefFoundError
EDIT: Recently got it working by making a batch file that does this:

```
set /p CP=<cp.txt
java -cp %CP%;testing.jar me.pale.main.Main

```

and cp.txt is this

```
C:\Users\*\Desktop\LWJGL293\lwjgl-2.9.3\jar\lwjgl.jar;C:\Users\*\Desktop\LWJGL293\lwjgl-2.9.3\jar\lwjgl_util.jar;C:\Users\*\Desktop\LWJGL293\lwjgl-2.9.3\jar\jinput.jar;C:\Users\*\Desktop\LWJGL293\slick-util.jar

```

Recently, I've been in my head about LWJGL and creating games, and have made a simple test thingy. I tried to build the jar using eclipse, but when I run the jar file, it errors out. When I use Command Prompt, this is the output:

```
D:\>java -jar testing.jar
Picked up _JAVA_OPTIONS: -Xmx8192M
Error: A JNI error has occurred, please check your installation and try again
Exception in thread "main" java.lang.NoClassDefFoundError: org/lwjgl/LWJGLException
        at java.lang.Class.getDeclaredMethods0(Native Method)
        at java.lang.Class.privateGetDeclaredMethods(Unknown Source)
        at java.lang.Class.privateGetMethodRecursive(Unknown Source)
        at java.lang.Class.getMethod0(Unknown Source)
        at java.lang.Class.getMethod(Unknown Source)
        at sun.launcher.LauncherHelper.validateMainClass(Unknown Source)
        at sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source)
Caused by: java.lang.ClassNotFoundException: org.lwjgl.LWJGLException
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        ... 7 more

```

My native folder is correct, I've checked it.

The project runs perfectly fine in the IDE

Here's what is in my build path:

```
jinput.jar
lwjgl_util.jar
lwgl.jar > NativeLibLoc: [Native Dir]
slick-util.jar
jre system library [SE-1.8]

```

I don't know what the problem is, but thank you for anyone's help.

# Answer
According to this StackOverflow answer: https://stackoverflow.com/questions/29334257/java-lang-noclassdeffounderror-org-lwjgl-lwjglexception

> I figured it out so I will post it in case anyone else having the same problem stumbles upon this page. I had to use an older version of lwjgl.jar, version 2.9.3 worked from the old lwjgl website http://legacy.lwjgl.org/ .

There is also this StackOverflow answer: https://stackoverflow.com/questions/20044200/java-lang-noclassdeffounderror-with-lwjgl

> Try to run it like this:
>
> java -cp lib\win32\lwjgl.jar;Valor.jar Main
>
> The problem is that the -cp option is ignored when -jar is used.
>
> Alternatively, you could extend the class path by adding a Class-Path: entry in your manifest and putting lib\win32\lwjgl.jar in it.
>
> Class-Path: lib\win32\lwjgl.jar
> 1 votes

---
Tags: opengl, java, lwjgl
---


# Question
Title: Retrieving shared video memory using SharpDX
I am trying to retrieve the total available video memory using SharpDX via DXGI, using the Description of the best available adapter.

The DedicatedVideoMemory is correct (1GB in my case), but the SharedSystemMemory value is wrong - and in fact is a negative number (-1073549312, in case that's of interest). The correct value should be 3072MB, as reported by my system information and when running the Microsoft VideoMemory\_2012 example application (which also queries DXGI).

Any ideas what might be going on? Or is there another way to get this information using SharpDX? I need to scale some textures according to the available resources, and I need to know the shared component as well as the dedicated.

# Answer
This happened to me when my App was 32 bit. Try 64 bit and see if the number is correct then...
> 0 votes

---
Tags: directx, sharpdx
---


# Question
Title: How can I offset a raycast a certain distance from the camera no matter which way it is facing?
I am raycasting from the camera, which allows me to get the object that the player is looking at within a certain range.

The issue I have is that the camera can be zoomed out away from the player, so the raycast can come up short and I need the raycast to be a very specific length.

So I thought that if I get the distance from the camera to the player, I can then offset the starting position of the raycast, and this would also prevent objects getting returned between the camera and the player.

* Line A is what I am doing right now.
* Line B is what I get when trying to offset the raycast.
* Line C is what I want to achieve with the raycast.

Here is my current code I use for raycasting from the camera without trying to offset it. I tried adding the `dist` to the `start` but I think I need something else but not sure.

```
dist = camera_position - player_position
start = camera_position
forward = camera_rotation * Vector3.Forward
end = start + forward * 500

```

I tried changing `start` to include the distance between the camera and player thinking it would just shift the start of the raycast forward.

`start = camera_position + dist`

This still didn't work, the raycast would actually be further back. So I thought that maybe I need to somehow use the forward vector of the camera in the calculation.

`start = camera_position + (dist * forward)`

This worked a little better for 2 directions, but was still offset wrong. Where the crosshair was placed was not where the raycast was hitting.

# Answer
> 1 votes
```
dist = camera_position - player_position

```

The variable you've called `dist` here is not a distance, but a *displacement*: that's a distance along a specific *direction*. Which direction? The line from the player to the camera.

So this line:

```
start = camera_position + dist

```

Says to move the start point back *away* from the player, until it's twice as far away as the camera is.

If you want to shift the start position of the ray along the camera's forward vector by the *distance* between the player and the camera, then first you need to get that distance: it's the scalar magnitude of the displacement, also called the length of the vector.

It might be called different things depending on your vector library, or if you're rolling your own you can get it using Pythagorean theorem:

```
magnitude(vector) = sqrt(dot(vector, vector))

```

We can use this magnitude like so:

```
camera_to_player = player_position - camera_position
camera_distance = magnitude(camera_to_player)
start = camera_position + camera_forward * camera_distance

```

See how this stays parallel to the camera's forward vector, because we're using its direction, and discarding the direction from the displacement we were using before by converting it to a scalar distance value.

---
Tags: raycasting
---


title: How does one escape the GPL?

text:
# Question
Title: How does one escape the GPL?
**DISCLAIMER** I don't pretend to know anything about licensing. In fact, everything I say below may be completely false!

Backstory:

> Recently, I've been looking for a decent game engine, and I think I've found one that I really like, Cafu Engine.
>
> However, they have a dual licensing plan, where everything you make with the engine is forced under GPL, unless you pay for a commercial license. I'm not saying that it's a bad engine, they even say that they are very relaxed about the licensing fees. However, the fact that it even involves the GPL scares me.

So my question is basically, how does one escape the GPL.

Here's an example: The id Tech engine, also known as the Quake engine, or the Doom engine, was the base for the popular Source engine. However, the id Tech engine has been released under the GPL, and the Source engine is proprietary. Did Valve get a different license? Or did they do something to escape the GPL? Is there a way to escape the GPL? Or, if you use GPL'd source code as a base for another project, are you forced to use the GPL, and make your source code available to the world. Could some random person take the id Tech engine, modify it past the point of recognition, then use it as a proprietary engine for commercial products? Or are they required to make it open source.

One last thing, I generally have no problem what-so-ever with open source. However I feel that open source has it's place, but that is not in the business world.

# Answer
> 31 votes
1. If you hold copyright on source code, you can release that code however you like. Releasing it under GPL does not preclude a release under another non or even more restrictive license. I am not sure of the particulars of Source/id Tech but would suppose that Valve negotiated their own license.
2. If you use GPL code in your project, you are required to provide the source code to the users. This does Not mean you are required to run a website or keep a copy of it to provide on demand. This does Not mean that you are required to make all changes public as soon as you make them - it is only when you redistribute the software, that the code and the changes you make go with it. (http://www.gnu.org/licenses/gpl-faq.html#GPLRequireSourcePostedPublic)
3. If you use even a line of GPL code in your project, you are now bound by the terms of the GPL. One (though not the only way) is to release your code under GPL as well (or don't release it at all).
If you modify it past the point of recognition and do not abide by the terms, you will probably get away with it (i.e. you won't be sued) but just because you'd get away with it doesn't mean you aren't in violation of the license, or make it right.
4. To use 'GPL'd code' without GPL you have to get it under another license, so that its no longer 'GPL'd code' (by paying Cafu). There is no way out of the GPL - it was designed specifically to be a viral license by its inventors and its purpose would be negated if it were possible.

That said, if you want to use GPL code in your program, you could create a standalone entity that your application utilizes (whether dynamic linking satisfies this is debatable - but generally it's accepted that when the result is a single program, the GPL is invoked). So for example, you could create a new project with GPL code and yours, that you release with your (proprietary) application, along with the GPL and source code. Your application communicates with it however via CLI or RPC and therefore can remain free of the GPL.

Nowadays many developers adopt LGPL, which allows linking in most of its forms without GPL transferring to the destination project. (If you modify the library itself however, you must still provide the code of the library.)

Note that further to Point 2, it is considered polite to publish any improvements you make to open source code, regardless of the license.

# Answer
> 70 votes
You escape the GPL by paying the developers for a commercial license.

# Answer
> 12 votes
You're basically asking "How do I steal someone else's code?" If you want to use someone's copyrighted code, you have to get a license from them. If the only license you have from them to use their code is the GPL then you must abide by it or you are violating their copyright. If you can get them to give you a different license for their code then that is fine, but you don't *escape* the GPL.

# Answer
> 9 votes
Do you actually need to escape the GPL? All the GPL requires you to do is release your own source code under the GPL. It does not apply to game levels, art assets etc. You can still sell your game and make the code available via the GPL to people who buy it if they want it, or make it available online to everyone.

The only issue is if you want to use third-party non-GPL libraries, as then you won't be able to distribute them along with your GPL engine.

If you do need to escape the GPL, look at their licensing page they sound flexible enough that you should be able to come to an agreement.

# Answer
> 5 votes
There are a lot of misunderstandings about what the GPL actually is and actually means, and I'm detecting one in your question:

> everything you make with the engine is forced under GPL

That's actually not the case at all. The engine source remains under the GPL for sure, but it pays to have a read of the GPL FAQ, particularly the parts of it that relate to the output of a GPL program, which I believe are relevant here: http://www.gnu.org/licenses/gpl-faq.html#GPLOutput

> **Is there some way that I can GPL the output people get from use of my program? For example, if my program is used to develop hardware designs, can I require that these designs must be free?**
>
> In general this is legally impossible; copyright law does not give you any say in the use of the output people make from their data using your program. If the user uses your program to enter or convert his own data, the copyright on the output belongs to him, not you. More generally, when a program translates its input into some other form, the copyright status of the output inherits that of the input it was generated from.
>
> So the only way you have a say in the use of the output is if substantial parts of the output are copied (more or less) from text in your program. For instance, part of the output of Bison (see above) would be covered by the GNU GPL, if we had not made an exception in this specific case.
>
> You could artificially make a program copy certain text into its output even if there is no technical reason to do so. But if that copied text serves no practical purpose, the user could simply delete that text from the output and use only the rest. Then he would not have to obey the conditions on redistribution of the copied text.

This changes your situation quite a bit. You're not actually in a position where any content you develop for or with this engine also falls under the GPL; that content is yours, you own the copyright for it, and you can license it as you wish.

IANAL, etc

# Answer
> 4 votes
Only the person, the group of people, or the activity that owns the code can change its own license.

If that code is yours you can change license every time you want, decide to be payed or not, you can do what you want, but if the code it's not yours you stick with the license if you want to avoid troubles; big troubles.

The owner can also refuse to accept to be payed, it's a situation like the one that you have with the patents, if you can prove that you own the code doesn't mean that you are putting it on the market for money, many many times the patent or the license is supposed to force the market or the user to stay in a confined space.

The answer is no and the only way to change the license is hoping that the owner will do that.

# Answer
> 4 votes
The idea is simple - if company wrote the code, it thus owns all the rights, and thus it can give it to some parties under GPL license, to others under commercial license, and to someone else they can give it as a gift, or rent, or whatever they want.

The fact that they provided the code to some party under GPL, places GPL restrictions on *that party*, but it can place no restrictions on ***code owner***.

Only, if code owner used in their software some **3-rd party** GPL code, written and owned by someone else, then their whole project is locked into GPL forever (or until they remove this 3-rd party GPL code or obtain a non-GPL license for it). *Please note that that the same is equally true for no-GPL, 100% commercial engine - if they happen to include some GPL code, they violate GPL, have no right to sell commercial licenses and you have no right to buy such license.*

Thus, if all the code in the "Cafu Engine" is written by Cafu staff, you have no problem with the GPL. If you get a commercial license from Cafu, then the GPL license does not apply to **you** at all.

# Answer
> 2 votes
There's one way to "escape" GPL or (practically) any other license. Make a clean-room implementation.

Hire two groups of people. The task of the first group is to study the original material in minute detail and describe it. The second group, who never, ever get to see the original material, will write a new implementation based on the description.

This is how BIOS on original PC clones was created; the BIOS was the only bit IBM didn't let other people copy.

This doesn't mean that you're safe from lawsuits.. patents and "look and feel" crap is still out there, and at least in the US, anyone can sue anyone for no particular reason (or at least it seems so..)

# Answer
> 1 votes
Regarding the question about the Quake engine: code can be released under GPL and also under other licenses. Valve licensed Quake by paying money to iD. Later, everyone in the world was granted a GPL License (sic) to use the Quake source code. When iD GPLed the engine, they didn't retroactively convert other licenses to GPL; that would be impossible. In fact, iD can still license the Quake engine under a different license if they wish, as they own the original copyright.

# Answer
> -1 votes
You don't if you're being ethical. You're harming the development team. At the very least, you probably cannot get around the GPL, and if you close source your code you'd owe the developers any profits earned from their code.

---
Tags: licensing
---


# Question
Title: Godot 3 - When body enters Area2D move Camera2D
I'm totally new to Godot 3 engine. I want a game with static camera, so it can't smoothly follow player. I made an Area2D signal when\_body\_entered witch teleports main character to next area of map. Now I need to know how to move the camera (in Vector2 or just Y axis) when player enters the area.

# Answer
---

## Multiple cameras

Have multiple `Camera2D`. Then on the handler for `"body_entered"` signal of your `Area2D` you can set `Camera.current = true` for the `Camera2D` of the next room (areas of the map). And set `current` to `false` for the prior camera.

Alright, if you are going to have references to the cameras in your script, you may instead export some `NodePath`s for them. Something like this:

```
export var old_cam_path:NodePath
export var new_cam_path:NodePath

func when_body_entered(body:Node) -> void:
    get_node(new_cam_path).current = true
    get_node(old_cam_path).current = false

    # Also teleport the player character

```

Now, you should be able to select the old and the new camera in the inspector panel.

---

## Teleporting Camera

Alright, but we don't want to change cameras, we want to move the camera. Well, add some `Position2D` nodes to mark the position for the camera, and then we can do this:

```
export var cam_path:NodePath
export var cam_target_path:NodePath

func when_body_entered(body:Node) -> void:
    var cam := get_node(cam_path) as Camera2D
    var cam_target := get_node(cam_target_path) as Position2D
    cam.position = cam_target.position

    # Also teleport the player character

```

By the way, you can use the same approach to teleport the player character.

---

I'll also remind you that you can use the collision layers to filter what the `Area2D` detects. Also, a common approach is to use groups to discern between the bodies. You can add groups to nodes in the Node panel on the Groups tab. Then in code use `body.is_in_group("group_name")` to check.

---

## Traveling Camera

Another thing you can do with this is to *tween* over time the camera position instead of changing it instantly. To do that we can use a `Tween` node. Which in this case I will go ahead and create from code instead of adding it in the editor:

```
export var cam_path:NodePath
export var cam_target_path:NodePath

var tween:Tween

func _ready() -> void:
    tween = Tween.new()
    add_child(tween)

func when_body_entered(body:Node) -> void:
    var cam := get_node(cam_path) as Camera2D
    var cam_target := get_node(cam_target_path) as Position2D

    var seconds:float = 1.0
    tween.interpolate_property(cam, "position", cam.position, cam_target.position, seconds)
    tween.start()

    # Also teleport the player character

```

Here we are telling the `Tween` to move the `"position"` of the `camera`, from the current value of `camera.position` to the current value of `camera_target.position`, in the span of `seconds`.
> 5 votes

---
Tags: godot, gdscript, body
---


# Question
Title: Can't check collision between a mask and a rect in pygame
I'm new to using masks in Pygame and I'm having trouble with them. I have already learned how to check collisions between two masks but I'm wondering about an effective way to check collisions between a rect and a mask.

I've seen this post on stackoverflow : collisions between rect and mask but I didn't understand the answer and I don't even want to create my own function to do this work as I think there is a way to do it with the pygame functions.

So I tried to find a way myself and this is my attempt:

```
class Rectangle:
    def __init__(self) :
        self.x, self.y = 240, 300
        self.rect = Rect(self.x, self.y, 50, 50)
        # I have made a function to get the coordinates of the center of an image or a rect
        self.center = center(self.x, self.y, self.rect)
        self.mask = pygame.mask.Mask((50, 50), True)
        # some code

    def blit(self) :
        # update the pos of the center
        self.center = center(self.x, self.y, self.rect)
        pygame.draw.rect(MyScreen, 'green', self.rect, border_radius=2)
        # some code

class Circle:
    def __init__(self) :
        self.image = load('redcircle.png')
        self.x, self.y = 400, 220
        self.mask = pygame.mask.from_surface(self.image)
        self.center = center(self.x, self.y, self.image)

    def blit(self) :
        # update the pos of the center
        self.center = center(self.x, self.y, self.image)
        MyScreen.blit(self.image, (self.x, self.y))

myrectangle = Rectangle()
mycircle = Circle()

collision_detection() :
    # I also created a function called 'offset' to calculate the offset
    # However I still don't understand what an offset is, that's why I'm just calculating it automatically
    if mycircle.mask.overlap(myrectangle.mask.get_rect(center=myrectangle.center), offset(mycircle, myrectangle)):
            print('it worked !')

```

This code didn't work And I got a "TypeError: argument 1 must be pygame.mask.Mask, not pygame.Rect" error.

So now I'm looking for a simple way to detect collisions between a mask and a rect object and as I mentionned in the comments in the code above, I still don't understand what is an offset that the function `pygame.mask.overlap` takes though I also checked this post. So I'm looking for an easy explanation, thanks !

# Answer
The way you create your "rectangle mask" seems appropriate and roughly in line with the question you've linked to on StackOverflow:

```
self.mask = pygame.mask.Mask((50, 50), True)

```

Now that this is out of the way, it seems that the `mask.overlap` method that you use expects a `Mask`, not a rectangle. Since you have defined that "rectangle mask" in your `Rectangle` object, you just need to pass it to the other object's `overlap` method.

```
if mycircle.mask.overlap(myrectangle.mask, offset(mycircle, myrectangle)):

```

The `offset` the `overlap` method expects is only the difference in x/y between the two objects "top left" corners. In your example, I assume that the call to `offset(mycircle, myrectangle)` returns the difference

```
[myrectangle.x - mycircle.x, myrectangle.y - mycircle.y]

```
> 1 votes

---
Tags: collision-detection, pygame
---


# Question
Title: Camera doesnt track player properly on different resolution
Hello i have 2d mobile game where camera follow players car, on my mobile phone with resolution 2960x1440 everything works fine but when i start the game on tablet with resolution 2160x1620 the camera shows only a half of the car... i made some drawings for better imagination :)

I was trying to do it by myself for a few days but i am new in unity and i do not fully understand Camera class

i have this script on my camera:

```
public GameObject playerPos;
private Vector3 lastPlayerPosition;
private float distanceToMove;
void Start()
{
    lastPlayerPosition = playerPos.transform.position;
}
void Update()
{

        distanceToMove = playerPos.transform.position.x - lastPlayerPosition.x;
        transform.position = new Vector3(transform.position.x + distanceToMove,         transform.position.y, transform.position.z);
        lastPlayerPosition = playerPos.transform.position;

}

```

# Answer
In unity, you can use Cinemachine to define a region on the screen and the camera will move to keep your object inside that region. I think the Framing Transposer is the behaviour you're looking for.

See their tutorial or install the package and install one of their samples for an interactive demo.
> 0 votes

---
Tags: unity, camera
---


# Question
Title: Record/History of moves and state of entire game after that move for a Turn based game
My first question here! :)

Im trying to conceptualize how I would go about recording the moves of my players, and also the state of my game after the calculations of that move.

For example, Final Fantasy tactics.

1. UnitA makes an attack
2. Calculations will be done
3. Store the last move, and also the state of the game after that move.

In the example above, for example, I use Firebase firestore to update the players of the state of the game. In that firestore document, i will update it with the latest move and its effects, together with the latest state of game.

My concern is in number 3, where should I put the record of the previous moves and state of the game after those moves. The purpose of this is for example, I want to replay the match. With records of each moves and states of the game after those moves, I will be able to replay the match accurately. My concern is, it seems recording all these seems huge data because, if a unit moves, I would have to store the entire state of the game, which includes all units hp/position in tile map/buffs/ abilities states(cooldown) etc.

What I have thought of so far Option: A: (Bad)Store them in same document as the latest document snapshot. Like create an array where it will contain the record of move and snapshot for that move B: (I think better than A but so many documents will be created) Create one firestore document for each move with the state of the game after that move and store them on a separate firestore collection.

May I ask for advice.

Thanks in advance

EDIT:

The game is a typical turn based game with 2 players (for now, in my plan, i want it to be dynamic, could be 2 teams with multiple players in each team. Or 2 or more teams). But for now, just 2 players playing against each other. Each player controls units. Each unit has several abilities to use.

Abilities may Stun, apply Buff, and/or Damage etc the target unit/units. And those status may linger on on the targeted unit. For example, Silence or Stun for 2 turns. These are just few example of `attribute` effects, but there are more and could be further increased in the future.

Unit A, and Unit B are allies. Unit X is their enemy. On previous turn, Unit X casted a `channeling` stun to Unit B. Rendering Unit B unable to move. Now on new turn, Unit A stuns Unit X, freeing Unit B. This is the example i listed above. Another example is below

Unit A, and Unit B are allies. Unit X is their enemy. On previous turn, Unit X casted `silence` to Unit B. Now on new turn, Unit A casts a `repel` buff to Unit B so he can casts spells again.

Reasons why I am considering storing every state per move:

1. Replay purposes and displaying the state of the game accurately. Say for example, replay can be paused, and the viewer of the replay can check the state of the game (units, buffs, cooldowns, etc)
2. Debugging purposes, say for example, a bug was reported saying a certain skill isn't working as expected during a certain condition.

# Answer
> 1 votes
*It depends* \- first of all start with whatever you have and later upgrade if problems occur. If storing whole state becomes a problem then...

...Command pattern is the way to go, as others said. Storing a state after each move is... not a way to go. *No, let me rephrase*. It's ***wasteful*** but good at prototyping stage. "You feel that it's bug prone". Yes, but you will squash those bugs, like all other titles do... I've never seen anyone storing EVERY state because they feel insecure.

I'm getting a vibe that you are a bit of a novice and try to overengineer something simple. Realistically speaking as long as you can replay things deterministically (storing RNG seed etc) you have a very lightweight way of keeping state. I recommend reading this free webbook about Game PRogramming Patterns to get more understanding

You can solve it all easily by combining the command pattern and storing **SNAPSHOTS** of state. Let's say you record a full state after 20 moves - so you have those key frames that store full state and delta moves that transform a state bit by bit. To replay you just go to snapshot and replay several actions from there. Same goes for sending state for debugging (idea taken from GDC talk about Rewind in Braid as linked in the @Charlys answer). And the best part about snapshots - they are simple - you basically store state and several actions - it's a minuscule difference from storing *every* state.

You can control frequency of snapshots however you want - If rewinding a replay takes too long you just increase granulity of snapshots. Determine how frequent snapshots should be done by examining what amount of moves takes an instant to replay and doesn't produce hangups.

Also to your Firebase database - usually things like that are done very infrequently, like once or twice a day when the network congestion is very low. Basically your whole state should be kept on server until it's synced with the DB. I don't exactly know how Firebase Firestore's pricing model looks like, but considering snapshots looks like a good and easy way of optimizing resource utilization.

Snapshots also allow you to test your determinism - you can detect if you have some bugs when you replay all moves from the initial state and compare it to the stored snapshots. If they diverge - you just binary search for snapshot where undeterminism was introduced.

@Edit, Because I didn't put emphasis on that - ***first do something that works and later if you have problems - upgrade***.

# Answer
> 1 votes
**TL;DR**

Go with the simplest, most robust solution until it becomes a problem.

**Saving the entire game state**

From my understanding game is turn-based, with a super finite amount of actors and actions on a small map at anytime. I can almost guarantee that it will never be a problem saving your entire game state into a single Firestore document. So go with the simplest, least bug prone solution. You're a single dev, your resources are super precious and should be spent elsewhere, on the actual game. Saving the entire game state over saving just the deltas or actions between turns might actually represent an **economic optimization** and save you money, this is because the Firestore monetization model is largely based off **document reads**. So if you want to go see what the end state of a 58 turn match looked like, instead of having to read 58 documents in order and be charged for each read, you can just get a single snapshot of the 58th turn instead.

**If this becomes a problem**

If this ever becomes an insufficient strategy due to memory limitations, or whatever else, then it's no big deal to move to a command-pattern (or saving deltas) based solution later, as underlined in @Tooster's response. Now at least you'll know that you're not wasting your time, over-engineering a solution which never had to be. I doubt this will be the case for your game though, and if your priority is the game and not the programming, then I would strongly recommend only doing once you prove that the simpler, more robust solution won't be sufficient.

**Resources**

Jon Blow has a good talk in which he talks about how he did rewind in Braid. A very different game with very different problems. Nevertheless his solution was pretty straight forward, and because of that he avoided having to constantly squash bugs in his rewind system, and could devote his resources elsewhere.

---
Tags: architecture, turn-based, replays
---


# Question
Title: How does a PackedScene work when passed in an exported variable
To my beginner understanding, in order to use a scene saved on the drive, one must first use `ResourceLoader.load()` to load the scene to acquire a `PackedScene`, then instantiate it using `PackedScene.instance()` to acquire the `Node` that can be finally added as a child.

Following this principle, one can easily export a script `String` variable and use it to set which scene will be loaded by a node - even with convenient hints like this:

```
export(String, FILE, "*.tscn") var scene_path

```

But that's not fully descriptive in my opinion. I want to select a scene - an only scene - in that exported variable. Looking around the internet, this Godot Q&A post mentions one can export a `PackedScene` variable like any other to link to another scene. So I immediately thought of this:

```
export(PackedScene) var new_scene = null

```

This looks much cleaner - especially the ability to initialize it to `null`, as well as having access to methods like `can_instance()` to catch any accidental false inputs in the editor... however, this looks like there is one important link of the chain I mentioned at the start missing. In the end, I'm still selecting the `PackedScene` as a path on disk, so when does the `load()` happen?

Is this a valid and correct use of the `export` keyword, or could this come back to haunt me later if I overuse it?

# Answer
Yes, this is perfectly valid use of `export` and `PackedScene`. In fact, you can do this with any `Resource` (please notice you use a *`ResourceLoader`* not a "SceneLoader"). The `Resource` type has support for serialization and deserialización out of the box.

*See When and how to avoid using nodes for everything.*

---

When the game starts it has to load (and instance) the main scene. When you change the scene to another scene, Godot has to load (and instance) that another scene. Or when you tell Godot to load a `PackedScene`, Godot has to load that scene.

To tell Godot to load a `PackedScene` you can use `preload` (loads on parse), `ResourceLoader.load`, `load` (simplified `ResourceLoader.load`), or `ResourceLoader.load_interactive` (loads in stages to avoid blocking the game while loading large resources, each stage load a subresource).

And if the `PackedScene` that is being loaded happens to have nodes that export some `Resource` (such as `PackedScene`), those has to be loaded alongside too.

*That is when the load of the `PackedScene` happens. I hope that makes sence.*

---

Furthermore, this is not only for `PackedScene`. You can export any other `Resource` type, for example `export(Shape)` works.

---

Aside, I also want to mention that the editor support for exporting custom resources is not great. If you do `export(CustomResource)` where `CustomResource` is a `Resource` type you created, it won't work. Instead you are forced to do `export(Resource)`, which results in the editor showing all possible `Resource` types under the sun for you to select.

Workaround:

```
tool
# …

export(Resource) var variable:Resource setget set_variable
func set_variable(new_value:Resource) -> void:
    if !(new_value is CustomResource): new_value = CustomResource.new()
    variable = new_value

```

See the proposal Add first-class custom resource support.
> 3 votes

---
Tags: godot, gdscript
---


# Question
Title: Is attribution sufficient for a CC BY-SA 3.0-licenced font in a video game?
I'm creating a video game I intend to sell on computers, and I want to use a font that is under the license "Attribution-ShareAlike 3.0 Unported (CC BY-SA 3.0)".

Do I have to sell my game under the same license, or is it enough just to credit the creator?

I have done research but I'm still unsure, specifically for fonts.

Font: https://www.1001fonts.com/7-12-serif-font.html

# Answer
> 6 votes
> Is attribution sufficient for a CC BY-SA 3.0-licenced font in a video game? Is it enough just to credit the creator?

Yes.

> Do I have to sell my game under the same license?

No.

The web clearly states "the material".

Here, *the material* is the font. If you only *use* the font in your game, you only need to give the appropriate credit:

> You must give appropriate credit, provide a link to the license, and indicate if changes were made. You may do so in any reasonable manner, but not in any way that suggests the licensor endorses you or your use.

If you were to also *modify* the font and use the modified version in your game, you would need to make it available to others under the same license: Attribution-ShareAlike 3.0 Unported (CC BY-SA 3.0).

# Answer
> 1 votes
## Summary:

* If you've used it, attribution is required.
* If you've created a new separate artistic element from it, you must distribute your contribution.

## Explanation:

It comes down to how you are using the font. From the license text:

> ShareAlike — If you remix, transform, or build upon the material, you must distribute your contributions under the same license as the original.

Using the font as is to display the player score does not remix, transform, or build upon the material.

Creating a new font with gore drips for displaying damage taken would be transformative. The *new font* would need to be released under the same license; the game *uses* the derivative font, but *is not itself* a derivative font. Attribution is still required in some context with the game, but the game itself is not subject to the CC license.

However, let's say the gore drips weren't part of a new font itself, but instead were added separately (perhaps as a special effects shader). In that case, the original font is *not* being transformed directly and is not a "separate artistic element". Because there's no new font that could be released, the "distribute your contributions" clause would not be applicable.

And in all cases, Creative Commons isn't a great license choice for software and creativecommons.org recommend against using it as such:

> **Can I apply a Creative Commons license to software?**
>
> We recommend against using Creative Commons licenses for software. Instead, we strongly encourage you to use one of the very good software licenses which are already available. We recommend considering licenses listed as free by the Free Software Foundation and listed as “open source” by the Open Source Initiative.
>
> Unlike software-specific licenses, CC licenses do not contain specific terms about the distribution of source code, which is often important to ensuring the free reuse and modifiability of software. Many software licenses also address patent rights, which are important to software but may not be applicable to other copyrightable works. Additionally, our licenses are currently not compatible with the major software licenses, so it would be difficult to integrate CC-licensed work with other free software. Existing software licenses were designed specifically for use with software and offer a similar set of rights to the Creative Commons licenses.

Instead, they go on to say:

> While we recommend against using a CC license on software itself, CC licenses may be used for software documentation, as well as for separate artistic elements such as game art or music.

---
Tags: legal, fonts
---


# Question
Title: Recycling bullets versus spawning them on demand
Until now, I know 2 bullets' algorithms/configurations : (I mean 2 ways of logically creating a bullet class)

1. Make a bullet class and create only one instance from it that represents the bullet. The bullet hides under the player's image until he shoots it. Then, he won't be able to shoot again before it reaches the end of the screen and then hides again under the player's sprite. (This configuration uses only one bullet instance for every bullet type, it means that the player cannot shoot multiple bullets of the same type at once)
2. Make a bullet class and repeatedly create new instances of it as much as the player needs and as long as he can shoot. (depending on the firerate)

Personally, I like the second algorithm, however, I think that creating many instances does slow the performance especially when the number of these instances becomes bigger and bigger (especially at an advanced stage of the game).

So I have some questions in this topic:

1. Will using numpy arrays instead of lists (in order to store the instances) decrease the risk of slowing the game performance ?
2. Will deleting some instances regularly prevent from losing the performance ?

pseudocode for this :

```
if len(bullets_list) >= 5:
    del bullets_list[:4]

```

Btw I want to know what happens exactly (technically) when an instance is deleted from a list in Python/Pygame. And if there is already an answer for this, just attach it with your answer ;)

3. Are there any other algorithms to develop a bullet class ?
4. Are there any improvements to the previous algorithms in order to have a good & stable performance and to ensure a good UX ?
5. Finally, how can I choose which configuration/algorithm to use depending on my game ? (What are the standards to follow to determine the answer to this question)

# Answer
> 1 votes
The method that most games use is a variant on 1 where there are multiple instances which get recycled. How many you pool depends on your game.

This way the CPU performance doesn't vary as more bullets are spawned.

You can do this by adding a field in your bullet data that lets you test whether the bullet is active (like a time to live that become negative).

On each shot you look through the list to find the first bullet that is inactive and then initialize it to be active. When updating you can do what's needed to prevent the dead bullets from affecting the render and gameplay

When doing numpy processing then do numpy processing, don't grab the data one by one into python code to do math on instead tell numpy to do the math in bulk on the array directly. The strength of numpy lies in these bulk operations.

---
Tags: algorithm, python, pygame, spawning, object-pools
---


# Question
Title: How do I guarantee that important one-time events in my UDP network protocol get received?
I'm creating an online arena game server (moba) that players can play together. 2v2 or 3v3. The game is similar to Battlerite.

I chose client/server architecture with deterministic server that tells clients about positions, actions etc. I assume everything is OK and players have good connection, so for now i don't care about prediction or lag compensation. I also use static state update -- server sends all needed data to players even if a player didn't move it sends his position, also spell cast data are in state update too. I use UDP for my network backbone and 50ms tick rate on server side. in client side we use interpolation between two update to make game seems smooth . If command to move arrives after a period when you get next update you will move.

**here is my client code:**

```
    public void loop()
    {
        while (client_started)
        {
            try
            {
                receive();
            }
            catch (Exception e)
            {
                throw e;
            }
            try
            {
                send();
            }
            catch (Exception e)
            {
                throw e;
            }
        }
    }
    private void send()
    {
        if (disconnected)
            return;
        try
        {
            foreach (var item in need_ack_packets)
                send(item.Value);

            on_sampling?.Invoke(command_sample);
            if (command_sample.has_data)
            {
                send(command_sample.to_udp_packet());
                command_sample.clear();
            }
        }
        catch (Exception e)
        {
            throw e;
        }
    }
    private void receive()
    {
        try
        {
            var data = client.Receive(ref receive_endpoint);

            if (data.Length == 0)
            {
               //------
            }

            var pack = udp_packet.from_bytes(data, aes_crypto);

            if (pack.is_ack)
                need_ack_packets.TryRemove(pack.ack_to_message_id, out _);
            if (pack.need_ack)
                send_ack(pack);
            if (pack.has_body)
               {
                    on_data_receive?.Invoke(this, pack.body);
                }
        }
        catch (Exception e)
        {
            throw e;
        }
    }

```

As you can see on the client side I send data after each server update receive and if an important packet must be sent I send it again and again until server ACKs for that (I send sample in 50 ms rate too). The movement or attack is not important for me but spells are. so i can make sure all important data will reach to server with ACK so in worst sample maybe we have delay.

But my problem is on the server side. Let me give you an example :

* player no. 1 sends a spell/skill cast -- assume it's a powerful strike with a sword or a roll forward.
* the packet is dropped.
* client sends it again.
* server receives it and ACKs. (100 ms delay until now)
* in next update server sends to all that player no. 1 casts a spell.

---

1. **what if our own player didn't get this update ?** (as I said there is no prediction so he's waiting until server's command)
2. **what if another player didn't get this update ?**

I searched a lot about this subject but can't find answer to this scenario. All documents talk about movement and if an update drops, "don't worry it will be sent soon again (50 ms latter)".

Lets say the spell is roll so if server receive that command will change player position forward for 1 second (a bit in each tick). If a player miss two updates he has a new position but he missed spell cast information. Lets say the spell is powerful strike it must happen in 1 or 2 update so if a client miss two updates he missed it or if we resent spell cast to unlucky client (if attacker and target move) in new update client sees attacker and target are in new positions and there is a spell cast request in update too so powerful strike can't cast on target due to distance between them.

please correct me if I made mistakes in any step of my work.I'm searching for an efficient way to handle these scenarios. how to send important update (repeat whole update, repeat important parts)? how play animations attacks etc to make game smooth? how handle new positions and delayed spell casts?

# Answer
One approach I've seen is to include in each packet an ID of the last update you received from this client/server, or a bitmask of which packets you've received in a sliding window.

When forming an update packet to send, you include the current state info, plus any "important" messages from any packet for which you don't yet have a confirmation of receipt.

That might mean you end up sending "I cast spell X at timestep Y" 2-3 times before the first one gets acknowledged, but that and the acknowledgment ID/mask are only a few bytes of extra bandwidth if you use your bits efficiently, rather than a whole separate stream of packets on their own. And because you repeat yourself "eagerly", a dropped packet will usually incur only a single packet interval of latency, rather than 3 x your one-way communication delay (to wait for the initial receipt, then note the missed acknowledgement and re-transmit, then receive the re-transmission on the other side).

By including the time stamp when the important action occurred, you can ensure it's not double-counted when two copies of it are received. And you can use that to back-date its effects when received late, fast-forwarding the animations or other feedback to get back on track with the consensus timeline.

Obviously to prevent cheating, your server will validate that a back-dated event like this lines up with a gap where a packet failed to arrive, and keep track of clients who are dropping a lot of packets this way: they're either on a very poor quality connection, or are cheaters strategically skipping packets to try to exploit the back-dating, and either way they should probably be dropped from the match.
> 2 votes

---
Tags: unity, c#, client-server, server, game-state
---


title: Using Lua to define NPC behaviour

text:
# Question
Title: Using Lua to define NPC behaviour
I'm working on a RPG in C using Lua for event scripting like NPC behavior. I ran into a design problem.

I have created Lua threads in the C API for each game object which can be a NPC. So this:

```
function objinteract(o)
        if o.id == 1 then
                textbox("Hello I'm ",o.name,"!");
                yield();
        end
end

```

Is what happens when the player talks to the NPC. But I'm not sure on how to implement walking/wandering.

I could do it like this:

```
function update(o)
   if o.id == 0 then
       movewest(o.id,3); -- move NPC three tiles west.
       yield();
       movenorth(o.id,3); -- move NPC three tiles north.
       yield();
       moveeast(o.id,3); -- move NPC three tiles east.
       yield();
       movesouth(o.id,3); -- move NPC three tiles south.
       yield();
   end
end

```

Though this is a good solution, if the NPC were to be talked to, the flow of the script would be lost because I'm using one thread for each NPC. Any solutions for this?

# Answer
> 1 votes
Instead of using a fixed path, you could define four waypoints `{0,0, -3,0, -3,3, 0,3}` and iterate through them. This means you'd need `move_to_point` instead of `movewest`.

Maintain the current destination and if interrupted, you resume travelling to that destination once you want to wander again. Additionally, this system will scale to more complex travelling behaviours.

---

I always like to think of AI divided into two: brain and body. The brain is the behaviours deciding *what* we should do and the body is the *how*. Both of them revise their decisions regularly (but not necessarily every frame).

Example: the brain decides "go to wander point A". The body determines the path and begins executing it. The player interacts with the NPC and the brain decides the player is most important so it switches to conversation behaviour. The body stands there and starts gesturing. When the conversation completes the brain re-selects the next waypoint.

So in your example, you might choose the action and then perform one update worth of that action:

```
function update(o)
   if o.id == 0 then
       -- brain:
       local action = determine_action(o.id)
       -- body:
       if action.talk then
           talk(o.id)
       elseif action.walk then
           -- might not get all the way to dest
           move_towards_dest(o.id, action.dest)
       end
       yield();
   end
end

```

Your talk could also yield which forces the conversation to continue and prevents interruption. (If I remember lua coroutines correctly.)

---
Tags: lua, coroutines
---


# Question
Title: Unity Event destroys all GameObjects if there are more than two listeners
I've been writing a system where, if a raycast hits a 2D gameObject, a `UnityEvent` is fired and the `Shot()` method is executed. It works fine if the amount of listeners receiving the callback is equal to one, in this situation it destroys only clicked GameObject (which is what I need). As soon as you add another callback (AudioSource, Playing Particles), it destroys all GameObjects, which I don't want to be destroyed.

Class with Event:

```
public class ItemRaycastHit :  MonoBehaviour
{
    [SerializeField] private UnityEvent _shot;
    void Update()
    {
        if(Input.GetMouseButtonDown(0))
        {
            Vector2 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            RaycastHit2D hit = Physics2D.Raycast(mousePos, Vector2.zero);
            if (hit.collider.TryGetComponent<ClickableObject>(out ClickableObject clickable))
            {
                _shot?.Invoke();
            }
        }
    }
}

public class ClickableObject : MonoBehaviour
{
    public void Shot()
    {
        Destroy(gameObject);
    }
}

```

Image of the clickable object in inspector

# Answer
That is how it works. I'm not sure why you want to do this? You have a collider there, so just use the OnMouseDown event manager instead of the Update. See the example on the Unity manual: https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnMouseDown.html
> 0 votes

# Answer
It looks like you wanted to write this:

```
public class ItemRaycastHit :  MonoBehaviour
{
    [SerializeField] private UnityEvent _shot;

    void Update()
    {
        if(Input.GetMouseButtonDown(0))
        {
            Vector2 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            Collider2D hit = Physics2D.OverlapPoint(mousePos);
            if (hit != null
            && hit.TryGetComponent<ClickableObject>(out ClickableObject clickable))
            {
                // Invoke the Shot method on *only*
                // the one ClickableObject that we clicked on.
                clickable.Shot();

                // Use our event to notify anything *that is NOT*
                // a ClickableObject that might want to also respond.
                _shot?.Invoke();
            }
        }
    }
}

```

You can now remove your `ClickableObject`s from the list of listeners for the `_shot` event. We'll call their `Shot()` method directly when they're clicked. You can use the event to inform any third party that is not this script AND is not the object that was clicked.

I also changed your raycast code to an `OverlapPoint` check, since that expresses the intention more clearly than a raycast with no direction.
> 0 votes

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


title: Space out units to a grid pattern

text:
# Question
Title: Space out units to a grid pattern
So imagine an RTS game, with ~150 units all cramped together, just staying chill. What I would like is to "space them out" so that they d form a grid. This is useful for example when a large area attack is about to happen so Player would like to minimize damage.

Naive solution is simple: find the middle of all units, calculate side of the grid (~sq root of number of units) and make it larger than current mess. For each point of the grid, find the nearest unit among "units to place" and give him order to move to that grid point. Remove that unit from total list of "units to place", proceed with next grid point. Stop when no more units to place.

Naive solution is obvious and I have implemented it, but I think there might be a less expensive solution, which would not require me to calculate distances for every point?

I am not asking for implementation, just some pointers, if any, or links to resources.

# Answer
> This is useful for example when a large area attack is about to happen so Player would like to minimize damage.

Sounds like you're thinking of giving the player the option to specify formations, so other spacing options (like boids) won't work.

I have two ideas for you.

# Manhattan distance from origin

What you have sounds good, but you could also try a less-precise method of placing the units that only finds distances relative to one point:

1. determine the bounds of the grid
2. sort a list of the units by their distance from the top left of the grid (the grid origin)
3. pop off units from the list and assign them to grid spaces that get gradually farther from the grid origin (instead of iterating row by row, you iterate by an L shape)

# Truncate position to int

Another method to find grid candidates would be to truncate the unit's floating point position into an integer grid position: take grid, rotate to align to world axes, translate into world coordinate space, round values of unit positions into grid cell buckets and subtract the grid offset. Some cells may have multiple units, but you can resolve that by tracking the grid occupancy (as a 2d array of bool or unit pointers) and looking in nearby cells instead of doing more distance comparisons.
> 1 votes

---
Tags: algorithm, grid, rts
---


title: All kinds of 2key controls

text:
# Question
Title: All kinds of 2key controls
I want to find all possible ways to control a game using 2 keys on input.

**1. Summarize the problem**

I find a brand new game engine that has only two inputs but great potential! And the community of this engine needs as many control methods as possible. I want to find, develop and share all of them! (Player may control not only character but any possible types of game.)

**2. Provide details and any research**

Сapabilities of keys:

* press one key (short hold)
* hold one key
* press both keys (short hold)
* hold both

Input method: 2 keys on a keyboard or 2 halves of sensor screen.

**3. When appropriate, describe what you’ve tried**

Examples of existing methods (dir -\> direction):

* *key1*: switch dir (right, down, left, up, right, down, ...); *key2*: move
* *key1*: switch dir (right, left, right, left, ...); *key2*: move
* *key1*: left move; *key2*: right move
* *key1*: turn left; *key2*: turn right; *hold both*: move forward

If you have any ideas, please, leave the answers!

# Answer
> 0 votes
It is unclear to me if you support directional or not. If you have up, down, left, right and two buttons… That's six buttons!

I'll assume you don't have six buttons like that. Just two.

Let us not pretend that you would have to adapt to the limitation of this two button engine. If you play it to its strength then you would pick **auto-runners**, **auto-battlers** (see "Menus" below) or **rail shooter games**. And of course **rhythm games**.

Also know that with only two buttons, the impact of speed to difficulty is going to be large. Thus, the game might need to be slower than expected for the same difficulty.

And no, I'm not claiming these are every posible two button input scheme. But the approaches I describe here should - at least - help with any game genre.

---

Well, you need are four commands (five with "do nothing", which will let press nothing be): "Next option", "Prior option", "Enter" and "Exit". And you have a hierarchy of menus.

In fact, actually, you only need three: "Next option", "Enter", "Exit". And have the options loop.

We can do better:

* Next option
* Do option
* Change menu

So you would have a menu of menus that you go to when you use "Change menu". From there you can select which menu you want to use. Once inside a menu, you operate with "Next option" and "Do option". *And you use "Change menu" when you want to go to another menu.*

I would make "Change menu" be holding both buttons. Then "Next option" and "Do option" can be each a button. Or if you prefer to have "Next option" and "Prior option" each be a button. Then "Do option" can be holding one button.

And then build your game control scheme around that. This approach would fit well with **visual novels**, **quiz games**, or with menu based **RPG combat**. Also **board games**, **card games**, **idle games**, **element combination games**, and good chunk of **puzzle games** can also be menu based. And **text adventures** could be adapted by providing a menu of the valid options (see also "typing" below).

I want you to frame in your mind all the control schemes here as menus. They are special menus. And there are ways to change menus. So, if there is some special game mechanic I didn't think of… Make it another menu! *A Tetris piece falling? That's a menu!*

By the way, there is a proper name for this: input modes. But I'll call them menus for this answer.

---

## Strategy game and such

Let us make it difficult, we want an strategy game. So you need to select units, and point to where you want them to move.

As we said, there are multiple menus:

* The unit select menu. Each unit is an option. "Next option" means next unit. "Do option" means toggle selection.
* The point menu. This one gives you a pointer. The options are direction (up, down, left, right). "Next option" means next direction. "Do option" means move.
* The command menu. This one also works with the pointer. The options are commands you can issue to the selected units. (e.g. "move here"). The available options may differ depending on the position of the pointer (e.g. if it is on an enemy unit, the "attack" command is available. Or if it is a building where you create units, there are commands to create them). Or you could use it to deploy units (for example for a tower defense or a tactic game).

---

How about a MOBA? I think it is similar enough to an strategy game. Something I would do different is adding a path menu, where you can pick or change the path your units will follow. There must be an ability menu, which is where most direct combat would happen. And a purchase menu, for items and upgrades, or even extra units.

*By the way, I imagine something similar - but simpler - would do for a lemmings-like game.*

---

## Action side scroller and such

Alright, probably not what you had in mind, but you said "any possible types of game".

If we want something more action oriented. Where actions need to happen fast. Then we got to be creative. For example for a side scroller:

* Hold Button 1: Move to the left
* Hold Button 2: Move to the right
* Tap Button 1: Attack left
* Tap Button 2: Attack right
* Double Tap Button 1: Dash left
* Double Tap Button 2: Dash right
* Tap Button 2, Button 1: Grab left
* Tap Button 1, Button 2: Grab right
* Tap both buttons: Jump
* Hold both buttons: Change menu

And use context! For example:

* If you dash away from an enemy, it is a dodge.
* If you time your attack with an enemy attack, it is a parry.
* If the enemy is away, the attack is a ranged attack.
* If you attack while jumping, it is a ground slam.
* If you are grabbing, then instead of dashing, you throw.
* If you are grabbing, then grab is a finisher.
* If you grab a wall, you climb.
* If you are jumping and you attack a wall, it is a wall jump.

It does not have to be like this. Perhaps your character does not jump. Or does not grab. And so on. Perhaps it does other things, like charging power for an attack. Or it can flip gravity. Or it uses a grappling hook, or whatever… Listen: you got to make your game unique.

In fact, replace the grabbing thing with changing weapons (let grabbing be a weapon if that needs to be the case), and attack is using the weapon.

---

## Action top down

Let us say we want a top down game. The menu approach works. Each direction is an option. "Next option" is change direction "Do option" is walk.

Now, if you consider the environment, it works better. For example, you can make every doorway and every object you can interact with an option.

But let us say, this is a top down *action* game. There are enemies, and you need to attack in real time. Then we need to get creative again. What comes to mind are **tank controls**:

* Button 1: rotates to the right
* Button 2: rotates to the left
* Tap both buttons: attack
* Hold both button: move

You can use context again! If the enemy (in the direction you are attacking) is nearby the attack is melee, if it is away, it is a ranged attack. Or if the character does not have ranged attacks, then perhaps attacking in the direction of an enemy that is away is a dash and attack, closing the distance. Oh, and that does not have to be "attack", it can be "interact". You know, pick an item, talk, and so on.

Alternatively, you can make attack by running into the enemies. So that you don't need to distinguish "attack" and "move". Yes, that won't work if you want ranged attack, but lets you nicely add "Change menu":

* Button 1: rotates to the right
* Button 2: rotates to the left
* Tap both buttons: move/attack/interact
* Hold both button: Change menu

One menu can be "shooting" mode, where you don't move, just shoot. And you can change to other menus. For example, your character and equipment menus for those classic top down RPGs. *And just so you don't have to tap so much to move, you can make move toggle.*

By the way, those being tank controls, they also work to control a vehicle. for example for a **racing game** or a **vehicular simulator** on land.

---

## Shooters

Something that would certainly be a problem is a *time sensitive* shooter (first person or over the shoulder). Auto target I say. What to shoot is a menu. Perhaps fallout pip-boy style. Or just Ocarina of Time auto-target style. By the way, the same general idea would work for **point and click** games.

Of course, in a shooter we don't only aim. We also move. We can base movement on the tank controls idea:

* Button 1: Rotates to the right
* Button 2: Rotates to the left
* Tap both buttons: Attack (auto target)
* Hold both button: Change menu

Another menu would be to select a target:

* Button 1: Next target
* Button 2: Prior target
* Tap Both buttons: Do
* Hold Both buttons: Change menu.

In fact, if also include nearby areas, not only enemies. *It might even include other things, such as destructible enviroment.* Then "Do" depends on what the target is. If it is an enemy, the character attacks. If it is an area, then the character walks to that area. You can make the character walk until it reaches the destination, but still allow to select targets and shoot.

Yet another menu can be to change weapons. Or even to select abilities for a hero shooter.

---

You could, of course, use the pointer with directions idea from the strategy game for aiming. Perhaps with auto-bullet time.

A variant would be:

* Button 1: increase
* Button 2: decrease
* Both buttons: change axis/slider

Which I could work for steering in a **flight simulator**. You could also distinguish tapping both button and holding both buttons to add a shoot function.

---

## Sports

For most ball games, you should be able to automatically pick player closer to the ball, plus tank controls.

If you are doing boxing, each button could be punch. But it does not make sense to hold a punch. So those could be blocks. Holding both could do something else. Different sequences of taps one and the other could be combos.

Other games can be simplified further, for example tennis could be move left, move right, auto swing, like pong. By the way, an interesting take on football is an auto-runner.

I believe the changing axis/sliders approach I was describing for the flight simulation would work for golf, bowling and similar.

---

## Game menu

You might need a way to escape some of these control schemes to access a game menu. Let that be another reason to put a Change menu option.

However, there is another way to make a game menu: make it diegetic. Place something in the game world that the players interacts with, and that is the game menu.

Also, the menu should come up on game over. Which reminds me. If there is saving and it makes sense, have auto save, and have it rotate slots. So the player does not have to open a menu to save, and on game over the player can pick which auto save to load.

---

## Typing

Hmm… You say "any possible types of game". But how do you make a typing game? I suppose you could make a virtual keyboard. Each key is an option. "Next option" means next key, and "Do option" means press. In fact, you could make "Do option" be toggle press.

Furthermore, you can make a virtual game controller, and make "any possible types of game" work with that. *I didn't promise it would be a fast input system.*

We can do better, with Binary search!

* Button 1: Go to left child branch
* Button 2: Go to right child branch
* Both buttons: Go to parent

So you make your menu of options (e.g. the keyboard) as a tree. Where the effective options are the leafs of the tree (e.g. a key or a letter). And when there are no child branches, then either Button 1 or Button 2 are "Do option".

Also, if you are trying to help the player to type (instead of typing being the game), you can make a binary search for words in a dictionary instead. Or you could be writing letters, but when you are on a leaf, Button 1 types the letter, and Button 2 takes you to an autocomplete menu.

---

## Combining single button schemes

I will also remind that there is always the "tell me where to stop" approach. You would have the options of the menu passing one by one. *"Change menu" can be an option*. And then the player press a button when the current option is the one they want. That is a single button input scheme.

A variant of this would be holding to select the option. That is, tapping does the default option. But if you hold, the options will be changing, and whichever is the current option when you release is what you do.

*I can imagine something similar for an asteroids inspired game, where the ship is turning as long as there is no input. Holding the button moves. Tapping it shoots.*

*Now you have the second button free to do something else!*

Here is something else to do with one button: Taps and Holds. *It is like morse code. Or binary.* You can encode the options in a binary tree (again). A tap takes you to the left branch, and a hold takes you to the right branch. A long pause is "Do option" (if the combination of taps and holds took you to a valid leaf, otherwise it does nothing), and takes you back to the start to type another combination.

Imagine: On your left hand you have the "tell me where to stop" menu. The first option is "attack", so if you keep tapping, you do normal attacks. Or you could wait until an useful special attack appears on the menu. Meanwhile, on the right you have the "tap and hold" menu, and there your input is reactive to what the enemy is doing (the enemy could telegraph what to input), if you do it correctly, you may dodge attacks or even counter.

---
Tags: movement, control, character-controller, motion-control
---


# Question
Title: How to make the loop to get to the end and stop at the end?
This is what I'm trying to archive and it's almost working fine :

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

public class Test : MonoBehaviour
{
    public FLookAnimator lookAnimator;
    public Transform[] targets;
    public float switchingTime;
    public bool switchingLoop = false;

    private bool loopOnce = true;

    // Start is called before the first frame update
    private void Start()
    {
        StartCoroutine(SwitchTargetsPeriodically());
    }

    private void Update()
    {

    }

    IEnumerator SwitchTargetsPeriodically()
    {
        for (int i = 0; true; i = (i + 1) % targets.Length)
        {
            if (i < targets.Length - 1 && switchingLoop)
            {
                loopOnce = true;

                lookAnimator.ObjectToFollow = targets[i];
            }

            if (switchingLoop == false && loopOnce)
            {
                if (i < targets.Length - 1)
                {
                    lookAnimator.ObjectToFollow = targets[i];
                }
                else
                {
                    loopOnce = false;
                }
            }

            yield return new WaitForSeconds(switchingTime);
        }
    }
}

```

The problem it's looping the targets.Length - 1 and if I change it to targets.Length then it will not loop at all. but if I'm doing targets.Length - 1 it will loop between 3 targets but there is 4 targets.

# Answer
> 0 votes
Solved it. not sure if it's the best way but it's working as I wanted.

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

public class Test : MonoBehaviour
{
    public FLookAnimator lookAnimator;
    public Transform[] targets;
    public float switchingTime;
    public bool switchingLoop = false;

    private bool loopOnce = true;

    // Start is called before the first frame update
    private void Start()
    {
        StartCoroutine(SwitchTargetsPeriodically());
    }

    private void Update()
    {

    }

    IEnumerator SwitchTargetsPeriodically()
    {
        for (int i = 0; true; i = (i + 1) % targets.Length)
        {
            if (i <= targets.Length - 1 && switchingLoop)
            {
                loopOnce = true;

                lookAnimator.ObjectToFollow = targets[i];
            }

            if (switchingLoop == false && loopOnce)
            {
                if (i <= targets.Length - 1)
                {
                    lookAnimator.ObjectToFollow = targets[i];
                }

                if(i == (targets.Length - 1))
                {
                    loopOnce = false;
                }
            }

            yield return new WaitForSeconds(switchingTime);
        }
    }
}

```

# Answer
> 0 votes
Instead of this really strange for-loop, I would just create an infinite while-loop and nest a regular for-loop within it which iterates once through all the targets:

```
IEnumerator SwitchTargetsPeriodically()
{
    while (true)
    {
        for (var i = 0; i < targets.Length; i++)
        {
            lookAnimator.ObjectToFollow = targets[i];
            yield return new WaitForSeconds(switchingTime);
        }
        yield return null;
    }
}

```

In case you wonder what the `yield return null` after the for-loop does: This covers the edge-case that there are 0 targets. Without that line, the game would freeze because the while-loop would spin forever without an interruption. The `yield return null` causes the coroutine to pause until the next frame, when there might perhaps be a target.

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