title: Entity System creating Components

text:
# Question
Title: Entity System creating Components
Over every entity system I see implemented in C++, or even in Java/C# (e.g. the Artemis framework). I see components not allocated via a new operator (or something similar, e.g. `std::make_shared`). For example:

```
entity.addComponent(new Position(32, 4, 5));
entity2.addComponent(new Position(5, 6, 7));
// those two position components that were just created
// may/may not be together in memory

// or even:
// how can you avoid using new here? (in the implementation)
entity.addComponent<Position>(32, 4, 5);

```

Doesn't this harm performance, as there would be cache misses (since new can allocate data anywhere from the heap)? How would you implement a system in such a way that the components of each type are allocated contiguously in memory, so you avoid cache misses? I mainly want to know how one would do so in C++.

# Answer
> 9 votes
Most entity systems don't use Data Oriented Design. Note that entity system doesn't necessarily imply DOD, it just means splitting gameplay functionality into different component classes giving entities certain features and behavior. You can (very easily) create a bloated and horribly slow Object-Oriented version of an entity system. So entity systems are just a design concept. DOD is a completely orthogonal code design concept that can however be applied very easily to entity systems.

So on to your questions:

> Doesn't this harm performance, as there would be cache misses (since new can allocate data anywhere from the heap)?

Yes. Well, maybe. It all depends on access patterns. But yeah, if you want to update all Position components in one go, well designed and aligned data can be far more efficient. Still, know your data and know how you use your data te be sure.

> How would you implement a system in such a way that the components of each type are allocated contiguously in memory, so you avoid cache misses?

There are multiple ways to do that using preallocated memory and such, you could use multiple smaller pools for finegrained memory control or if you know how much a level is going to use, you can just allocate that much memory etcetera etcetera. This is all described in the answers the others gave.

That could be a solution, but I think you're treating a symptom, not the real problem: You want to use classes. Don't do that, if possible. It's bad for a number of reasons, among which is cache locality. There is no reason for either the entity or the components to be classes. Now I've talked about this at more length in my answer here: When/where to update components I'll give you a very quick rundown though, or just read the long answer there and skip the next two paragraphs

All the entity is is an identifier that binds together a number of components. The entity could just be a unique integer. It can also be a class with a set of pointers pointing to all component data if you need that. Still, I don't see the necessity for that. If an entity is a unique integer, you could just as easily write a helper function to get a component given an entity id.

So now to get rid of the component classes themselves. There's no actual need for that either. What you need is two things: some data stored somewhere for each component (component data) and some way to update that data (component behavior). What a component class does is combine those two, but there are other ways. For instance, creating a component system where there are managers for each component type. All component data is stored in arrays in the manager, accessed using the entity id (which is just an integer as I said above, more about that in my answer here). The behavior is one simple update() function in the manager class which updates all components it manages in one go, fully utilizing the cache locality and optimization benefits a single update loop provides.

The same thing could be done using component classes which are aligned in memory, but there are still a lot of issues with that approach, most important of which are memory/cache related. What happens when you delete a component from memory? You can't just move one of the other components into the empty space, since that would mess up all pointers pointing to that component. How big is your component class data? It may very well be about the size of one cache line (64 bytes in modern x86). If that's the case, your system will hardly be any faster than one where data is all over memory.

The biggest issue is how you use your data. How much component data do you need each update? Say you have a component with a position (vec3), velocity (vec3) and two other 4 byte variables. That's 32 bytes of data per component (assuming you don't use any virtual function crap). Now when you update your component, you may need all variables and you need to load all data. That's fine. Cache line size is 64 and your components are all packed in memory, so when you load one component, you automatically load the next one into cache. Great. Now what happens when you only need to access the position for another unrelated update loop. You load 64 bytes of data, but it's only got 2 vec3's you need. You've just wasted 40 loaded bytes of data. This is exactly what DOD is about avoiding.

If on the other hand, you had a component manager class which stores component data in number of arrays, one for positions, one for velocities and two for the other data, your cache will be utilized fully in both situations. So if you only need velocities, when it loads one, it will load 64 bytes around it into cache. That's more than five velocity vectors. When you need all data, it will do the same for the data in the other arrays.

So to summarize, I'll quote a bit from another answer I gave here

> So the goal of DOD isn't using linear arrays, it's maximizing cache utilization by placing data that is accessed at (about) the same time adjacent in memory. If you nearly always access 3 variables at the same time, you don't need to create 3 arrays for each variable, you could just as easily create a struct which contains only those 3 values and create an array of these structs. The best solution always depends on the way you use the data. If your access patterns are linear, but you don't always use all variables, go for separate linear arrays. If your access patterns are more irregular but you always use all variables at the same time, put them in a struct together and create an array of those structs.

Hope this helps! Let me know if anything is unclear or if I missed something!

# Answer
> 1 votes
`entity.addComponent<Position>(32, 4, 5);`

Is definitely possible using C++11 variadic templates, with no performance difference from the original versions.

```
struct Entity
{
    std::vector<std::unique_ptr<Component>> components;

    template<typename T, typename... TArgs> T& createComponent(TArgs&&... mArgs)
    {
        auto result(new T(std::forward<TArgs>(mArgs)...));
        components.push_back(std::unique_ptr<Component>(result));
        return *result;
    }
}

Entity entity;
entity.createComponent<Position>(32, 4, 5); // valid

```

Cache misses will be present when allocating with new, but it's not so bad. In my entity system I can create/destroy \>10000 components without noticeable frame loss. It will probably never be a bottleneck, unless you require an amazingly high amount of entities/components.

If you want to check my implementation, it's on GitHub.

If you want to check a data-oriented component entity system, check out Artemis.

# Answer
> 1 votes
It's my ComponentContainer code:

```
  #pragma once
#include <cassert>
#include <vector>
#include <unordered_map>
#include "tool/config.h"
#include "component.h"

struct ComponentContainerData {
    ComponentType type;
    size_t sizeOfComponent;
    size_t capacity;
    size_t freeIndex;
};

template<typename ComponentClass>
struct Components {
    size_t size;
    ComponentClass* components;

    ComponentClass& operator[](size_t index) {
        return components[index];
    }
};

class ComponentContainer {
public:
    bool componentExist(ComponentHandle component) {
        assert(component != 0 && "Null component request (null component is always invalid)");
        return componentHandles.find(component) != componentHandles.end();
    }

    template<typename ComponentClass>
    ComponentClass* getComponent(ComponentHandle component) {
        assert(componentExist(component));
        return (ComponentClass*) componentHandles[component];
    }

    template<typename ComponentClass>
    ComponentClass* getComponent(Entity owner) {
        assert(entityExist(owner));

        for (unsigned int i = 0; i < containers.size(); i++) {
            if (containers[i].second.type == ComponentClass::type) {
                for (unsigned int j = 0; j < containers[i].second.freeIndex; j++) { //TODO: possible optimalization - owner is sorted
                    ComponentClass* component = (ComponentClass*) containers[i].first + j;
                    if (component->owner == owner)
                        return component;
                }
                return nullptr;
            }
        }
        return nullptr;
    }

    template<typename ComponentClass>
    Components<ComponentClass> getComponents() { //when optimalization mentioned in comment below(containers field) will be done, it will be simple return {containers[ComponentClass::type.....
        for (unsigned int i = 0; i < containers.size(); i++) {
            if (containers[i].second.type == ComponentClass::type) {
                return {containers[i].second.freeIndex, (ComponentClass*) containers[i].first};
            }
        }
        return {0, nullptr};
    }

    template<typename ComponentClass, typename ...CmpArgs>
    ComponentClass* createComponent(Entity owner, CmpArgs&& ...cmpArgs) {
        assert(entityExist(owner));

        auto container = locateAndPrepareComponentContainer<ComponentClass>();
        if (!container)
            return nullptr;

        ComponentClass* createdComponent = new (container->first + sizeof(ComponentClass) * container->second.freeIndex)
                ComponentClass(owner, nextComponentHandle, std::forward<CmpArgs>(cmpArgs)...);

        componentHandles[nextComponentHandle] = (Component*) &container->first[sizeof(ComponentClass) * container->second.freeIndex];
        ComponentHandle currentHandle = nextComponentHandle++;
        container->second.freeIndex++;

        logger.info("Created new component. Owner: %u, Handle: %llu, (int)Type: %d", (unsigned int) owner, currentHandle, (int) ComponentClass::type);
        return createdComponent;
    }

    template<typename ComponentClass>
    void deleteComponent(Entity owner) {
        assert(entityExist(owner));

        for (auto& container : containers) {
            if (container.second.type == ComponentClass::type) {
                ComponentClass* currentComponent = (ComponentClass*) container.first;
                for (unsigned int i = 0; i < container.second.freeIndex; i++, currentComponent++) {
                    if (currentComponent->owner == owner) {
                        logger.info("Deleted component %llu. Type: %d, Owner: %u", currentComponent->handle, (int) ComponentClass::type, (unsigned int) owner);

                        componentHandles.erase(currentComponent->handle);
                        currentComponent->~ComponentClass();

                        ComponentClass* lastComponent = (ComponentClass*) container.first + --container.second.freeIndex;
                        if (currentComponent != lastComponent) {
                            memcpy(currentComponent, lastComponent, sizeof(ComponentClass));
                        }
                        return;
                    }
                }
                logger.warn("Cannot delete component type %d with owner %u: component not in container", (int) ComponentClass::type, (unsigned int) owner);
                return;
            }
        }
        logger.warn("Cannot delete component type %d with owner %u: component not found, even container don't exist", (int) ComponentClass::type, (unsigned int) owner);
    }

    bool entityExist(Entity entityID) {
        assert(entityID < entityExistingTable.size() && "Entity with this id cannot exist (and we're reading garbage)");
        return entityID < entityExistingTable.size() && entityExistingTable[entityID];
    }

    Entity createEntity() {
        entityExistingTable.push_back(1);
        return Entity(entityExistingTable.size() - 1);
    }

    void deleteEntity(Entity owner) {
        assert(entityExist(owner));

        for (auto& container : containers) {
            Component* currentComponent = (Component*) container.first;
            for (unsigned int i = 0; i < container.second.freeIndex; i++) {
                if (currentComponent->owner == owner) {
                    logger.info("deleteEntity: Deleted component %llu. Type: %d, Owner: %u", currentComponent->handle, container.second.type, (unsigned int) owner);

                    componentHandles.erase(currentComponent->handle);
                    currentComponent->~Component();

                    Component* lastComponent = (Component*) container.first + --container.second.freeIndex;
                    if (currentComponent != lastComponent) {
                        memcpy(currentComponent, lastComponent, container.second.sizeOfComponent);
                    }
                    continue;
                }
                char* rawCurrent = (char*) currentComponent;
                currentComponent = (Component*) (rawCurrent + container.second.sizeOfComponent);
            }
        }
    }

    ~ComponentContainer() {
        for (auto& container : containers) {
            free(container.first); //FIXME: this only deallocates memory, won't call destructors. (components shouldn't have destructors but...)
        }
    }

private:
    std::vector<std::pair<char*, ComponentContainerData> > containers; //TODO: possible optimalization: it should be containers[i].second.type == i. So a)change it to map, b)when creating container fill fields with 0 while
    std::unordered_map<ComponentHandle, Component*> componentHandles; //untill desired type is if containers.size < type, else just change this 0 to appropiate type. 0 can be indicated by pair {nullptr, {}} or sthk
    ComponentHandle nextComponentHandle = 1; //maybe even component handle stuff will be unnecessary, since it will be fast.

    std::vector<char> entityExistingTable;

    template<typename ComponentClass>
    std::pair<char*, ComponentContainerData>* locateAndPrepareComponentContainer() {
        for (auto& container : containers) {
            if (container.second.type == ComponentClass::type) {
                if (container.second.freeIndex >= container.second.capacity) {
                    if (!resizeContainer(container, sizeof(ComponentClass), (int) ComponentClass::type)) {
                        return nullptr;
                    }

                    for (unsigned int i = 0; i < container.second.freeIndex; i++) {
                        ComponentClass* elem = (ComponentClass*) container.first;
                        componentHandles[elem[i].handle] = &elem[i];
                    }
                }
                return &container;
            }
        }

        if (!createNewContainer<ComponentClass>()) {
            return nullptr;
        }
        return &containers.back();
    }

    bool resizeContainer(std::pair<char*, ComponentContainerData>& container, size_t sizeOfElement, int typeID) {
        logger.info("Resizing component container for type %d. Current Capacity: %u", typeID, container.second.capacity);

        size_t capacity = container.second.capacity * config.get("ECS.growFactor", 2);
        char* result = (char*) realloc(container.first, capacity * sizeOfElement);
        if (!result) {
            //try to get at least necessary amount of memory
            capacity = container.second.capacity + 1;
            result = (char*) realloc(container.first, capacity * sizeOfElement);
            if (!result) {
                logger.fatal("Cannot resize component container, even by 1 element. Desired capacity: %d, Sizeof(Type): %d, type: %d", capacity, sizeOfElement, typeID);
                assert(!"resizeContainer: cannot allocate memory for new element");
                return false;
            }
        }

        container.second.capacity = capacity;
        container.first = result;
        return true;
    }

    template<typename ComponentClass>
    bool createNewContainer() {
        ComponentContainerData metadata;
        metadata.type = ComponentClass::type;
        metadata.capacity = config.get("ECS.initialCapacity", 128);
        metadata.sizeOfComponent = sizeof(ComponentClass);
        metadata.freeIndex = 0;

        char* rawComps = (char*) malloc(sizeof(ComponentClass) * metadata.capacity);
        if (!rawComps) {
            //try to get at least necessary amount of memory
            metadata.capacity = 1;
            rawComps = (char*) malloc(sizeof(ComponentClass));
            if (!rawComps) {
                logger.fatal("Cannot create new container, even for 1 element. Sizeof(Type): %d, Type: %d", sizeof(ComponentClass), (int) ComponentClass::type);
                assert(!"Create component: cannot allocate memory for new container; even for 1 element");
                return false;
            }
        }

        containers.push_back({rawComps, metadata});
        return true;
    }
};

```

