# Question
Title: Entity/Component Systems in C++, How do I discover types and construct components?
I'm working on an entity component system in C++ that I hope to follow the style of Artemis (http://piemaster.net/2011/07/entity-component-artemis/) in that components are mostly data bags and it's the Systems that contain the logic. I'm hoping to take advantage of the data-centric-ness of this approach and build some nice content tools.

However, one hump I'm coming across is how to take some identifier string or GUID from a data file and use that to construct component for an Entity. Obviously I could just have one big parse function:

```
Component* ParseComponentType(const std::string &typeName)
{
    if (typeName == "RenderComponent") {
        return new RenderComponent();
    }

    else if (typeName == "TransformComponent") {
        return new TransformComponent();
    }

    else {
        return NULL:
    }
}

```

But that's really ugly. I intend to be adding and modifying components frequently, and hopefully building some sort of ScriptedComponentComponent, such that you could implement a component and system in Lua for the purposes of prototyping. I'd like to be able to write a class inheriting from some `BaseComponent` class, maybe toss in a couple of macros to make everything work, and then have the class available for instantiation at runtime.

In C# and Java this would be pretty straightforward, since you get nice reflection APIs to look up classes and constructors. But, I'm doing this in C++ because I want to increase my proficiency in that language.

So How is this accomplished in C++? I've read about enabling RTTI, but it seems most people are wary about that, especially in a situation where I only need it for a subset of object types. If a custom RTTI system is what I need there, where can I go to start learning to write one?

# Answer
*A comment:*
The Artemis implementation is interesting. I came up with a similar solution, except I called my components "Attributes" and "Behaviors". This approach of separating types of components has worked very nicely for me.

*Regarding the solution:*
The code is easy to use, but the implementation might be hard to follow if you're not experienced with C++. So...

# The desired interface

What I did is to have a central repository of all components. Each component type is mapped to a certain string (which represents the component name). This is how you use the system:

```
// Every time you write a new component class you have to register it.
// For that you use the `COMPONENT_REGISTER` macro.
class RenderingComponent : public Component
{
    // Bla, bla
};
COMPONENT_REGISTER(RenderingComponent, "RenderingComponent")

int main()
{
    // To then create an instance of a registered component all you have
    // to do is call the `create` function like so...
    Component* comp = component::create("RenderingComponent");

    // I found that if you have a special `create` function that returns a
    // pointer, it's best to have a corresponding `destroy` function
    // instead of using `delete` directly.
    component::destroy(comp);
}

```

# The implementation

The implementation is not that bad, but it's still pretty complex; it requires some knowledge of templates and function pointers.

**Note:** Joe Wreschnig has made some good points in the comments, mainly on how my previous implementation made too many assumptions about how good the compiler is at optimizing code; the issue was not detrimental, imo, but it did bug me as well. I also noticed that the former `COMPONENT_REGISTER` macro did not work with templates.

I've changed the code and now all of those problems should be fixed. The macro works with templates and the issues that Joe raised have been addressed: now it's much easier for compilers to optimize away unnecessary code.

***component/component.h***

```
#ifndef COMPONENT_COMPONENT_H
#define COMPONENT_COMPONENT_H

// Standard libraries
#include <string>

// Custom libraries
#include "detail.h"

class Component
{
    // ...
};

namespace component
{
    Component* create(const std::string& name);
    void destroy(const Component* comp);
}

#define COMPONENT_REGISTER(TYPE, NAME)                                        \
    namespace component {                                                     \
    namespace detail {                                                        \
    namespace                                                                 \
    {                                                                         \
        template<class T>                                                     \
        class ComponentRegistration;                                          \
                                                                              \
        template<>                                                            \
        class ComponentRegistration<TYPE>                                     \
        {                                                                     \
            static const ::component::detail::RegistryEntry<TYPE>& reg;       \
        };                                                                    \
                                                                              \
        const ::component::detail::RegistryEntry<TYPE>&                       \
            ComponentRegistration<TYPE>::reg =                                \
                ::component::detail::RegistryEntry<TYPE>::Instance(NAME);     \
    }}}

#endif // COMPONENT_COMPONENT_H

```

***component/detail.h***

```
#ifndef COMPONENT_DETAIL_H
#define COMPONENT_DETAIL_H

// Standard libraries
#include <map>
#include <string>
#include <utility>

class Component;

namespace component
{
    namespace detail
    {
        typedef Component* (*CreateComponentFunc)();
        typedef std::map<std::string, CreateComponentFunc> ComponentRegistry;

        inline ComponentRegistry& getComponentRegistry()
        {
            static ComponentRegistry reg;
            return reg;
        }

        template<class T>
        Component* createComponent() {
            return new T;
        }

        template<class T>
        struct RegistryEntry
        {
          public:
            static RegistryEntry<T>& Instance(const std::string& name)
            {
                // Because I use a singleton here, even though `COMPONENT_REGISTER`
                // is expanded in multiple translation units, the constructor
                // will only be executed once. Only this cheap `Instance` function
                // (which most likely gets inlined) is executed multiple times.

                static RegistryEntry<T> inst(name);
                return inst;
            }

          private:
            RegistryEntry(const std::string& name)
            {
                ComponentRegistry& reg = getComponentRegistry();
                CreateComponentFunc func = createComponent<T>;

                std::pair<ComponentRegistry::iterator, bool> ret =
                    reg.insert(ComponentRegistry::value_type(name, func));

                if (ret.second == false) {
                    // This means there already is a component registered to
                    // this name. You should handle this error as you see fit.
                }
            }

            RegistryEntry(const RegistryEntry<T>&) = delete; // C++11 feature
            RegistryEntry& operator=(const RegistryEntry<T>&) = delete;
        };

    } // namespace detail

} // namespace component

#endif // COMPONENT_DETAIL_H

```

***component/component.cpp***

```
// Matching header
#include "component.h"

// Standard libraries
#include <string>

// Custom libraries
#include "detail.h"

Component* component::create(const std::string& name)
{
    detail::ComponentRegistry& reg = detail::getComponentRegistry();
    detail::ComponentRegistry::iterator it = reg.find(name);

    if (it == reg.end()) {
        // This happens when there is no component registered to this
        // name. Here I return a null pointer, but you can handle this
        // error differently if it suits you better.
        return nullptr;
    }

    detail::CreateComponentFunc func = it->second;
    return func();
}

void component::destroy(const Component* comp)
{
    delete comp;
}

```

# Extending with Lua

