# Question
Title: Collision between complex polyominoes travelling at different velocities
My first post here if there's anything wrong please do highlight it :) First and foremost the problem I'm facing is practically identical to this earlier post here : Falling Blocks and complex shapes

For ease of use here is the graph used to explain the above problem:

I do have a working build that uses a similar approach to the answer suggested in the post above. However what I'm currently trying to do is move the polyominoes continuously with an independent velocity so that it accelerates as it falls.

The answer suggested in the link above only works if you assume all the shapes move at a constant velocity due to the way my game works the "ground" can be removed and blocks that were once static can start to fall again.

The problem arises when a block with a higher velocity collides with one with a lower velocity at the bottom. You could make it so that these blocks slow down as they "collide" with the slower blocks but using this approach causes a problem in cases 3 and 4 where the 2 interlocking shapes will collide endlessly with one another and just not fall.

I have tried a few ideas but they just don't seem to really work. And for anyone who wants to say it's too complex or try something simpler well I don't really have a choice in the implementation it's what someone else wants :(

Also I don't think that it really matters but I'm using Unity to build this game just in case if you wanted to know.

Again I thought it wouldn't hurt to throw this question out there rather than just bashing my head by myself.

the method that handles collisions:

```
protected bool handleVerticalMovement(ref Vector2 moveDelta)
{
    var ySign = (int)Mathf.Sign(moveDelta.y);
    var yDeltaMag = Mathf.CeilToInt(moveDelta.y * ySign);

    for (int i = 0; i < _monominoes.Count; i++)
    {
        var x = _monominoes[i].gridPositionX;

        for (int yDelta = 0; yDelta <= yDeltaMag; yDelta++)
        {
            var y = Mathf.CeilToInt(_monominoes[i].transform.localPosition.y * ySign + yDelta) * ySign;

            // check if it has hit the boundary of the grid
            if (!Board.Instance.IsValidTile(x, y))
            {
                var deltaToBoundary = Mathf.Clamp(y, 0, Board.Instance.height - 1) -
                                     _monominoes[i].transform.localPosition.y;

                if (moveDelta.y * ySign <= deltaToBoundary * ySign) break;

                moveDelta.y = deltaToBoundary;

                return false;
            }
            // ignore if the cell is empty or is part of this shape
            if (Board.Instance.GetTileAt(x, y) == null ||
                Board.Instance.GetPolyominoAt(x, y) == this) continue;

            //check to see if i hit a tile that is grounded
            if (Board.Instance.GetTileAt(x, y).isGrounded)
            {
                var detltaToGround = y - _monominoes[i].transform.localPosition.y - ySign;

                if (moveDelta.y * ySign <= detltaToGround * ySign) break;

                moveDelta.y = detltaToGround;

                return false;
            }

            var deltaToTile = Board.Instance.GetTileAt(x, y).transform.localPosition.y -
                               _monominoes[i].transform.localPosition.y - ySign;
            // if the tile is not grounded check to see the delta movement will overlap the tile if so cap the delta
            if (moveDelta.y * ySign <= deltaToTile * ySign) break;

            moveDelta.y = deltaToTile;
            break;
        }
    }

    return true;
}

```

To further elaborate my current thought process on the matter currently this method takes in a delta value iterates through the grid to see if it collides with anything. If does collide with something it will adjust the delta value and if it hits the the bounds of the grid or any shape that's grounded it will exit returning false meaning after moving this frame it will also be grounded..

The complication arises when one block hits another block that's also not grounded adjusting the delta value to slow it down it will cause the 2 blocks in case 3 and 4 to collide into each other infinitely causing them to float in mid air.

What I've tried to do is call the other block's handleVerticalMovement method to ask how far it can move and this in turn will end up a sort of recursive call to other blocks that that other block will hit. I managed to get this to work when the blocks were moving one cell at a time but it doesn't seem to work as well when the blocks are moving continuously with a pseudo gravity value causing the blocks to accelerate overtime.

I have thought about clumping the block's together and making them fall as one object this will definitely solve case case 3 and 4 but this can potentially cause problems with case 5 and 6 where if one object gets hit and becomes grounded the other "connected" block should still be able to fall a bit more.

This means if I were to make them fall as one block while they are free falling when one the "sub" blocks collides I still need some way to identify what can continue falling what blocks cannot.

Again if there's any gaping holes in my logic please do point it out.

# Answer
So after a little bit of trial an error I got something that works. I still have a few bugs in my game but it might be due to other parts of the code that are causing bugs.

```
protected bool handleVerticalMovement(ref Vector2 moveDelta, HashSet<Polyomino> hitMinos)
{
    var ySign = (int)Mathf.Sign(moveDelta.y);
    var yDeltaMag = Mathf.CeilToInt(moveDelta.y * ySign);

    for (int i = 0; i < _monominoes.Count; i++)
    {
        var x = _monominoes[i].gridPositionX;

        for (int yDelta = 0; yDelta <= yDeltaMag; yDelta++)
        {
            var y = Mathf.CeilToInt(_monominoes[i].transform.localPosition.y * ySign + yDelta) * ySign;

            if (!Board.Instance.IsValidTile(x, y))
            {
                var deltaToBoundary = Mathf.Clamp(y, 0, Board.Instance.height - 1) -
                                     _monominoes[i].transform.localPosition.y;

                if (moveDelta.y * ySign <= deltaToBoundary * ySign) break;

                moveDelta.y = deltaToBoundary;

                return false;
            }

            var otherMino = Board.Instance.GetPolyominoAt(x, y);

            if (Board.Instance.GetTileAt(x, y) == null || otherMino == this) continue;

            if (hitMinos.Contains(otherMino))
                break;

            if (Board.Instance.GetTileAt(x, y).isGrounded)
            {
                var detltaToGround = y - _monominoes[i].transform.localPosition.y - ySign;

                if (moveDelta.y * ySign <= detltaToGround * ySign) break;

                moveDelta.y = detltaToGround;

                return Board.Instance.GetTileAt(x, y).isAnimating;
            }

            var deltaToTile = Board.Instance.GetTileAt(x, y).transform.localPosition.y -
                               _monominoes[i].transform.localPosition.y - ySign;

            if (moveDelta.y * ySign <= deltaToTile * ySign) break;

            if (otherMino == null ||
                Board.Instance.processedPolyominos.Contains(otherMino))
            {
                moveDelta.y = deltaToTile;
                break;
            }

            hitMinos.Add(otherMino);

            if(otherMino.handleVerticalMovement(ref moveDelta, hitMinos))
                break;

            return false;
        }
    }

    return true;
}

```

so the method still looks the same except when I hit a tile that's not grounded I call that tile's handleVertcalMovemt method but I add that tile to a hashSet that contains all the shapes that were hit before. When I exit this method i would have a set of all the different polyominos that were would be hit if the root polyomino were to move down. From here all these shapes as one shape and move them all at once. This is practically the same to clumping shapes together except this builds the shape on the fly instead of caching them in a list.
> 0 votes

# Answer
Actually that is not that hard. As I don't know your complete design, I will just talk a bit more general.

I assume, each block construct as an independent enitity. So in picture 2 as an example, you would have 3 entities. I also assume, that your design includes mass for each entity. If all this is correct then next will help you.

As soon as 2 entities collide, determine the one with the bigger mass. This entitiy transforms into the parent entity of all other entities colliding. So now they all move no more independent, they are driven by the parent. The velocity break if 2 objects collide is a physics based calculation.

After the collision just move the parent with it's break down velocity.

When another collision is detected to the calculation again, but update the mass of the parent object to have the mass of all children too.

---

We go through all of your example pictures with my parent/child system.

Picture 1 - 1 Entity

Keeps falling till `grounded`

Picture 2 - 3 Entities

Green Entity and yellow Entity fall red entity is `grounded`. Let's assume green entity has a higher velocity then the yellow one and hits yellow before any of both get's grounded.

Green Entity detects a collision with yellow. We decide (because mass doesn't care for you) that green as first entity get's the new parent. So we set for yellow the parent as green and for green the child to yellow. Next they keep falling. Yellow is no longer moved or done collision detection because it has a parent. We move green and ask if has children and use both data for collision detection and movement.

We detect a collision of 1 child, yellow collided with the floor. So we set it to be grounded, remove it from the parent and set it has no parent. Next we do this for green, it collides with yellow, has no children anylonger so just set it as grounded. Done.

Picture 3 - 2 Entities

We detect a collision between green and red. We take green as the first entity of our list and set the children as red and on red the parent as green. Next we do collsion and movement only for green, because red has a parent and so will not be used in collision detection and movement.

Green hits the ground and will be marked grounded. Green has children so we remove the children and set their parents to be null.

Next we check red and detect a collision with green. we set green as parent of red and it is no longer part of the collision detection. But it is not grounded. As soon as green get's removed from the board, we free red and red will eventually start falling again till also grounded.

Picture 4 - 3 Entities

Red/Green is the same as on Picture 3.

Green detects a collision with it's children against yellow. Yellow is grounded and has there for the "master" right. So we set Green with it's children as a child of yellow. They are no longer used for collision detection, as long as yellow exists.

If yellow get's removed of the board, remove the children of yellow and set their parents to null, and they start falling again.

Picture 5 - 3 Entites

If we assume yellow falls faster or red or both have same velocity doesn't care. The algorithm is allways the same.

We assume red falls faster.

We detect a collison between yellow and red. yellow will the get the parent because first in the entity list. Next we detect a collision of yellow's child with green.

We set green as the parent of yellow because green is grounded and so the master. We free all children of yellow because yellow is connected of a master/grounded entity. We also free yellow of green because it is no longer colliding with green.

So yellow starts falling again and detects a collision between yellow and red. But red is connected to a master/grounded entity so we set yellow as a child of red and red as a child of green and set on all

Picture 6 - 3 Entites

Same as picture 5.

---

You see how the algorithm grows from picture to picture. To summarize the algorithm.

1. Check if entity collides with another entity
2. Check if the colliding entity is a "grounded" one
3. If not grounded determine one as parent and set the rest as children
4. If grounded free all children and do collision again for all
5. If grounded and not children, set as children of grounded.
6. If colliding with ground - free all children and set grounded

Done.

That's it.
> 0 votes

---
Tags: 2d, collision-detection, grid
---


# Question
Title: Method of handling audio and memory in game
I've started coding a new game project and I've implemented Ogre for the graphics rendering and begun thinking about the audio side of things.

I was considering using the SFML audio component for implementing audio. It is cross platform and can handle streaming music from the file or playing sounds loaded into memory from a buffer.

My initial thoughts were along the line of creating an audio manager class that can load all the relevant sounds into memory and then just be able to play them by reference when required. My concern there was the potential memory use of having a whole lot of sounds loaded into memory.

This is the code I came up with as a very rough test of what I was thinking. Obviously it would need to be improved a lot but it does seem to work.

```
#include <vector>
#include <string>
#include <iostream>
#include <unistd.h>

#include <SFML/Audio.hpp>

class gameSound
{
public:
gameSound();
~gameSound();

bool loadSound(std::string filename);

std::string name;
sf::SoundBuffer buffer;
sf::Sound sound;
};

gameSound::gameSound(){}
gameSound::~gameSound(){}

bool gameSound::loadSound(std::string filename) {
if(!buffer.loadFromFile(filename))
    return false;

sound.setBuffer(buffer);

return true;
}

class SoundManager
{
public:
SoundManager();
~SoundManager();

void PlaySoundByName(std::string name);
void AddSound(gameSound* snd);

std::vector<gameSound*> sounds;
};

SoundManager::SoundManager(){}
SoundManager::~SoundManager(){

while(!sounds.empty())
{
    sounds.pop_back();
}

}

void SoundManager::AddSound(gameSound* snd) {
sounds.push_back(snd);
std::cout << "gameSound added with name: " << snd->name << " total sounds : " << sounds.size() << std::endl;
}

void SoundManager::PlaySoundByName(std::string name) {

for(std::vector<int>::size_type i = 0; i != sounds.size(); i++) {
    if(sounds[i]->name == name) {
        std::cout << "Match found for " << name << std::endl;
        sounds[i]->sound.play();
    }
}

}

int main()
{

SoundManager* smgr = new SoundManager();

gameSound* s1 = new gameSound();
s1->loadSound("sound.ogg");
s1->name = "Sound";

gameSound* s2 = new gameSound();
s2->loadSound("alarm.ogg");
s2->name = "Alarm";

gameSound* s3 = new gameSound();
s3->loadSound("dog-grunt.ogg");
s3->name = "DogGrunt";

smgr->AddSound(s1);
smgr->AddSound(s2);
smgr->AddSound(s3);

smgr->PlaySoundByName("DogGrunt");

sleep(2);

smgr->PlaySoundByName("Alarm");

sleep(2);
return 0;
}

```

I know with most systems these days, especially gaming systems, there is usually plenty of memory so it might not be an issue. I was considering implementing a way to load the most important sounds into memory for instant access and then have less common sounds loaded and freed from memory as they are required.

I am interested to know how others have approached the handling of audio required for a game and if I am on the right track.

# Answer
> 3 votes
From a conceptual point of view you seem to be on the right track. Here is the way I did it.

I'm currently developing a 3D game that I wanted to be able to run on low-memory Windows Phones. My game has lots of 20k tri models, so memory management was a problem.

In essence, to solve my problem I broke my game down into about 4 sections: Global, menu, space, and station. At the beginning all global data (like UI and basic sounds) were loaded. Every time the game changes state, it unloads whatever is unnecessary an loads the data for the new state.

Note that I did this for all assets, not just sounds. This vastly improved performance. Obviously, you can make it as granular as you want, but remember that the law of diminishing returns applies.

---
Tags: sfml, audio, memory-efficiency, memory
---


# Question
Title: "Binding" script functions to C++ functions
I appreciate the answer to this question might be a little too broad for SE, but hopefully someone can point me in the right direction.

I'm developing a small scripting language for use in my game engine, and naturally in order to do really useful things with it, it needs to hook into actual C++ functions in my game.

For example, say I have an **Inventory** class, with a public function, **checkItem(itemID)** that is designed to check whether a certain item is in the current inventory or not.

I'd love to be able to define a scripting function that calls the built-in checkItem function for its value during some script's lifetime. Is there a standard / simple-to-implement procedure for doing this? Something that has a similar effect to LuaBind, for example?

I can of course add instructions to my scripting VM that call the functions internally, but this will make the VM a bit of a mess and require implementing separate operations for each function I wish to call.

# Answer
There is no one way to bind an engine with a scripting language, nor is there really an easy way or a best way, it's all very dependent on your architecture, scope and ambitions, I can think of two basic strategies to accomplish what you want.

The first option you already suggested: Calling functions from the VM, this is is the simplest and easiest solution **if you can keep it small**! It can quickly spiral into unsustainable spaghetti as you haphazardly add more and more functionality, but with proper forethought and planning it might be all you need

Secondly you could try to implement a message passing system within your engine where the VM would just generate a message from input and send it out to the proper object. This is a more robust solution as it decouples your VM from the engine and far easier to grow and shrink. **But** it would add a small performance and memory hit, and it could be a lot of work to implement, maybe even to much.

The hidden third option is to use a mix of the two, binding for perfomance critical sections and messaging for less demanding part, of course this would be an even more complex thing to design and implement well.

Whatever path you may choose prepare yourself, creating a language is like raising a child, it will be more difficult and frustrating and time-stealing than you can even imagine and you will bang your head into the nearest hard surface many, many times! But if you persevere and keep at it and show lots of love, it will be a very rewarding experience that you will always cherish and no matter what the world thinks, in your eyes she will always be unique and special.
> 3 votes

# Answer
It might be worth using an existing scripting language unless you really really *REALLY* want to do this yourself.

You will need to write an interpreter for your scripting language and a library to expose your game engine API to the interpreter. Writing the interpreter and library is a fair amount of work in and of themselves but there is more, you also need to create a language. At this point things get pretty tricky and theory comes into play. Take a look at the specification for Python, or C specification for some idea of the things you will need to consider.
> 0 votes

---
Tags: c++, scripting
---


title: Fade in and fade out Gui texture

text:
# Question
Title: Fade in and fade out Gui texture
i am beginner in c# that i want have fade-in and fade-out. i write script but why didn't work:

```
using UnityEngine;
using System.Collections;

public class FADE : MonoBehaviour {
    private var alpha = 1.0;
    private var fadeDir = -1;
    private Texture2D myGUITexture;
    float fadeSpeed = 0.2;
    int drawDepth = -1000;

    void OnGUI(){

        alpha += fadeDir * fadeSpeed * Time.deltaTime;
        alpha = Mathf.Clamp01(alpha);

        GUI.color.a = alpha;

        GUI.depth = drawDepth;

        GUI.DrawTexture(Rect(0, 0, Screen.width, Screen.height), fadeTexture);
    }
}

```

# Answer
> 1 votes
finally i can resolve my problem.

```
 using UnityEngine;

 public class FADE : MonoBehaviour
 {
     private float alpha = 1.0f;
     private float fadeDir = -1;
     public Texture2D myGUITexture;
     float fadeSpeed = 0.2f;
     int drawDepth = -1000;

     void OnGUI()
     {
         alpha += fadeDir * fadeSpeed * Time.deltaTime;
         alpha = Mathf.Clamp01(alpha);

         GUI.color = new Color(GUI.color.r, GUI.color.g, GUI.color.b, alpha);
         GUI.DrawTexture(new Rect(0, 0, Screen.width, Screen.height), myGUITexture);
         GUI.depth = drawDepth;
     }
 }

```

---
Tags: unity
---


# Question
Title: Deferring royalties for assets until revenue is earned
I am developing a game and I want to use some assets that are available online for a fixed price, I want to sell my game and actually make money off of it. I have contacted the owners and they will sell it to me for a fixed price to use commercially. However, I am on a very limited budget and don't really want to pay up front for the assets.

What I want to know is how to defer the costs contingent on whether I make any money. In other words, they give me the models, and then I promise to pay them back out of the first revenue. If the project dies, I'm not out any money.

Other than my word as an honest guy, how could I convince them to agree to this? Would they charge me more because of risk involved?

# Answer
Just negotiate with them. If they're willing to take a royalty, they will. If not, you'll have to get other assets.
> 7 votes

---
Tags: legal, intellectual-property
---


title: libgdx tiledmap rendering optimazation

text:
# Question
Title: libgdx tiledmap rendering optimazation
I'm new to game development can anyone show me how to render tiles which were only seen by the camera I cant seem to find straight answer in google.

The game is in 2D and im using tiled

# Answer
> 1 votes
If you are using OrthogonalTiledMapRenderer or another renderer that inherits from BatchTileMapRenderer, then you should be calling setView before rendering the map. There are two overloads of setView

```
@Override
public void setView (OrthographicCamera camera) {
    batch.setProjectionMatrix(camera.combined);
    float width = camera.viewportWidth * camera.zoom;
    float height = camera.viewportHeight * camera.zoom;
    viewBounds.set(camera.position.x - width / 2, camera.position.y - height / 2, width, height);
}

@Override
public void setView (Matrix4 projection, float x, float y, float width, float height) {
    batch.setProjectionMatrix(projection);
    viewBounds.set(x, y, width, height);
}

```

You'll notice that each version sets a viewBounds, which is a rectangle. Any tiles outside of this rectangle will not be rendered. In other words, the first overload of setView is already doing this calculation for you. However, if you want fine control over this viewbounds rectangle, you can use the second overload.

# Answer
> 0 votes
So you will need a normal orthographic camera and an orthogonal tiled map renderer (assuming you are using square tiles) then you set the view of the tiled map renderer to the camera and call the tiled map renderer to render

https://github.com/libgdx/libgdx/wiki/Tile-maps

---
Tags: libgdx
---


# Question
Title: What happens if I increment a completed achievement on Google Play?
This question is about GPGS (Google Play Game Services). Say we have three achievements like:

* Achievement A: Kill a total of 3 enemies
* Achievement B: Kill a total of 6 enemies
* Achievement C: Kill a total of 12 enemies

As they are all measured with total amount of kills, when players kill an enemy, all them three should increase. So what happens if I continue to send increments after total amount exceeds 3 for A, 6 for B, 12 for C?

# Answer
If you attempt to increment an incremental achievement beyond the number of steps defined for that achievement, nothing happens. See the documentation for `gpg::AchievementManager::Increment` (or the same variant of the API for whatever language you prefer).
> 2 votes

---
Tags: android, google-play, google-play-services
---


title: Libgdx Delta time stutter?

text:
# Question
Title: Libgdx Delta time stutter?
Alright, so I want my guy to move, I simply use this code.

```
velocity.y = speed;

```

Same goes for velocity.x Thing is, the lower the framerate the slower he moves.

But, if I add delta time, the player will sometimes, randomly, jitter back. Now I've traced the problem to be the delta time, but I don't know why. This is a small output of my delta time.

```
0.017027862
0.01713779
0.015907489
0.017954277
0.015993927
0.016019527
0.017010393
0.017026054
0.016008984
0.01701702

```

So it doesn't really vary that much per frame, still the jittering keeps happening.

Any possible solutions?

# Answer
Delta time should not be used to calculate velocity, but position.

When you set velocity.y to speed, you are saying

```
"My character will move <speed> pixels per second in the y axis".

```

Later, when you update the actor's position you will calculate the y position by

```
character.position.y += velocity.y * deltaTime;

```

An easy way to think about this is distance = velocity * time
> 5 votes

---
Tags: libgdx, movement
---


title: How can I model a star?

text:
# Question
Title: How can I model a star?
I'm trying to model a star in Unity, and it, sort of works, but it's not ideal. Currently, I'm using a large sphere with a self-illuminating material containing a star texture applied to it's surface, and a spotlight to create the effect of starlight, like this:

While it works, it doesn't look the greatest. I'm looking for an effect more along the lines of how Kerbal Space Program models a star:

How can I achieve this effect?

# Answer
> 23 votes
* Use an animated texture.\* There are some good ones in the store for \< $10.
* Add a Halo. You can use the particle system, or just a transparent glow texture on a billboard in front of the sun with a script to re-position the texture when the camera moves. This hides the aliased edges of the sphere model, allowing you to use a lower poly model, and looks nice.
* Rotate the sun, slowly.
* Use particle system for eruptions.
* Use a custom shader to make the edges match well with the halo(multiply normal with camera vector to find edges).

The animated gif shows a static texture first, followed by a number of additions, in order:

1. Animated Texture
2. Brighten the edges of the sphere based on normals
3. Add camera-facing transparent billboard with white/yellow halo
4. Particles, moving from the center to the outside, then fading
5. Add 2 transparent "ray" billboards, facing the camera and rotating along the camera axis in opposite directions.

With the animated texture, be sure to use mipmaps, or it will look horrible at some distances. Slow framerates in the texture (10 fps) are fine when looking at a sun from far away, but when you get close, you may also want to use a higher framerate. If you don't have a high framerate texture or can't waste the video memory for one, you can use a custom shader to interpolate every other pixel based on the previous and next image.

By changing use of Hue/Saturation/Value inside the shader, you can get results like these, without ever having to modify the texture:

I started with a cheap model from the store so I didn't have to do the animated texture. On the other hand it means I can't share the current prefab, because the texture is purchased.

---

\*Alternatively, you can look into mapping 2D noise on a sphere and use 3D noise for the time dimension, or use 4D noise if you don't want to do the mapping and can spare the performance.

# Answer
> 10 votes
Other then the particale system and halo effects Vadim mentioned you could create your own shader effect. There is some introduction to shaders for Unity and the possibilities are endless.

# Answer
> 2 votes
Try using a Particle System and a halo effect. You could also add a light to the star and have a bloom effect on your camera.

---
Tags: unity, lighting, graphic-effects
---


# Question
Title: Why is my performance so poor when accessing elements in an unordered_map?
I'm trying to implement a component based architecture on a game engine project. Each `GameObject` has an `unordered_map` that holds a pointer to `Component` base class. At this point, I only have one component derived class, which is the `Transform` class. I wanted to implement this component based architecture similar to the Unity's convention: I want to get a component of game object by calling the member template function like `GetComponent<Transform>()`.

Here are the headers:

**Component.h**

```
enum type{
    TRANSFORM   // more will be added later
};

class Component // base class
{
public:
    Component() : _owner(NULL) {}
    virtual ~Component(){}
    static type Type;

protected:
    GameObject* _owner;
};

```

**Transform.h**

```
class Transform : public Component
{
public:
    Transform();
    ~Transform();
    static type Type;

    void Rotate(float deg);

    // to be encapsulated later on
    Vector2D _position;
    float _rotation;
    Vector2D _scale;
};

```

**GameObject.h**

```
class GameObject
{
public:
    GameObject();
    ~GameObject();

    void Update();
    //and more member functions

    template<class T>
    T* GetComponent();
private:
    // some more private members
    unordered_map<type, Component*> _componentList; // only 1 component of each type
};

template<class T>
T* GameObject::GetComponent()
{
    return static_cast<T*>(_componentList[T::Type]);
}

```

---

My initial implementation used `std::vector` for keeping `Component*` and the application ran at 60 fps (I also have a frame rate controller, which just limits the FPS to 60). When I changed to the `unordered_map` for accessing those component pointers, the performance went downhill to 15 FPS.

I only draw two quads and I call `GetComponent<Transform>()` only 6 times per frame at this point, so there is not much going on in the scene.

---

**What I tried?**

I tried to use `const char*`, `std::string`, `type_info` and finally `enum type` as key values for the `unordered_map` but nothing really helps: all implementations got me 15-16 FPS.

What causes this performance issue? How can I isolate the issue?

<sub> I hope I provided enough detail, feel free to ask for more code if necessary </sub>

# Answer
> 2 votes
Turns out, I was doing something really wrong. The problem was in the gameloop where I updated the components.

```
for (auto component : _componentList){
    //   ^ not reference -> lots of ctor/dtor calls -> low fps
    if(component) component->Update();

```

# Answer
> 2 votes
**I suspect your problem is because cache misses sky rocketed once you introduced `unordered_map`..**

Well, storing `vector<Component*>` isn't the most cache friendly strategy, yet when you used unordered\_map, **you introduced another level (or two) of indirection**, `unordered_map` is hash table with array of linked lists, so when you lookup an item, first it needs to hash the key to lookup the linked list, and then search through the list for the component. Also storing pointers for Component, doesn't guarantee the objects are contiguous in memory unless you are using a special kind of memory pools/allocators.

For better in-depth discussion I suggest you read Sean Middleditch Slot Maps and optimization patterns, component design from Game Programming Patterns.

---
Tags: c++, optimization, component-based
---


# Question
Title: How to figure out hidden fields in an .ini file?
I'm not sure if this is the right place to ask this, but I can't think of anywhere else that would fit better.

Fallout 4 has just recently released, and I'm wondering what exactly can I edit in the ini. I know you can add certain things that aren't already present in the ini. For example, to change the FOV:

```
[Display]
fDefaultWorldFOV=100
fDefault1stPersonFOV=100

```

However, how do I figure out what other 'hidden' fields are? In Skyrim, for example, you can change the camera like this:

```
[Camera]
fOverShoulderAddY=0.0000
fOverShoulderPosZ=10.0000
fOverShoulderPosX=0.0000
fOverShoulderCombatAddY=0.0000
fOverShoulderCombatPosZ=10.0000
fOverShoulderCombatPosX=0.0000

```

Surely it's not just trial and error?

# Answer
> 2 votes
Like most reverse-engineering tasks, there isn't necessarily a fool-proof method of accomplishing this.

* In some cases the existence of these features "leak" via customer support (or developer) interactions because they exist to support diagnostics or debugging.
* In some cases, they are discovered through to references in the documentation for modding tools or as references within scripts that can be read with said modding tools.
* Sometimes users can simply guess at their existence based on the fact that a game shares a common engineering lineage with another game that is better understood (Fallout 4, for example, is pretty obviously an iteration of the Skyrim tech).
* Tools like `strings` can be used to scan a file, such as an `.exe`, for bits of data that look like text. This is a fairly reasonable, simple way to poke around for hidden `.ini` settings or command-line arguments, assuming the engine parses them in a straightforward and obvious fashion. Such an approach will general involve a sequence of string comparisons against hard-coded options (like `fOverShoulderCombatAddY` from your example) and will often show up by running `strings`. Looking at the text found around *known* settings may provide some clues about undocumented settings.

The last one is probably the approach you'd take if you were starting from "scratch" trying to dig up any undocumented options. It's not a guaranteed win by any stretch, but it's a nice balance of simplicity and effectiveness that makes a good starting place.

---
Tags: modding, configuration, skyrim-modding
---


# Question
Title: How to pass an interface to Java from Unity code?
First, let me say that this is my first experience with Unity, so the answer may be right under my nose. I've also posted this question on Unity's answers site, but plugin questions don't seem to be as frequently answered there.

I'm trying to create a plugin that allows me to access an SDK from my game. I can call SDK methods just fine using `AndroidJavaObject` and I can pass data to them with no issue. But there are some SDK methods that require an interface to be passed.

For example, my Java function:

```
public void attemptLogin(String username, String password, LoginListener listener);

```

Where `listener`; is a callback interface. I would normally run this code from Java as such:

```
attemptLogin("username", "password", new LoginListener() {
    @Override
    public void onSuccess() {
        //Yay! do some stuff in the game
    }

    @Override
    public void onFailure(int error) {
        //Uh oh, find out what happened based on error
    }
});

```

Is there a way to pass a C# interface through JNI/Unity to my `attemptLogin` function? Or is there a way to create a mimic-ing interface in C# that I can call from inside the Java code (and pass in any kind of parameter)?

Thanks in advance! :)

# Answer
Main Unity selling point is that it is cross platform. What this means for your question is that I would strongly suggest not calling SDK functions directly, but doing as much as possible through Unity provided API's. In short do the authentication using Unity API. This way, you will write connectivity code once, and it will work on all platforms. Unity will take care of the platform differences. In particular look at:

http://docs.unity3d.com/Documentation/Components/net-SocialAPI.html

If you really need to interoperate C# and Java, I am sorry but my answer is lacking on this.
> 1 votes

# Answer
Since Unity 4.2 there is a class called Androidjavaproxy which can do exactly what you are looking for.

This class can implements any Java interface in Unity.
> 1 votes

# Answer
I was confused by your use of the term "interface", since that is a keyword that C# responds to. However, when you described a "callback interface" I realized you're talking about something different: a way for the Java code to call functions in Unity (rather than only the other way around).

This is done using the command UnityPlayer.UnitySendMessage (imported into Java by including Unity's classes.jar file). This command will invoke methods on a named object. So for example, `UnityPlayer.UnitySendMessage("GameObjectName", "MethodName", "Message to send")` would call MethodName() on the object GameObjectName, and pass the message to that method.

To ensure that my custom plugins have an object to send messages to, I usually have my plugin scripts create an object named something like MyPlugin\_instance and use DontDestroyOnLoad() to make sure that object is never removed from the scene. That code looks like:

```
public class TestPlugin : MonoBehaviour {
   private static TestPlugin _instance;
   public static void Initialize() {
      if (_instance != null) {
         Debug.Log("TestPlugin instance was found. Already initialized");
         return;
      }
      Debug.Log("TestPlugin instance not found. Initializing...");
      GameObject owner = new GameObject("TestPlugin_instance");
      _instance = owner.AddComponent<TestPlugin>();
      DontDestroyOnLoad(_instance);
   }
rest of class...

```
> 0 votes

---
Tags: c#, java, android, unity, jni
---


title: Slow tile map rendering

text:
# Question
Title: Slow tile map rendering
I'm having an issue with my tilemap renderer, with small maps (like 40\*40 tiles) it works fine but with maps that have 400\*400 tiles the framerate becomes really slow when I try to move the camera.

Here are my rendering methods

```
/// Renders the map
void Map::Map::render(sf::RenderWindow& window)
{
    for (auto c : m_tiles)
    {
        for (Tile& tile : c)
        {
            m_renderer.render(tile);
        }
    }
}

```

And for the TileRenderer

```
void Renderer::TileRenderer::render(const Map::Tile& tile) const
{
    try
    {
        if (m_previousType != tile.getType())
            m_sprite.setTextureRect(getTypeTextureRect(tile.getType()));

        m_sprite.setPosition(tile.getAbsolutePosition());

        m_renderWindow.draw(m_sprite);
        m_previousType = tile.getType();
    }
    catch (ETileTypeUndefined e)
    {
        Logger::getInstance().log(e.what());
    }
}

```

Any idea to solve that poor framerate ? It doesn't seems to be a memory issue. Visual Studio debugger tells me that external code spend a lot of time in the renderer's render function (calls to sf::RenderWindow::draw(sf::Drawable) I guess).

# Answer
> 2 votes
I think what you're looking for is to draw all of your tiles each frame to a sf::RenderTexture and then render that single object to the screen.

The render texture is stored in an offscreen texture which is great for precomputing a complex static texture (like a level's background from multiple tiles) etc.

Example:

```
// Create a new render-window
sf::RenderWindow window(sf::VideoMode(800, 600), "SFML window");
// Create a new render-texture
sf::RenderTexture texture;
if (!texture.create(500, 500))
    return -1;
// The main loop
while (window.isOpen())
{
   // Event processing
   // ...
   // Clear the whole texture with red color
   texture.clear(sf::Color::Red);
   // Draw stuff to the texture
   texture.draw(sprite);  // sprite is a sf::Sprite
   texture.draw(shape);   // shape is a sf::Shape
   texture.draw(text);    // text is a sf::Text
   // We're done drawing to the texture
   texture.display();
   // Now we start rendering to the window, clear it first
   window.clear();
   // Draw the texture
   sf::Sprite sprite(texture.getTexture());
   window.draw(sprite);
   // End the current frame and display its contents on screen
   window.display();
}

```

# Answer
> 1 votes
You are going to have to embrace level of details. The rendering itself may already be using mipmaps, so the reduction filter will not consume lots of bandwidth to draw sprites that end up being 2x2 on the screen even if its texture is originally 200x200. Your problem comes from too many draw calls !
so you are going to have to make a decision about what could be completely cut out of the render after a certain level of zoom out.
Maybe you don't need terrain details like stones or bushes who knows.
You could also identify all the static parts of your world, and fuse this all together by using DanoThorn's technique of baking them into an impostor. Most complex worlds require layers, so you can bake in layers as necessary. You will need a cache manager to keep baked impostors with a garbage collection technique based on frequency of use. When the camera spans impostors will move out of screen. You can attach a "counter of not-rendered frames" and the highest get de-allocated first when you decide it's time to free memory.
This is all very costly, so you have to decide. Do you need to zoom out so much that you will pay to implement all of this ? or will you cut the feature altogether and be content by limiting the zoom out factor so that your on-screen number of tiles never exceed 5k/10k top ?
Your game, your choice.

---
Tags: tilemap, sfml
---


# Question
Title: How to blur image using glsl shader without squares?
I want to blur image with Gaussian blur algorithm. And I use the following shaders:

Vertex shader

```
attribute vec4 position;
attribute vec4 inputTextureCoordinate;

const int GAUSSIAN_SAMPLES = 9;

uniform float texelWidthOffset;
uniform float texelHeightOffset;

varying vec2 textureCoordinate;
varying vec2 blurCoordinates[GAUSSIAN_SAMPLES];

void main()
{
    gl_Position = position;
    textureCoordinate = inputTextureCoordinate.xy;

    // Calculate the positions for the blur
    int multiplier = 0;
    vec2 blurStep;
   vec2 singleStepOffset = vec2(texelHeightOffset, texelWidthOffset);

    for (int i = 0; i < GAUSSIAN_SAMPLES; i++)
   {
        multiplier = (i - ((GAUSSIAN_SAMPLES - 1) / 2));
       // Blur in x (horizontal)
       blurStep = float(multiplier) * singleStepOffset;
        blurCoordinates[i] = inputTextureCoordinate.xy + blurStep;
    }
}

```

Fragment shader

```
uniform sampler2D inputImageTexture;

const lowp int GAUSSIAN_SAMPLES = 9;

varying highp vec2 textureCoordinate;
varying highp vec2 blurCoordinates[GAUSSIAN_SAMPLES];

void main()
{
    lowp vec3 sum = vec3(0.0);
   lowp vec4 fragColor=texture2D(inputImageTexture,textureCoordinate);

    sum += texture2D(inputImageTexture, blurCoordinates[0]).rgb * 0.05;
    sum += texture2D(inputImageTexture, blurCoordinates[1]).rgb * 0.09;
    sum += texture2D(inputImageTexture, blurCoordinates[2]).rgb * 0.12;
    sum += texture2D(inputImageTexture, blurCoordinates[3]).rgb * 0.15;
    sum += texture2D(inputImageTexture, blurCoordinates[4]).rgb * 0.18;
    sum += texture2D(inputImageTexture, blurCoordinates[5]).rgb * 0.15;
    sum += texture2D(inputImageTexture, blurCoordinates[6]).rgb * 0.12;
    sum += texture2D(inputImageTexture, blurCoordinates[7]).rgb * 0.09;
    sum += texture2D(inputImageTexture, blurCoordinates[8]).rgb * 0.05;

    gl_FragColor = vec4(sum,fragColor.a);
}

```

This produces an image with a lot of blurred squares.

But. How to get something like this?

# Answer
The kind of artefacts you're seeing - the squares - are often caused by not sampling some pixels within the blur range. Since you're only using 9 samples, and your blur is quite soft, this is likely the case here. You're effectively blurring a lower-resolution image, but the next fragment over is blurring a slightly different lower-resolution image, and so on.

There are many approaches to blurring, but since you specifically mention Gaussian blur, I present two options without changing the blurring algorithm:

1. Use more samples within your blur range, so that you're not skipping over pixels in the original image; or
2. Downsample the image first, so that, at the resolution you're blurring, you're not skipping pixels.
> 1 votes

---
Tags: opengl, glsl, blur
---


title: Quaternion rotation problems

text:
# Question
Title: Quaternion rotation problems
I want to rotate my model and I have X and Y rotations. Here is my code:

```
D3DXQUATERNION q, qrotation;

D3DXQuaternionRotationAxis(&q, &D3DXVECTOR3(1.0f, 0.0f, 0.0f), m_matrixRotX*0.0174532925f);
qrotation = q;

D3DXQuaternionRotationAxis(&q, &D3DXVECTOR3(0.0f, 1.0f, 0.0f), m_matrixRotY*0.0174532925f);
qrotation *= q;

D3DXMatrixRotationQuaternion(&worldMatrix, &qrotation);

```

But I get the same gimbal lock. What is the problem?

EDIT 1: OK, but how can I rotate my object if I have X Y and Z rotations?

EDIT 2: Here is all my code:

```
m_matrixRotY += (float)m_mouseStateX;
m_matrixRotX += (float)m_mouseStateY;
if (m_matrixRotY >= 360.0f)m_matrixRotY = 0.0f;
if (m_matrixRotX >= 360.0f)m_matrixRotX = 0.0f;

D3DXQuaternionRotationYawPitchRoll(&qrotation, m_matrixRotY*0.0174532925f, m_matrixRotX*0.0174532925f, 0.0f);

D3DXMatrixRotationQuaternion(&worldMatrix, &qrotation);

```

I want to rotate my object in world static XYZ axis (world orientation not local orientation).
Each frame I get mouse x y states and add them to total rotation. Is it wrong that I am counting total rotation and then creating the quaternion from it?

NOTE: `m_mouseStateX = current_mouse_state - previous_mouse_state`

# Answer
"Is it wrong that I am counting *total rotation* and then creating \[a\] quaternion from it?"

**Yes, because rotations do not combine like simple addition.**

(In mathematical terms, rotations in three dimensions are not commutative)

Here's an example you can do with any old mug. Turn it 90 degrees on the vertical axis, then flip it over away from you (finish drinking your coffee before this step), then turn it another 90 degrees on the vertical. Hypothetically, you've now turned it 180 degrees on the vertical axis and 180 degrees on the horizontal, right?

But if you do all 180 degrees of vertical axis rotation at once and then the horizontal, you don't get the same result.

So, you can't model a rotation as a running total of each incremental rotation step's angles. As soon as you have more than one axis in play, the result of the "total" rotation will tend to diverge from your intuitive expectations for each incremental step. This is most pronounced in gimbal lock, when two of your incremental rotation axes become the same, but it creeps in throughout.

The solution is to separate the concepts of your current orientation from the rotation you want to apply to it.

* You can store your current orientation as a quaternion or a matrix (though quaternions have some additional nice properties like being compact and less prone to accumulated rounding errors / easier to correct).
* Then compute the change in rotation you want to apply as a separate quaternion or matrix.
* Finally, multiply these two together to update your current orientation, getting the result of "starting from this orientation, apply this rotation at the end":

```
newOrientation = rotationChange * currentOrientation;

```

(Order matters here too: assuming you're using a multiplication convention where vectors go on the right, this says "apply the rotation change relative to worldspace, after currentOrientation has been applied" - flipping the multiplication order says "apply the rotation change relative to the object's local axes / before currentOrientation has been applied")

There are a couple of ways to apply this strategy to your case:

*Fix #1: Accumulate changes every frame*

Each frame, you calculate an incremental rotation from the mouse movement since the previous frame, and construct a new quaternion from these angles. Because the angles aren't being totalled over several frames they stay small and (mostly) well-behaved. Multiply this change by your currentOrientation to update it. Each incremental rotation step is performed relative to the current displayed orientation of the object.

*Fix #2: Compute rotation for the net mouse movement.*

Another approach is to store the mouse position and object orientation at the beginning of the rotation move (eg. when the user presses the mouse button over your object), and then each frame compute a rotation that takes the original mouse position to the new mouse position. Compose this with your currentOrientation, but save it to a new variable that you use for display only, keeping currentOrientation the same to repeat the process next frame. Only at the end of the rotation move (eg. when the user releases the mouse button) do you save the composed display rotation into the current object orientation variable. This can reduce drift from summing up many small/noisy cursor movements, which can make it fussy to get back to the original orientation.

Note that neither of these approaches is typically suitable out of the box for controlling a camera, since they don't give any special meaning to the up direction out of the box. Without some up correction, a camera will tend to roll about its viewing axis over time - see the "mostly" call-out above.
> 5 votes

---
Tags: directx, rotation, quaternion
---


title: Making knockback in c++

text:
# Question
Title: Making knockback in c++
I want to implement a "knockback" in my 2D game, but I have no idea how to do it. I've found some tutorials on google but nothing help. (My knowledge about math is a little limited when we're talking about Cartesian plane)

Well let's just figure out, I have the player and the monster on my map (2 vectors) and when I touch the monster, BOOOM, I get "knockbacked" at the OPPOSITE direction (not left, right, top or bottom) that I touch him.

I have the following code on my project:

CollisionManager.cpp

```
CollisionManager::CollisionManager()
{
}

CollisionManager::~CollisionManager()
{
}

bool CollisionManager::checkCollisionWithWall(SDL_Rect box, std::vector<Tile*> tiles)
{
    return touchesWall(box, tiles);
}

void CollisionManager::checkCollisionEnemy(Player * player, GameObject * enemy)
{
    if (enemy->type() == std::string("Enemy"))
    {
        return;
    }
    if (SDL_HasIntersection(&player->getCollisionBox(), &enemy->getCollisionBox()))
    {
        player->collision(enemy);
    }
}

```

The player's collision function (almost nothing here):

```
void Player::collision(GameObject* collisionObject)
{
    isKnockbacking = true;
    hp -= 2;

}

```

Ahh and my moving function is inherited from my Entity class:

```
void Entity::checkTileCollision(std::vector<Tile*> tiles)
{
    if (isKnockbacking == false) {
        //Move the dot left or right
        v2DPosition.m_x += v2DVelocity.m_x;
        collisionBox.x = v2DPosition.m_x;

        //If the dot collided or went too far to the left or right
        if ((v2DPosition.m_x < 0) ||
        (v2DPosition.m_x + 18 > Game::Instance()->getScreenWidth()) ||
        collisionManager->checkCollisionWithWall(collisionBox, tiles))
        {
            //Move back
            v2DPosition.m_x -= v2DVelocity.m_x;
            collisionBox.x = v2DPosition.m_x;
        }

        //Move the dot up or down
        v2DPosition.m_y += v2DVelocity.m_y;
        collisionBox.y = v2DPosition.m_y;

        //If the dot collided or went too far up or down
        if ((v2DPosition.m_y < 0) ||
        (v2DPosition.m_y + 18 > Game::Instance()->getScreenHeight()) ||
        collisionManager->checkCollisionWithWall(collisionBox, tiles))
        {
            //Move back
            v2DPosition.m_y -= v2DVelocity.m_y;
            collisionBox.y = v2DPosition.m_y;
        }
    }
}

```

I've followed LazyFoo, SDL Game Development book and some other tutorials on YouTube to make it.

If I need to be more specific, just tell me.

# Answer
To move an object in reverse simply multiply it's velocity by -1, the infrastructure seems to be in place so modifying the collision function should suffice :

```
void Player::collision(GameObject* collisionObject)
{
     isKnockbacking = true;
     hp -= 2;
     v2DPosition += v2DVelocity * -1 * someScalar
}

```

someScalar could be another number to increase the distance moved.
> 2 votes

---
Tags: c++, sdl2
---


title: Websocket Scalability w/ Player Skills

text:
# Question
Title: Websocket Scalability w/ Player Skills
About 8 months ago, I asked this question, and received a lot of valuable information from the community.

I have switched to `nodejs`, since then, and am finishing up my game. I am deeply concerned about networking issues pertaining to the usage of WebSocket data being sent through my current architecture; especially since my game uses an authoritarian server, and doesn't utilize peer to peer.

My game is a Diablo 2 inspired action RPG. As we know, for action RPGs, players utilize a lot of skills, and if games are instanced based, all players in the game need to be notified.

---

I am worried about scalability. Here is an example:

Shooting a fireball has a 0.5 second cool-down. This is how the data is sent:

* **Client** \[Skill id, Skill rotation\] -\> Server
* *Server* \[Checks cooldown, notify's players skill is being used\]
* **Client** \[If fireball hits monster, send attack signal\] -\> Server
* *Server* \[Checks cooldown, player's range to mob, calculates damage, etc & spits out damage numbers to all players\]

---

All this happens in less than 1 second. The WebSocket server is not even sending out the Monster AI update packets to do damage to the player, nor the monster's fireballs. So now, basically double the amount of data is being sent through the WebSocket and to all player's in a game. It gets worse; imagine if 20 players are online attacking monsters. My `nodejs` server will be on fire.

This method is not even 100% cheat proof, as I'm waiting for the fireball to hit the monster on the client-side to send the attack signal, instead of doing all that on the server. The problem is, I would have to be running a physics engine on the server, which would bog down `nodejs`'s event loop even more. I'm using the P2 Physics engine from Phaser, and not simple AABB; otherwise, I could just check for collisions server-side.

To close, when a player moves around the map, the server notifys everyone else in the same game. The same goes for when a player drops an item, or when loot is generated from a monster. I just feel like I'm clogging my WebSocket server up, and am doing something wrong with all this data being sent across the pipe.

---

So with all this said,

* Am I worrying too much about the amount of data being sent across WebSockets?
* Is this data being sent normal for a games that utilizes an authoritarian server?
* Would a Redis Pub Sub system be an ideal solution to my problems?

# Answer
Send as few packets as possible, with as much detail in them as needed, without impacting on the players' experience of the game.

Do not send every entity's movement to every player. "Activate" entities for players based on whether they're within a certain range (sight + 20%, perhaps) and inform them about actions only then.

As for the attack function, it's bad because it doesn't sync very well. Client needs to tell the server that it fired a fireball at X time. If that's within Y, server will accept it as legitimate and tell nearby players that at X time, a fireball is moving in Z direction, so that they can re-create the exact trajectory of the fireball.
> 3 votes

---
Tags: game-design, architecture, websocket
---


title: What is CC_Time in cocos2dx?

text:
# Question
Title: What is CC_Time in cocos2dx?
I was following this tutorial to understand using custom shaders : http://www.cocos2d-x.org/wiki/User\_Tutorial-Realistic\_looking\_animated\_real-time\_clouds

I understand that CC\_Time is Cocos2d-x built-in uniform vec4-object that holds different versions of time in it's components. Can someone please explain or point me to a resource so that I can understand what are its different components. Thanks.

# Answer
The source file CCGLProgram.cpp located in cocos2d\cocos\renderer provides the answer:

```
  // This doesn't give the most accurate global time value.
        // Cocos2D doesn't store a high precision time value, so this will have to do.
        // Getting Mach time per frame per shader using time could be extremely expensive.
        float time = _director->getTotalFrames() * _director->getAnimationInterval();

        setUniformLocationWith4f(_builtInUniforms[GLProgram::UNIFORM_TIME], time/10.0, time, time*2, time*4);
        setUniformLocationWith4f(_builtInUniforms[GLProgram::UNIFORM_SIN_TIME], time/8.0, time/4.0, time/2.0, sinf(time));
        setUniformLocationWith4f(_builtInUniforms[GLProgram::UNIFORM_COS_TIME], time/8.0, time/4.0, time/2.0, cosf(time));

```
> 2 votes

---
Tags: cocos2d-x
---


# Question
Title: Can USB device be aware of in-game death?
I intend to design a peripheral that changes state (in this case, LED color) in response to software state (ideally, player death in-game). I have adequate experience in manufacturing design, but not on the driver/software side of things. Before I try to contract out the driver/software need, I'd like an objective opinion from those who know (GameDev SE) whether or not this is even possible.

***Potential Use-case:*** *player in Source-engine game dies \>\> peripheral lighting changes from green to red for duration of dead period. Player respawns, lighting returns to green state.*

Are there hooks in modern engines that would allow a USB peripheral to be aware of this sort of specific game condition? We don't want to require customers to install and run a background process to monitor state. That's way too intrusive.

# Answer
> 2 votes
The PS4 controller has a lightbar. It is used in (for example) Towerfall Ascension to indicate player id (red for player one, blue for player 2 etc.) and Transistor (mimics the swords speech). Those games are made in C#/Monogame. I also understood that Unity, provided you have the PS4 license, can access the lightbar. So there is definitely a possibility to do what you're looking for.

If I understand correctly, you plan to design your own device. USB is a bidirectional so you can send a datastream to a device. So it is up to you to design the device to accept a stream and interpret the meaning of the data being sent. So in your example, the code should sent an RGBA code to the USB device. The Device reads the value and sets the color (RGB) and uses the Alpha as brightness value.

There are many libraries out there for languages to send and receive data to a USB device. So a Google query may point you to the language of your choice.

---
Tags: game-state
---


title: Manager Game Logic

text:
# Question
Title: Manager Game Logic
I'm currently trying to figure out a way where I can achieve the following;

**Pre-Calculate the game** \- This will predetermine any event / interaction between the players.

**Simulate the calculation** \- Over a 2 minute period it will show what happens at the pre calculated time.

The interactions will be determined by a class for position. Where certain positions are able to interact with other positions and randomised/calculated evens occur. However, my main problem is trying to think of where to start. I'm pretty good when it comes to programming. However, I've never designed an engine that is capable of doing this.

So I'm sat here wondering what the first step is, how do I determine a logical outcome i.e every player interacting in the first 10 seconds is a no go, how do I even determine a timeframe for their interaction when it's pre-calculated? I would probably have an easier time just running the functions for 2 minutes and relying on methods to determine the outcomes. However, I want to pre calculate it.

Can anyone give me a few pointers so I can actually get my teeth stuck into this?

Thanks.

# Answer
Are you looking to build something like Frozen Synapse http://www.frozensynapse.com/ ? The game queues the player movements and actions, in the precalc phase the game 'plays' these actions. And finally shows the results where the player can manipulate time to see the action.

There are two strategies I can currently think of. It depends on the scale and complexity your game needs which one suits best.

**Option one**: In the simplest way one could accelerate time (1s passes in 1ms). The results of each 'tick' is stored in a frame-snapshot. The queue for a gameobject could be cleared if the gameobject is destroyed or prevented from continuing (for example another object locks a door the player planned to pass). The snapshot could then include particles for bullet impacts or grenade explosions where random shrapnel may destroy objects or cause near misses.

The result is a series of frames that can be played out in the 'result phase'. One could also do interpolations for slowmotion or other effects. Since you have frames the player can analyse by replaying or slide the time back and forth. The 'frames' can be optimised to only include deltas.

**Option two**: Depending on your game idea, you may queue player actions and calculate outcomes based on timing. For example, if a player moves towards a point, calculate the distance and speed and determine the point in time the player will arrive. This may be harder to do, but it may help depending on what you're planning to do.

Compare this to a simulation of a solar system, where everything happens on a larger timescale so accelerated time would still cause the simulation to run for quite some time.

In this case only store a list of events that happen at timestamps so you can replay the simulation using the calculations and spawn the events at the given timestamps so the replay is always the same.
> 0 votes

---
Tags: logic
---


title: Determine if Plane is seen by Camera

text:
# Question
Title: Determine if Plane is seen by Camera
If I have an arbitrary plane (center and normal) or a quad (center, normal and width and height) and a camera (frustum, projection & view matrix, etc). Then how would I go about calculating if the plane/quad is visible to the camera?

Additionally how would I calculate to check if it's the front or the back of the plane/quad that is visible to the camera?

---

My first idea was to do some ray vs plane intersection, but then I realized that it of course wan't going to work!

```
bool plane_visible = false;
const float denom = plane_normal.dot(camera.getLook());

if (abs(denom) > 0.0001f)
{
    const float t = (plane_position - camera.getPosition()).dot(plane_normal) / denom;

    plane_visible = (t >= 0.0f);
}

```

---

Using the dot product of the plane/quads normal and the camera's look direction. Will give wrong results!

For instance, use the following image as an example! A dot product will tell me that I'm looking at the face that's facing outwards of the frustum. Though the face that I'm actually looking on is face facing inwards the frustum/towards the camera!

# Answer
> 2 votes
For determining if the plane is 'looking' towards or away from the camera, you already have some of the code. The dot product between the camera "looking" and the plane normal will be \> 0 if they are facing each other, and \< 0 if looking away.

As for detecting if the plane is within the view frustum, you could try calculating bounds over the entire view from camera to max\_distance and checking if any of the vertices in the plane are in the volume?

# Answer
> 1 votes
The robust solution is to build a frustum of planes symbolising the camera and check the plane against all of them.

The first part involves creating the frustum which can be a bit tricky if you're lacking in basic linear algebra;

Start with transposing the matrix you're using to transform from worldspace to projected space, the reason for this is because we're going to transform Next, create the 6 projected normals and multiply them by the cameras transpose view matrix:

1. *nNear* = (0,0,1,1) X *tvm*
2. *nFar* = (0,0,-1,1) X *tvm*
3. *nRight* = (-1,0,0,1) X *tvm*
4. *nLeft* = (1,0,0,1) X *tvm*
5. *nTop* = (-1,0,0,1) X *tvm*
6. *nBottom* = (1,0,0,1) X *tvm*

I'm assuming directx coordinates here. This gives us the frustum planes normals in worldspace and lets us proceed into the next step.

For the second part I'll assume the plane is of limited size, infinite planes are a bit different.

Divide the plane into four points and for each point draw a vector from the point to each frustum plane and check if the dot product of that vector and the frustum planes normal is greater or equal to zero,

*v0* · *pn* \>= 0 where *v0* = point-\>plane

Unless all points result in less then zero and are behind any of the frustums plane the plane will be visible to the camera.

Thirdly to find out the direction of the plane use the dot product of the normal and the vector from the plane to the viewpoint, any point on the plane will suffice.

*v1* · *pn* \>= 0 where *v1* = plane-\>eye

---
Tags: collision-detection, mathematics, intersection
---


# Question
Title: Is there a way to get what pixel is being processed within the fragment shader?
In OpenGL, a fragment shader goes through each pixel, right? So is it possible (within the shader itself) to get what pixel it is processing and color each specific pixel?

# Answer
> 4 votes
There is, in the fragment shader, a variable called gl\_FragCoord. This contains the coordinates of the currently executing fragment shader.

Note that (by default) a pixel at pixel coordinates (x,y) will have gl\_FragCoordinates of (x+0.5,y+0.5)

# Answer
> 1 votes
Not too sure what you mean, but you can get the current pixel coordinate in the fragment shader by using gl\_FragCoord! This is considerably easier than interpolation, as mentioned in the other answer.

Here are more details: https://www.opengl.org/sdk/docs/man/html/gl\_FragCoord.xhtml

# Answer
> -1 votes
you can attach u and v coordinates for each vertex and then fragment shader interpolates those u and v coordinates for each pixel. UV coordinates are used to calculate where to sample from textures but they can be also used directly for math.

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


# Question
Title: Is it ok to use copyrighted assets for educational purposes?
A friend and I were wanting to create a Pokemon battle simulator in our mobile development class as our final project but are worried whether or not it would be permissible under "Fair Use" for educational purposes. We have no plans on doing anything with the game after the class and our presentation of the app, we just wanted to try to clone some very basic parts of it onto Android.

Edit: I'm located in the US.

# Answer
Users of this site are mainly game developers, not lawyers, so we're not able to give you legal advice.

However, I have been told that "Fair Use is a *defense*," not a classification. You don't get to label your creation "fair use" - rather, if an IP holder tries to sue you, you can *try to claim* fair use as a defense. That still means going to court most likely, which is probably something you don't want to risk.

Consider using game content that's offered freely under a permissive licence, like what you can find at opengameart.org, game-icons.net, or Kenney.nl. That way you can be confident you're in the clear, and your game project will look more original as a bonus. :)

And if it's for a school project, your instructors will probably appreciate you using content with appropriate permission - since using other people's assets without permission is not typically a practice that schools want to teach or reward. By creating or seeking out content you have permission to use, you're demonstrating resourcefulness and a respect for fellow creators.
> 29 votes

# Answer
Considering that there is a tag in this site named "licensing" and another named "copyright", I understand you bringing up such question to here before thinking of hiring a lawyer. But as the other two answers have already stressed, it's important to have it clear that *most people here are probably not well equipped to give you the accurate technical answer you are looking for*.

That said, if I understood your question correctly, you are thinking of using Pokemon characters for a school project. So, in similar situations when I was at university, it was frequent that people asked their institutions for counseling on that kind of matters. That is the first thing you should do. Educational institutions often have people with specific expertise on the specific law details related to the educational world - for instance copyright for educational uses and fair use (see more about fair use here, besides reading the basic wikipedia description).

In fact, there are often flexibilities when the use is purely educational - i.e. presenting a project in a class. However, the two important details are the meaning of what is "educational purpose" and whether you plan to take assets directly from the original source. For instance, posting online a learning game project, made for learning purposes, but which uses trademarked assets, not only is known to be a problem, but Nintendo has already fought that battle and took down a fan-made non-profit learning project: http://ca.ign.com/articles/2015/03/31/nintendo-takes-down-super-mario-64-hd-fan-project

But again, you should think of asking you own institution - specially because laws vary by country. Besides, maybe that is a fairly good question for https://law.stackexchange.com/. A similar question was already asked there, but from a Denmark-based poster and didn't got answers due to being non-specific. Maybe you can try it with further details there: https://law.stackexchange.com/questions/5226/use-material-without-permission-for-educational-purposes

Lastly, in case you feel unsure or get negative answers by your institution, what you can always do is try to simulate the combat system from Pokemon games but with your own characters and present it as such. It means, you can explain that you are going to present an application of the ideas behind how you understand the combat system and, for that, you are going to illustrate the problem using you own "creatures".
> 14 votes

# Answer
It's quite simple: If you do not hold copyright to a work, you are not allowed to reproduce it. Since using it in class would be reproduction, you are not allowed to do it under US copyright law.

The one exception is "fair use" (well, there are others, but if they applied you'd probably know about it). It is very clearly defined and there is a plethora of court cases covering specific instances. You should peruse this information and decide for yourself (better yet, ask a lawyer) whether your work is fair use or not. We cannot decide for you, and even if we wanted to, we are not supposed to give legal advice on this site.

That said, your case does not sound like fair use. Speaking very broadly, fair use exists so that you can't abuse copyright to stop people from talking *about* your work - it is not a magic loophole that lets you ignore copyright whenever you want simply because you are doing it for "educational purposes". Yes, copyright holders can prevent you from using their work, even if you are not deriving any income - perhaps they are worried you will hurt their image, or that you will cause them to lose the copyright, or they think they can force you to pay for it - the reason is irrelevant, the point is that the law gives them the right. If this was not the case, every infringer would start claiming they are somehow doing it for educational purposes and completely sidestep the spirit of copyright law (in fact, back in the day software pirates used to claim their cracks were for "educational purposes only" - I don't believe that worked too well, since the practice hasn't persisted, while the lawsuits have).

Incidentally, Wikipedia has a section on common misconceptions which include:

> "Any use that seems fair is fair use."
>
> "Noncommercial use is always fair."

Note that both statements are false.
> 8 votes

# Answer
tl;dr: No, it's not.

Reproducing content you don't have a license for to reproduce is not allowed by *copyright* law. Fair use *might* save your bacon here. You probably don't want to rely on that. Do you really want to take the risk to be sued where you can try to defend your work as transformative and/or educational, and have the judge/jury determine whether the portion of the work you used stands in proportion to how transformative your use of the copyrighted material is? I wouldn't want to bet $50 on the outcome of that case. Would you want to bet statutory damages of up to $30.000,- per work on it?

Aside from copyright law, you would also tangle with trademark law. The name Pokemon, and (many of) the individual Pokemon are trademarks. Your use of those trademarks may also fall faul of trademark infringement.

Nintendo has been known to actively pursue their copyright and trademarks. See for example http://arstechnica.com/tech-policy/2015/08/pokemons-copyright-lawyers-wipe-out-themed-pax-pre-party/

Summing up:

* You don't have a license for this use, so in principle you're not allowed to do this
* You might be able to get away with a fair use defense if you're sued
* Apart from possibly violating copyright law, you may also be violating trademark law.
* Nintendo is known to actively litigate against this kind of use
* You probably don't want to be in this situation at all
> 2 votes

---
Tags: copyright, education
---


# Question
Title: Tracking launch errors for your game with a simple c++ app
I am trying to create a simple app to track launch errors for my game. The idea is to launch a c++ program, that in turn launches the main game .EXE file with CreateProcess(). The c++ app then proceeds to wait untill the process finishes and shows an error report to the user, if the error happened. This is how I implemented this:

```
#include <windows.h>
#include <iostream>
#include <string>
using namespace std;

int main()
{
    // additional information
    STARTUPINFO si;
    PROCESS_INFORMATION pi;

    // set the size of the structures
    ZeroMemory(&si, sizeof(si));
    si.cb = sizeof(si);
    ZeroMemory(&pi, sizeof(pi));

    const string appName = "MAIN.exe";
    const string appLocation = "";

    // start the program up
    BOOL result = CreateProcess((appLocation + appName).c_str(),   // the path ".." <- перейти вверх "\\" <- относительный путь.
        NULL,        // Command line
        NULL,           // Process handle not inheritable
        NULL,           // Thread handle not inheritable
        FALSE,          // Set handle inheritance to FALSE
        0,              // No creation flags
        NULL,           // Use parent's environment block
        NULL,           // Use parent's starting directory
        &si,            // Pointer to si structure
        &pi);           // Pointer to PROCESS_INFORMATION structure

    if (!result)
    {
        MessageBox(HWND_DESKTOP, ("Could not locate " + appName + "! Please reinstall the game!").c_str(), "Error!", MB_OK);

        // We failed.
        return FALSE;
    }
    else
    {
        // Successfully created the process.  Wait for it to finish.
        WaitForSingleObject(pi.hProcess, INFINITE);

        DWORD exitCode = NULL;
        // Get the exit code.
        result = GetExitCodeProcess(pi.hProcess, &exitCode);

        // Close process and thread handles.
        CloseHandle(pi.hProcess);
        CloseHandle(pi.hThread);

        if (!result)
        {
            // Could not get exit code.
            MessageBox(HWND_DESKTOP, "ERROR!", "Error!", MB_OK);
            return FALSE;
        }
        else if (exitCode != 259 && exitCode != 2)
        {
            if (exitCode == 1)
                MessageBox(HWND_DESKTOP, "ERROR!", "Error!", MB_OK);
            else
            {
                string errorString = to_string(exitCode);
                LPCSTR errorText = errorString.c_str();
                MessageBox(HWND_DESKTOP, errorText, "Launch error!", MB_OK);
            }
        }

        // We succeeded.
        return TRUE;
    }

    //MessageBox(HWND_DESKTOP, "Text here", "Text here", MB_OK);
    return 0;
}

```

From my humble tests I did not see any performance decrease, however, the c++ process is constantly sitting in the background and I wonder if there might be any problems with I that I should know about. Maybe there is a safer/easier way to implement this?

**UPDATE:** Just to clarify here are the reasons why I need this app (alongside trying to track errors internaly, which I already do):

I am developing on c# and XNA 4.0 for .Net Framework 4.5.1. And just that setup can lead to several issues:

1)The user might not have XNA 4.0 redist installed;

2)The user might have Windows 7 with vanila .Net 4.0 and not 4.5.1;

3)The user might have Windows XP which I do not support (due to .Net target 4.5.1);

4)The user might have a GPU which does not support DX 10, (a requirenment for XNA 4.0).

But in most of those cases the app will simply crash on startup, and from what I read, there is no way to catch an error internaly as they happen at an assembly level.

# Answer
> 1 votes
On a modern computer one more idle process in the background would barely be noticeable especially since you use a WaitForSingleObject.

I do however question the usage of a second process for retroactive compatability checking, if you're that concerned parts might missing then package the game with the proper redistros so you always know they're there.

Or just leave the responibility with the end user to have a proper enviroment, you can't be expected to nanny on them about everything, if a player tries to run it on an Apple II they can't be surprised when it crashes.

---
Tags: c++
---


# Question
Title: how to naturally rotate a ball according to its velocity on a surface, a wall
I develop a game on cocos2d-x cpp. There is a ball sprite in my game. I move the ball on a surface(wall) via touch events but it can't naturally rotate according to its velocity.

if i use ballSprite-\>runAction(..) in update(float dt) method then it doesn't rotate.

i use following code:

```
void GameLayer::updateBall(float dt)
{
  float deltaRotateX = 360.0f * _ballVelocityX;
  _ballSprite->setRotation(90.0f- CC_RADIANS_TO_DEGREES(deltaRotateX));
}

```

But the ball doesn't naturally rotate. it discretely rotate.
it can't naturally rotate according to its velocity.

Thanks.

# Answer
Edit:

Here is some math

```
Circ = radius * 2 * 3.14

dx = ball_speed * dt

```

to get deltaAngle `a` lets solve `a/dx=(2*3.14)/circ`

```
a = (2*3.14*dx)/circ

```

sobstituting `circ = radius * 2 * 3.14`

we get

`a = dx/radius`

so delta angle belongs to speed , dt and radius

putting this stuff into love2d we get

```
function ent:update(dt)
    local dx = ent.speed*dt
    local alpha = dx / (ent.radius )
    self.x = self.x + dx    --update position
    ent.rot=ent.rot +  alpha --update rotation
end

```

follows a test example:

Finaly , adding acceleration :

```
function ent:update(dt)
    ent.speed = ent.speed + ent.accel *dt
    local dx = ent.speed*dt
    local alpha = dx / (ent.radius )
    self.x = self.x + dx    --update position
    ent.rot=ent.rot +  alpha --update rotation
end

```

we get
> 3 votes

---
Tags: sprites, cocos2d-x, rotate
---


# Question
Title: Check whether a game object is inside the boundary
I'm developing a small children game similar to Paperama. Here the player can scale rotate and move the object anywhere in the screen and the player should fit it in the boundary. I'm okay with everything (scale, move, rotate etc..) but I couldn't think of a way how to measure the percentage where the target object is inside the boundary object. Here is a graphical representation of what I want to achieve.

I tried comparing vectors and positions but it's so complex and inefficient for symmetrical objects where multiple positions are acceptable to fill the void.

Thanks in advance! :)