It has all components of the same type in array, and all arrays are in one array, so there is no need to update ComponentClass if new components are added. It also forwards arguments to components.

component.h:

```
    #pragma once
#include <boost/serialization/strong_typedef.hpp>

enum class ComponentType {
    SampleComponent, //for unit test
    PositionComponent,
    SpriteComponent,
    RectComponent,
    MovementComponent,
    CollisionComponent,
    SizeComponent
};

using ComponentHandle = unsigned long long;

BOOST_STRONG_TYPEDEF(unsigned
        int, Entity);

struct Component {
    Component(Entity owner, ComponentHandle handle) : owner(owner), handle(handle) {
    }

    virtual ~Component() {
    }

    Entity owner;
    ComponentHandle handle;
};

```

tool/config.h is unneded, it's only config.get calls, their second value is default.

All derived Components must have static variable of type ComponentType and name type

# Answer
> 0 votes
If you absolutely want to do this, you can use a custom memory allocator that reserves a chunk for each Entity and places its components continously inside that chunk. However this may waste memory again, which can (in theory) cause more cache misses too...

However... unless you have solid proof that this causes slowdowns for you, don't worry about it. Premature optimization can eat up a lot of your time, not only when creating the system, but also when maintaining it later. Most likely your game engine's speed isn't going to be determined by trivial things like this, not to mention that complex components (the ones that may actually slow things down for you) are most likely larger and would cause cache misses anyway.

Having said that, your particular example may be somewhat valid. I think the position of an entity should be bundled together with the entity itself (part of the class, not a component) for two reasons. First of all, if you do a *lot* of data processing on the entities, it may improve performance. But more importantly, each entity can only have one position, and the possibility of adding several position components breaks this rule, causing problems.

# Answer
> 0 votes
A possible solution is a ComponentManager class. This one is similar to a tuple of vectors in that it should keep a mapping of types to the index of each Component type vector. After that it all comes down to representing the components of an entity using indices to the appropriate vectors.

---
Tags: c++, architecture, entity-system, design-patterns, data-oriented
---


# Question
Title: How to create sprites, programatically without using prefabs?
I have different types of images for different sprites. and i am not certain that how much different sprites(images) i will have to show. So, i gotta create the sprites and apply textures programatically at runtime.

Now, I defiantly can't use prefabs because it will restrict me with the number of different sprites i can use. and also, changing texture on one sprite prefab instance in game, will change all the sprites prefab, that's not acceptable in my case.

Is there a way i can create sprites without having to create static prefab ?

where ever i looked for the solution every time i got the same answer "create a prefab", which is what can not be done in my case.

# Answer
> 2 votes
Your question is very unclear.

You can use prefabs if you *copy* from them into your sprites instead of referencing. This way sprites you get will be independent from prefabs after creation, so you can change prefabs and sprites will remain as they were made.

# Answer
> 0 votes
You can change to texture that the sprite is showing in code by doing something like

public Texture2D texture;

Sprite.texture = texture;

If you want to know everything about sprites please check out this link:http://docs.unity3d.com/ScriptReference/Sprite.html