I should note that with a bit of work (it's not very hard), this can be used to seamlessly work with components defined in either C++ or Lua, without ever having to think about it.
> 38 votes

# Answer
It seems like what you want is a factory.

http://en.wikipedia.org/wiki/Factory\_method\_pattern

What you can do is have your various components register with the factory what name they correspond to, and then you have some map of string identifier to constructor method signature to generate your components.
> 9 votes

# Answer
I worked with Paul Manta's design from the chosen answer for a while and eventually came to this more generic and concise factory implementation below that I'm willing to share for anyone coming to this question in the future. In this example, every factory object derives from the `Object` base class:

```
struct Object {
    virtual ~Object(){}
};

```

The static Factory class is as follows:

```
struct Factory {
    // the template used by the macro
    template<class ObjectType>
    struct RegisterObject {
        // passing a vector of strings allows many id's to map to the same sub-type
        RegisterObject(std::vector<std::string> names){
            for (auto name : names){
                objmap[name] = instantiate<ObjectType>;
            }
        }
    };

    // Factory method for creating objects
    static Object* createObject(const std::string& name){
        auto it = objmap.find(name);
        if (it == objmap.end()){
            return nullptr;
        } else {
            return it->second();
        }
    }

    private:
    // ensures the Factory cannot be instantiated
    Factory() = delete;

    // the map from string id's to instantiator functions
    static std::map<std::string, Object*(*)(void)> objmap;

    // templated sub-type instantiator function
    // requires that the sub-type has a parameter-less constructor
    template<class ObjectType>
    static Object* instantiate(){
        return new ObjectType();
    }
};
// pesky outside-class initialization of static member (grumble grumble)
std::map<std::string, Object*(*)(void)> Factory::objmap;

```

The macro for registering a sub-type of `Object` is as follows:

```
#define RegisterObject(type, ...) \
namespace { \
    ::Factory::RegisterObject<type> register_object_##type({##__VA_ARGS__}); \
}

```

Now usage is as follows:

```
struct SpecialObject : Object {
    void beSpecial(){}
};
RegisterObject(SpecialObject, "SpecialObject", "Special", "SpecObj");

...

int main(){
    Object* obj1 = Factory::createObject("SpecialObject");
    Object* obj2 = Factory::createObject("SpecObj");
    ...
    if (obj1){
        delete obj1;
    }
    if (obj2){
        delete obj2;
    }
    return 0;
}

```

The capacity for many string id's per sub-type was useful in my application, but the restriction to a single id per sub-type would be fairly straightforward.

I hope this has been useful!
> 1 votes

# Answer
Building off of **@TimStraubinger**'s answer, I built a factory class using **C++14** standards which can store ***derived members with an arbitrary number of arguments***. My example, unlike Tim's, only takes one name/key per function. Like Tim's, every class being stored is derived from a *Base* class, mine being called *Base*.

## Base.h

```
#ifndef BASE_H
#define BASE_H

class Base{
    public:
        virtual ~Base(){}
};

#endif

```

## EX\_Factory.h

```
#ifndef EX_COMPONENT_H
#define EX_COMPONENT_H

#include <string>
#include <map>
#include "Base.h"

struct EX_Factory{
    template<class U, typename... Args>
    static void registerC(const std::string &name){
        registry<Args...>[name] = &create<U>;
    }
    template<typename... Args>
    static Base * createObject(const std::string &key, Args... args){
        auto it = registry<Args...>.find(key);
        if(it == registry<Args...>.end()) return nullptr;
        return it->second(args...);
    }
    private:
        EX_Factory() = delete;
        template<typename... Args>
        static std::map<std::string, Base*(*)(Args...)> registry;

        template<class U, typename... Args>
        static Base* create(Args... args){
            return new U(args...);
        }
};

template<typename... Args>
std::map<std::string, Base*(*)(Args...)> EX_Factory::registry; // Static member declaration.

#endif

```

## main.cpp

```
#include "EX_Factory.h"
#include <iostream>

using namespace std;

struct derived_1 : public Base{
    derived_1(int i, int j, float f){
        cout << "Derived 1:\t" << i * j + f << endl;
    }
};
struct derived_2 : public Base{
    derived_2(int i, int j){
        cout << "Derived 2:\t" << i + j << endl;
    }
};

int main(){
    EX_Factory::registerC<derived_1, int, int, float>("derived_1"); // Need to include arguments
                                                                    //  when registering classes.
    EX_Factory::registerC<derived_2, int, int>("derived_2");
    derived_1 * d1 = static_cast<derived_1*>(EX_Factory::createObject<int, int, float>("derived_1", 8, 8, 3.0));
    derived_2 * d2 = static_cast<derived_2*>(EX_Factory::createObject<int, int>("derived_2", 3, 3));
    delete d1;
    delete d2;
    return 0;
}

```

## Output

```
Derived 1:  67
Derived 2:  6

```

I hope this helps people needing to use a **Factory** design which does not require an identity constructor to work. It was fun designing, so I hope it helps people needing more flexibility in their **Factory** designs.
> 1 votes

---
Tags: c++, component-based, entity-system
---


# Question
Title: How do I make game objects move towards the player, when the player is within a set range?
I am trying to make game objects, like a coin or ammo clip, gravitate towards the player when they are within a set radius. I have seen this implemented in quite a few old school 90's games; when the player walks near anything, I want it to move to the player for collection. I can already handle the collection.

This is what I have, so far:

```
using UnityEngine;
using System.Collections;

public class MoveCoinsTowardsPlayer : MonoBehaviour
{
    public Transform target;
    public float speed;

    void Update()
    {
        float step = speed * Time.deltaTime;
        transform.position = Vector3.MoveTowards(transform.position, target.position, step);
    }
}

```

How do I make game objects move towards the player, when the player is within a set range?

# Answer
You could simply check the distance of the coin to the player, however, you would need to store a record of each coin and iterate through each instance during each `Update()` method, in order to check.

We will assume you have a static number of coins, and have pre-loaded them into an array. This is the most cost effective, in comparison to using a `List`. If you dynamically add coins to the level, you will have to use a `List<MoveCounTowardsPlayer>`, and add the coins to the list as they are created.

```
class MoveCoinTowardsPlayer : MonoBehaviour
{
    public Transform target;
    public float speed;
    public bool isMoving = false;

    void Update()
    {
        if(isMoving)
        {
            transform.position = Vector3
                .MoveTowards(transform.position, target.position, speed * Time.deltaTime;
        }
    }

    public void MoveToPlayer(Transform player)
    {
        target = player;
        isMoving = true;
    }
}

class Player : MonoBehaviour
{
    ///<summary>The array of coins available in the level.</summary>
    public MoveCoinTowardsPlayer[] coin;
    ///<summary>The range within which the player will pick up coins.</summary>
    public float pickupRange;

    void Update()
    {
        for(int i = 0; i < coin.Length; i++)
        {
            if(coin[i] != null && Vector3
                .Distance(transform.position, coin[i].transform.position) <= pickupRange)
            {
                // If the coin still references a valid object, and its distance to
                // the player transform is within pickup range,
                // start moving it towards the player.
                coin[i].MoveToPlayer(transform);
            }
        }
    }
}

```

---

All in all, the above solution seems like a waste of resources, given that it iterates through all coins during a single update. I would personally add a kinematic sphere collider (circle, if your working in 2D). You can make this collider the size of your pickup radius, and use collision to determine collection.

You would also need a collider on the coins, as well as a tag to identify them as coins.

```
class Player : MonoBehaviour
{
    public string coinTag;

    void OnTriggerEnter(Collider other)
    {
        if(other.tag == coinTag)
        {
            other.gameObject.GetComponent<MoveCoinTowardsPlayer>()
                .MoveToPlayer(transform);
        }
    }
}

```
> 1 votes

---
Tags: unity, c#, collision-detection
---


# Question
Title: How to not freeze the main thread in Unity?
I have a level generation algorithm that is computationally heavy. As such, calling it always results in the game screen freezing. How can I place the function on a second thread while the game still continues to render a loading screen to indicate the game is not frozen?

# Answer
> 58 votes
**Update:** In 2018, Unity is rolling out a C# Job System as a way to offload work and make use of multiple CPU cores.

The answer below predates this system. It will still work, but there may be better options available in modern Unity, depending on your needs. In particular, the job system appears to resolve some of the limitations on what manually-created threads can safely access, described below. Developers experimenting with the preview report performing raycasts and constructing meshes in parallel, for example.

I'd invite users with experience using this job system to add their own answers reflecting the current state of the engine.

---

I've used threading for heavyweight tasks in Unity in the past (usually image & geometry processing), and it's not drastically different than using threads in other C# applications, with two caveats:

1. Because Unity uses a somewhat older subset of .NET, there are some newer threading features and libraries we can't use out of the box, but the basics are all there.
2. As Almo notes in a comment above, many Unity types are not threadsafe, and will throw exceptions if you try to construct, use, or even compare them off the main thread. Things to keep in mind:

* One common case is checking to see if a GameObject or Monobehaviour reference is null before trying to access its members. `myUnityObject == null` calls an overloaded operator for anything descended from UnityEngine.Object, but `System.Object.ReferenceEquals()` works around this to a degree - just remember that a Destroy()ed GameObject compares as equal to null using the overload, but is not yet ReferenceEqual to null.
    * *Reading* parameters from Unity types is usually safe on another thread (in that it won't immediately throw an exception as long as you're careful to check for nulls as above), but note Philipp's warning here that the main thread might be modifying state while you're reading it. You'll need to be disciplined about who's allowed to modify what & when in order to avoid reading some inconsistent state, which can lead to bugs that can be devillishly hard to track down because they depend on sub-millisecond timings between threads that we can't reproduce at will.
    * Random and Time static members are not available. Create an instance of System.Random per thread if you need randomness, and System.Diagnostics.Stopwatch if you need timing info.
    * Mathf functions, Vector, Matrix, Quaternion, and Color structs all work fine across threads, so you can do most of your computations separately
    * Creating GameObjects, attaching Monobehaviours, or creating/updating Textures, Meshes, Materials, etc. all need to happen on the main thread. In the past when I've needed to work with these, I've set up a producer-consumer queue, where my worker thread prepares the raw data (like a big array of vectors/colours to apply to a mesh or texture), and an Update or Coroutine on the main thread polls for data and applies it.

With those notes out of the way, here's a pattern I often use for threaded work. I make no guarantee that it's a best-practice style, but it gets the job done. (Comments or edits to improve are welcome - I know threading is a very deep topic of which I only know the basics)

```
using UnityEngine;
using System.Threading;

public class MyThreadedBehaviour : MonoBehaviour
{

    bool _threadRunning;
    Thread _thread;

    void Start()
    {
        // Begin our heavy work on a new thread.
        _thread = new Thread(ThreadedWork);
        _thread.Start();
    }

    void ThreadedWork()
    {
        _threadRunning = true;
        bool workDone = false;

        // This pattern lets us interrupt the work at a safe point if neeeded.
        while(_threadRunning && !workDone)
        {
            // Do Work...
        }
        _threadRunning = false;
    }

    void OnDisable()
    {
        // If the thread is still running, we should shut it down,
        // otherwise it can prevent the game from exiting correctly.
        if(_threadRunning)
        {
            // This forces the while loop in the ThreadedWork function to abort.
            _threadRunning = false;

            // This waits until the thread exits,
            // ensuring any cleanup we do after this is safe.
            _thread.Join();
        }

        // Thread is guaranteed no longer running. Do other cleanup tasks.
    }
}

```

If you don't strictly need to split work across threads for speed, and you're just looking for a way to make it non-blocking so the rest of your game keeps ticking, a lighter-weight solution in Unity is **Coroutines**. These are functions that can do some work then yield control back to the engine to continue what it's doing, and resume seamlessly at a later time.

```
using UnityEngine;
using System.Collections;

public class MyYieldingBehaviour : MonoBehaviour
{

    void Start()
    {
        // Begin our heavy work in a coroutine.
        StartCoroutine(YieldingWork());
    }

    IEnumerator YieldingWork()
    {
        bool workDone = false;

        while(!workDone)
        {
            // Let the engine run for a frame.
            yield return null;

            // Do Work...
        }
    }
}

```

This doesn't need any special cleanup considerations, since the engine (so far as I can tell) gets rid of coroutines from destroyed objects for you.

All the local state of the method is preserved when it yields and resumes, so for many purposes it's as though it was running uninterrupted on another thread (but you have all the conveniences of running on the main thread). You just need to make sure each iteration of it is short enough that it's not going to slow your main thread unreasonably.

By ensuring important operations aren't separated by a yield, you can get the consistency of single-threaded behaviour - knowing that no other script or system on the main thread can modify data you're in the middle of working on.

The yield return line gives you a few options. You can...

* `yield return null` to resume after the next frame's Update()
* `yield return new WaitForFixedUpdate()` to resume after the next FixedUpdate()
* `yield return new WaitForSeconds(delay)` to resume after a certain amount of game time elapses
* `yield return new WaitForEndOfFrame()` to resume after the GUI finishes rendering
* `yield return myRequest` where `myRequest` is a WWW instance, to resume once the requested data finishes loading from the web or disc.
* `yield return otherCoroutine` where `otherCoroutine` is a Coroutine instance, to resume after `otherCoroutine` completes. This is often used in the form `yield return StartCoroutine(OtherCoroutineMethod())` to chain execution to a new coroutine that can itself yield when it wants to.

+ Experimentally, skipping the second `StartCoroutine` and simply writing `yield return OtherCoroutineMethod()` accomplishes the same goal if you want to chain execution in the same context.

    Wrapping inside a `StartCoroutine` may still be useful if you want to run the nested coroutine in association with a second object, like `yield return otherObject.StartCoroutine(OtherObjectsCoroutineMethod())`

...depending on when you want the coroutine to take its next turn.

Or `yield break;` to stop the coroutine before it reaches the end, the way you might use `return;` to early-out of a conventional method.

# Answer
> 0 votes
You can put your heavy calculation into another thread, but the Unity's API is not thread safe, you have to execute them in main thread.

Well you can try this package on Asset Store will help you to using threading easier. http://u3d.as/wQg You can simply use only one line of code to start a thread and execute Unity API safely.

# Answer
> 0 votes
Using Svelto.Tasks, you can return the result of a multi threaded routine to the main thread (and therefore unity functions) quite easily:

http://www.sebaslab.com/svelto-taskrunner-run-serial-and-parallel-asynchronous-tasks-in-unity3d/

# Answer
> 0 votes
@DMGregory explained it really well.

Both threading and coroutines can be used. Former to offload main thread and later to return control to main the thread. Pushing heavy lifting to seprate thread seems more reasonable. Therefore, job queues might be what you are after.

There is really good JobQueue example script on Unity Wiki.

---
Tags: unity, multithreading
---


title: Modern Loot Table Concepts

text:
# Question
Title: Modern Loot Table Concepts
First, allow me to apologize, because this is going to be a fairly long post. I've given this topic a lot of thought, and even experimented with concepts and previous implementations.

When I imagine a loot table, I always think of something a little like how World of Warcraft does theirs. Here is a picture example:

Now, just using visual cues, when can pretty much dissect the way the loot system works, but let's also go ahead and use some Wowhead statistics to glean a better understanding for what we're dealing with. Here's a quick mock up:

As you can see, the loot system that World of Warcraft uses is quite dynamic. It's not exactly a roulette, but can, at it's base level, resemble one in ways. My first implementation of a Loot Table avoided the concept of a roulette, and even a weighing mechanic(which gives certain items a greater probability of being taken from the table, and leave others). I did not like the idea of weighing items in this nature. So I made something sort of like this:

This Loot Table was more of a "List". Basically, I would loop through each item, test it's probability, and if it was succesful, I would add it to a list of drops. This worked well in theory, but I was quick to notice a fatal flaw in the system.

Consider this output:

```
Ore_Copper x1
Nugget_Copper x2
Gem_Diamond x1
Gem_Emerald x1
Gem_Topaz x1

```

That's an exgaggeration, but if you look at the basic structure it's entirely possible...but what if we didnt want to drop 4 types of gem? And also, the collective probability of the gems also makes you practically guaranteed to recieve at least one, because you have a 10%\*5 chances to get one. Now, this may be ok for a game, but it's not what I had intended. I wanted the ability to drop gems, but with only one chance. I wanted the probability of recieving a gem to be exactly 10%. So...how do we fix this? Here's what I came up with:

So what's happening now? We have essentially built a roulette system. Instead of a direct collection of `LootTableItem`s, we now defer items into independent collections. `LootTableList`s. Each list has it's own probability, much like my original `LootTable`, but now we can successfully organize items into their own "pool" within a single `LootTable`. If we want an item to be less rare than another, we just add extra instances to the desired `LootTableList`. Then, when my `LootTable` is running it's algorithm, it selects one item from the `LootTableList`. This is great, but it also brought up another issue. What if I wanted all items in a `LootTableList` to be dropped, or have a chance of dropping? Well, I went ahead and added an extra field, called `CollectAll`. When this field is checked, it avoids picking one item, and instead picks all items in the `LootTableList`.

After planning all this, and doing my homework on the subject, I came to creating this kind of LootTable. I'm also fairly certain that this is also the type of LootTable that World of Warcraft is using, or at least conceptually they're very close. Here's the code:

```
using System;
using System.Collections.Generic;
using System.Linq;
using GrimoireDevelopmentKit.Framework.Interfaces;
using GrimoireDevelopmentKit.Framework.Maths;
using GrimoireDevelopmentKit.Framework.Utilities;

namespace GrimoireDevelopmentKit.Framework.Collections
{
    [Serializable]
    public class LootTable : Dictionary<string, LootTableList>, ICopy<LootTable>
    {
        public string Identifier { get; set; }
        public AdvancedRandom Random { get; set; }

        public int TotalItems
        {
            get
            {
                int total = 0;
                foreach (LootTableList list in this.Values)
                {
                    total += list.Values.Count;
                }
                return total;
            }
        }

        public LootTable(string identifier = null)
            : this(identifier, new AdvancedRandom())
        {
        }

        public LootTable(string identifier, AdvancedRandom random)
        {
            Identifier = identifier;
            Random = random;
        }

        public void Add(LootTableList list)
        {
            if (!Contains(list))
            {
                Add(list.Identifier, list);
            }
            else
            {
                throw new ArgumentException("Key: '" + list.Identifier + "' already exists!");
            }
        }

        public bool Remove(LootTableList list)
        {
            return Remove(list.Identifier);
        }

        public bool Contains(string listIdentifier)
        {
            return ContainsKey(listIdentifier);
        }

        public bool Contains(LootTableList list)
        {
            return Contains(list.Identifier);
        }

        public List<LootTableResult> Next()
        {
            Range probabilityScope = new Range(0, 100);
            List<LootTableResult> drops = new List<LootTableResult>(TotalItems);
            foreach (LootTableList list in Values)
            {
                bool success = Random.NextRange(probabilityScope) <= list.Probability;
                if (success)
                {
                    if (list.CollectAll)
                    {
                        foreach (LootTableItem item in list.Values)
                        {
                            int quantity = Random.NextRange(item.Quantity);
                            if(quantity > 0)
                            {
                                drops.Add(new LootTableResult(item.Identifier, quantity));
                            }
                        }
                    }
                    else
                    {
                        LootTableItem item = list.ElementAt(Random.NextInteger(0, list.Count)).Value;
                        int quantity = Random.NextRange(item.Quantity);
                        if(quantity > 0)
                        {
                            drops.Add(new LootTableResult(item.Identifier,quantity));
                        }
                    }
                }
            }
            return drops;
        }

        public void Copy(LootTable other)
        {
            this.Clear();
            this.Identifier = other.Identifier;
            this.Random = other.Random;
            foreach (LootTableList list in other.Values)
            {
                this.Add(list.MakeCopy());
            }
        }

        public LootTable MakeCopy()
        {
            LootTable copy = new LootTable();
            copy.Copy(this);
            return copy;
        }
    }

}

```

***My Question:***

***Is there a better and more modern conceptual foundation that I could use to achieve this kind of loot table?***

Are there any game developers on this site that have created Loot Tables of this nature? I just want to know if I could improve my concept, *not just the code*, but the concept itself. I'm certain there is more that can be done to improve upon my work. I'm just looking for advice from people experienced in this subject.

I can also post my implementation into a separate project if it would *help people help me*. In fact, I think I'm going to work on that right now actually.

EDIT

Just realized I forgot to code the Quantity count in the LootTableLists, which if coded, would allow a LootTableList to be collected from multiple times during the same drop.

# Answer
> 2 votes
You are on the right track. That is where I would start. All of your components share the identifier and quantity. It makes sense to add chance property and use composite pattern.

```
public class Droppable
{
    public string Name { get; private set; }
    public uint QTY { get; private set; }
    public float Chance { get; private set; }

    public Droppable(string name, float chance, uint qty)
    {
      this.Name = name;
      this.QTY = qty;
      this.Chance = chance;
    }

    public virtual bool ShouldDrop()
    {
    // random drop check
    }
}

```

You can then create your loot table extending `Droppable` component.

```
public class DropBundle extends Droppable
{
    public bool CollectAll { get; private set; }
    private List<Droppable> _items;

    public DropBundle(string name, float chance, uint qty, bool collectAll, List<Droppable> items): base(name, chance, qty)
    {
        CollectAll = collectAll
        _items = items;
    }

    public override bool ShouldDrop()
    {
    // random drop check and if yeas run should drop check for other items
    }
}

```

You also need your item class that would also extend `Droppable`

```
public class DropItem extends Droppable
{

   public override bool ShouldDrop()
   {
      // random drop check
   }
}

```

Notice `DropBundle` holds references to other `Droppable` components. That means you can then next them as much as you want, eg.:

* 5% of finding 10 gold coin (DropItem)
* 10% of finding a coin (DropBundle) wich can be either gold (20%) or silver (80%)
* 20% of finding a chest (DropBundle) that can have 10% chance of finding a coin (DropBundle) which can be either gold, silver or copper, etc.

All of those scenerios are then possible without changing dependency tree too much. The only thing you have to remember is obviously implement randomisation and keep in mind that sum of chances of nested droppables should be 1 (100%) for simplicity sake.

Another great advantage of using composite pattern is ability to later on use that implementation for data you can dynamically read from static XML (or JSON) file.

---
Tags: game-design, game-mechanics
---


# Question
Title: Using 60 frames per second causes the screen to leave a drawn trail of textures, when there is movement
I'm trying to implement a frame rate feature, and I have noticed that using 60 frames per second causes the screen to leave a drawn trail of textures, when there is movement.

Here's the code I'm using to make the frame rate feature:

```
public void render(float deltaT){
    currentLevel.updateWorld(deltaT);

    if((fps+=deltaT) >= 1.0/60.0){
        fps = 0;
    }else
        return;

    super.render(deltaT);
    Gdx.gl.glClearColor(103 / 255f, 69 / 255f, 117 / 255f, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);

    currentLevel.updateScreen(deltaT, gameCamera);
}

```

The `currentLevel.updateWorld` updates the game's logic. The `currentLevel.updateScreen` method updates the camera's position, drawn to the screen.

# Answer
You don't need to limit the framerate yourself within LibGDX. The framework handles that for you. You can enable vsync in your game by adding this line to your desktop configuration:

```
config.vSyncEnabled = true;

```

Or in-game using

```
Gdx.graphics.setVSync(true);

```
> 3 votes

---
Tags: libgdx, frame-rate, spritebatch
---


title: Handling keyboard input in SDL2

text:
# Question
Title: Handling keyboard input in SDL2
I'm using SDL2 with .NET bindings. Keyboard handling is encapsulated in static class, and keyboard handling code part looks like this:

```
// class members
private static int _numkeys;
private static IntPtr _keysBuffer;
private static byte[] _keysCurr = new byte[(int)SDL_Scancode.SDL_NUM_SCANCODES];
private static byte[] _keysPrev = new byte[(int)SDL_Scancode.SDL_NUM_SCANCODES];

// called once, to get buffer pointer
_keysBuffer = SDL_GetKeyboardState(out _numkeys);

// update keyboard state each frame
var tmp = _keysPrev;
_keysPrev = _keysCurr;
_keysCurr = tmp;
// copy new state
Marshal.Copy(_keysBuffer, _keysCurr, 0, _numkeys);

```

all is workig as expected mostly, however once in while one of the following behavior occurs:

1. Physical key is pressed, but no key press is detected. Keypress is detected after key repeat interval.
2. Physical key is pressed, but no key press is detected. Lasts for infinite amount of time.

For example, I press Right (`D`), the movement to right starts, shortly after I press Fire (`SPACE`), movement is stopped, no firing occurs, then after key repeat interval firing starts, but movement to Right is stopped despite key is also still pressed.

Unfortunatelly I have both 1) not discovered 100% reproducible pattern for the bug yet (seems like it happens on burst sequental presses), 2) have no ideas what is the cause.