# Answer
> 3 votes
What if you did this by lining up specific points instead of the percentage of the object.

What I mean is to match each vertex. For a polygon matching all vertexes with an appropriate vertex to some variable degree of success will read as equal positions.

# Answer
> 0 votes
You could try Boolean polygon intersections, or polygon-polygon clipping. Both can be looked up easily, thus I'm not going to talk about their implementation. IMO polygon-polygon clipping is easier though.

The algorithm is as follows: First compute the area of the target polygon. Next clip (or intersect) the user-handled polygon by the target polygon, that is the target polygon is the clipping polygon, and the other polygon is the clipped polygon. Compute the area of the polygon returned by the above operation. If it is equal to the area of the target polygon, it is a complete fit. The percentage is the above area divided by target polygon area * 100.

# Answer
> 0 votes
I think you're approching this from the wrong angle, you don't really need to check if an object is inside another object. You just need to check if an objects scale, position and rotation matches a set target and average the percentage of each category.

Calculating a score could be something like this quick pseudocode:

* dist% = max(0, DISTANCESCOREBASE - dist(obj.pos,target.pos))/100
* scale% = max(0, 1-abs(target.scale-obj.scale))
* rot% = 1-(totalAngle(target.rotation, obj.rotation))/(PI/2)
* tot% = (dist% + scale% + rot% ) / 3