# Answer
> 0 votes
What I did in a game (there's slot that displays a sprite that depends on the "element" chosen) is:

1. Set a sprite renderer component on the prefab.
2. Create sprites (not textures) in Resources/Sprites/Elements
3. Set a script component on the prefab
4. Define an private attribute "Sprite\[\] sprites"
5. In the Awake method use "sprites = Resources.LoadAll ("Sprites/Elements");"
6. When I change the element of the player I use gameObject.GetComponent().sprite = sprites\[elementIndex\] to update the image

You may need some aditional logic to be sure that you're setting the correct sprite from the array. You can use the name property of the sprites for this.

EDIT: I know that you said you don't want to create sprites, but maybe you're just avoiding them because you couldn't find a way to use them, so I think this solution would help.

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


# Question
Title: RPG like hit points growth algorithms help
I am currently making an XNA game in C#. I want to increase health as the player level up. I am currently using this equation.

> MaxHealth = Convert.ToInt32(100 * Math.Pow(1.17, level - 1));

Its fine before the first 20 levels, but afterwards the health starts to increase extremely fast:

> Level 1: 100 Hp.
>
> Level 20: 1.975 Hp.
>
> Level 30: 9.493 Hp.
>
> Level 40: 45.630 Hp.
>
> Level 100: 658.546.089 Hp.
>
> Level 109: Crash: value too big for an integer.

How should i create these growth algorithms, so that the growth of hit points pr. level, will increase slowly. This is just an example, if you know a better growth rate, I will be happy to know that too.

> level 2: Hp = base health + 60 (Base health = 100)
>
> level 3: Hp = base helath + 60 + 120
>
> level 4: Hp = base helath + 60 + 120 + 180.

But the max health formular will run on every update/tick, so all this should happen in the same calculation.

**Edit:**

Thank you all for your input, I really appreciate it. But while away from the question, I found a solution myself. Thank you very much. The solution:

```
if (level < 35)
    this.baseMaxHealth = Convert.ToInt32((vitality * 10) + Math.Pow(level, 2) * 4);
else
    this.baseMaxHealth = Convert.ToInt32((vitality * (level - 25)) + Math.Pow(level, 2) * 4);

```

I added vitality as an upgrade you can spend skill points or something on

**EDIT 2:**

I improved the code a bit

```
        if (level < 35)
            this.baseMaxHealth = Convert.ToInt32((vitality * 10) + Math.Pow(level, 2) * 4);
        else if (level > 125)
            this.baseMaxHealth = Convert.ToInt32((vitality * 100) + Math.Pow(level, 2) * 4);
        else
            this.baseMaxHealth = Convert.ToInt32((vitality * (level - 25)) + Math.Pow(level, 2) * 4);

```

# Answer
Long ago I did the math for different growth functions for an RPG (that I didn´t use in the end). I was playing around with five basic growth curves, as show below.

The curves are:

* **Red**: Exponential. Grows slowly at the beginning, very fast at the end.
* **Blue**: Quadratic. Average growth curve.
* **Black**: Linear.
* **Green**: Flipped quadratic. Grows more slowly with time.
* **Yellow**: Flipped exponential. Grows quite fast at the beginning, quite slow at the end.

The formulas that govern each one of these curves are the following (I'm omitting linear in the rest of the discussion for simplicity).

* **Red**: `y=z^x`
* **Blue**: `y=(x/z)^2`
* **Green**: `y=-((x-MAXIMUM LEVEL)/z)^2+MAXIMUM VALUE`
* **Yellow**: `y=-z^(-(x-MAXIMUM LEVEL))+MAXIMUM VALUE`

Where MAXIMUM LEVEL is the maximum level you expect to stop at, MAXIMUM VALUE is the maximum value you expect for that level, and z is a coefficient you need to calculate. Also note that all curves start at 0 for x = 0 (not exactly, more on this later).

So, how do you calculate this z? For that, you need to use the Blue and Red functions.

For the Blue (quadratic), you know that at `x=MAXIMUM LEVEL`, `y=MAXIMUM VALUE`. Therefore you can take `(MAXIMUM LEVEL/z)^2=MAXIMUM VALUE` and solve for z.

For instance, you want the max level to be 200 and the maximum HP to be 7000. Therefore you would calculate

```
(200/z)^2 = 7000
sqrt 7000 = 83.6660026534
200/x = 83.6660026534
200/83.6660026534 = z
2.39045721867 = z

```

And therefore the function is `y=(x/2.390)^2`. Notice that the same value can be used for the Green curve, and therefore that function would be `-((x-200)/2.390)^2+7000`.

For the Red curve (exponential) you know that `z^MAXIMUM LEVEL=MAXIMUM VALUE`. Therefore you only need to calculate z as the MAXIMUM LEVEL'th root of MAXIMUM VALUE.

For instance, following the previous example, z would be the 200'th root of 7000, or 1.0452627896377216... This value can be applied to the Red and Yellow curve to obtain `y=1.0452627896377216^x` and `-1.0452627896377216^(-(x-200))+7000`.

I hope that helps you.

## Some observations

There are a couple of details I would like to point out but are not essential to the discussion.

### Curve shape

It is possible to change the value of the exponent of the Blue curve to make it more or less pronunciate. As the example below shows, the lower the exponent, the closer to a line, and the higher, the close to a step.

Similar results can be obtained by playing around with exponential exponents, although the result is much less satisfactory.

### Exponential gap

Although it is hard to appreciate in the image, the exponential curves have a small gap at the first (Red) or last (Yellow) points. This occurs because `z^x` is 1 for x=0, not 0 as we would expect. In order to create a really proper curve that passes through the first and last point, you need to define two curves, and then blend them together in a smooth transition. For our example of value 100 at point 100, the curves would have this aspect.

* **Red**: `y=((100-x)/100)*(1.04712^x-1)+((x)/100)*1.04712^x`
* **Yellow**: `y=((100-x)/100)(-1.04712^(-(x-100))+100)+(x/100)(-1.04712^(-(x-100))+101)`

**Caveat**: I am no mathematician, is late at night and I am sleepy. This analysis may contain errors. Use at your own discretion.
> 7 votes

# Answer
You could use a logarithmic function:

Example function:

```
double increment = Math.Log(level + 1);

```

Example output:

> Level 1 increment: 0.693147180559945
>
> Level 2 increment: 1.09861228866811
>
> Level 3 increment: 1.38629436111989
>
> Level 4 increment: 1.6094379124341
>
> Level 5 increment: 1.79175946922805
>
> Level 6 increment: 1.94591014905531
>
> Level 7 increment: 2.07944154167984
>
> Level 8 increment: 2.19722457733622
>
> Level 9 increment: 2.30258509299405
>
> Level 10 increment: 2.39789527279837

...

> Level 99 increment: 4.60517018598809
> 3 votes

# Answer
There are lots of simple functions to realize those curves.

\\$40x^2 - \frac{1}{8}x + 200\\$

(link to the above formula on Wolfram)
This one grows in a smooth curve since I used \\$x^{1.5}\\$:

\\$5x^{1.5} - \frac{1}{9}x + 200\\$
(link to the above formula on Wolfram)

Play around with the values.
> 3 votes

# Answer
Since these are possible solutions I figured why not ...

HP in my experience has always been something that increases very slowly, XP required for next level tends to be the big exponential. I would go with your second example or you could try reducing the 1.17 in your pow call to something like 1.02 for a more gradual increase.

You could also consider using a float instead of an int or using a level cap :)
> 0 votes

---
Tags: xna, c#, mathematics
---


# Question
Title: Monobehaviour can not find a member OfType in Unity
This is the line where I am getting above mentioned error:

```
var listeners = FindObjectOfType<MonoBehaviour> ().OfType<iPlayerRespawnListener> ();

```

I have already imported these libraries including `System.Linq` which has the above mentioned method `OfType`:

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

```

Where is it going wrong and how to fix this?

# Answer
To expand on OP's answer: the crucial difference is the use of `FindObjectOfType` versus `FindObjectsOfType`.

* `FindObjectOfType` returns a single object.
* `FindObjectsOfType` returns an array of objects.

Linq's `OfType` extension method requires an enumerable collection (such as an array), which is why you were seeing that error and why switching calls fixed it.
> 2 votes

# Answer
Resolved by changing `FindObjectOfType` to `FindObjectsOfType`:

```
var listeners = FindObjectsOfType<MonoBehaviour> ().OfType<iPlayerRespawnListener> ();

```
> 0 votes

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


title: isometric tile tiled format javascript

text:
# Question
Title: isometric tile tiled format javascript
Okay im having a problem with drawing an isometric map exported from tiled.
Here is my problem.
where it should be like this

Here is the code that i used to reproduce the 1st image, what's wrong with it?

```
for (var y = 0; y < this.height; y++){
            for (var x = 0; x < this.width; x++){
                counter++;
                var sprite = this.tilemap.getSprite(this.data[ counter ], this);
                var drawX = 0, drawY = 0;

                if ( sprite ) {
                    var cell = sprite.cell[ this.data[counter] ];
                    if (!cell) continue;

                    if (this.orientation == 'isometric') {
                        // Isometric maps
                        drawX = x * cell.w;
                        drawY = y * cell.h;
                    }

                    if (sprite && cell){
                        Engine.currentGame.ctx.drawImage(
                         sprite.sprite.img,
                         cell.x,
                         cell.y,
                         cell.w,
                         cell.h,
                         drawX,
                         drawY,
                         cell.w,
                         cell.h
                        );
                    }
                }
            }
        }
        game.currentGame.ctx.restore();
        return this;
    };

```

UPDATE:

```
var counter = 0;
        game.currentGame.ctx.save();
        for (var x = 0; x < this.width; x++){
            for (var y = 0; y < this.height; y++){
                counter++;
                var sprite = this.tilemap.getSprite(this.data[ counter ], this);
                var drawX = 0, drawY = 0;

                if ( sprite ) {

                    //console.log( counter );
                    var cell = sprite.cell[ this.data[counter] ];
                    if (!cell) continue;

                    if (this.orientation == 'isometric') {
                        // Isometric maps
                        drawX = x * cell.w;
                        drawY = y * cell.h;
                    }

                    if (sprite && cell){
                        Engine.currentGame.ctx.drawImage(
                         sprite.sprite.img,
                         cell.x,
                         cell.y,
                         cell.w,
                         cell.h,
                         drawX,
                         drawY,
                         cell.w,
                         cell.h
                        );
                    }
                }
            }
        }
        game.currentGame.ctx.restore();
        return this;