For now I just want, a fresh view on my code (is it solid?) and maybe some ideas on what to check. Thanks!

# Answer
Surprisingly it actually turned out that Quentin was right is some sense. It was not keyboard ghosting however, but pure keyboard malfunction. It just happened that it really not reporting some keys pressed then they are. And it was incosistent as the "bug" was.

I used Keyboard Ghosting Demonstration page and Keyboard Ghosting & Rollover Test windows app for the test.

The costly piece of garbage was replaced by my old good membrane keyboard and the "bug" is gone now.
> -1 votes

# Answer
This could be a hardware issue as stated by @Quentin.

Anyways, you could write a workaround tracking the KEYDOWN and KEYUP events instead of trying to fetch the keyboard state, i'm not pretty sure how it works in C#, i've never worked with SDL2 in that language, but here's an example of how do I manage it in C++, i suppose it's pretty similar.

Instead of doing that, what you would need is an array of unsigned char, writting 1 into the key code index when pressed and 0 when released.

After that you will have the state of the keyboard with no hardware state dependency
> 3 votes

---
Tags: c#, input, sdl2, keyboard, .net
---


# Question
Title: How to convert a premade mesh into voxels so I can use algorithms such as marching cubes
I have a mesh that was created in a 3D program which is the terrain the player will walk on. I want to allow the terrain to be deformable by the player, but for it to be smooth (not like Minecraft).