You'll have to refine the algorithms for the exact scoring-system you want but hopefully this can set you on your way.

# Answer
> 0 votes
There is a struct named "Bounds" in Unity, which allows you to define "areas" in the worldspace, which can later be used for position comparision.

Here are the steps for you to follow:

1. Get the object's bounds from either collider or renderer (they are usually same).
2. Move the center of bounds to the area you want to check.
3. Use Contains boolean to find out if the center of your gameobject is inside that area - using center should be enough for approximate calculations.

**Note:** If you want absolute results, compare centers of extents and corners one by one with the corresponding point on bounds.

Here is the API referance for Bounds: http://docs.unity3d.com/ScriptReference/Bounds.html

---
Tags: c#, game-design, unity
---


# Question
Title: p2.js body position is NaN when spawned inside of each other
I'm working on a project for which I need a physics engine. At the moment I'm playing around with p2.js but I'm running into a problem:

When I try to create multiple bodies (circles and/or boxes) which overlap the positions are set to NaN as soon as world.step() is called. The bodies have a mass of 5 and are dynamic.

In very rare occasions it does actually work. How can I make sure it works every time? Do I have to wait for the bodies to be initialized?

4 circles before the simulation starts, once world.step is called the positions of these circles is NaN:

```
var world = new p2.World({
    gravity: [0, 9.82]
});
function PhysicsBody(type, x, y, widthOrRadius, height) {
    this.body = new p2.Body({
        mass: 5,
        position: [x, y],
    });
    this.type = type;
    if (this.type == 'rectangle') {
        this.shape = new p2.Box({ width: widthOrRadius, height: height });
    }
    else if (this.type == 'circle') {
        this.shape = new p2.Circle({ radius: widthOrRadius });
    }
    this.body.addShape(this.shape);
    world.addBody(this.body);
}
var bod1 = new PhysicsBody('circle', 0, 0, 32);
var bod2 = new PhysicsBody('circle', 10, 0, 32);

```