```

# Answer
> 2 votes
From the screens it's kinda obvious, that your tiles are positioned wrong.

So it seems your X axis needs to go from top-left to bottom-right and Y axis from top-right to bottom-left. Right now X goes from left to right and Y from top to bottom. Can you update your code to accommodate for that?

Also your spacing between the tiles is too big, but first - solve the first issue ;)

# Answer
> 1 votes
Iso-tiled maps needs "Z-axis" work, where you must draw from the upper left, moving to the bottom right, as you already know, you must overwrite already existing tiles.

Your code right now is a basic work for common 2D tilesets.

`if (this.orientation == 'isometric') {
 // Isometric maps
 drawX = x * (cell.w / 2);
 drawY = y * (cell.h / 2);
}`

This should do the trick.

---
Tags: javascript, tilemap, isometric, tiled
---


title: Run Love2D on iphone and android

text:
# Question
Title: Run Love2D on iphone and android
I have a game developed in lua using love 2d, and now i want to run it in ios/android.

Is there any porting or way available to do that.

Thanks.

# Answer
There are experimental/inprogress ports to both platforms.

Andriod This one is not associated with the Love2D team.

iOS This one is being created by the Love2D team.
> 1 votes

---
Tags: android, ios, lua, love2d
---


# Question
Title: How do I resolve a collision involving more than two objects?
I have working functions that compute the overlapping polyhedron, contact points, depth of penetration (DOP), etc. of the overlap between two objects with convex polyhedra shapes.

I know how to resolve the collision between two colliding movable objects, for example by moving one of them DOP units along the penetration normal.

**Problem:** What is a simple method to resolve collisions between more than two objects? For example, let's say objects A, B and C are in collision such that A overlaps with B, and B overlaps with C. If I move A to resolve its collision with B, then A might overlap with C (or any other object in the scene), and now if I resolve the collision between A and C, one of them might overlap with another object. To me, it seems an endless chaining effect. Is there any standard algorithm to resolve collisions between more than two objects simultaneously (batch collision resolving) such that at the end of the day, there are no pairs of objects overlapping?

**Note:** In my problem statement it is assumed that a scene initially filled with possibly overlapping objects with convex polyhedron shapes is given to my collision resolver engine.

# Answer
Separate your collision detection in to two phases: Collision Detection and Collision Resolution.

In the first step find all obstacles that collide with object A. Then compute for each obstacle the vector and force required to resolve the collision.

In the second step add all vectors/forces together and apply them to object A.

This is a simple and effective way to solve most collisions when there are not too many things to collide with. More advanced solutions exist. For that take a look at this answer How to separate colliding objects without creating more collisions (also linked by Icy Defiance in the comments).
> 2 votes

---
Tags: collision-resolution
---


# Question
Title: Export session variables easily and permanently in php
I feel like I must be missing something simple, or misunderstanding sessions or cookies. I want to save all session variables and allow players to copy/paste a long string to load the game up from a different computer or give to someone else, much like in Cookie Clicker or Adventure Capitalist etc. There is no need for sql, or for any kind of security; people can "cheat" if they want to.

# Answer
These things still usually work with SQL. Each saved game state gets a unique ID - usually a long string of hex characters - that identifies the entry in the DB. You then share this string.

You could do it without SQL using Mongo or the file system or something, of course.

Simpler games can get away with just encoding all of the game state into a string, but this will quickly become a *very huge string* (longer than is allowed in a cookie) for anything non-trivial. Old NES games would use this trick (using icons instead of letters for "passwords") but they had extremely little state to store (usually just which level you got to start at, and maybe a small set of upgrade items).
> 1 votes

---
Tags: php, savegame
---


# Question
Title: Implications of using a single ID3DXSprite object to render multiple images
I wanted to know if using a single Sprite object to render all 2D textures on screen is better than using one sprite for each 2D texture in performance.

**EDIT:** Using single sprite refers to using a single ID3DXSprite Object to render all textures.

# Answer
> 1 votes
ID3DXSprite is an object designed to help manage drawing sprites efficiently. There is no reason to have more than one ID3DXSprite object. If you need different options for different sprites then use multiple Begin/End groups.

The reason you shouldn't have more than one is because of how ID3DXSprite interacts with the device.

* Begin: Prepares a device for drawing sprites.
* Draw: Adds a sprite to the list of batched sprites.
* End: Calls ID3DXSprite::Flush and restores the device state to how it was before ID3DXSprite::Begin was called.

As you can see Begin and End alter the device state. Having more than one Begin/End active would break the built in device state management, so if you're going to have only one begin/end combo then there is no point in multiple ID3DXSprites.

# Answer
> 0 votes
If you mean, you want to lay out multiple subtextures onto one big texture, then yes there are advantages to that. This technique is called a "Texture Atlas".

The first advantage is that you will end up with less resource files in your project. For example, if you want to texture the six faces of a cube with different textures, you'd end up with 6 texture images. By packing all into a single texture atlas and using corrected UVs, you can pack them in a single file. The performance benefit is that you need less file access operations when loading resources in your game.

A second advantage is that you need less swapping of textures when rendering your game. In the worst case scenario, every subtexture is bound to a different texture in memory. You'd need to swap textures for every object being rendered, causing overhead.

In case of sprites (such as in old video games), the individual sprites are often layed out on a grid. Every sprite often corresponds to a different pose of the animation. In this case, the term "Sprite Sheet" is often used instead of "Texture Atlas". The concept is the same however.

Two particularities need to be taken into account though. First, you want to make sure that the subtextures you pack into a single texture are relevant. This means, that if one of the subtextures is used, it should be likely for other subtextures on the same sheet to be used. Otherwise you lose the advantage of less texture swapping.

Second, when using linear filtering, mipmapping or anisotropic mipmapping, bleeding effects can occur. This means that sprites will blend with the edges of neighbouring sprites. To solve this problem, add a small margin around your subtextures when packing them into an atlas or sheet. It can also be beneficial to reduce the level of mipmaps generated.

So in brief, packing multiple subtextures into a single texture is an excellent idea! If artifacts such as edge bleeding were to occur, add a small margin around the subtextures.

---
Tags: sprites, directx9
---


# Question
Title: Using A*Pathfinding on terrain created by scripts?
I'm looking to use A\* Path-finding as a method of navigating my game terrain. Trouble is, my terrain is built upon play using a script and A\* grid does not detect this, therefore marking all nodes as "un-walkable".

I'm wondering if anyone knows a solution for this or an alternative path finding method. I have tried enabling the terrain to spawn on edit more using ExexcuteInEditMode, but this does not seem to work either.

The terrain was generated through a fantastic guide called Procedural Terrain Tutorial.

Would greatly appreciate any help I'll be able to get.

I've attached some screenshots for clarity :

# Answer
Based on your picture and your other questions you are using the Arongranberg A\* Pathfinding Project.

First, be sure that in your Grid, the layer of the Playground is selected in your Mask. In your example this means that the Playground is in the layer `Ground`.

Second, use Update-Graph over every generated area (that means you create area, then you update the graph). If you add any obstacles after that, you have to update the graph again (or add obstacles before Graph-Update).

Additional note: You use a grid-graph, but your field seems to be made up of hexagons. You may use a point-graph with the points beeing located in the center of the hexagons. But I'm making assumptions about your game here.
> 1 votes

# Answer
Once your terrain is built **start by manually turning down booleans for unwalkable nodes to walkable,** You may think this as a forced method, but you need to assign

```
bool isWalkable(node){if isRight || isLeft ==NULL{
//# manual declaration of boundary nodes to unwalkable nodes, and when script starts,
//have start and end on boundary reinitialized to walkable, hence charachter can stand.
/*code here*/
}}