From what I have read from existing questions similar to mine, I need to use an algorithm such as Marching Cubes (which I don't understand yet). From what I understand, those types of algorithms are suited for procedural generation.

My question is; How do I convert my mesh into voxels so that I can use algorithms such as Marching cubes?

Is it simply a matter of cutting up my mesh in chunks?

If it helps, I will be using C# and Unity 3D.

# Answer
If you are interested in procedural terrain generation I suggest first this article.

Also I try to correct your thinking of this.

Most important, **Voxels** are what you are searching and which are the **output of the map generator**. A **mesh** though is describing the **surface of an object** which can be *displayed by an engine*.

Voxels in more detail are scalar values without an dimension which are used for being distributed equal over a dimension.

This means, they are simply values in a space describing whether a position in space is in an object or not in an object.

So what's all that about, why Voxels? The Voxels represent world data very well and can also be edited easily (they fit into human thinking). Also the result of surface extraction of Voxels is always predictable. Meshes are not suitable for changing the world, they aren't in am easy editable format and can be broken easily.

### How is the workflow?

1. You create data aka Voxels with the procedural map generator
2. You need to extract the so called "isosurface" from the voxel data.

In short, you need to find a valid surface representation of your voxel data.

### How to achieve this?

One algorithm would be Marching Cubes, however out there are even more algorithms and so far I know unity already has build in helpers for Voxel data.

The iso surface then is a mesh which can be displayed.
> 0 votes

---
Tags: unity, algorithm, terrain, mesh
---


title: How to set emission level through C#

text:
# Question
Title: How to set emission level through C#
I am willing to change emission level through code without affecting its color.

(i.e., changing the brightness number shown in the box at the right side of the inspector, while keeping the emission color unchanged)

I have tried this so far, but I don't know how to use my `value` variable to update the material:

```
public class EmissionColourChange : MonoBehaviour {

    Material thisMat;
    Color c;
    public float value;

    void Start () {
        thisMat = GetComponent<Renderer>().material;
        c = GetComponent<Renderer>().material.color;
        thisMat.EnableKeyword("_EMISSION");
        value = c.r;
    }

    void Update () {
        thisMat.SetColor("_EmissionColor", new Color(c.r,c.g,c.b));
    }
}

```

# Answer
> 5 votes
You're bang on for a low-dynamic range emissive colour. To get access to brighter emission we need to move to a high-dynamic range, which is outside the range of the `Color` type.

So, we replace it with a Vector:

```
thisMat.SetColor("_EmissionColor", new Vector4(c.r,c.g,c.b,0) * value);

```

Now you have access to make the colour as bright as you want by increasing the multiplier value. This is what changes the number shown to the right of the emission colour swatch in the inspector.

Note that the colour & value you put in isn't exactly the parameters you'll see in the material inspector when you look at the result. Because we're mixing together the colour and brightness level, Unity has to tease them apart again to show in the inspector. It looks like it does that by setting the multiplier value equal the greatest component of the colour (R, G, or B), then divides the colour by that. So you'll still have:

```
myColour * myBrightnessMultiplier = inspectorColour * inspectorBrightnessMultiplier

```

it just might pick a different way of splitting the brightness representation between the two parts. The rendering math should all come out the same.

# Answer
> 0 votes
If you take the time to look at the color to give to the Emission field, you will see that it uses the **HSV Color model** (hue, saturation, and lightness), not the "traditional" RGB one.

Make sure the lightness value of your color is \> 0 if you want the emission to be visible.

---
Tags: unity, shaders, lighting
---


# Question
Title: What is the difference between expand(), grow() and fill() in libGDX?
I am currently working with scene2d tables. But I am tired of using hit and trial to make the layout I wanted. Can anyone explain the meanings of expand, fill and grow? I need the behaviour like wrap\_content and match\_parent as in android.

Some code I tried is:

```
    Table contentTable = scoreDialog.getContentTable();
    contentTable.debugAll();

    Table topTable = new Table();
    topTable.debugAll();
    topTable.top();

    topTable.add(timeImage).colspan(2).pad(5);
    topTable.add(timeProgressBar).colspan(5).pad(5);
    topTable.add(bonusLabel).colspan(3).pad(5);
    topTable.row();
    topTable.add(alignImage).colspan(2).pad(5);
    topTable.add(alignProgressBar).colspan(5).pad(5);
    topTable.add(penaltyLabel).colspan(3).pad(5);

    contentTable.row();
    contentTable.add(topTable).colspan(10).pad(5).expandX().align(Align.center);
    contentTable.row();

    contentTable.add(scoreLabelDialog).colspan(10).pad(5).expandX().align(Align.center);
    contentTable.row();

    starsTable = new Table();
    starsTable.setHeight(50);
    contentTable.add(starsTable).pad(5).colspan(10).expandX().align(Align.center);

```

# Answer
> 8 votes
**Expand**: expands the `cell` that the actor is currently placed in to occupy the largest possible area without changing other cells size. For example if the cell is `50 x 50` and there is `50px` of empty space to the sides of the cell it will resize to `100 x 50`. Only changes the size of the `cell`, not the `actor`.

**Fill**: makes the `actor` occupy the entire space of the `cell`. For example if the actor is `50 x 50` and the cell is `100 x 100` the actor will be resized to `100 x 100`. Only changes the size of the `actor` not the `cell`.

**Grow**: both expand and fill at the same time.

---
Tags: libgdx, scene2d
---


# Question
Title: Why would a game developer write their own engine instead of using existing ones?
I have observed that many big and well-known game developers often develop their own engines. Examples include Valve, Crytek, Ubisoft, Epic Games and Square-Enix.

Could it simply be because they can, or is it likely that existing engines do not meet enough requirements, so we would develop our own? I can hardly imagine a game that requires a specific engine. The likes of of Unity or Unreal are simply enough to make any kind of game; even if not, they have source code, which can be modified to satisfy even some extraordinary needs.

Why would a game developer write their own engine instead of using existing ones?

# Answer
> 53 votes
There are several reasons a studio may choose to "build" instead of "buy" their technology:

* Legacy technology; a studio may have started building their own toolchain before there was existing, viable middleware for it.
* Specific requirements; a studio may have a particular collection of requirements that is not well-suited to existing middleware or
* Budget concerns; a studio may not be able to afford the expense or contractual obligations of existing middleware.
* "Not built here syndrome;" the studios technical leadership may be wary (reasonably or unreasonably so) of technology they did not build and therefore do not fully understand.

In general, it does make good sense to own and control the things that are critical to the success of your business, and to outsource those that aren't.

For some studios, the design or storytelling aspect of their games may be the critical resource they expect to capitalize on for success. For those studios, it makes sense to simply buy technology that will allow their designers to realize the appropriate vision.

For others, technology may be the foundation for success. Studios that build MMOs, for example, generally will need to build that infrastructure themselves because it is critical to their success (and existing middleware is generally inappropriate, at least for larger, "AAA" titles).

Note that some of the studios you listed (Crytek and Epic in particular) have basically *stopped* trying to be dominating forces in the games market directly, and almost certainly make far more as middleware vendors than they do as game developers.

# Answer
> 19 votes
as said by Josh Petrie:

> "**Not built here syndrome**;"

I am also writing my own engine, and I suppose the reason will be different for every developer out there, but in fact - I generally don't like working in other peoples code. I am compulsive in the sense that *If I feel I could build it myself, then there's no point in settling for anything else*.

I tested out various types of game engines, rendering API and such, notably Ploobs, UNITY WaveEngine, XNAFinalEngine, Love, Ogre, etc.. many more... I wanted to start writing games - I downloaded a lot looking for a good comfortable and well documented entry point...

My problem however, was at the time I had no idea what was happening below the engine. I wanted good control, and I wanted a framework I know like the back of my hand. I came up with the idea "HEY! I think the only way I'm gonna learn how the thing works *and understand it* is to try building my own engine entirely and completely from scratch. Most of my programming history was with web and processing solutions - this was a whole new ball game for me.

Which is what I ended up doing.

So I chose to set up XNA since I already knew C#, and started thinking about how or where I should start. I needed an idea.

I decided that, **no matter what, I would go straight into 3D**.

Getting the basics down was cool - the sprite batch stuff, but as I progressed I ended up discovering new barriers and obstacles - my first real one being the **batch limit**. My goal was to build a game that could at render at least 10000 entities in the view frustum at any time.

I embarked on a new journey of implementing Shader Based Instancing (and learned HLSL while I was at it) , I ditched XNA's built in Model and Effect objects to write my own replacements instead. I had trouble understanding the VBO streams at first; I broke things - I went online asking questions about the instancing stuff and kept at it until I finally understood what the GPU was doing. It paid off; now I had over twenty thousand test entities zooming around in my viewport after a couple days of debugging my VBO with PIX (dxsdk).

Now I had "some" idea of how rendering pipelines worked, but wasn't done yet - I ended up creating my own game-state, camera, post effects, and entity objects, moved away from the XNA Content Pipeline by building my own loaders (personal dislike towards the XNB thing ), created a complicated depth sorted and blend-state separated geometry chain and also had instanced sprites and text all being projected into the game scene.

I kept adding on, fixing, changing and experimenting with this continuously for almost an entire year. In the end, it came out pretty good. I now had an understanding of what is going on under the hood, because I created it - my baby.

Now my engine was mostly stable and just about finished. It isn't perfect: the scripting is honky and the GUI wasn't great at all. But I still loved it. Thousands of lines of code, assets and media - holed up in a private 2GB git repository, and all the headaches I had to go through trying to do a type of development I never did before. Every obstacle I overcame was a lesson learned - and a relief.

I pulled off almost everything I wanted in it.

**But in the end - I decided it was time to put her down.** As much as I satisfied myself writing such a huge engine by myself, with advice from the net, and other gamedev buddies, I decided that I'm gonna do it all over again - and do it better - because now this time I *mostly* know what I'm doing.

That project still sits tucked away in my GIT repo.

My second pass at writing a new engine (this time on MonoGame), is progressing well. When something breaks, it's easier to fix. Less mess. I hope to publicly show off my game sometime this year, because I tend to be a bit 'too' attached to my code.

In the end writing my own engine is how I learned 'how' to do it, while being able to say that I know and understand exactly what every component does, and how they are supposed to work. I actually HATE reading other people's code, especially for large undocumented projects. I want everything I use to be built by me.

This is just me though. I doubt I'll ever use a pre-made engine, probably because I think it's just more fun for me to write my own frameworks than to sit and deal with someone else's code - full control.

# Answer
> 15 votes
The absolute key reason to write your own engine (and it surprises me that nobody has called this out yet) is for **debugging**.

If you've written a big, complicated game, and there's a crash bug in it, and you have the source code (and are intimately familiar with that source code by virtue of having written it), then you can simply attach a debugger to the process and find what's causing the crash. Done.

If you're using somebody else's commercially-available engine, and you don't have the source code for that engine (you normally don't), then debugging any problems that come up -- even inside your own code -- is going to be monumentally more difficult. And if you run into a bug inside the engine itself, you won't be able to solve them yourself. How would you like to be a week out from your release date and have someone discover a crash bug in the engine you're using -- a crash bug which you can't fix because it's inside a proprietary engine to which you don't have the source code? I've seen this happen -- you've got no choice but to lodge an urgent support call with the vendor and hope that they can (and are interested in) fixing the problem for you, while you scrabble around, trying to guess at a workaround which will avoid hitting the bug in the engine which you don't know what it is.