# Answer
> 0 votes
The code seem to run fine. See this JSFiddle: http://jsfiddle.net/w5dthnaw/

How do you call world.step() ? Perhaps some strange value got passed to it. You can call it in the following ways:

1. `world.step(dt)` where dt is the number of seconds for a tick, for example `1/60`.
2. `world.step(dt, elapsedTime, maxSubSteps);`, for example `world.step(1/60, 1/60, 10);`

All numbers you pass to step() must be nonzero.

---
Tags: javascript, physics-engine
---


# Question
Title: How i can play movie in unity by script(android platform)?
my script is correct in pc platform but when i switch on android platform i have compiler error cs0246, why i can not export my apk file. how i can play movie in unity android platform by other way?

```
     public class NewBehaviourScript : MonoBehaviour {
     public MovieTexture myMovie;

     void Start()
     {
         myMovie.Play();
     }

     void OnGUI()
     {
         GUI.DrawTexture(new Rect(0, 0, Screen.width, Screen.height), myMovie);
     }
 }

```

# Answer
I ran into the same issue with a cross platform port I needed to do with WebGL, WebPlayer, and other platforms that are unable to play videos in Unity. Unfortunately, the process is too involved to write your own implementation for each platform in Unity. Though it is possible.

After researching and going through the many assets for movie playback in Unity (I also needed to support video scrubbing), I came upon the AVI video playback plugin for Unity, which has ample support and works on every platform regardless of your settings. The greatest part of the plugin is it gives way more granular support than Unity's MovieTextures. It supports rewind, frame-by-frame step backward/forward, pause, fast forward, and looping. The only major drawback is that your videos have to be in the plugin's AVI format, and the plugin itself is slightly expensive (currently $49). I'd recommend waiting for it to be on sale, though the amount of time and effort you'll save will definitely be worth the price.