```

So that all values lying at the edge of the terrain grid are neutralised, and all values inside will be determined by A\* script which is followed after this step, if your start and end are nonwalkable at start, after A\* pathfinding , they have to be walkable for algo to start, which is then followed by UV Mapping which can invoke and take care of these calls

* containsPoint (Vector a, Vector b, Vector c, Vector p);
* DistanceSegmentSegment3D (Vector s1, Vector e1, Vector s2, Vector e2)
* static Vector3\[\] ConvexHull (Vector3\[\] points) And if you think that the above code will work just once, add it in update method and try catch it by throwing new exception on selfupdate, whenever it is called again.

Hope this helps...
> 0 votes

---
Tags: unity, path-finding, terrain, procedural
---


# Question
Title: How can I debug live multiplayer servers effectively?
I have a multiplayer server made by a small team of developers and we have bugs that crop up on our live server occasionally that we simply can't reproduce while playing with our small team on a live server.

It clearly isn't feasible to attach a debugger and halt the world on a live shard... so what are some effective strategies in debugging multiplayer games while they are still running?

Attaching a debugger is fine on a developer server, but perhaps not always feasible to reproduce the bug or always effective.

# Answer
> 10 votes
Configure your servers to capture and save crash dumps (if you run on Windows, MiniDumpWriteDump and SEH is a good place to start) so that you can diagnose hard crashes offline. You'll probably want to make sure your release builds generate and archive a PDB or other symbol- and debug-help related data internally as well as provide a mechanism to allow you to correlate the crashed build ID and the proper PDB (et cetera) for in-house examination.

You may want to familiarize yourself with debuggers other than Visual Studio -- later versions of VS are much better at just "doing the right thing" with a minidump but it's also worth looking at WinDbg, which is a standalone debugger that's more expressive (but much harder to learn to use). It's saved me a lot of trouble on occasion.

For code in C#, for example, minidumps plus the SOS extension for WinDbg make for a very useful postmortem debugging environment for managed code.

Additionally, the process that collects the crash dumps should probably report metrics back to you somehow so you can monitor how frequently you are getting live crashes.

As for handling non-crash bugs, build logging and metrics gathering tools. This is harder to do after the fact, but possible (it's much easier if you integrate the construction of these metrics into the construction of the software itself, but the ship has probably sailed on that option by now).

You want to allow for the logging of just about anything. In an ideal world, you want to support the ability to *add logging after the fact* without having to reboot the entire (player-facing) server. Whether or not this is possible depends largely on how your server infrastructure handles failover -- if you can bring a new build of the server executable (with new logging) up and transparently migrate users over there before beginning your analysis, that'd be best. Of course, that's not a small task to accomplish either.

But at the very least you'll want your logging to be toggle-able -- you don't want to log everything, everywhere, for every user, all the time. You should gate the ability to enable the log to a server-side check of a user's rights (so only developer or GM users can toggle it) and only communicate that log data through a private, back-end channel that your developers can access from the privileged side of the network.

On top of the logging you can build your own custom live debugging UI, if you log in a structured enough form. This is essentially a debugger you can connect (again, only through the internal side of the network) that parses the log data (when enabled) and displays it in a more human-readable form, but does not halt execution of the server process itself. That way you disrupt other players minimally.

Obviously you can tailor the specificity of this to your needs and your actual problem. I'd recommend that approach actually -- build a log/debug view that's very specific to the actual problem you are having and generalize it after the fact. That way you focus on the real issue first and don't get lost trying to build an overly complex generalized system with features you may not yet need.

# Answer
> 0 votes
Starting to log crash dumps are a good start, but it might not tell you the whole story. Your users have a diversity of hardware/network connections and may use the game in ways you may not have imagined. The crash dumps may tell you WHAT the error was, but not what the conditions on the clients or even your server were at the time the crash dump occur.

To help you establish a full picture, you'll want to make use of logging and log not only crash dumps from your game server software but also server environment variables and things on your client related to how it interacts with your server.

From my experience running games, you don't want to get involved in creating your own logging tools. Log data can swell up into the giga or terabyte level, and between managing that volume of data AND building a tools, you'll end up using a lot of your server guys simply to maintain logging. It's a lot quicker to just use a 3rd party logging service like Loggly to get up and running.

Regardless of the path you pick to collect, here are the logs you’ll want to consider collecting:

**Game server application logs:** You can log most any information from your application to file or SYSLOG socket. So within your application code, log any crash or exception information. Also think about logging your gameplay mechanics for things that would indicate when they're failing so that you get a list of events that led to the error.

**General server logs:** Most everything from the server, system logs, web server logs, database logs, etc. This data can help you spot any abnormalities in server performance which might indicate why a bug is happening.

**Client logs:** A lot of online game bugs stem from high latency caused by a slow client-side network or from bugs in the client sending incorrect data or commands to the server. You want to log anything within the client that has to do with communication with the server or manipulation of user's data to catch these client-driven bugs.

**As far as how you'd collect the log data itself** Try to avoid storing logs directly on live servers, logs blow up to huge volumes, and you really don't want to be managing log retention & purge issues on live servers. For anything you want to log you can choose to write it to file and then have a SYSLOG agent or send it directly to a SYSLOG socket and have it sent out to a provider like Loggly directly. For logging anything on the client, you'd simply store any data you'd want to log in JSON format and send it direct from the client using HTTP methods.

It sounds like you don't already have logging implemented, so you'll need to implement it into your server software and take it live. It would be elegant to somehow push this update while your game is live such it doesn't interrupt player experience, but if you don't have a way of doing this, I wouldn't spend a lot of effort on creating it just yet; one problem at a time. Just take down the servers at a time you know there are a low volume of players and patch logging-enabled updates then.

---
Tags: c#, multiplayer, server
---


# Question
Title: Correct way of modelling for a multiplayer FPS game
I was wondering what was the best way to model characters for an first person shooter game?

Assuming I have 2 modes to show, first person view (the player's view) and 3rd person view (viewing other players) - Here is a sample of what I mean

I guess the simplest way to do it would be managing only the 3rd person view, and try and make the camera on the player "look through the eyes" of the 3rd person model, but I failed to achieve any decent results using this method, due to the model's animation not working well in first person view.

Thanks

# Answer
How many first-person shooters do you know where the player can see their legs when looking down?

Most games use completely different models for other characters and for the player-character when in first-person view. In first person view, the player-character usually doesn't have a body, except for the arms and the currently held item, which are always positioned relative to the current viewport.

The first person models for the arms and items are permanently in the view of the player and always seen from close-up. This means they are often the most prominent 3d models in the game, which means that they deserve extra attention. The first-person versions of arms and weapons are usually much more detailed than the third-person versions.
> 2 votes

# Answer
Short answer: use a model for first-person view and another model for third-person.

Reasons:

1. In first-person view, you need to show a very detailed hand and weapon, since the first-player will always have a close-up view. Also, the animation should be very realistic. In third-view models, details may be not so critical.
2. A good animation for one point of view may not be so good for another point of view. You've found already that is usually harder to get a nice animation when "looking through the eyes" of the 3rd-person model. If you have to animate a simplified 1st-person model, you'll find it easier.

Look an example of using this approach: link.

If you follow this suggestion, don't forget that other players must see only your 3rd-person model (that's obvious), but you also need to consider other side-effects, like: shadows, mirrors and body collision.
> 1 votes

---
Tags: multiplayer, models, first-person-shooter
---


title: Why are huge polygon amounts bad?

text:
# Question
Title: Why are huge polygon amounts bad?
It is always said that the polygon amount of a single modell must be as little as possible when it comes to realtime simulations such as computer games. (Or at least lower than when rendering a movie) I am fully aware that this must be done in order to save performance. But aside from that information i cannot find *why* huge polygon amounts must be avoided.

(In Short: I know that polygons eat performance. I want to know why they eat performance)

So my question would be: What happens when a frame is rendered? The polygons are surely somehow processed in the graphicard. What happens there?. If possible i would like to have some links to sites containig this information.

# Answer
Whenever a frame is rendered, your graphic card must translate the coordinate in 3-dimensional space of every polygon corner (aka vertex) to the two-dimensional space on the monitor. This is done by multiplying each vertex with a projection matrix which represents the current position, angle and field-of-view of the camera.

Only after this is done, the graphic card knows which polygons are actually on the screen and not behind the camera or hidden behind other polygons. It then processes with various other calculations for each on-screen polygon, like which texture it is showing and how it is lit.

That means your graphic card must perform a number of calculations for each polygon. The more polygons you have, the more does it have to calculate. Your graphic card can only perform a limited amount of calculations per second, so more polygons means a lower framerate.
> 5 votes

# Answer
Like Phillip said one should always optimize your models for a specific goal. That said, i want to add some extra info on the creation of 3D models. Nowadays the polygons are not the bottleneck but texture space is. Since we bake so much into the texture for details (think: Diffuse, normal, occlusion, light, etc) and a top notch graphics card can only store 1GB of textures.

When an 3D object is close to the view it can takes up most of the screen which can be perhaps `1920x1280` pixels. If that single object has a `1024x1024` texture that texture is only partially seen since you only see a part of the object. So maybe `512x512` of that texture is actually seen, this gets translated to you screen resolution and thus blurred. 4 `1024x1024` textures for a single object (different map types) can easily take up `10MB`. Where someone rather uses a `2048x2048` texture space or larger for this object but that will take up about `40MB` which would already be 4% from the `GDDR` memory of a graphics card with 1GB of memory. And that just for a smallish object in a scene of thousands. Besides this map and CG designers have plenty of tricks up there sleeves for reusing objects and textures.

Still, less polygons means better performance. And since we can do so much with texture space 3D artists focus on contour (the outline of the model). It's not possible to make the outline of a model more detailed without adding more polygons, within a model we can use textures to make just a couple of polygons look as detailed as thousands.
> 1 votes

# Answer
Increasing polygon count has performance impact in few key areas:

1. There is a limit that GPU can issue new triangles (e.g. 4 per clock), normally 1 per Shader Engine (AMD) / Graphics Processing Cluster (NVIDIA). If your GPU runs at 1GHz and has 4 SE's/GPC's that puts absolute peak limit of 4 billion triangles per second on the GPU - normally not a bottleneck.
2. GPU must run vertex shader for each vertex of each triangle, so heavier the shader more costly the geometry processing. There is post-transform LRU cache which remembers some number of previously processed vertices (GPU specific but it's somewhere around 32) that are shared between triangles to reduce processing cost (for indexed primitives) so it's important to optimize index buffer for this cache.
3. The data for vertices that are processed by vertex shader must be fetched from GPU memory, and there is pre-transform cache helping to reduce the bandwidth usage. The data is fetched as cache lines (e.g. 64 byte chunks) thus it's good if the vertex data is aligned to cache lines to reduce bandwidth usage. E.g. vertex size 28 is worse than 32 because some vertices require 2 cachelines being fetched from memory. Also the pre-transform cache is motivation to reorganize vertex data to be accessed more locally, if your vertex size is smaller than cacheline (or unaligned).
4. When you increase polygon count of a model you also reduce the triangle size. This has a negative impact on pixel processing performance because GPU's don't process individual pixels but pixel quads of 2x2 pixels. Now pixels in the quad that are outside the rasterized triangle are rejected which wastes processing power. This is a performance issue for objects with a lot of microtriangles and may result up to 75% waste in pixel processing.
> 1 votes

---
Tags: graphics, performance
---


# Question
Title: How to detect Lagoons and Lakes on a random Island Map
I have an engine which generates random Islands. At the moment it tends to generate quite a lot of lagoons and lakes. I would like to know of a feasible way of detecting them so that I can mark them as different terrain (i.e., salt water for lagoons).

Note: lagoons must be treated differently than lakes. I don't know what the threshhold for a lake should be, but obviously bodies of water close to the coast should be marked as salt water so the player is affected properly when trying to drink the water.

# Answer
> 1 votes
I think the easiest way to do this is with a flood-fill algorithm.

* Pick a square that you know is water, and not a lagoon (eg. top-left corner's water tile)
* Flood fill, marking any water tile with a flag
* Mark any water tiles left that don't have the flag as lakes/lagoons.

I assume you know what flood fill is (looking at all adjacent tiles recursively until you run out of tiles).

# Answer
> 1 votes
There is always brute force solution if you find yourself stuck and speed is not priority (one-time generation).
In you case simple BFS/DFS might suffice. Just pick a node of desired type(either land of water) and continue your search, finding all tiles of same type within the graph(terrain part). Continue while there are any nodes not visited.

---
Tags: procedural-generation, level-design, c++
---


# Question
Title: Increasing resources overtime for a browser-based game
I've been interested in developing a browser game ala OGame or Ikariam etc. Basically, a menu is displayed with your resources and, overtime, they increase depending on how advanced are you in the game.

Now then, the "resources" information for all players is stored in a MySQL database.

I've considered two methods to keep track of a player's resources:

---

## Update database every second

Every second, something like

```
UPDATE `Players` SET `Gold` = `Gold` + `GoldProduction`

```

This is one option. However, performing a query every second for a potentially large table of players is not exactly appealing - but I might be underestimating my server. Am I?

---

## Calculate it when needed

Since you get gold every second, technically the amount of gold any player has should be

```
(currentTime - creationTime) * goldProduction

```

What if the player spends gold? Well, gold spending should affect a variable `goldModifications`:

```
goldModifications + ((currentTime - creationTime) * goldProduction)

```

So if you spend 100 gold, `goldModifications` would be `-100`.

But wait. Players can **upgrade** their gold production. Hence, `goldProduction` isn't constant and this formula is flawed...

... Maybe when you upgrade your gold production, `goldModifications` will be modified by your current amount of gold (so if you had 1500, we would do `goldModifications += 1500`), then `creationTime` will be overwritten to the current time.

---

So I have two methods. One is incredibly simple (just update the database), but I am unsure if it is too much overhead or not. The other is very complex as there could be any number of factors affecting gold production, but certainly requires less processing power.

What should I do? What do those popular games actually do?

# Answer
> 2 votes
tl;dr

The resources should only be controlled by the `Server` (securely) as a decision making entity; The actual work could be offloaded to `Clients` and later verified lazily by the `Server`.

Long story:

How often you update the resources is up to you, your hardware and desired gameplay experience. I don't see why it requires you to update every second? What about every 10 seconds? But if it does, I am sure it is entirely possible with the right hardware. Remember, data that changes frequently could be stored in game memory and only updated to database for storage / backup purposes (with constraint validation).

When a user logs in (assuming production continues when offline), one could simply check the last date the user was online, how much `X` resource she had and use that to calculate her current amount of resource `X`. When she plays, let her handle the money, again checking if she is cheating by verifying constraints online. When the client makes a transaction, you could check that the current amount of resource `X` corresponds with the constraints (what the clients claims matches what the server thinks), calculating the resource state and leaving a tiny buffer for synchronization.

It all depends on the complexity of the game. In general I think you are doing three things that don't necessarily mix well (if taken to extreme) but could work fine depending on your server HW.

1. Updating game state frequently.
2. Stored all data on a server DB.
3. Run game as HTTP POST/GET requests, not a concurrent game server.

Again, I don't see why updating every second should be a huge concern but some benchmarks and tests you could easily perform would alleviate or affirm your suspicions. Then you could lower the rate of updates and/or employ a different strategy (offloading some of the work to client-side \[Angular\]) or something like that.

# Answer
> 0 votes
I am also trying to make a online game in PHP and encounter also this problem. My solution was actualy pretty simple. In Assuming you are using different city's or planets, you will need a database table for the city/planet. In this database you store the current resources and the resources per hour. And also a timestamp.

For upgrading resources facility (gold mine for example) i have a database that has all the building ques with a begin time and end time.

i then have made a page that i include on every page in the game. It first checks if there are any building ques for the selected city that should be finished since last time database was entered. If that gold mine was finished at let say 12.00 and the timestamp on your city was 11.00 and current time is 13.00. What the page does, it calculates all the resources for the time 11.00 to 12.00. Then it will update the gold per hour in the city table. And then it recalculates the resources from 12.00 to 13.00.

when all the above is done, it puts the timestamp on current. But as you have all the resources per hour from the second run, you can store it in an array and let a local timer run to update the resources on screen. But since you include the above mentioned page on every page, when you go to the next page it will acces the database to see what the current resources should be. So the local data is only for viewing.

I hope all is clear. Else just ask

---
Tags: browser-based-games, php
---


title: Incosistent jump, stuttering

text:
# Question
Title: Incosistent jump, stuttering
I've written this C# code to handle movement in my testing project. The game is supposed to be 2D, some kind of a platformer, just to get me started with Unity. However, it seems there's something odd going on. The movement isn't particularly smooth (especially in Editor, it's a bit better when built and ran as .exe file) and jumping is very inconsistent, meaning sometimes it jumps to a certain height and sometimes it jumps ridiculously high. Seems random.

```
using UnityEngine;
using System.Collections;