Game development is hard, but debugging is orders of magnitude harder. In my book, anything which makes game development harder but debugging easier is a *huge* net win.

# Answer
> 9 votes
There are very good answers here but they're missing one important additional point.

**Many of today's licensable engines started out as dedicated engines**.

Let's take Unreal as an example because it's so ubiquitous.

Today when you think of Unreal you tend to think of an engine that you license and can use instead of having to build your own, but that wasn't always the case, and once upon a time the Unreal engine didn't even exist as a separate entity.

Once upon a time there was a **game** called Unreal. The developers of it **decided to build their own engine rather than license an existing one**. Fast forward through several iterations and that engine becomes the Unreal engine we know today.

The point is that this is a chicken-and-egg problem. Every bit of middleware you can license started somewhere, and it often didn't start out as middleware at all (sometimes it wasn't even written with the *intention* of becoming middleware and it's current status is effectively an *accident*). People write their own engines because ultimately **somebody** has to write the engine, and today's dedicated engine might become tomorrows licensable middleware.

# Answer
> 3 votes
There are others reasons a studio may choose to "build" instead of "buy" their technology:

* **New platforms**: new mobile OS, console or controlers. Think about leapmotion, google glass, etc. The cross-plataform support is hard
* **New game mechanics and/or in-game editors**: Think about FEZ, some years ago (2D vs 3D)
* **Lack of good free open-source game editors**. Lack of good documentation on existing source of old games
* Evolution of the **tools in the studio toolchain** (or add new ones)
* **Engine pricing and license wars**

I also agree with specific requests/needs and engine pricing and license wars force some studios to roll out some engines.

The good motives to "buy" or "use" other engines are:

* **Code Reuse**: a engine already used in other games is more tested, more stable and mayhave most of the features needed, starting from day one.
* **Extend**: you can extend some open source engines.
* **Free**: or almost free, since even free open source engines, need some developer time to learn.

# Answer
> 2 votes
Historical reason (mostly).
Which is related to pricing.

Every game you saw running Unreal or CryEngine in the past years had to pay a huge amount of money. Especially if you want to get the source code (ie.: you wanted UE, not UDK only.)

But this changed. Now everyone can afford even bigger engines, as the price race started.
What that means...

* You will see much more games using both UE4 and CryEngine.
Though, they won't be AAA games like they've been.
* Custom requirements and needs for each projects won't go away.
See the Warhammer40k/COH engine at Relic, or the one that Generals used at EA.
So even if anyone can afford the bigger engines, they don't neccesarily offer a better choice.
* There are others on the market. Like Unity.
People love it for it's ease-of-use, fast performance, and the huge asset store.
Of course, Unity is able to deploy to almost any platform.

So yeah. Needs, pricing in the past and such.

# Answer
> 1 votes
My answer differs from the existing ones, so I add it although it's late:

If you take the Valve example from the question, or the Witcher series the process was:

* License an engine
* Modify/adapt engine to your purpose
* Release game and generate money
* Create own engine for next game

The same approach is taken by almost all financially reasonable developers who develop their own engine. By modifying an engine they build up knowledge how an engine works, and run into design constraints which result from a licensed engine. At the end they have the in-house knowledge necessary to create an engine, the cash to fund the creation of an engine, and a project which will benefit from a dedicated engine. At that point the reason for building an engine is: Because it's the smart thing to do.

# Answer
> 0 votes
What about the team organization?

Behind the debug stuff are the documentation & support, no the code, because at the end I didn't want that my building group will touch the code of my own engine. That could be a mess.

So, I need a support group to do that. But that raises the costs: more people, more places, more line phone, more administration...

One solution to this may be outsource... to a middleware company, releasing resources to my business of making games, i.e. to the creative group and writers.

For an starting up company it's not a bad option to use and not build. And, after getting a critical mass of incomes, may be, just may be, you will want to build your own engine...

# Answer
> 0 votes
well. for most games that use their own engine created by their developers. often. they can't do things with 3rd party engine. so they make their own to make the development of their own game easier to do. or possible at least.

and many games that use their own engine just generally. work better. because they're more custom and 100% fit their task. and the game itself feels differently. its really easy to play a game and say thats made by. unreal engine or whatever. more custom engine generally and should result in a game that feels unique. looks unique and works uniquely and it should perform better than a game that was created on a pre-made engine.

# Answer
> -2 votes
my programming teacher told us, only use API's/methods/classes/functions which you know how to build

because if you dont know how to build it and are using somebody else's work chances are you dont know how it works and when you dont know how something works then you are alot more prone to error and problems and hitting walls of confusion

learning simple things can when compounded result in strange problems, let alone something complex like a game engine especially when you are supposed to use that game engine to run your game which can lead ot many unexpected results and problems

and game engine dont follow logical code or any other logic when they are built , sure there is some things which can be expected but in reality everything is going to be built based on somebody elses understanding and knowledge of some programming language or how some system works

for example if i choose to write a mathematical equation i can write it so many ways i can represent it with polynomials, or differential calculus or basic geometry or algebra or whatever suits me but sometimes i would write in a certain form/format because i want to be able to manipulate what is easily available , such as if i planed to do alot of vertex manipulation i might write this mathematical model using basic geometry, however if i wanted to change the curve using gradients i might focus on differential calculus to be able to easily manipulate the gradients etc and same goes for whatever it is i plan to have easier access to

and sometimes the current game engine might not give me the flexibility of what i intend to do or even maybe it gives you that option but its very hard to do so because the game engine focuses on physics forces as its main source of motion and manipulation of objects in the game

anyway i hope i made it clear what i was trying to point out

---
Tags: game-industry, business
---


title: first person character controller error

text:
# Question
Title: first person character controller error
I have opened new scene, deleted camera and imported first person character controller from Standard assets. I placed plane on scene and put first person character controller on plane.

I got this error:

> Assets/Standard Assets/Characters/FirstPersonCharacter/Scripts/RigidbodyFirstPersonController.cs(3,27): error CS0234: The type or namespace name `CrossPlatformInput' does not exist in the namespace`UnityStandardAssets'. Are you missing an assembly reference?

How to fix it?

# Answer
To have the controller working properly, here is what you must import:
> 1 votes

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


title: Perspective projection in Open GL