Here's the Asset Store link: https://www.assetstore.unity3d.com/en/#!/content/15580

Here's the forum thread about the plugin as well: http://forum.unity3d.com/threads/movieplayer-for-unity-plays-mjpeg.229458/
> 2 votes

# Answer
`MovieTexture` is desktop only. You can't use these on mobile platforms. That includes Windows Phone, iOS and Android (at least).

There are some plugins on the Asset Store that do this on the various platforms, but not all of them have been updated to work with Unity 5. Tread carefully when trying to solve this problem.
> 0 votes

---
Tags: unity
---


# Question
Title: How do I write a shader that lights up when objects are near a surface?
In this *Overwatch* gameplay video, the character's shield lights up white in areas that are near other objects' geometry.

Note the white edges on the blue shield, near the floor, walls and pillar.

I believe the shield has its own model and the effect is done with a shader, but I'm lost trying to figure how to translate the concept of "nearness" to shader programming.

# Answer
> 29 votes
A general outline:

1. Create a *depth map* of your scene without the shield. You can get this effectively for free, since transparent objects are often rendered in a later pass anyway. Otherwise, you can create the depth map by rendering the scene sans shield onto an RTT with a depth shader.
2. Render your scene normally, pass the depth map to your shield shader.
3. In the shader, compute the difference in scene depth from the shield fragment's depth, and use that difference to modify the fragment colour.