public class PlayerMovement : MonoBehaviour {

    public float MaxSpeed = 10f;
    public float JumpForce = 700f;
    public Transform GroundCheck;
    public LayerMask WhatIsGround;

    bool facingRight = true;
    bool isOnGround = false;
    float groundRadius = 0.2f;

    void FixedUpdate()
    {
        isOnGround = Physics2D.OverlapCircle(GroundCheck.position, groundRadius, WhatIsGround);
        if (isOnGround && Input.GetAxis("Jump") > 0)
        {
            rigidbody2D.AddForce(new Vector2(0, JumpForce));
        }

        float move = Input.GetAxis("Horizontal") * MaxSpeed;
        rigidbody2D.velocity = new Vector2(move, rigidbody2D.velocity.y);

        if ((move < 0 && facingRight) || (move > 0 && !facingRight))
            Flip ();
    }

    void Flip()
    {
        Vector3 scale = transform.localScale;
        scale.x *= -1;
        transform.localScale = scale;

        facingRight = !facingRight;
    }
}

```

Can anyone tell me what's wrong? There are just two simple platforms and one character, everything done in 2D mode with 2D psychics. The funny thing is that every tutorial handles movement differently and as a beginner in game development I'm kinda baffled by it.

Oh, and the version of Unity is 4.5.3f3, if that changes anything... I'm considering trying the newest beta of 4.6 to see if it is any better, because they're bragging about the new GUI and better 2D physics.. Also, I'm using Windows 8.1.

# Answer
It's because of the variable IsOnGround and duration of jump key.

Imagine this, no matter how fast you are. Update will be called 60times a second. That makes jump key true for more than a instance. Also it takes player time to achieve lift off making isOnGround true for more than one instance . Hence the inconsistent jump, try switching isOnGround to off the instant he jumped in that if statement and switching it back on, like a second later.

P.S you can use a diff var to achieve that effect as well.

Platform games on physics engine will always be hard to perfect, its not unity's fault.
> 1 votes

---
Tags: c#, 2d, unity, physics
---


# Question
Title: Moving an object continuously when left or right key is pressed
I want the object to move continuously as long as key is pressed to left when left arrow is pressed and to right when right arrow is pressed. Instead of moving continuously it moves first time and then never moves again.What seems wrong with this code?

```
void Update()
{
    if (Input.GetKey(KeyCode.LeftArrow))
                {
                    var _speedleft = 0.2f;
                    this.transform.position = new Vector3 (Input.GetAxisRaw("Horizontal") * _speedleft *Time.deltaTime, this.transform.position.y, this.transform.position.z);
                }

                if (Input.GetKey(KeyCode.RightArrow))
                {   var _speedright = 0.2f;
                    this.transform.position = new Vector3 (Input.GetAxisRaw("Horizontal") * _speedright *Time.deltaTime, this.transform.position.y, this.transform.position.z);
                }
}

```

# Answer
> 2 votes
You are assigning the same position at every frame when the related key is pressed. Adding the value should solve the problem.

```
this.transform.position += new Vector3 (Input.GetAxisRaw("Horizontal") * _speedright *Time.deltaTime, this.transform.position.y, this.transform.position.z);

```

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


# Question
Title: How do "game maker" tools like Blitz3D create .exe files?
There are several applications like Blitz3D or other kinds of game construction tools that compile scripts or other game data to a single executable file. How do they do that?

# Answer
Different tools approach that in different ways, but the way Blitz3D does it is to wrap the code and an interpreter into a bundle. Then when you run the exe, that launches the interpreter and passes in the bundled code. It's pretty much the same as how, say, Python works when using py2exe.

In many game development tools, the code that is bundled along with the executable is simply raw text that the interpreter parses. However some take a bytecode approach like Java, where the source-code is turned into an intermediate form that the virtual machine uses. I think Unity uses this latter approach but I'm not sure.

Off the top of my head all game development tools I can think of that package executables are either based on this approach of a core interpreter/virtual machine and then packaging it with the code, or are libraries that you compile in Visual Studio or whatever.
> 10 votes

# Answer
Program flow, variable handling and the like are compiled into pure machine code, whereas the high-level commands are implemented as C++ library functions which are called from the runtime library compiled into every Blitz-generated executable. Non of the Blitz Basic family is interpreted like Python.
> -1 votes

---
Tags: tools, blitzmax, deployment
---


# Question
Title: Unity 2D, C# - Make object move diagonally by a certain angle?
I have a sprite object which I want to move in 8 directions. Left, Right, Up, Down, Left top, Right top, Left down, Right down. The view is 2D with a isometric projection. The difficulties I am having is when the object needs to move diagonally. I need to work out how I can move the sprite in fixed degrees diagonally so its parallel to the isometric world.

I have a diagram to demonstrate.

Here the green arrows are the diagonal movement that I need. The code I have for up, down, left and right movement is already in,

```
void FixedUpdate ()
    {

            speed = 10f;
            //pos = Camera.main.ViewportToWorldPoint (new Vector3 (0.5F, 0.5F, Camera.main.nearClipPlane));
            //transform.position = new Vector3 (pos.x, pos.y, -1F);

            if (Input.GetKey (KeyCode.D)) {
                    ///rigidbody2D.AddForce (Vector2.right * speed);
                    rigidbody2D.velocity = Vector2.right * speed;

            } else if (Input.GetKey (KeyCode.A)) {
                    //rigidbody2D.AddForce (-Vector2.right* speed);
                    rigidbody2D.velocity = -Vector2.right * speed;
            } else if (Input.GetKey (KeyCode.S)) {
                    //rigidbody2D.AddForce (-Vector2.up * speed);
                    rigidbody2D.velocity = -Vector2.up * speed;
            } else if (Input.GetKey (KeyCode.W)) {
                    //rigidbody2D.AddForce (Vector2.up * speed);
                    rigidbody2D.velocity = Vector2.up * speed;
            } else {
                    rigidbody2D.velocity = Vector2.zero;
            }
    }

```

I had a look at the Transform class and the various variables and functions but I don't know what to use or start with. This is because I am very new to Unity and maths such as rotations, axis, etc. So a helping direction would be massively appreciated. Thanks.

# Answer
> 2 votes
```
//temp helper variable
var moveAmount = Point.Zero;

            if (InputHandler.KeyPressed(Keys.A) || InputHandler.KeyPressed(Keys.Left))
                moveAmount.X -= 1;
            if (InputHandler.KeyPressed(Keys.D) || InputHandler.KeyPressed(Keys.Right))
                moveAmount.X += 1;
            if (InputHandler.KeyPressed(Keys.W) || InputHandler.KeyPressed(Keys.Up))
                moveAmount.Y -= 1;
            if (InputHandler.KeyPressed(Keys.S) || InputHandler.KeyPressed(Keys.Down))
                moveAmount.Y += 1;
// do stuff
rigidbody2D.velocity = moveAmount * speed;