text:
# Question
Title: Perspective projection in Open GL
I am trying to convert a 3d point into a 2d point using a perspective projection. I'm new to OpenGL and may not have fully understood how this works. How exactly do I calculate the near and far values?

The vertex values I want to consider are between 1, 1, 1 and 16, 16, 16. So if I consider a output texture of size 16 x 16. Will my near and far be 0 and 16 respectively?

Does this transformation take care of scaling my vertex values between 0 and 1 as well?

# Answer
> 1 votes
You don't usually calculate these, you set them to a value, and you tweak them depending on the outcome. There are some limitations too:

The near plane needs to be bigger than 0, but if it's too small, then you'll have some issues later. OpenGL has a higher precision closer to the camera, and with a near plane of 0.01 units, the difference between the actual distance and the distance based on the depth buffer'll be around 100 units at 1000 units, which results in z-fighting. If the far plane is too high, then the same thing can happen.

You should probably use 0.1 for the near plane distance and 100 or 50 for the far plane distance. There's virtually no reason to go below these.

---
Tags: opengl-es2, perspective
---


# Question
Title: What are the parameters for btHingeConstraint::setLimit?
What does each parameter in `btHingeConstraint::setLimit` do to the hinge constraint?

```
void btHingeConstraint::setLimit    (   btScalar    low,
        btScalar    high,
        btScalar    _softness = 0.9f,
        btScalar    _biasFactor = 0.3f,
        btScalar    _relaxationFactor = 1.0f
    )

```

# Answer
The parameters `low` and `high` are the angles restricting the hinge. The angle between the two bodies stays in that range. For no restriction, you pass a lower limit \<= -pi and an upper limit \>= pi here. This might be useful for things that rotate completely around other things, for example wheels on a car. For the other three parameters, I can only guess, so I don't claim this answer is complete.

`_softness` might be a negative measure of the friction that determines how much the hinge rotates for a given force. A high softness would make the hinge rotate easily like it's oiled then.

`_relaxationFactor` might be a measure of how much force is applied internally to bring the hinge in its central rotation. This is right in the middle of the low and high angles. For example, consider a western swing door. After walking through it will swing in both directions but at the end it stays right in the middle.

`_biasFactor` might be an offset for the relaxed rotation of the hinge. It won't be right in the middle of the low and high angles anymore. `1.0f` is the neural value.

I'll update this when I found out more. Currently, I can't test this manually, and the documentation seems to lack here.
> 3 votes

# Answer
The `low` and `high` parameters are indeed the angle limits of the hinge, however the other three parameters (`_softness`, `_relaxationFactor`, and `_biasFactor`) can be set and are copied from the constraint to its `btAngularLimit` before it is "tested" but are never actually used. It looks like plans to allow for soft constraint limits were never finished.
> 0 votes

---
Tags: physics, bullet-physics
---


# Question
Title: How To Fix Strange White Edges With DOF and Fog in Unity?
I'm using global fog and the standard assets Depth Of Field script but it has a strange effect on the edges of far away objects.

How can I make the white edges along the trees blend smoothly into the fog?

# Answer
I tried using a different depth of field shader (also in standard assets). This solved the problem. It must use a different method I guess.
> 1 votes

---
Tags: unity, effects, depth, image-effects, fog
---


# Question
Title: How many matrices do i need to represent a rectangular figure and translate it?
I'm learning math at the moment and i can't really understand the purpose of the matrix. Yes, i've watched several tutorials out there and reading the book but still confused.

Correct me if i'm wrong. We need one matrix to represent one point(vertex) on the screen. So to represent a rectangular, we need 3 matrices. Right?

# Answer
To greatly simplify:

Each point in a polygon is a vertex. A vertex is represented by a vector\*. A vector is a group of numbers (typically floating point numbers) typically used to represent either a point\** in space or a direction. In the context of video games, this is usually 2-4 numbers, where each number corresponds to a spatial dimension (X, Y, Z and W - don't worry too much about W, that's a separate matter).

A matrix on the other hand is a grid of N by M numbers which typically represents a linear spatial transformation, i.e. a translation (movement in space), a rotation and a scale (size up, size down). (It can also be used for projection, but projection can be usually be thought of as a mixture of translation, rotation and scaling anyway.)

From a mathematician's point of view, a vector is equivalent to a 1 by N (or N by 1) matrix, which is probably where you're getting confused. When programming games, most people treat vectors and matrices to be distinct entities because they have different purposes.