# Demo

I wrote a simple WebGL demo of that.

## Line by line

Let's go over the fragment shader code in detail:

```
float solidsDepth = texture2D(depthMap, gl_FragCoord.xy / dims).r;

```

Sample the depth map at every fragment. Remember to divide by your viewport dimensions to convert your fragment from screen space \[0, width/height\] to normalized \[0.0, 1.0\] coordinates. At this point, if you simply set the fragment color to the sampled depth map pixel, it would look like this:

The depth map is grayscale, so you can get the value from any channel (I used `r` here).

```
float solidsDiff = 1.0 - smoothstep(
    zNear,
    zFar,
    gl_FragCoord.z / gl_FragCoord.w
  ) - solidsDepth;

```

You can then use that depth sample to find the difference between the scene depth and the depth of the shield fragment. Remember to normalize your depth also, to take it from \[zNear, zFar\] (the near and far planes of your camera) to \[0.0, 1.0\]. `smoothstep` does this nicely. The `1.0 -` is to invert the value such that `solidsDiff` is 1.0 when the difference is the maximum (zFar - zNear) and 0.0 at the minimum (0.0).

Note that I've assumed `solidsDepth` was already normalized in the depth shader that created the depth map.

```
float alpha = 0.3 + max(0.0, 1.0 - log(100.0 * (solidsDiff - 0.005) + 1.0));

```