```

---
Tags: c#, unity, rotation, physics, isometric
---


title: Lookup table in shader opengl es

text:
# Question
Title: Lookup table in shader opengl es
What I need is apparently very simple, a lookup table in a fragment shader. It seems that the natural way would be an array `float lut[]`, but in some implementations of OpenGL ES I am getting an error

> "profile requires index expression to be compile-time constant".

Next approach would be a 1D texture filled with the values, but again OpenGL ES doesn't like that :)

What would be the simplest way to have a lookup table of 256 float elements in the fragment shader? (I guess it will be a 2d texture but it looks like it is some overhead and I am not sure if it's possible to handle two textures on a shader)

P.S. I am a very beginner in OpenGL but what I need is simple handling of images in textures.

# Answer
Yes, indeed, some ES implementations don't support non-const indexing of arrays, which complicates code quite a bit. 1D textures are also not supported on GL ES 2.0 or lower.

You can certainly overcome this by using a 2D texture with a height of 1 pixel. It will effectively behave like a 1D array.

Another approach might also be computing the value dynamically, instead of using a lookup. This might actually be faster, since memory access patterns are usually a problem on GPUs, whereas a lot of computing power is available. So you might also consider the possibility of replacing the lookup by an on-the-fly computation of the value.
> 1 votes

---
Tags: opengl, shaders
---


# Question
Title: Performance Difference Between Content.Load and Texture.FromStream xna
Is there any performance difference between Texture2Ds loaded using the content pipeline and Texture2Ds loaded using `Texture2D.FromStream()`?

# Answer
Not a significant one, though this depends a lot on what you're trying to achieve. Keep in mind that `Texture2D.FromStream()` returns a default format of `SurfaceFormat.Color` /w non-premultiplied alpha data, whereas with the pipeline you have full control over what you want to do with the texture.

The distinguishing feature between the two is flexibility as opposed to performance. With that said, you really shouldn't decide between the two based on whatever miniscule difference in loading there maybe.

If you really need to know what that difference *might* be, you can just measure it yourself with a stopwatch.
> 0 votes

# Answer
Last time I was looking at benchmarks for this (quite some time ago), `Texture2D.FromStream` was actually *faster* than `Content.Load<Texture2D>`.

The overwhelmingly slowest part of the process, it turns out, is transferring data from disk.

When using `Texture2D.FromStream`, you can load a PNG or JPEG file. These file formats use image-specific data compression, resulting in very small files.

Whereas `Content.Load<Texture2D>` loads an XNB file which is the raw image data, with some general-purpose compression (in release builds), which results in a much larger file.

Even though decoding PNG or JPEG files is far more processor intensive, it ends up being faster, because your game doesn't spend as long waiting on the disk.

**BUT:** First of all, don't trust my results. Measure it yourself. It may be different on your hardware, or with your specific images. (IIRC, the first time I heard about this was for Windows Phone.)

And, this is an optimisation. Prefer to do the simple thing (`Content.Load<Texture2D>`) until and unless you have a compelling reason to do something else.
> 1 votes

---
Tags: xna, c#, performance
---


# Question
Title: Friction not working for Vehicle in BulletPhysics
I am creating a vehicle using bullet-physics engine (v 2.82).

I created a **ground ( btBoxShape )**, **a box** and **a vehicle** (following the demo). But friction between ground and vehicle wheels seems not working.

As soon as the vehicle is placed in 3d world, it starts moving forward.

**START :**

Steering works for the vehicle, but engineForce and brakingForce does not work (i.e. I cannot speed-up or stop the vehicle) :

I create physics world like this :

```
void initPhysics()
{
    broadphase = new btDbvtBroadphase();
    collisionConfiguration = new btDefaultCollisionConfiguration();
    dispatcher = new btCollisionDispatcher(collisionConfiguration);
    solver = new btSequentialImpulseConstraintSolver();

    dynamicsWorld = new btDiscreteDynamicsWorld(dispatcher, broadphase, solver, collisionConfiguration);
    dynamicsWorld->setGravity(btVector3(0, -9.81, 0));

    // Debug Drawer
    bulletDebugugger.setDebugMode(btIDebugDraw::DBG_DrawWireframe);
    dynamicsWorld->setDebugDrawer(&bulletDebugugger);

    //groundShape = new btStaticPlaneShape(btVector3(0, 1, 0), 1);
    groundShape = new btBoxShape(btVector3(50, 3, 50));
    fallShape = new btBoxShape(btVector3(1, 1, 1));

    // Orientation and Position of Ground
    groundMotionState = new btDefaultMotionState(btTransform(btQuaternion(0, 0, 0, 1), btVector3(0, -3, 0)));
    btRigidBody::btRigidBodyConstructionInfo groundRigidBodyCI(0, groundMotionState, groundShape, btVector3(0, 0, 0));
    groundRigidBody = new btRigidBody(groundRigidBodyCI);
    dynamicsWorld->addRigidBody(groundRigidBody);

    ///////////////////////////////////////////////////////////////////////
    //              Vehicle Setup
    ///////////////////////////////////////////////////////////////////////
    vehicleChassisShape = new btBoxShape(btVector3(1.f, 0.5f, 2.f));
    vehicleBody = new btCompoundShape();

    localTrans.setIdentity();
    localTrans.setOrigin(btVector3(0, 1, 0));
    vehicleBody->addChildShape(localTrans, vehicleChassisShape);

    localTrans.setOrigin(btVector3(3, 0.f, 0));
    vehicleMotionState = new btDefaultMotionState(localTrans);
    //vehicleMotionState = new btDefaultMotionState(btTransform(btQuaternion(0, 0, 0, 1), btVector3(3, 0, 0)));
    btVector3 vehicleInertia(0, 0, 0);
    vehicleBody->calculateLocalInertia(vehicleMass, vehicleInertia);
    btRigidBody::btRigidBodyConstructionInfo vehicleRigidBodyCI(vehicleMass, vehicleMotionState, vehicleBody, vehicleInertia);

    vehicleRigidBody = new btRigidBody(vehicleRigidBodyCI);
    dynamicsWorld->addRigidBody(vehicleRigidBody);

    wheelShape = new btCylinderShapeX(btVector3(wheelWidth, wheelRadius, wheelRadius));
    {
        vehicleRayCaster = new btDefaultVehicleRaycaster(dynamicsWorld);
        vehicle = new btRaycastVehicle(vehicleTuning, vehicleRigidBody, vehicleRayCaster);

        // never deactivate vehicle
        vehicleRigidBody->setActivationState(DISABLE_DEACTIVATION);
        dynamicsWorld->addVehicle(vehicle);

        float connectionHeight = 1.2f;
        bool isFrontWheel = true;

        vehicle->setCoordinateSystem(rightIndex, upIndex, forwardIndex); // 0, 1, 2

        // add wheels
        // front left
        btVector3 connectionPointCS0(CUBE_HALF_EXTENT-(0.3*wheelWidth), connectionHeight, 2*CUBE_HALF_EXTENT-wheelRadius);
        vehicle->addWheel(connectionPointCS0, wheelDirectionCS0, wheelAxleCS, suspensionRestLength, wheelRadius, vehicleTuning, isFrontWheel);
        // front right
        connectionPointCS0 = btVector3(-CUBE_HALF_EXTENT+(0.3*wheelWidth), connectionHeight, 2*CUBE_HALF_EXTENT-wheelRadius);
        vehicle->addWheel(connectionPointCS0, wheelDirectionCS0, wheelAxleCS, suspensionRestLength, wheelRadius, vehicleTuning, isFrontWheel);
        isFrontWheel = false;
        // rear right
        connectionPointCS0 = btVector3(-CUBE_HALF_EXTENT+(0.3*wheelWidth), connectionHeight, -2*CUBE_HALF_EXTENT+wheelRadius);
        vehicle->addWheel(connectionPointCS0, wheelDirectionCS0, wheelAxleCS, suspensionRestLength, wheelRadius, vehicleTuning, isFrontWheel);
        // rear left
        connectionPointCS0 = btVector3(CUBE_HALF_EXTENT-(0.3*wheelWidth), connectionHeight, -2*CUBE_HALF_EXTENT+wheelRadius);
        vehicle->addWheel(connectionPointCS0, wheelDirectionCS0, wheelAxleCS, suspensionRestLength, wheelRadius, vehicleTuning, isFrontWheel);

        for (int i = 0; i < vehicle->getNumWheels(); i++)
        {
            btWheelInfo& wheel = vehicle->getWheelInfo(i);
            wheel.m_suspensionStiffness = suspensionStiffness;
            wheel.m_wheelsDampingRelaxation = suspensionDamping;
            wheel.m_wheelsDampingCompression = suspensionCompression;
            wheel.m_frictionSlip = wheelFriction;
            wheel.m_rollInfluence = rollInfluence;
        }

    }

    ///////////////////////////////////////////////////////////////////////

    // Orientation and Position of Falling body
    fallMotionState = new btDefaultMotionState(btTransform(btQuaternion(0, 0, 0, 1), btVector3(-1, 5, 0)));
    btScalar mass = 1;
    btVector3 fallInertia(0, 0, 0);
    fallShape->calculateLocalInertia(mass, fallInertia);
    btRigidBody::btRigidBodyConstructionInfo fallRigidBodyCI(mass, fallMotionState, fallShape, fallInertia);
    fallRigidBody = new btRigidBody(fallRigidBodyCI);
    dynamicsWorld->addRigidBody(fallRigidBody);

}

```

I step physics world like this :

```
// does not work
vehicle->applyEngineForce(maxEngineForce, WHEEL_REARLEFT);
vehicle->applyEngineForce(maxEngineForce, WHEEL_REARRIGHT);
// these also do not work
vehicle->setBrake(gBreakingForce, WHEEL_REARLEFT);
vehicle->setBrake(gBreakingForce, WHEEL_REARRIGHT);
// this works
vehicle->setSteeringValue(gVehicleSteering, WHEEL_FRONTLEFT);
vehicle->setSteeringValue(gVehicleSteering, WHEEL_FRONTRIGHT);

dynamicsWorld->stepSimulation(1 / 60.0f, 10);

```

However If I apply brakingForce to all 4 wheels (i.e. including WHEEL\_FRONTLEFT and WHEEL\_FRONTRIGHT), then my vehicle stops, but keeps sliding/moving forward very very slowly.

How do I fix this ?

# Answer
I got it working. Just had to edit these two lines :

```
    vehicle->applyEngineForce(maxEngineForce, WHEEL_REARLEFT);
    vehicle->applyEngineForce(maxEngineForce, WHEEL_REARRIGHT);

```

and replace **maxEngineForce** with **gEngineForce**.
> 1 votes

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


# Question
Title: Handling Event for multiple Sprite with one Event Listener in Andengine
In my app i need to add multiple sprite and add event to them. What i am doing now is using individual event listener for each and every sprite which is a kind of mess.

```
buttonS[0] = new Sprite(x_pos += 0, y_pos, orangeNumImage[0], this.getVertexBufferObjectManager()) {
        @Override
        public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
            if(pSceneTouchEvent.isActionDown()) {
                //Perform Some task
                }
                return true;
            } else {
                //Perform Some task
                return false;
            }
        }
    };

    buttonS[1] = new Sprite(x_pos += 115, y_pos, orangeNumImage[1], this.getVertexBufferObjectManager()) {
        @Override
        public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
            if(pSceneTouchEvent.isActionDown()) {
                //Perform Some task
                }
                return true;
            } else {
                return false;
            }
        }
    };

```

I was searching to handle this event with just one event listener and make the code shorter.

In normal android (without andengine) we could use something like this (by using android:onclick to areaTouched in button):-

```
public void areaTouched(View view) {
    Button nextclick = (Button) findViewById(R.id.button_nextClick);
    Button b = (Button)view;
    int check = Integer.parseInt(b.getText().toString());
    if (check == i){
          ........
    }
}