In your case, a rectangle can be represented by 4 vertices, which can then be translated by 1 translation matrix. In this case (assuming you're doing this in 2D space and not 3D space) the 4 vertices could be said to be four 1x2 matrices (or 2x1 matrices) and the translation matrix would be a 3x3 matrix, meaning that you technically have 5 matrices from a mathematician's viewpoint. From a programmer's viewpoint though, you would only have 1 matrix because vectors/vertices are typically considered to be different from matrices.

---

* Some people define that a vertex is in fact a vector with additional information used for rendering (e.g. a colour). Some define it as a vector used to represent a point in a polygon. Terminology has blurred over time and many things that used to have important differences are now thought of as synonymous in some cases. The term 'vertex' is one of these.

\** Some people consider points and vectors to be different (that points are points in space and vectors are directions) and some people consider them synonymous. Likewise, some libraries have separate `point` and `vector` constructs and some use `vector` where others would use `point`. This is another common source of confusion.
> 1 votes

# Answer
It really depends on what you mean by rectangular figure. If you mean a rectangle in 2D space, then you need at least 4 points to represent it but that's not enough for drawing the shape.

When you're drawing a shape, you need to specify its triangles. Let's say you have a rectangle with the points \[0, 0\], \[0, 2\], \[1, 0\], \[1, 2\]. To draw this you need to specify at least two sets of dots. First one would be something like \[\[0, 0\], \[0, 2\], \[1, 0\]\] which would draw the first triangle. The second one would be something like \[\[0, 2\], \[1, 2\], \[1, 0\]\] which would draw the second one. Notice that I'm going clockwise when representing the triangles. This really doesn't matter much so long as you draw them all the same way. If you draw one clockwise and the other one anti-clockwise, then you'll only see them on the opposite sides of the shape.

Anyway, this 2D rectangle is represented by two triangles and four points in space. That's would make six matrices in total. Seven, if you count the overall matrix that is the shape itself.

In 3D space it's a bit more complicated. You now have 8 points in space, and you have to define 6 faces for the rectangular prism. Each face will need two triangles, which means 12 matrices. In total, you would have 8 for points and 12 for triangles, which makes 20 matrices.

Of course the correct terminology is vertex and vertices but they're still represented as matrices, or rather arrays, in game development.
> 0 votes

---
Tags: mathematics, graphics, matrix
---


# Question
Title: Is speed runs ranking mechanism heuristic or statistics based?
I'm looking to implement some sort of speed run mode in my game.

Let's say I want to assign each level three 'winning' bars, (bronze, silver and gold for example), which are independent of the player, and are based only on the difficulty of the level itself.

I can think of two methods:

* Having a heuristic which outputs these three bars, given the level's settings.
* Spending some time for testing the game over several players, and collecting statistics (mainly time to completion), in order to determine the bars.

Are both methods considered acceptable? Or is one of them is somewhat "banned"?

---

I would also like to consider a more limited situation, where there's not a real option to perform a wide-scale statistics collection. Would that completely throw the second method off the windows? Or is small-scaled (for example, having 5-10 players playing a level for a few times) is usually enough in common indie game developer scales?

I guess the answer here should depend on the nature of the game itself, but I wonder if this certain type of test ('winning bars' for speed runs) is considered easy to handle.

# Answer
> 1 votes
In my personal experience, it depends on the game and its complexity. But it's not uncommon to use player/designer statistics and base values off them.

Often heuristics don't give accurate values for all levels and you might waste a lot of time trying put together an accurate algorithm for all of your level types.

What you might find though, is what ever scores/times you think are achievable, players will always beat your estimates so take that into consideration.

---
Tags: heuristics
---


# Question
Title: Security concerns related to HTML 5 games
I would like to know if people could modify an HTML 5 game's code to harm either the server or other players whom visit the page.

More specifically, whether someone could modify a simple game that doesn't have things like high-scores, global stats, log-in, etc. to harm other users and/or the server the game is hosted on.

Is this only a concern for games that retrieve data to be stored on the server itself?

# Answer
> I would like to know if people could modify an HTML 5 game's code

Yes.

Like all web technologies, the client has full access to the local code; they can browse the source, modify it and send unexpected data to the server, or sniff what the server is sending to the client, but not displayed.

> to harm either the server

Yes. This is not specific to games, though, you could check for any web security resources and they would apply to games.

> or other players whom visit the page.

Maybe. The least bad thing that could happen to them is that one malicious client is causing a DoS (denial of service) attack and prevents the other players from playing; the worst that could happen is that their private data is stolen. But again, this is not specific to games.

---

If the game code and content is downloaded from the server, and the player can play the game without needing to communicate with the server again, there is less worries to have. Your players will be able to cheat, but since they're in their own bubble, it's generally not a concern.

If you introduce the features that you have mentioned, then, yes, at that point, it starts to be a concern: cheating from players, players trying to hack the server to get more in-game currencies, get the other players information, etc.
> 5 votes

---
Tags: javascript, html5, client-server, security
---


# Question
Title: How to create OpenGL models like the ones created by blender's wireframe modifier?
How could I create programatically wireframe models like this out of a triangular mesh? What'd be the algorithm behind?

<sup>(Source)</sup>

Creating an additional mesh using lines instead triangles or just using a single mesh with the typical geometry shader using barycentric coordinates are the most straightforward approaches. But they're far away from being as cool as the results shown in the above link.

So I was wondering how difficult would be creating a new mesh like the shown in the above link, would it be possible to achieve by just having a simple triangle soup?

# Answer
You can find blender's code that creates the wireframe mesh here.

Effectively you want to create a tube around each edge in the mesh. So if you wanted to use eight edges to make the tube, you would create eight new edges for each existing edge, move them parallel to the edge by radius distance and using the original edge as the centre point rotate them by 45 degress each. Then subdivide and join with faces.
> 2 votes

---
Tags: opengl, blender, 3d-meshes
---


# Question
Title: Need some insight on mesh triangulation and geodesic spheres
I am making a game that's going to use a Class 1 (This is (n,0)) Goldberg Polyhedron as the map, that is I'm planning on using the hexagons and 12 pentagons as tiles for a tile-based game.

When it came to generate this shapes, I researched online and came to the conclusion that the best way to get there is to do an icosphere appropiately divided and then find it's dual shape so I got to work onto that and I came up with a code that will generate the vertices of an icosahedron divided just like I wanted and with zero duplicates.

Now my problem is, I'm having a lot of trouble finding a nice way to triangulate all this faces, because as some edges are shared the vertex index vary a lot. I'm gonna post some of my code and see if someone can help me out here cause i've been thinking about this for hours and I'm sure I'm just missing something.

```
void Subdivide(int frequency, List<Vector3> vertList, List<TriangleIndices> faces){

    List<Vector3> workingList = new List<Vector3> ();
    for (int i = 0; i < faces.Count; i++){
        float div = frequency + 1;
        Vector3 v1 = vertList [faces[i].v1];
        Vector3 v2 = vertList [faces [i].v2];
        Vector3 v3 = vertList [faces [i].v3];

        for (float k =0; k <= (frequency + 1); k++) {

            for (float j = 0; j <= div; j++){
                if (div == 0) {

                    for (int c = 0; c < workingList.Count; c++) {
                        if (workingList [c] == ((v1 + (k / (frequency + 1f)) * (v3 - v1)) + 1f * ((v2 + (k / (frequency + 1f)) * (v3 - v2)) - (v1 + (k / (frequency + 1f)) * (v3 - v1)))).normalized) {
                            isDupe = true;
                        }
                    }

                    if (isDupe == false) {
                        workingList.Add (((v1 + (k / (frequency + 1f)) * (v3 - v1)) + 1f * ((v2 + (k / (frequency + 1f)) * (v3 - v2)) - (v1 + (k / (frequency + 1f)) * (v3 - v1)))).normalized);
                    } else {
                        isDupe = false;
                    }

                } else {
                    for (int c = 0; c < workingList.Count; c++) {
                        if (workingList [c] == ((v1 + (k / (frequency + 1f)) * (v3 - v1)) + (j / div) * ((v2 + (k / (frequency + 1f)) * (v3 - v2)) - (v1 + (k / (frequency + 1f)) * (v3 - v1)))).normalized) {
                            isDupe = true;
                        }
                    }
                    if (isDupe == false) {
                        workingList.Add (((v1 + (k / (frequency + 1f)) * (v3 - v1)) + (j / div) * ((v2 + (k / (frequency + 1f)) * (v3 - v2)) - (v1 + (k / (frequency + 1f)) * (v3 - v1)))).normalized);
                    } else {
                        isDupe = false;
                    }
                }

            }
            div --;
    }

    Triangulate (frequency, workingList);
}

```

This is a function that given the frequency, this is the number of vertices that are placed between two vertexes on the original triangle, a list of vertices, and a list of faces it will, without duplicates, subdivide the faces accordingly. Then it calls the triangulate function that is supposed to group this into actual faces.

This for a frequency 'f' means that now every edge will have 2+f vertices instead of 2. I use this definition of frequency because it's what it's used when talking about Goldberg polyhedra.

```
void Triangulate(int frequency, List<Vector3> vertList){
    List<TriangleIndices> faces = new List<TriangleIndices> ();
    int div = frequency + 1;
    int divRecursive = 0;

    for (int k = 0; k < frequency + 1; k++) {

        for (int i = 0; i < div ; i++) {
            faces.Add (new TriangleIndices (i + divRecursive, i + 1 + divRecursive, i + div + 1 + divRecursive));
        }
        for (int i = 0; i < div - 1; i++) {
            faces.Add (new TriangleIndices (i + 1 + divRecursive, i + div + 2 + divRecursive, i + div + 1 + divRecursive));
        }
        divRecursive += div + 1;
        div--;
    }

    List< int > triList = new List<int> ();
    for (int i = 0; i < faces.Count; i++) {
        triList.Add (faces [i].v1);
        triList.Add (faces [i].v2);
        triList.Add (faces [i].v3);
    }

    Debug.Log("There are " + faces.Count +" faces and " + vertList.Count + " vertices");
    mesh.vertices = vertList.ToArray ();
    mesh.triangles = triList.ToArray();
    mesh.RecalculateNormals();
    mesh.RecalculateBounds ();
}

```

This is my triangulate function, and at the moment, it only does the first face because i'm not sure how to do the other faces. Worth noting some stuff about it, divRecursive is a variable used to store the first vertex of the next line, div stands for divisions and is the number of divisions on each edge.

Now I need them to be grouped in faces to be able to then find the center of each face and apply a duality transformation to get the shape I actually want so if you have any tips for that too I'd be more than happy to hear them.

EDIT: This is a small video showing how it works

# Answer
My preferred approach is to split the geosphere into flat charts, bent a little to fit a simple square grid so they're easier to reason about:

Let's say we split the underlying icosahedron into 5 of these charts as shown above. To avoid duplicating work, we can apply a rule that vertices along the top & right edges of each chart "belong" to a different chart (including a bonus 6th chart for the North & South Pole vertices). This lets us construct a well-defined regular ordering of the vertices and triangles in terms of their grid coordinates:

We can iterate over each rectangle of solid dots in this image to produce the vertices in this order, without ever visiting a vertex twice and needing to check for a duplicate.

Once we have the vertices in order, it's super fast to identify the vertices bounding a given triangle. And for Class-I geodesics we have the extra-nice property that each triangle "belongs" unambiguously to exactly one chart, so we can simply number them across each row like so:

(Of course all the numbering rules I've used here are arbitrary, and you can choose a different way to exploit the grid structure to still get the same predictability with whatever numbering scheme you prefer)

Here's an example of how we could build a triangle list (3 vertex indices per triangle) using the structure developed thus far:

*(**Disclaimer:** this was all just written for this answer - I haven't compiled this code, so it's very likely there are typos or off-by-one errors I didn't spot, but it should at least show the flavour of this approach)*

```
// Set up some reference values based on the size of our geosphere.
int rowSize = 2 * frequency;
int chartSize = rowSize * frequency;

int northPoleIndex = chartSize * 5;
int southPoleIndex = northPoleIndex + 1;

// (Our vertices array has northPoleIndex + 2 entries in total)

int t; // Tracks which triangle index we're writing to next.

for(int chart = 0; chart < 5; chart++) {

   // First, construct all the triangles wholly surrounded by black dots.
   // (ie. 0-13, 16-29, 32-45...)
   for(int row = 0; row < frequency; row++) {
      for(int col = 0; col < rowLength; col++) {

          // index of the vertex at the bottom-left of the cell.
          int baseVertex = chartSize * chart + rowSize * row + column);

          // 2 triangles per cell, 3 indices per triangle.
          t = 2 * 3 * baseVertex;

          // Top-left triangle in the cell.
          indices[t++] = baseVertex;
          indices[t++] = baseVertex + rowSize + 1;
          indices[t++] = baseVertex + rowSize;

          // Bottom-right triangle in the cell.
          indices[t++] = baseVertex;
          indices[t++] = baseVertex + 1;
          indices[t++] = baseVertex + rowSize + 1;
      }
    }

    // Now we handle triangles that border on the next chart & the poles.
    int nextChart = (chart + 1) % 5;

    // North pole cell.
    int topLeft = chart * chartSize + chartSize - rowSize;
    int nextTopLeft = nextChart * chartSize + chartSize - rowSize;
    t = 2 * 3 * topLeft;

    indices[t++] = topLeft;
    indices[t++] = nextTopLeft;
    indices[t++] = northPoleIndex;

    indices[t++] = topLeft;
    indices[t++] = topLeft + 1;
    indices[t++] = nextTopLeft;

    // Continue rightward along the top edge of the chart, to its midpoint:
    for(int edge = 1; edge < frequency; edge++) {
        int baseVertex = topLeft + edge;
        int nextChartBase = nextTopLeft - rowSize * edge;

        indices[t++] = baseVertex;
        indices[t++] = nextChartBase;
        indices[t++] = nextChartBase + rowSize;

        indices[t++] = baseVertex;
        indices[t++] = baseVertex + 1;
        indices[t++] = nextChartBase;
    }

    // Next, continue from the midpoint of the top edge toward the right corner.
    ...

    // Then the top-right corner cell
    ...

    // Then down the right edge to the bottom
    ...

    // And lastly the bottom-right cell, bordering on the South pole
    ...

```

It's a little annoying to break out each segment of the rectangle into its own little loop, so an alternative method you can consider would be to lay all the charts out on a single x-y grid, and provide a function that takes an x,y coordinate and returns the corresponding vertex index.

```
int VertexIndex(int x, int y, int frequency) {
    // (Assuming integer division rounding toward zero)
    int chart = y / frequency;

    int col = x - frequency * chart;

    // Catch references off the top of the left zig-zag edge:
    if( col < 0 ) {

        // North pole.
        if(col = -frequency)
           return frequency * frequency * 10;

        // Bend references up to vertical edge.
        y -= x;
        x = 0;
    }
    // Catch references off the right of the other zig-zag edge:
    else if ( col >= 2 * frequency ) {

        // South pole.
        if(y - chart * frequency == 0)
            return frequency * frequency * 10 + 1;

        // Bend references up to next horizontal edge.
        int nextY = (chart + 1) * frequency;
        x = frequency + nextY - y;
        y = nextY;
    }

    // Wrap references off the top of the chart back around to the bottom.
    y %= frequency * 5;

    // Return the computed index.
    return y * 2 * frequency + col;
}

```

Now we can have a much simpler-looking loop (though it does more conditional logic at each step):

```
int t = 0;
for(int chart = 0; chart < 5; chart++) {
   for(int row = 0; row < frequency; row++) {
      for(int col = 0; col < 2 * frequency; col++) {
          int x = chart * frequency + col;
          int y = chart * frequency + row;

          int a = VertexIndex(x, y, frequency);
          int b = VertexIndex(x + 1, y, frequency);
          int c = VertexIndex(x + 1, y + 1, frequency);
          int d = VertexIndex(x, y + 1, frequency);

          indices[t++] = a;
          indices[t++] = c;
          indices[t++] = d;

          indices[t++] = a;
          indices[t++] = b;
          indices[t++] = c;
      }
   }
}

```

I hope that gives you some useful leads!
> 3 votes

---
Tags: unity, c#, tiles, tilemap
---


# Question
Title: Using Racing Wheel force feedback with a JavaScript game
I have a Thrustmaster T80 Racing Wheel that I am using while developing an online game with ThreeJS.

I have already made it so I can drive the car with the wheel and the game knows when I crash the car. But looking online I couldn't find a way to make the wheel 'rumble' or shake when the car crashes.

The wheel does support this on other (downloaded exe) games but it would be amazing if it was possible to achieve in a JS game, but I couldn't find any mention of doing this online.

# Answer
The term you are looking for is "haptic feedback". There seem to be a bunch of Javascript libraries that do this, for an example take a look at Haptics.js.
> 1 votes

---
Tags: javascript, force-feedback
---


title: Bounce ball after collision

text:
# Question
Title: Bounce ball after collision
I added Box Collisions (Walls) outside of the screen and a player (ball) with rigidbody and Circle Collider in dynamic forcing to a random direction.

I want the ball to bounce when it collides the wall.

*Bomb.cs*

```
private Rigidbody2D rigidbody;
private Vector2 direction;

// Use this for initialization
void Start () {
    rigidbody = gameObject.GetComponent<Rigidbody2D> ();
    direction = new Vector2 (Random.value, Random.value);
}

// Update is called once per frame
void FixedUpdate () {
    rigidbody.AddForce (direction);
}

```

# Answer
Just add a `Static` rigidbody 2D to all the walls.

Edit: I noticed now two problems.

1) You haven't assigned a physics material to your ball. Create a new physics material 2D in the assets, set its `Bounciness` to 1 and `Friction` to 0, then drag it to the `Material` of the ball's `Rigidbody 2D` component. You need the `Bounciness` != 0 in order to make the ball bounce on the walls.

2) You're adding every `FixedUpdate()` the same force to the ball, this will increase rapidly its velocity regardless of bounces, move the `AddForce` to `Start` for the moment, if you need to make further changes during runtime to the velocity of the ball, use the `AddForce` under an `if` statement of your choice, so it won't increase the velocity up to infinity (and making the ball go beyond the walls due to missed collision in a single physics timestep).

Edit 2: the code to randomly choose a direction but with a set speed.

```
using UnityEngine;

public class Ball : MonoBehaviour {

    Rigidbody2D rigidbody;
    Vector2 direction;
    public float startSpeed;

    void Start() {
        rigidbody = GetComponent<Rigidbody2D>();
        float radiants = 0;
        while (radiants == 0) {
            radiants = Random.Range(0, 2 * Mathf.PI);
        }
        direction = new Vector2(Mathf.Cos(radiants), Mathf.Sin(radiants));
        direction.Normalize();
        direction *= startSpeed;
        rigidbody.AddForce(direction);
    }
}

```
> 2 votes

---
Tags: unity, physics
---


# Question
Title: Is "entity component system" a principle or a pattern?
Since the ECS follows the principle *Composition over Inheritance*, and it makes the behavior of game objects can be changed in the runtime.

If ECS is a principle, from my memory of design patterns of GoF, the following patterns can accomplish the principle well:

1. Decorator pattern
2. Composite + Visitor

But I'm not sure about that ECS is a pattern like the above or a principle like Open Closed Principle, I've tried to find a video which explains ECS well but found nothing clear.

Current resources I found:

# Answer
> 8 votes
If I had to, I'd say ECS is probably a pattern. Principles are more generic, addressing multiple problem domains. Patterns tend to be more about establishing a shared vocabulary for sets of mostly-similar techniques.

The term "ECS" is used to refer to a technique of creating more-complex game objects (the "entities") out of smaller, less-complex-but-feature-complete objects (the "components"). It is fundamentally a narrowing in scope of the more general principle of preferring composition (as you noted), and I think that makes it sufficient narrow to describe it as a pattern, if you really wanted to get picky about it.

There are still plenty of different ways to actually *write* that code (just as there are many ways to *write* a visitor, or observer, or whatever other Gang of Four pattern strikes your fancy), most of which are perfectly correct. None of it is set in stone and none of it should be. This is probably why you're having a hard time finding a video describing it, because it's complex and there is no single accepted way to do it. Patterns are for assigning names to broad, complex behavior so we can talk about them more easily.

Yes, some patterns are similar and some combinations of patterns can be used to effective achieve the same results as other patterns, as you noticed. That's fine; they aren't supposed to all be orthogonal to eachother.

---
Tags: design-patterns, entity-component
---


# Question
Title: What are patterns and how to use them? (Othello/Chess...)
I'm currently trying to make a Othello-playing program. My biggest concern at the moment is the evaluation function of game positions. Currently my evaluation function is quite primitive...move counting, looking for corner plays etc.

I tried to implement the evaluation functions of IAGO(1981) and BILL(1986).

I tried to read a bunch of papers, Michael Buro's stuff especially, but I failed horribly. It seems as I miss some fundamental knowledge. I neither get to understand how patterns work nor how to create them.

As far as I understand they are used to rate constellations of rows, columns, edges, 3x3 corners etc.

I'd highly appreciate if someone could provide me the following information:

* What data structure has a pattern?
* Given a certain game position how would I make use of this pattern to evaluate the situation?

I think if I get answers to those questions, I'll probably be able to understand the following aswell, but I'll mention them anyway.

* How are patterns created? I saw that an approach is to assign static values to different squares of the game board, dependant of their current properties(color, stability). But then there is some iterative algorithm called.
* So are patterns created on the fly e.g. while searching a tree? Or computed before and used like a mask?

I hope this question isn't too broad, but I got the impression that creation and use of patterns is some obvious common knowledge, that everyone does almost the same way, like use of alphabeta.

# Answer
> 1 votes
This 1986 paper by Kai-Fu Lee of Carnegie Mellon University seems to be more focused on pattern classification. It's called A pattern classification approach to evaluation function learning.

Personally I struggle to understand the maths because I'm not very good with high level mathematics, but it seems that it's based on some sort of weighted summation of board features. Such features include "piece-count advantage, center control, and pawn structure".

Wikipedia also has a much simpler overview of pattern-based techniques.

Aparently there are also various pattern searching strategies that are worth looking into. For example here is an article about zero-window/null search (I know it's for chess, but chess and othello are somewhat similar in some respects).

---
Tags: chess, game-theory
---


# Question
Title: LibGdx, conflicting UI button clicks and screen touch events
My game's main game class is a Screen which also implements InputProcessor to handle touch events.

The screen renders a TMX map using an HexagonalMapRenderer and a Camera, like this:

```
_camera = new OrthographicCamera();
_map = new TmxMapLoader().load("1087.tmx");
_mapRenderer = new HexagonalTiledMapRenderer(_map);
_camera.setToOrtho(false, Gdx.graphics.getWidth(),  Gdx.graphics.getHeight());

```

To allow the user to scroll the map, I am overriding the touchDown and touchDragged methods; it works.

However, I also have a Scene2D Stage rendering on the Screen, which I use to display some buttons.

They get displayed. and I have created a ClickListener like this:

```
 button.addListener(new ClickListener(){

    @Override
    public void clicked(InputEvent e, float x, float y){
        System.out.println("Clicked!");
    }
 });

```

If I use

```
Gdx.input.setInputProcessor(this);

```

Only the Screen scrolling functions will work, and the buttons will become unresponsive.

On the other hand, if I use:

```
    Gdx.input.setInputProcessor(stage);

```

I will be able to use UI buttons, but the map will become unresponsive.

I'd like to enable both (map will scroll if user clicks anywhere BUT the UI buttons, it will then fire the button clicked listener), is there any way to do this?

Thanks.

# Answer
You should use an `InputMultiplexer` (javadocs | wiki) to combine the two input processors. It works like this:

```
InputMultiplexer multiplexer = new InputMultiplexer(this, stage);
Gdx.input.setInputProcessor(multiplexer);

```

This will allow you to use both processors at once. Remember that the return value of the functions are important (`true` / `false`)! If once function (let's say `touchDragged`) return `true` **no other input processors** will be called afterwards! The call order of the processors depends on the order you provide them:

```
InputMultiplexer multiplexer = new InputMultiplexer(this, stage);

```

yields different results, than

```
InputMultiplexer multiplexer = new InputMultiplexer(stage, this);

```

In the later example, the stage is called first, so it has a "chance" to any processed inputEvent.
> 2 votes

---
Tags: java, libgdx, input
---


# Question
Title: How can I have margins or padding around a texture in libgdx?
I am building a game using libgdx a 2048 like game and I draw the tiles of the board using textures (each texture represents a tile with the number 2 or 4 etc.)

I would like tohave a small space around the square textures. How can I do this ?

Thanks.

# Answer
> 0 votes
I'd suggest you give your actor (I suppose you use Scene2D) a bigger size, than your Image.

If you dont use Scene2D I recommend that you watch into it, because that would is the best way I can imagine to do such a game.

But as a final answer on your question: add transparency to your Image at the border. (which would go quite easy for once, but changing it would be a hell.

Or you try to use a Container. As example use Stack from Scene2D. You can place a bigger Image, which is transparent and on top of this Image a smaller one. Now you can scale your padding, or your Image, as you want.

https://libgdx.badlogicgames.com/nightlies/docs/api/com/badlogic/gdx/scenes/scene2d/ui/Stack.html

# Answer
> 0 votes
Why don't you simply offset the texture's position by some amount? If you want a `5px` border around your images simply offset the position by `5` and the images will have a `5px` gap between them. Assuming an array of the textures you want to draw you could do something like this:

```
float prevPos = 0;
for (Texture tex : texturesToDraw) {
    // 5px to the right of the previous textures position
    float texturePos = prevPos + 5;
    float textureWidth = tex.getWidth();
    prevPos = texturePos + textureWidth;

    batch.draw(tex, texturePos, 0);
}

```

---
Tags: libgdx, textures
---