You can then modify the alpha channel of your shield depending on the depth difference. Here we start at a minimum alpha of `0.3`, then create a nice sharp increase in alpha as we near `0.0` difference.

The `- 0.005` offset just adds a white margin to make the "intersection" thicker. Try modifying it!

```
gl_FragColor = vec4(vec3(1.0), alpha);

```

And finally, apply that alpha to your fragment color.

---

# Enhancements

You could make a curved shield, add plasma for an "energy shield" look (demo) or explore effects with just the intersections showing (demo).

The sky Your graphics card is the limit!

# Answer
> 5 votes
It's just using the depth map. It renders the world then renders the shield and takes a difference between the shield's rendered z value and the depth buffer z value to tint the pixel more white.

---
Tags: fragment-shader, graphic-effects, intersection
---


title: Draw lines in game scene

text:
# Question
Title: Draw lines in game scene
I want to do game for Android that allows draw lines. These lines should be **physic object** at the same time.

I am good at Unity3D and I tried in Unity3D. But it is not supported.

What engine should I use? Are there anybody has an idea about which engine is used in game like this?

# Answer
> 1 votes
I prefer you to use then libgdx or cocos2d, but these are just for rendering. You can also make your own renderer for android.
**Important point is that you use a physics system like Box2d.** There you can define your line as a body and simulate in your box2d world.