```

# Answer
Extend the `Sprite` class and add a method to add you own `TouchListener` and a method to set some user data. Or implement the touch logic in your new `Sprite` child class by overriding the `onAreaTouched` method. I don't think there is any other mechanism in AndEngine that would allow you to register a touch listener to Sprites.
> 1 votes

---
Tags: andengine
---


title: Decentralized Matchmaking in Unity?

text:
# Question
Title: Decentralized Matchmaking in Unity?
I'm making a card-playing game, similar to Magic Workstation. I've been looking into several options for networking. I have a working LAN version with the build in Unity networking, as well as Photon Cloud. Though I was now looking for a more decentralized way of doing multiplayer on the internet. It would be very very cool if there were no servers involved in finding other people. I would still let players host their own game-rooms others can join.

I Googled around for this, and everything I found was at least several years old. So I was wondering if anything new has popped up since then. I've seen several decentralized chat programs and even voice/video chat without any servers. But nothing for video games yet.

I did find some problems with this kind of networking. Mainly the lack of anti-cheat, but in my case the players check the moves themselves so this shouldn't be a problem. Other than that it's probably a bit slower, but card games are generally not very high-paced :P

Lastly, I'm making it in Unity using c#. I'll probably be running it in the webplayer (and later WebGL). So I'm mostly looking for c# library, or javascript. But any promising projects that do this are welcome.

Thanks a lot!

# Answer
> 2 votes
The built-in Unity networking would be fine for this. Sure, someone has to be a "server", but this doesn't have to mean much at all depending on how you program it. Unity does give you complete freedom on how you distribute the work across the players, and how they're all synchronised.

Of course the only problem here is the master server. You do need a master server, but it's only purpose is to help find games. I don't see how this would really get in your way, you can host your own master server as well.

Really, the Unity networking is what you make it. Photon on the other hand is VERY limiting.

---
Tags: unity, networking, matchmaking
---


title: Camera world matrix to view matrix

text:
# Question
Title: Camera world matrix to view matrix
I've been working on a game engine and I model every object in my scene graph as an "entity" this includes my camera.

My camera therefore has a position and rotation in world space and at the moment I am able to create a view matrix by taking the inverse of the cameras world space matrix.

However when I do this the camera looks in the opposite direction to what I would expect.

Why is that so?

# Answer
> 2 votes
I actually think everything is okay! All I needed to clarify in my system is which direction is forwards, and I picked -z and that seems to have fixed my confusion.

So it wasn't that my camera was facing the wrong direction, it was everything else that was facing the wrong direction!

Sorry for the confusion!

---
Tags: mathematics, camera, matrix, transformation
---


# Question
Title: Collision detection against complex shapes and curves
I am new in game development and for simple games bounding box collision is fine. However, let's say you have a shape or bitmap like this:

This is just an example but if you had more elaborate curves or even a whole shape which was more complex than a simple polygon or rectangle-like shape, how would you do precise collision detection? I am strictly speaking in 2D here. I just want to know the concept behind how you would do this.

# Answer
I'm going to assume you're representing your world as geometric primitives (points, lines, curves, polygons, etc.) rather than sprites. If you're using sprites and per-pixel collision detection, there's nothing special about odd-shaped objects. See this question for some ideas.

Using geometric primitives, the first step is to use a broad-phase algorithm to narrow down the possible pairs of objects that might intersect. See this Stack Overflow question. Checking for collisions between each candidate pair is called the narrow phase, and you have a couple of options.

The simplest solution is to just approximate your curve using a series of line segments. If the curve is a standalone object, you'd just treat the segments as you would any other line segments in the world. If the curve is the edge of some larger object, then as a pre-processing step you'd split the larger object into smaller convex shapes using a process similar to the trapezoid rule from basic calculus. The general term for this process is "convex decomposition", and computing an optimal decomposition of arbitrary polygons is NP-complete, but a good-enough or hand-crafted decomposition will work just fine. The smaller convex subparts can be easily checked for collisions using any of a number of algorithms.

A more difficult solution is to write a custom collision algorithm for collisions between each kind of geometric primitive you want to support. Assuming you already support collisions between points, line segments, rectangles, circles, and convex polygons, adding a curve like your example would require coding a custom algorithm for the following pairs:

* Point - sine curve
* Line segment - sine curve
* Rectangle - sine curve
* Circle - sine curve
* Convex polygon - sine curve
* Sine curve - sine curve

I wouldn't recommend this approach because it's complex and ends up being a lot of work. However, if you can figure out a way to represent your objects using only convex shapes, then the generalized GJK algorithm will work, even if your objects have curves.
> 1 votes

---
Tags: collision-detection, graphics
---


title: Jumping distance due to X velocity

text:
# Question
Title: Jumping distance due to X velocity
I would just like to know if there is a way to work out the distance of a jump depending on how fast the player is going. For example if the player has a velocity X of 10 and he presses the jump button he should jump further than if his X velocity was, say 4.

I have a working jump mechanic that when the jump button is pressed the velocity is set to a predefined value like -10; Then slowly gravity brings it down but I want it to feel more realistic by applying the jump distance according to his speed

Any way to implement this?

# Answer
If you're using velocities for this, the "jump distance" will be handled automatically. The distance on the X axis traveled during the jump is the product of the time in the air, and the X axis velocity. Say your jump takes one second to complete. If your character is traveling at 10 units per second on the X axis, during that one second jump, they will have traveled 10 units. If their speed is 4 units per second on the X axis, they will have traveled 4 units during the jump.

If you're experiencing otherwise, make sure you're maintaining the X velocity when changing your Y velocity for the jump.
> 1 votes

---
Tags: java, jumping
---


# Question
Title: Get highest (Y-axis) vertices from primitive d20 dice in xna
I have created a d20 dice (icosahedron) in xna and used BEPU physics to roll it. But now I'm trying to get the value from the dice after its rolled. I was thinking about looking for the 3 vertices that have the highest Y-axis coords after the dice rolled. so I could set something like this:

```
if (vertices[0].currentPosition.Y >= 2 && vertices[1].currentPosition.Y >= 2 && vertices[2].currentPosition.Y >= 2)
{
    diceValue = 5;
}

```

But how do i get the current position from the vertices? Or is there a better way to check what value is on top of the dice?

# Answer
If you have the rotation matrix, I think the the easier is to get the cos between the normals and forget the vertex position.

The cos will be max and near 1 when the angle among the two vectors is near 0.

Each normal will have a face value so get the face value of the normal nearest to Vector3.UnitY is easy.

```
 Vector3 FaceNormals = new Vector3[] { Vector3.UnitX, -Vector3.UnitX, Vector3.UnitY, -Vector3.UnitY}
 int FaceValue = new int[] { 1,2,3,4 }

float cos = -1;
int faceValue = 0;
for (int n=0; n<FaceNormals.Length; n++) {
  var RotatedNormal = Vectro3.TransformNormal(FaceNormal[n], RotationMatrix);
  var newCos = Vector3.Dot(Vector3.UnitY , RotatedNormal );
  if (cos<newCos) {
     FaceValue = FaceValues[n];
     vod = newCos;
  }
}

```

where the Vector3.UnitY is fixed, and the face normal are rotated, so calculation is now in world space.

EDIT:

If you want to use vertices... calculate the center of each face, if the face has two triangles correlated:

```
var j =0;
Vector3[] Centers = new Vector3[indices.Lengt/6];
Vector3[] Normals= new Vector3[indices.Lengt/6];

for (int i =0; i<indices.lenght; i+=6)
{
      Vector3 center;
      for (int n=0; n<6;n++) {
          center+= vertices[indices[i+n]].Position;
      }
      center/=6;

      var A = vertices[indices[i+1]].Position - vertices[indices[i]].Position
      var B = vertices[indices[i+2]].Position - vertices[indices[i]].Position
      normal = Vector3.Cross(A, B);

      Centers[j] = center;
      Normals[j] = normal;
      j++;
}

int[] FaceValues = { 1,2,3,4,5,6...}
float y = float.MinValue;
for (int n=0; n<Centers.Length; n++) {

    var rotated = Vector3.Transform(Centers[n], TransformMatrix);

    if (y < rotated.Y) {
        y = rotated.Y;
        FaceValue = FaceValues[n];
    }
}

```

You'll have the dice face value in "FaceValue"
> 1 votes

# Answer
Vertices are stored in memory using local coordinates. So no vertex has a "currentPosition," they're always positioned according to their offset from their original origin. In the "world," they are displayed according to some transformation: scale and rotation about their local origin, then translation with respect to the world origin. With the exception of static level geometry, vertices are almost never stored in a current position.

So, to get the "current" position of any vertex, you must apply a transformation to it that takes it from local to world space. Applied to all vertices, you need only find the vertices with the greatest Y coordinate.

It's been a while since I used XNA, but going off of the MSDN docs it should look something like this:

```
transform = Matrix.CreateFromQuaternion(dieRotation)
            * Matrix.CreateTranslation(diePosition);
var currentPositions = vertices
                       .Select(v => Vector3.Transform(v.Position, transform))
                       .OrderByDescending(p => p.Y)
                       .Take(numberOfVerticesPerFace)
                       .ToList();

```
> 1 votes

# Answer
You can calculate the orientations that the die will fall on, then test the current orientation against a pre-computed list of orientations to get the number.
> 0 votes

---
Tags: xna, xna-4.0
---


title: Minecraft Type Game Support Blocks

text:
# Question
Title: Minecraft Type Game Support Blocks
OK I have a game that is similar to minecraft in a sense. Players can build castles block by block. I'm using Unity3D and Photon Network for my game and I was wondering how I would handle detecting if blocks have a support system to the ground. Here is the game in question. Let me know what are some solutions besides using rigid-bodies I've tried doing that and it has severe performance issues over a network. Thanks

Youtube Video of Game

# Answer
> 1 votes
Why don't you implement a child parent system? If a block is placed next to a block of the same type or a supported connecting block then add the new block as a child. That way it keeps the data from the parent block relative. You can then remove that child if say it was destroyed and add physics support so you can see what would happen to the child of the destroyed child block.

# Answer
> 1 votes
What I would do is find each of the blocks neighbors (except above). Then for each one of it's neighbors, find that blocks neighbors. Then for each of those neighbors, find the next neighbors, etc. etc. Eventually you will find all of the connected neighbors in a sort of parent-child tree like user3667971 mentioned. If *any* of those blocks are connected to the ground, then you have support.

Note that if you are doing this every frame, then that is pretty inefficient. I would only generate the neighbor list once for each block, and user3667971's idea of just adding it as a child to create a tree, and then find the parent of the entire tree to test for the ground.

# Answer
> 0 votes
You can do a partially update of your world. Whenever you place/remove a block from your world, check all adjacent blocks.

---

If you **place** a block `A` ontop of Block `B`, then you check all sides around `A`. If any block (for example `B`) is directly below, one to the side and below or directly adjacent (if you want to support that), then place the block and it will rest. If no support is there, it will start to fall.

```
Checks required in pseudocode (No direct side-support, you'll figure it)

function blockPhysics()
    List<Block> toUpdate = new List<Block>();
    boolean isFalling = true;

    foreach( Block B near A ) //which is not falling at the moment
        if (A.y-1 == B.y && Math.abs(A.x - B.x) <= 1)
            //have block stay at position
            isFalling = false;
        else
            //remember B so we can tell him we are gone
            toUpdate.add( B );
        end
    end

    if( isFalling )
        //trigger our fall and handle it FIRST!
        fallDown(); //Your job to implement. You probably simply want to set a flag named canSupportOtherBlocks.

        //Then have every surrounding block do his own physic calculations.
        foreach( Block B in toUpdate )
            B.blockPhysics();
        end
    end
end

```

---

If you **remove** a block `B` from below Block `A`, then you trigger the blockPhysics from all surrounding blocks.

```
function remove()
    //we have to remove B first, otherwise this would disturb the Physics
    removeSelf();

    foreach ( Block A near B )
        A.blockPhysics();
    end
end

```

This will trigger any block `A` around `B` to check again it's support. This will possibly trigger a cascade of blocks falling. But what else do you expect if you build a reverse pyramid and remove the support.

---
Tags: unity, video
---