Why box2d?
-Because, it's easy to implement on your android game project and it's a good physics engine, which has lots of documentations on the web.

---
Tags: android
---


# Question
Title: Resource management with Lua integration
I have a questions about how to better implement resource management when integrating with Lua. I have an entity system that has gameplay logic done in Lua. One of the design points was that I wanted to simplify the script code as much as possible. To that end, things like sprites and sounds are generic "resource" handles (currently just integers) that are referenced, e.g.

```
self.image = resource("/foo/baz.png")
self.hurtSound = resource("/foo/bar.mp3")
...
play(self.hurtSound)

```

This works well, but I don't know when (from the native code side) it is safe to delete a resource because a Lua object could be holding on to it. I don't have "levels" where there are convenient "load/unload" points, so I'm wondering how I might safely achieve this without making the Lua code have to do anything complicated with resources. Essentially, I want garbage collection for unused resources. I'm not a Lua expert, so I'm sure there is some feature of the language that could implement such a behavior.

My requirement is that I should be able to copy handles around safely, e.g. do not need to call `resource()` twice to do some kind of "obvious" reference counting. Similarly, if `resource()` is called *n* times, but at least 1 reference is valid, then the resource should not be unloaded; i.e. simply because one value was \__gc'd, doesn't mean that all of them should be invalidated.

The native code implements the resource cache and simply needs to be informed when it would be *safe* to unload something (even if it doesn't unload it immediately).

Any Lua experts ran into similar sort of situations? What did you do to solve this problem?

# Answer
I always make resources be referenced by userdata so I can: Know what I'm accessing in the native code side (I could use a pointer and some kind of mambo jambo to do that but that is subject to another topic) and add it to the registry and in that way creating a reference to it that the garbage collector won't touch.

Refer to Lua registry section

Hope this helps.
> 1 votes

---
Tags: scripting, lua, resource-management
---


# Question
Title: How can I exclude my enemies from spawning in certain zones generated at random?
I have a code where I randomly generate enemy spawn position, but I want to exclude some areas since it's colliding with some sprites it shouldn't collide with.

This is the code where I generate the random points from where the enemy is coming from (from top,down, left and right):

```
int z = ran.nextInt(4);
int r1 = ran.nextInt(GameControl.CAMARA_WIDTH+1);
int r2 = ran.nextInt(GameControl.CAMARA_WIDTH+ 1);
int r3 = ran.nextInt(GameControl.CAMARA_HEIGHT+ 1);
int r4 = ran.nextInt(ControlJuego.CAMARA_HEIGHT+ 1);

```

I set the position of the enemy with the random variable:

```
if (var == 1) {
   newEnemy.getSpriteEnemy().setPosition(0, r1);
} else if (var == 2) {
   newEnemy.getSpriteEnemy().setPosition(GameControl.CAMARA_WIDTH, r2);
} else if (var == 3) {
   newEnemy.getSpriteEnemy().setPosition(r3, 0);
} else if (var == 4) {
   newEnemy.getSpriteEnemy().setPosition(r4, GameControl.CAMARA_HEIGHT);
 }

```

Later I move the enemies to the center of the screen.

An image for better vistualizatio of the problem:

I don't want my enemies to ever spawn behind any of the corner sprites or to collide with any of the corner sprites before entering the screen. How can I solve this problem? How can I exclude this areas?

Thanks in advance for the help.

# Answer
> 3 votes
If your corner sprites are as simple as you show here, you can avoid collisions by changing how you generate the random positions.

E.g. for the top, you currently generate a random int between 0 and `width` (well, ignoring that you seem to have transposed width and height in some spots). So suppose you have `yellowWidth`, the width of the yellow object at the top border, and `greenWidth`, the width of the green object similarly.

So the space between yellow and green is `width - (yellowWidth + greenWidth)`. If you generate your top value with `ran.nextInt((GameControl.CAMARA_WIDTH + 1) - (yellowWidth + greenWidth));` and add `yellowWidth`, it should fall between the two.

Given that your enemies aren't points but areas, you'll need to add a buffer to the sizes of yellowWidth and greenWidth. E.g. if you have `enemyWidth`, the final calculation would be something like:

`int r1 = yellowWidth + enemyWidth/2 + ran.nextInt((GameControl.CAMARA_WIDTH + 1) - (yellowWidth + greenWidth + enemyWidth));`

Just do the same with the other sides, switching to height and other-colored sprites as needed.

# Answer
> 1 votes
Chris is right about the first method (distribution shaping).

Now the second (roulette): that's the method I implemented in my game.
full source here: http://sourceforge.net/projects/extremecarnage

```
bool HostilesManager::SpawnHostile(SPAWN_POSITION_en spawnPos, int isprite)
{
    // create a new car
    CarsManager::CarAcsor newcar = ChiefManager::GetCarsManager()->Push(spriteFiles[isprite]);
    hostiles.push_front(newcar);
    // *hostiles.front().pcar and *newcar are aliases
    const int bordw = ChiefManager::GetTerrainManager()->GetBorderWidth();
    const Vector2i terrSize = ChiefManager::GetTerrainManager()->GetSize();

    // spawn ennemys on the far right position only
    if (spawnPos == SP_LEVEL_RIGHT)
    {
        // random vertically, but 500 pixel from the left-end
        newcar->SetPosition(terrSize.x + 500,
                            bordw +
                            rnd.Get(terrSize.y - bordw * 2));
    }
    else // MIDDLE
    {
        Rect rc(newcar->rect);

        // same tech than the terrain generator
        int security = 0;
        bool intersect = true;
        const int max_repeats = terrSize.x / rc.w + terrSize.y / rc.h;   // fast heuristic
        while (intersect && security < max_repeats) // util it fits
        {
            // random generation here
            rc.pos.x = bordw + 50 + rnd.Get(terrSize.x - rc.w - (bordw << 1));
            rc.pos.y = bordw + rnd.Get(terrSize.y - rc.h - (bordw << 1));
            // verify intersection with decors objects:
            intersect = ChiefManager::GetCollisionsAndProbing()->IntersectRect(rc);
            ++security;
        }
        if (security == max_repeats)    // that didnt work
        {
            hostiles.pop_front();
            return false;
        }
        newcar->SetPosition(rc.pos.x,
                            rc.pos.y);
    }
    // set the target
    hostiles.front().target.x = 0;
    hostiles.front().target.y = 64 + rnd.Get(terrSize.y - 128);
    // random start direction :
    newcar->angle = rnd.Get(359);

    newcar->GiveWeapon(game_vars::g_minigun_id);
    newcar->SetIAClass(iaClassID_simple, ChiefManager::GetIAManager());
    BOOST_ASSERT(newcar->GetIAClassID() == iaClassID_simple);

    if (isprite > 0)    // that's for stronger ennemies
    {
        newcar->health = 200;
        newcar->SetIAClass(iaClassID_strong, ChiefManager::GetIAManager());
        BOOST_ASSERT(newcar->GetIAClassID() == iaClassID_strong);

        newcar->GiveWeapon(game_vars::g_heavymg_id);   // and more dangerous
    }

    return true;
}

```

ok so you get more than you need but the crucial part is the russian roulette loop that retries when a collision happens. as you can see, it ensures termination by using an arbitrary maximum limit on iterations.

---
Tags: java, android, game-mechanics, andengine, android-studio
---


# Question
Title: Blender FBX exports to Unity3D have incomplete animation sequences
Using Blender, I have rigged and animated this model with this attack action.

I exported this model to an FBX format and imported the said FBX file into my Unity3D project. However, when I imported it, I noticed that the animation sequence is incomplete:

As you can see, the sword does not animate correctly and remains unmoved in its original position.

In Blender, the sword and scabbard are animated in Pose mode with IK and other constraints. However, as I understand it, FBX bakes these constraints into the animation, so I'm not sure if that causes the issue.

**Why is the sword not animating correctly? How do I fix this so that the Unity animation is 100% faithful to the Blender animation?**

# Answer
What's causing the problem is setting the `Animation Type` of the rig to `Humanoid`. I guess this causes the animation to lose its mapping to non-humanoid related bones.

What fixes the issue is setting the `Animation Type` to `Generic` like so:
> 0 votes

---
Tags: unity, animation, blender, rigging
---