# Question
Title: Unity editor PropertyDrawer custom button
I has a PropertyDrawer, everything goes fine, except one feature: I can't figure out how to add button and I use checkbox instead

```
using UnityEngine;
using UnityEditor;
using System.Collections;

[CustomPropertyDrawer (typeof (InteractiveObject))]
class InteractiveObjectPropertyDrawer : PropertyDrawer {

public override void OnGUI (Rect position, SerializedProperty property, GUIContent label) {

    EditorGUI.BeginProperty (position, label, property);
    position = EditorGUI.PrefixLabel (position, GUIUtility.GetControlID (FocusType.Passive), label);
    var indent = EditorGUI.indentLevel;
    EditorGUI.indentLevel = 0;
    Rect colorRect = new Rect (position.x, position.y, 40, position.height);
    Rect unitRect = new Rect (position.x + 50, position.y, 90, position.height);
    Rect nameRect = new Rect (position.x + 150, position.y, position.width - 150, position.height);

    EditorGUI.BeginChangeCheck();
    EditorGUI.PropertyField (colorRect, property.FindPropertyRelative ("show"), GUIContent.none);
    if (EditorGUI.EndChangeCheck() ) {
        RenderSettings.skybox.SetColor("_highlight", property.FindPropertyRelative ("id").colorValue);
    }

    EditorGUI.PropertyField (unitRect, property.FindPropertyRelative ("name"), GUIContent.none);
    EditorGUI.PropertyField (nameRect, property.FindPropertyRelative ("name"), GUIContent.none);
    EditorGUI.indentLevel = indent;
    EditorGUI.EndProperty ();
}
}

```

How I can add button there?

# Answer
> 4 votes
I've found how to add button to PropertyDrawer here

code:

```
 if (GUI.Button(text, "show")) {
     ...
 }

```

and result:

---
Tags: unity
---


# Question
Title: Get a Jump normal gravity based on Attractor Points, lines or Quad placed in the Level Design (in a Mario galaxy like gravity)
I have an algorithme to find.

I have a player in a 3D space on a random planet. My goal is to have an oriented gravity toward my planet. And when I jump: Find the right normal direction.

BUT I can't just get the normal of collision, here is why:

As you can see, the gravity must NOT be depending on the Normals collision, but must depend on this gravity point, line or quad I place in the Level Design

(see the 2 cube at the bottom of the planet, the jump of the player must NOT depend on the normal of collision (orange arrow), but must depend on the red arrow)

I have to find out depending on the position of the player, if the gravity will depend on the closest Gravity Point attractor, OR the closest line, OR the quad's normal direction. Here a real screenShot exemple:

I want this algorithm to be dynamic enough to be able to place points, lines or quad in the LevelDesign as I want. This algorithm will be called at each frame when the player is in the air.

And here an exemple of the most complexe shape I would like to manage:

Here I have a white point alone, a cyan line, and 2 quad (or 4 triangles)

# Answer
> 0 votes
Ok, Here is my first approach:

* loop through all attractor points, and save the closest one from the player.
* then, loop through all lines, and find for each line its nearest point from the player, with an algo:

At the end, select the closest point found.

* Finaly, if I have quad, get the closest point from the quad to the player

And when everything is done, find the nearest point found.

I'm afraid it's too much computation, if someone has a better approach I'm a taker.

**EDIT**: computation done and optimized, result in video (source in description of the video) https://youtu.be/bTRlOGiAM7w and here the process of LD creation: https://youtu.be/Q-Ivelnkew8

---
Tags: 3d, mathematics, algorithm, geometry
---


title: Mouse coordinate conversion Libgdx

text:
# Question
Title: Mouse coordinate conversion Libgdx
I have a camera:

```
//Map is a my object that wrapper of TiledMap class

```

In the create method:

```
this.renderer=new OrthogonalTiledMapRenderer(this.map.getMap();
this.camera=new OrthographicCamera();
this.camera.translate(map.getMapPixelWidth()/2, map.getMapPixelHeight()/2);
this.camera.update();
view=new StretchViewport(map.getMapPixelWidth(),map.getMapPixelHeight(), camera);
batch=new SpriteBatch();
In the update method:

```

this.renderer.setView(this.camera); this.renderer.render(); this.camera.update(); batch.setProjectionMatrix(camera.combined);

```
ArrayList<RectangleMapObject> layer=this.getObjectsFromLayer("collision");//find collision layers
//Mouse coordinates
int x=Gdx.input.getX();
int y=Gdx.input.getY();
Vector3 coordinateScreen=new Vector3(x,y,0);
Vector3 coordinateWorld=camera.unproject(coordinateScreen);
Rectangle rectMouse=new Rectangle(coordinateWorld.x,coordinateWorld.y,20,20);
for(RectangleMapObject rect: layer)
if(Intersector.intersectRectangles(rectMouse, rect.getRectangle(), rectMouse)){
                    System.out.println("COLLISION MOUSE-MAPOBJECT ");}

public ArrayList<RectangleMapObject> getObjectsFromLayer(String layerName){

        ArrayList<RectangleMapObject> array=new ArrayList<RectangleMapObject>();

        MapObjects og=this.map.getMap().getLayers().get(layerName).getObjects();

        for(MapObject object : og)
            if (object instanceof RectangleMapObject)
                array.add(((RectangleMapObject) object));
        return array;
}

```

My problem is that the collision between mouse and mapobject never occurs Also if I click on the area where stands the MapObject. I think it is a problem of conversion of the coordinates of the mouse. Thank you for your time.

# Answer
> 2 votes
You need to unproject your coordinates using the camera.

```
worldCoordinates = camera.unproject(new Vector3(screenX, screenY, 0));

```

Just use your camera to unproject a Vector3. If screenX and screenY in this example is Gdx.input.getX and Gdx.input.getY, is the mouse input on your screen and when you unproject it you can use that to hit something that is where you clicked.

# Answer
> 0 votes
If i understand this correctly then you take some data and then as part of the rendering process you distort the postition of that data ...

```
this.camera=new OrthographicCamera();
this.camera.translate(map.getMapPixelWidth()/2, map.getMapPixelHeight()/2);
this.camera.update();
view=new StretchViewport(map.getMapPixelWidth(),map.getMapPixelHeight(), camera);

```

Then you want to be able to pick on it.

Essentially you need to figure out how to do that distortion in reverse or use a raycast to determine the vertex you hit.

Essentially the logic goes something like this ... Figure out a line that goes through the mouse cursor in 3d space in the direction that the camera is facing. Set a start and end point for that line. Raycast using the start and end points. the ray will tell you the first hit vertex.

I'm not familiar with the api you are using but this should at least point you in the right direction.

It looks like you have code for determining the mouse position in the 3d world you now need to create a near and far position for your line then give those to a ray to determine what you clicked on.

Something like this may help you ...

https://stackoverflow.com/questions/24988852/raycasting-in-libgdx-3d

# Answer
> 0 votes
Tried to make it works with camera.unproject method, resulting in unsuccessful results, I decided to write a raw method myself, here we go :

```
@Override
public boolean mouseMoved(int mouseX, int mouseY) {
    OrthographicCamera camera = gameScreen.getCamera();

    float cameraX = camera.position.x - camera.viewportWidth / 2 * camera.zoom;

    float cameraWidth = camera.viewportWidth * camera.zoom;

    float mouseRelativeX = (float) mouseX / (float) Gdx.graphics.getWidth();

    float addRelativeX = cameraWidth * mouseRelativeX;

    float relativeX = cameraX + addRelativeX;

    float cameraY = camera.position.y - camera.viewportHeight / 2 * camera.zoom;

    float cameraHeight = camera.viewportHeight * camera.zoom;

    float mouseRelativeY = (float) -mouseY / (float) Gdx.graphics.getHeight();

    float addRelativeY = cameraHeight * mouseRelativeY + cameraHeight;

    float relativeY = cameraY + addRelativeY;

    MouseMoveEventManager.getInstance()
            .fireMouseMoved(new MouseMoveEvent(relativeX, relativeY, mouseX, Gdx.graphics.getHeight() - mouseY));
    return true;
}

```

---
Tags: java, libgdx, coordinates
---


# Question
Title: How to use This Keyword and using iterators to call class methods?
I've been over this for a long time, I can't seem to understand what is wrong, is the use of the this keyword right? I want to add the instance of the class that is being created to the vector 'allEntities' in the constructor, or am I not using the iterators right? I'm very new to c++ and programming in general so all help is appreciated.

GameObject.h

```
class GameObject {

public:
    GameObject(const char* texturesheet, SDL_Renderer* ren, int x, int y, int _maxHp, int _currentHp, int _strength);
    ~GameObject();

    static std::vector<GameObject> allEntities;

    void update();
    void Render();
    void movement(const char* coord, bool positive);
    int getMaxHp();
    void addMaxHp(int change);
    int getCurrentHp();
    void setCurrentHp(int change);
    int getStrength();
    void changeStrength(int change);
    void attack(GameObject &other);
    int getX() { return x; };
    int getY() { return y; };
    void setDirectionFacing(char direction) { directionFacing = direction; };
    char getDirectionFacing() { return directionFacing; };
private:

    int x;
    int y;
    int strength;
    int maxHp;
    int currentHp;
    char directionFacing;

    SDL_Texture* objectTexture;
    SDL_Rect srcRect, destRect;
    SDL_Renderer* renderer;

};

```

GameObject.cpp

```
GameObject::GameObject(const char* texturesheet, SDL_Renderer* ren, int xx, int yy, int _maxHp, int _currentHp, int _strength)
{
    allEntities.push_back(*this);
    renderer = ren;
    objectTexture = textureCreator::loadTexture(texturesheet, ren);
    GameObject::maxHp = _maxHp;
    GameObject::currentHp = _currentHp;
    changeStrength(_strength);
    x = xx;
    y = yy;
}
GameObject::~GameObject()
{

}

void GameObject::update()
{

    srcRect.h = 48;
    srcRect.w = 48;
    srcRect.x = 0;
    srcRect.y = 0;

    destRect.x = x;
    destRect.y = y;
    destRect.w = srcRect.w * 1.5;
    destRect.h = srcRect.h * 1.5;
}

void GameObject::movement(const char* coord, bool positive)
{

    if (coord == "x" && positive == true)
    {
        y -= 4;
        setDirectionFacing('w');
        std::cout << 'w' << std::endl;
    };
    if (coord == "x" && positive == false)
    {
        y += 4;
        setDirectionFacing('s');
        std::cout << 's' << std::endl;
    };
    if (coord == "y" && positive == true)
    {
        x += 4;
        setDirectionFacing('d');
        std::cout << 'd' << std::endl;
    };
    if (coord == "y" && positive == false)
    {
        x -= 4;
        setDirectionFacing('a');
        std::cout << 'a' << std::endl;

    };

}

void GameObject::Render()
{
    SDL_RenderCopy(renderer, objectTexture, &srcRect, &destRect);
}

int GameObject::getCurrentHp() { return currentHp; };

int GameObject::getMaxHp() { return maxHp; };

void GameObject::setCurrentHp(int change) { currentHp += change; };

void GameObject::addMaxHp(int change) { maxHp += change; };

int GameObject::getStrength() { return strength; }

void GameObject::changeStrength(int change) { strength += change; }

void GameObject::attack(GameObject &other)
{

}

```

game.cpp

```
GameObject* player;
player = new GameObject("player.png", renderer, 10 , 10, 10,  10, 2);
    for (std::vector<GameObject>::iterator it = GameObject::allEntities.begin(); it != GameObject::allEntities.end(); it++) {
        int hp = it->getCurrentHp();
        std::cout << hp << std::endl;
    }

```

I expect to print out the hp value which is 10, but instead it prints 0 instead.

Also I need this vector so when the player attacks, it checks every entity and sees if it is in the area of the attack in a for loop, is there any better way to do this?

# Answer
> 2 votes
These two lines in the constructor do not do what you think they do:

```
GameObject::maxHp = _maxHp;
GameObject::currentHp = _currentHp;

```

In the constructor, as in any class method, you access the class variables directly, like so:

```
maxHp = _maxHp;
currentHp = _currentHp;

```

Most compilers would probably catch this as a warning, and especially while learning I would recommend turning up your compiler warnings as high as they go, just on the general principle of getting a feeling for what the compiler is doing.

You need one more change because this line creates a **shallow copy** of the object being constructed and adds that **copy** to the allEntities vector, and it does that copy *before any member variables have been set*.

```
allEntities.push_back(*this);

```

I think that if you move that line after all the variables have been set then you're done. With a note: what you probably want to do later is make allEntities a vector of **pointers** to created objects and not a full copy, but since you're very new that can come later.

Also, for problems like this there's a technique called Rubber Duck Debugging that is very helpful https://en.wikipedia.org/wiki/Rubber\_duck\_debugging

---
Tags: c++, oop
---


# Question
Title: Diamond Square Algorithm - How to fix horrible diamond shaped artefacts and spikes?
I was attempting to follow this article explaining the implementation of a wrapping version of the diamond square algorithm.

I tried running it with dimensions of 128x128 and a "feature size" of 16, like in the article, but the resultant terrain is this monstrosity:

I read through past questions on this topic and am aware that there can be some issues with somewhat noticeable diamond or square shaped artifacts when using this algorithm, but this is definitely beyond that.

Here is my code:

```
private float GetHeightAtPoint(int x, int z)
{
    if (x < 0) { x = width + x; }
    if (z < 0) { z = height + z; }

    return fractal[(x % (width - 1)) + (z % (height - 1)) * width];
}

private void SetHeightAtPoint(int x, int z, float value)
{
    if (x < 0) { x = width + x; }
    if (z < 0) { z = height + z; }

    fractal[(x % (width - 1)) + (z % (height - 1)) * width] = value;
}

private void SquareStep(int x, int z, int size, float value)
{
    int halfSize = size / 2;

    float a = GetHeightAtPoint(x - halfSize, z - halfSize);
    float b = GetHeightAtPoint(x + halfSize, z - halfSize);
    float c = GetHeightAtPoint(x - halfSize, z + halfSize);
    float d = GetHeightAtPoint(x + halfSize, z + halfSize);

    float meanHeight = (a + b + c + d) / 4.0f;
    float adjustedHeight = meanHeight + value;

    SetHeightAtPoint(x, z, adjustedHeight);
}

private void DiamondStep(int x, int z, int size, float value)
{
    int halfSize = size / 2;

    float a = GetHeightAtPoint(x - halfSize, z - halfSize);
    float b = GetHeightAtPoint(x + halfSize, z - halfSize);
    float c = GetHeightAtPoint(x - halfSize, z + halfSize);
    float d = GetHeightAtPoint(x + halfSize, z + halfSize);

    float meanHeight = (a + b + c + d) / 4.0f;
    float adjustedHeight = meanHeight + value;

    SetHeightAtPoint(x, z, adjustedHeight);
}

private void DiamondSquare(int stepSize, float scale)
{
    int halfStep = stepSize / 2;
    for (int z = halfStep; z < height + halfStep; z += stepSize)
    {
        for (int x = halfStep; x < width + halfStep; x += stepSize)
        {
            SquareStep(x, z, stepSize, Random.Range(-1.0f, 1.0f) * scale);
        }
    }

    for (int z = 0; z < height; z += stepSize)
    {
        for (int x = 0; x < width; x += stepSize)
        {
            DiamondStep(x + halfStep, z, stepSize, Random.Range(-1.0f, 1.0f) * scale);
            DiamondStep(x, z + halfStep, stepSize, Random.Range(-1.0f, 1.0f) * scale);
        }
    }
}

/*
 * Generate a fractal map using diamond square algorithm and store in fractal[]
 */
private void GenerateFractal(int featureSize)
{
    fractal = new float[width * height];

    for (int z = 0; z < height; z += featureSize)
    {
        for (int x = 0; x < height; x += featureSize)
        {
            SetHeightAtPoint(x, z, Random.Range(0.0f, maxHeight));
        }
    }

    int sampleSize = featureSize;
    float randomScale = 1.0f;

    while (sampleSize > 1)
    {
        DiamondSquare(sampleSize, randomScale);

        sampleSize = sampleSize / 2;
        randomScale = randomScale / 2.0f;
    }
}

```

Could anyone give me any guidance here? One thing that was a bit suspect was that I had to make slightly different wrapping array access functions in order to make this run as I was getting negative values. You can see that my functions have the if statements checking for negatives, whereas the original implementation does not.

Thanks in advance

# Answer
> 4 votes
The main issue is your code for DiamondStep is the same as for SquareStep. As a result, it is populating the uninitialized target point using other uninitialized points. It should be using points in a diamond around the target:

```
float a = GetHeightAtPoint(x - halfSize, z);
float b = GetHeightAtPoint(x + halfSize, z);
float c = GetHeightAtPoint(x, z + halfSize);
float d = GetHeightAtPoint(x, z - halfSize);

```

As a minor issue, the article you linked wraps the coordinates using `x & (width - 1)`. This assumes `width` is a power of 2, and works for positive or negative coordinates. If you want to do the same with the modulus operator it should be `x % width`, not `x % (width - 1)`.

---
Tags: algorithm, procedural-generation, terrain
---


title: Game Engine Renderer Architecture

text:
# Question
Title: Game Engine Renderer Architecture
I'm currently building a game engine renderer but I got stuck when I had to separate engine and client code.

I had been following OpenGL tutorials to learn about buffer creation, etc so all my code for rendering was in a single place and was tied to that specific example.

I created a VBO, a IBO/EBO, a VAO and a shader, then set the `VertexAttribPointers` for that VAO (and VBO layout) and rendered it. Everything worked fine.

Then I created C++ abstractions for all of those "objects" and recreated the example; that also worked.

So what I wanted to do know is to have each of my game objects create a VBO and an IBO, create a global VAO in my renderer (since all my objects share the same layout) submit them to the renderer and have them rendered. But I discovered I could not setup vertex attribute pointers without having a VBO bound (I have none bound since they get created after the renderer starts up).

**So my question is:**

How should I set up the VAOs and VBOs for the renderer to work?

I read in some places that what I have to do is to set up few VBOs (so as to have little binding calls and draw calls) and then store every object inside that one giant buffer. (Of course while still creating different buffers for objects with different vertex layouts and different shaders). I also know that to do that you have to allocate a big buffer and then call buffer sub data to store the new data inside that one buffer, but what I don't know is how to store that data if it must be offset (because of its position in the world and how to update its position)

**So if that's the case my next question is:**

How do I create one giant buffer and then store different objects inside that one giant buffer and then render those stored objects with their respective positions? (For both static and dynamic objects).

# Answer
> 0 votes
In my engine I create a VAO and VBO for each model (not each object) I have in my game.

Aggregating models into a single VBO seems unnecessary to me. Binding a VBO is not an expensive operation.

Having too many drawcalls, on the other hand, can be expensive, so if you draw many instances of a single model you should look into instanced rendering.

The idea of instanced rendering is that some vertex attributes are shared between instances, like the regular stuff: vertex, normal, uv, etc. But in the same VBO, you also put per-instance data, typically a transformation matrix, one for each instance.

For instanced rendering, look into glVertexAttribDivisor, glDrawArraysInstanced (or glDrawElementsInstanced.)

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


# Question
Title: How much slower is it to draw on "half pixels"?
I've noticed that games like Diep.io are using floating decimal points for thin stroke lines on the grid. I have even tried this myself, by adding `0.5` to all of the positions for the grid lines to make the lines more thin.

I heard it from a friend that drawing on half pixels causes the GPU to do more work to smooth it out, like anti-aliasing. I am really trying to make my game look nice, by making the most smoothest lines as I can. How much slower is it really, and should I use it in an online competitive 2D game using Canvas?

# Answer
Since the GPU is already used to rendering on subpixels, it's not really an issue there. Also, no, it doesn't do anti-aliasing by default and no, it doesn't need to smooth it out.

On CPUs however, drawing a pixel at a corner of 4 actual ones can certainly lead to some performance issues, but it's still very minimal (even in the worst case scenario you're only drawing an extra border around the polygons).

If you still want to test it, there are built-in profilers in most modern browsers. In chrome it's F12 \> performance/profiling \> hit the red button and stop after a while
> 2 votes

---
Tags: rendering, graphics, floating-point
---


# Question
Title: endless Thorn (deal damage when taking damage) effect
I'm developing a card-based combat system for my game. (imagine a game like Magic The Gathering, or Hearthstone, or any CCG) I was writing the logic of the effect that I call "thorn". If a player has the thorn effect, everytime he got struck with some damage, he deals damage to his attacker.

I already had an event raised everytime a character is being damaged, so it seemed logical to me to use it.

the thorn effect starts to listen to the onDamage event and then it deals its damage.

The issue with this solution is that it can create an endless chain of thorn effect, if both parties have the thorn effect.

Player 1 attacks player 2.

Player 2 raises onDamage event.

player 2 resolves its thorn effect, and it deals damage to player 1.

player 1 raises onDamage event.

player 1 resolves its thorn effect, and it deals damage to player 2.

and it goes on.

There are many solutions I can think of, but none of them are actually satisfying to me. Any suggestions? Thanks for the answers

# Answer
> 5 votes
One option is to create a damage type called Reaction Damage, and construct your rules so that Reaction Damage does not trigger Reaction Damage.

The Thorn effect then becomes "When another player deals non-Reaction Damage to you, deal X Reaction Damage to that player"

This way you can cleanly separate initial effects from follow-up effects, and strictly restrict the depth of recursion for this class of abilities.

Once this is a keyword that you use consistently, it opens up new avenues for other cards to interact with these reaction abilities, like...

* Careful Strike: take no Reaction Damage this turn
* Counter Master: whenever you deal Reaction Damage, double the amount of Reaction Damage you deal
* Reactive Vampire: heal 1 health point any time you deal Reaction Damage

---

Another strategy is to use diminishing returns, so each invocation of Thorn or similar effects does less damage than the last (eg. by subtraction or division), and eventually the recursion "bottoms-out" at zero.

This can be more brittle than the hard recursion limit described above though. If there are enough damage-boosting/vulnerability effects in play, those could potentially counteract the diminishing returns and get us back into an infinite regress.

Usually in such a case one player or the other would eventually be defeated, and we could terminate the loop that way (halt all card effect events emitted by defeated players), but again there could be exotic effects in play that somehow interfere with this soft limit (eg. a zombie effect that lets the player finish one last turn after being reduced to 0 health).

So I think the hard limit on recursion is more robust to other comboing effects.

# Answer
> 2 votes
It’s a feature! More accurately, it’s a measure of protection via mutually assured destruction. If one of you attacks the other, you both immediately die. Instead, you must both continue to build up your army while waiting to find a way to remove the other’s thorn effect.

---
Tags: game-design, software-engineering
---


# Question
Title: Synchronized non-local CharacterController's velocity is stuck at the last movement in Unity3D
I have `CharacterControllers` as players in my **multiplayer** scene, and they got `NetworkTransforms` attached, with

* `Sync Mode = Sync Character Controller`.

When I **stop running** with my character, my character **stops on the other players' screens as well**.

I've got `MonoBehaviours` attached to them, where I control the character's animations based on `characterController.velocity`.

**The problem is this:**

The **animations won't stop** because `characterController.velocity` is the **same as it was when I was running**.

This only occurs on **non-local** characters, because the local player got `Local Player Authority` checked, so its controller isn't synced *from* the server but *to* the server.

Why and how could I fix this? Thanks in advance!

# Answer
I think this is an issue originating from **Unity's network code**, so after a few failed tries, I just fixed it by **calculating the velocity locally**.
> 0 votes

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


# Question
Title: Fix Pixel Shader "Stage did not run. No output"
I'm trying to set up a minimal D3D11 renderer but fail to get the pixel shader stage to run. The available answers here or the ones I found through Google couldn't help me, unfortunately.

Using Visual Studio's Graphics Debugger I could verify that my vertices are set correctly and the vertex shader also runs as expected. The debug layer doesn't report any issues either. As a test I disabled depth testing, stencil testing and backface culling as shown below with no changes.

I made sure that the viewport is set correctly as well as this seems to be a common source of this problem.

At this moment I can't think of any other cause for this issue and would be happy about any advice of what else to look out for.

* Disable depth/stencil test:

```
D3D11_DEPTH_STENCIL_DESC dsstate_desc = {};
dsstate_desc.DepthEnable             = false;
dsstate_desc.StencilEnable           = false;
dsstate_desc.DepthFunc               = D3D11_COMPARISON_ALWAYS;
dsstate_desc.DepthWriteMask          = D3D11_DEPTH_WRITE_MASK_ALL;
dsstate_desc.BackFace.StencilFailOp  = D3D11_STENCIL_OP_KEEP;
dsstate_desc.BackFace.StencilPassOp  = D3D11_STENCIL_OP_KEEP;
dsstate_desc.BackFace.StencilFunc    = D3D11_COMPARISON_ALWAYS;
dsstate_desc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
dsstate_desc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
dsstate_desc.FrontFace.StencilFunc   = D3D11_COMPARISON_ALWAYS;
d3d11device->CreateDepthStencilState(&ds_state, &this->ds_state);
d3d11context->OMSetDepthStencilState(this->ds_state, 0);

```
* Disable backface culling:

```
D3D11_RASTERIZER_DESC rasterizer_desc = {};
rasterizer_desc.AntialiasedLineEnable = false;
rasterizer_desc.CullMode              = D3D11_CULL_NONE;
rasterizer_desc.DepthBias             = 0;
rasterizer_desc.DepthBiasClamp        = 0.0f;
rasterizer_desc.DepthClipEnable       = false;
rasterizer_desc.FillMode              = D3D11_FILL_SOLID;
rasterizer_desc.FrontCounterClockwise = true;
rasterizer_desc.MultisampleEnable     = false;
rasterizer_desc.ScissorEnable         = false;
rasterizer_desc.SlopeScaledDepthBias  = 0.0f;
d3d11device->CreateRasterizerState(&rasterizer_desc, &this->rasterizer_state);
d3d11context->RSSetState(this->rasterizer_state);

```
* Pipeline view in debugger:

* Vertex shader transformation:

* Vertex shader:

```
struct VertexIn
{
    float3 position : POSITION;
    float3 normal   : NORMAL;
    float4 color    : COLOR;
};

struct VertexOut
{
    float4 color    : COLOR;
    float4 position : SV_POSITION;
};

VertexOut main(VertexIn i)
{
    VertexOut o;
    o.position = float4(i.position, 1.0f);
    o.color = i.color;
    return o;
}

```
* Pixel shader:

```
struct FragmentIn
{
    float4 color    : COLOR;
    float4 pos      : SV_POSITION;
};

float4 main(FragmentIn i) : SV_TARGET
{
    return float4(1.0f, 0.0f, 0.0f, 1.0f);
}

```

# Answer
> 1 votes
Found the problem, for future readers: I Failed to set up a correct blend state. For some reason I forgot to set the write mask for the render target. Works perfectly after setting

```
blend_desc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;

```

---
Tags: directx11, fragment-shader
---


# Question
Title: Where's the line between homage and copyright infringement?
My current WIP game contains a music note collectible mechanic which allows players to play short tunes if collected in the right order (usually very obvious by the layout of the collectibles). So far, I've kept it at references to Mozart or Beethoven, as this is what fits my game's theme. However, I was thinking of hiding, say, the first few notes of the Mario theme, or of Star Wars' Imperial March, in certain locations, as an homage.

Is this copyright infringement? I assume that having a whole copyrighted song reconstructed note by note like so would constitute a breach of copyright, but how about 10 recognisable notes?

Thanks! :)

# Answer
> 0 votes
The details will vary from jurisdiction to jurisdiction, but generally if the sequence of notes you string together is identifiable as somebody else's song, that's probably copyright infringement.

The idea that one can play "up to *n* seconds" of a song without incurring legal entanglements is generally incorrect. I know of no specific provision carving out that exception in US copyright law, for example, although I'm not a lawyer. I also know of no particularly specific definition of what "identifiable" would mean, or similar clear guideline that, for example "four notes is fine, five notes is infringement." It's all complicated.

Some jurisdictions have a "fair use" clause in their copyright doctrine, generally intended to enable parody, comment, or critique. Where it exists, fair use is almost always a *defense*, which means you've got to get sued and go to court to present it. Whether or not you actually have a reasonable case there is a matter for you and your lawyer to discuss. As above, it can be complicated.

So I'd suggest you skip out on the homages, as fun as it may be, it's probably not "a day in court" fun.

---
Tags: audio, copyright, music
---


# Question
Title: How to protect save game data when saving game over the network?
Newbie question please - I am working on my own RPG, using Unreal Engine 4 and C++.

Regarding data formats - I figured I would just make HTTP Post requests to store the data as JSON in AWS's DynamoDB, are there any security considerations to avoid players somehow tampering with the APi request/response such as, modifying progress state or items state - how is data safety ensured when making server calls? Should I encrypt the game data and decrypt it on the client?

I only want to prevent "casual tampering", because obviously client decryption will never be 100% safe. I just don't want to make it super easy to figure out "if I modify this value here, my armor increases 1000%"

Thank you,

# Answer
> 1 votes
1. Use HTTPS
2. Sign and/or encrypt the data with a key included in the app. This won’t stop somebody from modifying the app, but it will stop casual MITM attacks using a proxy server.
3. If you want to get fancy, have your server perform game state validation. Make sure things don’t look astronomically out of place. Of course, players can just find the largest value your system won’t reject.
4. Finally, and most importantly, just don’t care. As long as you are not making a freemium or online game, what does it matter if they want to have their own kind of fun, without disrupting others?

---
Tags: savegame, game-state, encryption
---


# Question
Title: What's the generally accepted way to coordinate game events between objects?
I'm a newbie when it comes to game development and I'm struggling to decide on a good and consistent architecture for having child game objects trigger actions at a higher parent level.

For instance, say that I have game objects like this (in Unity)

*This is a conceptual heirarchy, not the actual Unity scene heirarchy. `GameManager` and `PlayerStats` are `ScriptableObject`s in Unity. I have the hierarchy drawn like this because each scene can be thought of as a child of the overall game.*

```
GameManager (ScriptableObject)
|
|--> PlayerStats (ScriptableObject)
|
|--> Scene (the Unity scene)
     |
     |--> GUI (MonoBehaviour)
     |    |
     |    |--> Button (MonoBehaviour)
     |
     |--> Player (MonoBehaviour)
     |
     |--> Enemy1 (MonoBehaviour)
     |
     |--> Enemy2 (MonoBehaviour)

```

If I click the button in the GUI, I want the player to fire a gun. That requires the following things to happen:

1. Check that the player's ammo is greater than zero (done in `PlayerStats`)
2. Instantiate a new bullet in the scene (done in `Scene`)
3. Update the player's ammo (done in `PlayerStats`)
4. Update the GUI to show the new ammo count (done in `GUI`)
5. Play the "fire" animation (done in `Player`)

The "fire gun" event is triggered from the `Button` object, but it needs to perform actions on objects that it is not an ancestor of. There also needs to be some high-level coordination between objects, so that if the player is out of ammo, none of the subsequent actions take place.

Here are the ways I can think of to handle this logic, along with pros and cons:

**1. Do all logic within the button's Fire() method**

* Pros

+ Simple (all code is directly in the button's click handler)
* Cons

+ Violates single responsibility principle. The button is now responsible for game logic.
    + The button has to have references to a bunch of higher level game objects. This smells of poor design.

**2. Have the button's click handler call GameManager.FireGun()**

* Pros

+ The entire event sequence is coordinated from a high-level game object that only acts on its children
    + The `GameManager.FireGun()` method can be called from any other game event that I want to fire the gun from
* Cons

+ The `GameManager` class will be huge because it'll have a lot of these types of events.
    + The button has to call a method (`FireGun()`) from a higher-level object, and so it still has to have a reference to a parent object. This seems like poor design.

**3. The button's click handler puts a "fireGun" message on the bus, which is picked up by GameManager.OnGunFired()**

* Pros

+ Same pros as method 2, with the added benefit of the button not having a reference to its parent `GameManager`
* Cons

+ Same cons as above. `GameManager` will have a lot of "OnSomething" methods.
    + `GameManager` will have to subscribe/unsubscribe to a lot of messages.
    + Unit testing becomes more difficult. Rather than checking to see if a method was called on a mock, each unit test will need to set up a message bus, and verify that the correct messages were sent.

**4. Have GameManager, Player Stats, GUI, and Player all subscribe to the fireGun event**

* Pros

+ Code is split up between different classes, so `GameManager` won't end up with a bunch of big methods that coordinate every action.
    + Better adherence to single responsibility principle. All inter-object communication is done with the message bus, so objects don't have to know about each other.
* Cons

+ Difficult to do inter-object coordination, such as if the "fire" button is clicked and the player is out of ammo, none of the "fire gun" actions should happen. That could be solved by doing an ammo check in the button's `onClick`, but again that would require the button to know about higher level player objects.
    + Same unit testing difficulties as method 3.

Among these four architectures, which one(s) tends to be the most common in games (or is there a better way of doing this that I didn't mention)?

# Answer
> * Check that the player's ammo is greater than zero (done in PlayerStats)

This check belongs to the firing behavior, which as far as I understand and would recommend, should belong to the player.

`PlayerStats` should probably be exactly just that. A **data** class containing the player's stats. No actions should be within it, just data that drives or limits actions elsewhere.

---

> * Instantiate a new bullet in the scene (done in Scene)

This belongs to the firing behaviour, and should be done in the player.

---

> * Update the player's ammo (done in PlayerStats)

Same thing. Part of the firing behavior.

---

> * Update the GUI to show the new ammo count (done in GUI)

This should probably be done through an `Observable` pattern in an interface that changes the data in `PlayerStats`. Changes to `PlayerStats` should only be done through that interface, and changes cause the GUI to update autonomously through the observable pattern.

---

> * Play the "fire" animation (done in Player)

Already where it should be.

---

> The "fire gun" event is triggered from the Button object, but it needs to perform actions on objects that it is not an ancestor of.

There is no need for events to be children of what they trigger. They will trigger any listener registered to them, and you can register any listener from anywhere.

---

> 1. Do all logic within the button's Fire() method

No. You explained it yourself. Your 'pro' is a con. You're creating a god-class, and that's bad.

> 2. Have the button's click handler call GameManager.FireGun()

No. Your `GameManager` should manage your game-flow in general. Not specific actions of specific objects. Which the firing behavior, GUI update behavior, and all other stuff you listed, are.

> 3. The button's click handler puts a "fireGun" message on the bus, which is picked up by GameManager.OnGunFired()

No. Don't use messages. Use `UnityEvent`. And no. As I explained above, that firing behaviour should not be your gamemanager's responsibility. It belongs to the player.

> 4. Have GameManager, Player Stats, GUI, and Player all subscribe to the fireGun event

No. You seem to be fixated on an idea that everything should be set in motion by one trigger. But instead of that, you should let things follow their logical **sequence**. Including a sequence of one thing triggering the next as needed.

---

Here's how game behaviour would flow optimally, in my opinion:

1. Either in the editor, as an `Init()` method in the `GameManager`, or in each object. set up dependencies. In this case, that means registering the proper listener to the proper events.
2. GUI triggers an `UnityEvent` that calls a method, say, `Fire()`, in the `Player`.

Within `Fire()`:

3. The ammo is checked. If `ammo<1`, the behavior is interrupted right there with a simple `return`. Else...
4. Decrement ammo through an interface that will automatically update the GUI upon changes (with another `UnityEvent`).
5. Spawn bullet.
6. Give bullet it's initial force/speed.
7. Trigger the start of fire animation.
> 2 votes

---
Tags: unity, architecture, design-patterns
---


# Question
Title: Unable to select MonoDevelop to open XML file from Unity project
I am developing games in Unity but I have encountered a problem. After updating Unity I can no longer find MonoDevelop for editing XML files like my Android Manifest:

# Answer
> 1 votes
MonoDevelop was phased out in version 2018.1. You now need to use something different, like Visual Studio.

---
Tags: unity, android, xml, monodevelop
---


# Question
Title: why is GetComponent<ICameraControl> returning null?
As you can see in the attached image below and the code, I have added a class that implements the interface `ICameraControl` attached to a `GameObject`.

When I call `var controller = GetComponent<ICameraControl>();`, I get nothing returned (null), as in this example:

```
public class KeyboardHandler : MonoBehaviour
{
    private void Start()
    {
        var controller = GetComponent<ICameraControl>();
        if (null == controller)
            print("no ICameraControl found!");
    }
}

```

And the output is like this in the unity console:

> no ICameraControl found! UnityEngine.MonoBehaviour:print(Object) Assets.Player.KeyboardHandler:Start() (at Assets/Player/KeyboardHandler.cs:18)

Here's the `Camera Position Handler` attached to my game object:

Here's the interface implementation:

```
public class CameraPositionHandler : MonoBehaviour, ICameraControl
{
    private GameObject mainCamera;
    private Quaternion homePosition;

    private void Start()
    {
        mainCamera = GameObject.FindGameObjectWithTag("MainCamera");
        homePosition = mainCamera.transform.rotation;
    }

    private void LateUpdate() { }
}

```

Any ideas what I am doing wrong?

Much appreciated :) Matt

**Edit**: The keyboard script is on my player object (at bottom of the picture of the player object). And the Camera Position Handler is on the Camera Arm object. The Player object and Camera Arm objects are at the same level.

# Answer
> 2 votes
Consulting the docs on `GameObject.GetComponent`:

> Returns the component of Type `type` **if *the game object* has one attached**, `null` if it doesn't.

So when your `KeyboardHandler` script says `GetComponent<ICameraControl>()`, that's equivalent to:

```
this.gameObject.GetComponent<ICameraControl>()

```

ie. "Give me an instance of component **attached to the same `GameObject` as I am**, that implements the `ICameraControl` interface"

But you don't have an `ICameraControl` component on the `KeyboardHandler`'s game object, so the method correctly returns null.

It looks like what you might have meant was either:

```
cameraObject.GetComponent<ICameraControl>()

```

which would look for an `ICameraControl` on *some other* object you've provided, either via an Inspector reference or by looking it up with eg. `Camera.main`.

Or, the nuclear option:

```
FindAnyObjectByType<ICameraControl>()

```

which searches your whole scene for any instance of a matching type, attached to any object.

(Note: I've updated this answer from a previous version which used `FindObjectOfType`. In Unity 2021.3.18 and later, `FindAnyObjectByType` is a faster option.)

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


# Question
Title: Why is my texture displaying incorrect colours using dx11?
I am trying to load my data from a binary file (ppm) and create a texture using this data. It is important that I learn to do it this way as I am eventually going to be packing all of my textures into a single binary file and then index them so creating the texture with pure binary data is something that I need to be able to do.

It seems that the texture is drawing correctly, but the colours are incorrect. I saved my image as .ppm just for this test application.

Here is the code to load my data

```
ppm ppm;

ppm.read(std::string("textureppm.ppm"));

//just to ensure the data is correct
uint32_t val = ppm.pixels[0];
unsigned char r = (val & 0xFF000000) >> 24;
unsigned char g = (val & 0x00FF0000) >> 16;
unsigned char b = (val & 0x0000FF00) >> 8;
unsigned char a = (val & 0x000000FF);

ID3D11ShaderResourceView* texSRV = nullptr;
D3D11_SUBRESOURCE_DATA initData = { &ppm.pixels, ppm.width * sizeof(uint32_t), 0};

D3D11_TEXTURE2D_DESC desc = {};
desc.Width = ppm.width; desc.Height = ppm.height; desc.MipLevels = 1; desc.ArraySize = 1;
desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
desc.SampleDesc.Count = 1;
desc.Usage = D3D11_USAGE_IMMUTABLE;
desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;

ID3D11Texture2D* tex;
HRESULT hr = getDevice()->CreateTexture2D(&desc, &initData, &tex);

if (SUCCEEDED(hr))
{
    D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc = {};
    SRVDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
    SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
    SRVDesc.Texture2D.MipLevels = 1;

    hr = getDevice()->CreateShaderResourceView(tex,
        &SRVDesc, &texSRV);
}

if (FAILED(hr)) {
    throw 0;
}
else {
    setTexture(texSRV);
}

```

I have packed each byte into a `uint32_t` as it seems that is the format that is required `DXGI_FORMAT_R8G8B8A8_UNORM`

Here is the packing

```
uint32_t ppm::CreateRGBA(unsigned char r, unsigned char g, unsigned char b, unsigned char a)
{
    uint32_t value = 0;
    int r2 = (r & 0xff) << 24;
    int g2 = (g & 0xff) << 16;
    int b2 = (b & 0xff) << 8;
    int a2 = (a & 0xff);

    value += r2 + g2 + b2 + a2;

    return value;
}

```

This code produces the following texture

When the original texture is

Does anyone know what I am doing wrong?

# Answer
> 2 votes
It seems the packing order of the `uint_32` value was incorrect. I thought the packing should be RGBA left to right, rather than ABGR.

Switching the packing order around fixed this issue.

---
Tags: textures, directx11
---


# Question
Title: Cube map faster than 6 2D textures? - shadow mapping
I've managed to implement shadow mapping to a scene. However, I had problems using a cube map so I eventually gave it up and used 6 2D texture maps instead. To make this work with 6 2D maps, during the rendering process I have to identify in which texture of the 6 each fragment belongs. I'm afraid this could be dropping my frames significantly.

I'm not gonna go into many details for now. I will upload the relevant code if necessary. My main concern is if this method makes my program slower.Will my fps increase using a cube map?

# Answer
There is no need to use 6 individual textures as you can just use one big 2D strip with the dimensions x=shadowmap\_width y= 6\*shadowmap\_height and then do 6 renderpasses adjusting the viewport to draw at the right place of the texture. (`glViewport` \+ `glScissor` in openGL).

That way you only have one texture sampler in your shaders and don't need 12 rebindings per render iteration. Also PCF using poisson disk sampling gets a lot easier since you have 2D texture coordinates.

This blog goes a bit deeper in how to do this and also points out potential issues and how you could solve them: https://kosmonautblog.wordpress.com/2017/03/25/shadow-filtering-for-pointlights/
> 2 votes

---
Tags: shadow-mapping, cubemap
---


# Question
Title: How can I improve make it shorter the gate control script and how to make the doors stop at original position?
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GateControl : MonoBehaviour
{
    public float openSpeed = 1f;

    private GameObject[] doors;
    private bool entered = false;
    private bool exited = false;
    private Vector3[] doorsOriginPos;

    private void Start()
    {
        doors = GameObject.FindGameObjectsWithTag("Door");

        doorsOriginPos = new Vector3[2];
        for (int i = 0; i < doors.Length; i++)
        {
            doorsOriginPos[i] = doors[i].transform.position;
        }
    }

    private void OnTriggerEnter(Collider other)
    {
        if (other.tag == "Collider")
        {
            entered = true;
            exited = false;
        }
    }

    private void OnTriggerExit(Collider other)
    {
        if (other.tag == "Collider")
        {
            exited = true;
            entered = false;
        }
    }

    private void Update()
    {
        if (entered == true)
        {
            doors[0].transform.position += Vector3.up * openSpeed * Time.deltaTime;
            doors[1].transform.position += Vector3.down * openSpeed * Time.deltaTime;
        }

        if (exited == true)
        {
            for (int i = 0; i < doors.Length; i++)
            {
                if (doors[i].transform.position != doorsOriginPos[i])
                {
                    doors[1].transform.position += Vector3.up * openSpeed * Time.deltaTime;
                    doors[0].transform.position += Vector3.down * openSpeed * Time.deltaTime;
                }
            }
        }
    }
}

```

Seems too much code or too long and can be simpler.

And the part:

```
if (doors[i].transform.position != doorsOriginPos[i])

```

Never true. I want that when the doors are getting close they will stop at the original position and won't continue move up/down nonstop.

# Answer
Your code is actually fine. I got rid of the 'exited' bool because you don't need it. I also converted your two 'if statements' inside your Update to an 'if/else' statement.

As for the the line

```
 `if (doors[i].transform.position != doorsOriginPos[i])`

```

The reason that isn't returning true is because the door won't always return to its *exact* original position; it might be one decimal place off. For that reason, I replaced it with `Vector3.Distance`

Let me know what you think

```
using UnityEngine;

public class GateControl : MonoBehaviour
{
    public float openSpeed = 1f;

    private GameObject[] doors;
    private bool entered = false;
    private Vector3[] doorsOriginPos;

    private void Start()
    {
        doors = GameObject.FindGameObjectsWithTag("Door");

        doorsOriginPos = new Vector3[2];
        for (int i = 0; i < doors.Length; i++)
        {
            doorsOriginPos[i] = doors[i].transform.position;
        }
    }

    private void OnTriggerEnter(Collider other)
    {
        if (other.tag == "Collider")
        {
            entered = true;
        }
    }

    private void OnTriggerExit(Collider other)
    {
        if (other.tag == "Collider")
        {
            entered = false;
        }
    }

    private void Update()
    {
        if (entered)
        {
            doors[0].transform.position += Vector3.up * openSpeed * Time.deltaTime;
            doors[1].transform.position += Vector3.down * openSpeed * Time.deltaTime;
        }
        else
        {
            for (int i = 0; i < doors.Length; i++)
            {
                if (Mathf.Abs(Vector3.Distance(doors[i].transform.position, doorsOriginPos[i])) >= .01f)
                {
                    doors[1].transform.position += Vector3.up * openSpeed * Time.deltaTime;
                    doors[0].transform.position += Vector3.down * openSpeed * Time.deltaTime;
                }
            }
        }
    }
}

```
> 2 votes

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


title: Swift get the true date

text:
# Question
Title: Swift get the true date
I have a game and want to reward the user for going on every day. I want to be able to get the true date somehow. I do not want the device date, because the user could just change it and get free rewards. Is there a way for me to access the true date from apple time or something like that?

Thanks

# Answer
There are a couple of client libraries that you could use to call out to an NTP server and get the date over a network connection. I've not used either of these, but two that I quickly found are:

You'll need to likely define your own NTP service endpoint, but could easily use `pool.ntp.org`. The Kronos library appears to default to using `time.apple.com`.

Both look relatively easy to use and implement, with examples in the each of the project README.
> 1 votes

---
Tags: ios, swift
---


# Question
Title: Trying to set up a planting and harvesting system, but it only works in one trigger area?
What I want to happen is when the player presses alt, some time passes and an object is instantiated there. I also want it so that the player can't instantiate another object there until they've collecting the one they've planted there already. This is working when I only have one planting area, but once I have more than one planting area it no longer works- for some reason I'm only able to keep planting and collecting in just one of the trigger areas instead of all of them. What am I doing wrong?

```
public bool instantiated;
public bool inside;
public bool collected;
private IEnumerator coroutine;
public GameObject powerorb;
public Material[] material;
Renderer rend;

void OnTriggerStay2D(Collider2D Collider2D)
{
    if (Collider2D.gameObject.tag == "Player")
    {
        if (instantiated == false)
        {
            inside = true;
        }

        if (collected == true)
        {
            instantiated = false;
            collected = false;
            rend.sharedMaterial = material[0];
        }
    }
}

void OnTriggerExit2D(Collider2D Collider2D)
{
    inside = false;
}

    // Use this for initialization
void Start () {

    rend = GetComponent<Renderer>();
    rend.enabled = true;
}

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

    if (inside && Input.GetKeyDown(KeyCode.LeftAlt))
    {
        StartCoroutine("spawning");
    }

    if (instantiated == true)
    {
        StopCoroutine("spawning");
    }
}

IEnumerator spawning()
{
    rend.sharedMaterial = material[1];

    yield return new WaitForSeconds(8);
    Instantiate(powerorb, transform.position, transform.rotation);
    instantiated = true;
    inside = false;

    yield return null;

}

```

I reference if the object has been collected in another script with this:

```
 if (collecting)
        {
            GameObject.FindWithTag("PowerFarm").GetComponent<PowerFarmCoroutine>().collected =
        true;
            Destroy(gameObject);
        }

```

# Answer
> 2 votes
Look at this code:

```
void OnTriggerStay2D(Collider2D Collider2D)

```

The variable named the same as the type could be causing some issues.

# Answer
> 0 votes
I actually just found a solution but it's pretty messy and bootleg. What I did was I turned off the mesh renderer and translated the object really fast to trigger ontriggerexit, then destroyed it. I'm a little worried it may cause me problems later because of the messiness so I'd like to find another solution but here's what I have so far:

```
public bool instantiated;
public bool inside;
private IEnumerator coroutine;
public GameObject powerorb;
public Material[] material;
Renderer rend;

void OnTriggerStay2D(Collider2D Collider2D)
{
    if (Collider2D.gameObject.tag == "Player")
    {
        if (instantiated == false)
        {
            inside = true;
        }
    }
}

void OnTriggerExit2D(Collider2D Collider2D)
{
    if (Collider2D.gameObject.tag == "Player")
    {
        inside = false;
    }

    if (Collider2D.gameObject.tag == "FarmOrb")
    {
       instantiated = false;
       rend.sharedMaterial = material[0];
    }
}

    // Use this for initialization
void Start () {

    rend = GetComponent<Renderer>();
    rend.enabled = true;
}

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

    if (inside && Input.GetKeyDown(KeyCode.LeftAlt))
    {
        StartCoroutine("spawning");
    }

    if (instantiated == true)
    {
        StopCoroutine("spawning");
    }
}

IEnumerator spawning()
{
    rend.sharedMaterial = material[1];

    yield return new WaitForSeconds(8);
    Instantiate(powerorb, transform.position, transform.rotation);
    instantiated = true;
    inside = false;

    yield return null;

}

```

And then in the script where the object is being collected:

```
           if (collecting)
        {

            transform.Translate(Vector3.up * 5 );
            gameObject.GetComponent<Renderer>().enabled = false;
            startDisappearCount = true;
        }

    if (startDisappearCount == true)
    {
        disappearCount -= Time.deltaTime;

        if (disappearCount <= 0)
        {
            Destroy(gameObject);
        }
    }

```

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


# Question
Title: Referencing to objects in other scripts [Unity]
Hello guys just a quick question, I'm learning from this book and I got this error where

```
var backgroundBounds = GameObject.Find("background")
 .renderer.bounds;

```

is deprecated way of doing thins instead it says do it like this:

```
public SpriteRenderer backgroundSprite;
backgroundSprite = (SpriteRenderer)GetComponent(typeof(SpriteRenderer));

```

But when I set my GameObject to it which contains SpriteRenderer, on hitting the play button it will disappear and throw null exception.

# Answer
> -1 votes
```
var backgroundBounds = GameObject.Find("background").GetComponent<SpriteRenderer>().bounds;

```

---
Tags: unity
---


# Question
Title: How can I convert a tilemap to a Box2D world?
I want to use Box2D physics and lighting with a `.tmx` map. How can I "convert" a tilemap to Box2D world? My basic idea is to go through the tiles on the map and create an object for them in Box2D.

I'm using the Tiled map editor for the tilemap, and the target platform is PC.

Firstly, is this a good solution for my idea? Or is this even possible?
Secondly, if yes, then I dont know how to get the tile's position.

My code so far:

```
public class WorldLoader {
public static TiledMap map;

public static void loadMap(String mapName) {
    map = new TmxMapLoader().load(mapName);
    TiledMapTileLayer collisionLayer = (TiledMapTileLayer) map.getLayers().get("collision");

    for (int x = 0; x < collisionLayer.getWidth(); x++) {
        for (int y = 0; y < collisionLayer.getHeight(); y++) {
            Cell cell = collisionLayer.getCell(x, y);

            if (cell != null && cell.getTile() != null) {
               // float tileX = collisionLayer.getProperties().containsKey("x");
               // float tileY = cell.getTile().getProperties().get("y", Integer.class);

                BodyDef bodyDef = new BodyDef();
                bodyDef.position.set(tileX, tileY);

                PolygonShape shape = new PolygonShape();
                shape.setAsBox(16, 16);

                Body body = GameWorld.world.createBody(bodyDef);
                body.createFixture(shape, 0f);

                shape.dispose();
            }
        }
    }

}

```

}

# Answer
After banging my head against this problem for a day I found a wonderful tutorial on the very subject over at Sion Dream. I knew there was a way to use object layers!

In a nutshell, create an objects layer on your map (Tiled, Tide and the tutorial author's pick, Gleed, all provide this function), draw the shapes you want your Box2d static bodies to be, then use his MapBodyManager class (or your variation thereof) to convert them to Box2d bodies. Here's my variation on the relevant methods. The most important change I made? `polygon.getVertices()` and `polyline.getVertices()` became `getTransformedVertices()`. Forget that, and all your static bodies will be built at the origin!

```
public class MapBodyBuilder {

    // The pixels per tile. If your tiles are 16x16, this is set to 16f
    private static float ppt = 0;

    public static Array<Body> buildShapes(Map map, float pixels, World world) {
        ppt = pixels;
        MapObjects objects = map.getLayers().get("Obstacles").getObjects();

        Array<Body> bodies = new Array<Body>();

        for(MapObject object : objects) {

            if (object instanceof TextureMapObject) {
                continue;
            }

            Shape shape;

            if (object instanceof RectangleMapObject) {
                shape = getRectangle((RectangleMapObject)object);
            }
            else if (object instanceof PolygonMapObject) {
                shape = getPolygon((PolygonMapObject)object);
            }
            else if (object instanceof PolylineMapObject) {
                shape = getPolyline((PolylineMapObject)object);
            }
            else if (object instanceof CircleMapObject) {
                shape = getCircle((CircleMapObject)object);
            }
            else {
                continue;
            }

            BodyDef bd = new BodyDef();
            bd.type = BodyType.StaticBody;
            Body body = world.createBody(bd);
            body.createFixture(shape, 1);

            bodies.add(body);

            shape.dispose();
        }
        return bodies;
    }

    private static PolygonShape getRectangle(RectangleMapObject rectangleObject) {
        Rectangle rectangle = rectangleObject.getRectangle();
        PolygonShape polygon = new PolygonShape();
        Vector2 size = new Vector2((rectangle.x + rectangle.width * 0.5f) / ppt,
                                   (rectangle.y + rectangle.height * 0.5f ) / ppt);
        polygon.setAsBox(rectangle.width * 0.5f / ppt,
                         rectangle.height * 0.5f / ppt,
                         size,
                         0.0f);
        return polygon;
    }

    private static CircleShape getCircle(CircleMapObject circleObject) {
        Circle circle = circleObject.getCircle();
        CircleShape circleShape = new CircleShape();
        circleShape.setRadius(circle.radius / ppt);
        circleShape.setPosition(new Vector2(circle.x / ppt, circle.y / ppt));
        return circleShape;
    }

    private static PolygonShape getPolygon(PolygonMapObject polygonObject) {
        PolygonShape polygon = new PolygonShape();
        float[] vertices = polygonObject.getPolygon().getTransformedVertices();

        float[] worldVertices = new float[vertices.length];

        for (int i = 0; i < vertices.length; ++i) {
            System.out.println(vertices[i]);
            worldVertices[i] = vertices[i] / ppt;
        }

        polygon.set(worldVertices);
        return polygon;
    }

    private static ChainShape getPolyline(PolylineMapObject polylineObject) {
        float[] vertices = polylineObject.getPolyline().getTransformedVertices();
        Vector2[] worldVertices = new Vector2[vertices.length / 2];

        for (int i = 0; i < vertices.length / 2; ++i) {
            worldVertices[i] = new Vector2();
            worldVertices[i].x = vertices[i * 2] / ppt;
            worldVertices[i].y = vertices[i * 2 + 1] / ppt;
        }

        ChainShape chain = new ChainShape();
        chain.createChain(worldVertices);
        return chain;
    }
}

```

The best part of this method is that your shapes can be polygons or even circles, allowing for more than the basic square tiles and squared-off platforms (think hills!). Not only that, but you can create fewer, larger bodies without having to programmatically work out whether two adjacent tiles are visually part of the same object.

(Edit: the code wasn't quite working properly before. The change mentioned above (to `getTransformedVertices()`) fixed it. Also removed references to my utility classes, since they weren't relevant to the discussion.)
> 15 votes

# Answer
Yes, you want to iterate over the tilemap in x and y (inner and outer loops).

How large are your maps (n * m)? If quite small / sparse, you could use individual bodies for every solid tile. But this would rapidly get out of hand even though these would be static bodies, so you'd need to really keep your levels tight / tilemaps small. I probably would try to stay under a couple to a few hundred bodies for mobile, so you may have to generate maps accordingly in this case, i.e. use fewer obstacles.

If larger, then you need to conjoin adjacent obstacle tiles -- mainly walls and other multi-tile objects: If you're using an external app to generate your tilemap, you will need to examine the map and evaluate large contiguous sections of wall, store these in a separate data structure, and then convert each of these into large `b2Body`s. In this process, it can be useful to eliminate colinear vertices before creating your `b2Body`s from them, because the more vertices a body has, the more CPU time it takes to process.

If you're creating your tilemap at runtime instead, then I would suggest that you start with long objects, and use these as a kind of multi-tile "stamp" to create the tile map, while at the same time storing the "stamp" positions in another data structure (a list?). You could then use the secondary data structure for the creation of large `b2Body`s. This keeps you from having to do the tedious task described in the previous paragraph.

The point here is to reduce the number of bodies so your physics runs smoothly.

As for your tile's position: This is implicit in the 2D array indices. Let's say you consider every successive index (in x and y) in your tilemap to be a 2m distance. That would mean that the tile at index \[0, 3\] in your array is at position {0m, 6m} from the origin. So as you iterate on each index x and y, use these indices to determine the world position of the `b2Body` to be created from that 2D index.
> 4 votes

# Answer
Answer by daemonaka pretty much covers the issue, I've expanded it for ellipses (not enough points to write comment so have to write an answer). Maybe somebody will find it useful:

Firstly in `buildShapes` method you add case for ellipses:

```
...
else if (object instanceof EllipseMapObject) {
    shape = getEllipse((EllipseMapObject) object);
}
...

```

And getEllipse looks as follows:

```
private static final int ELLIPSE_APPROX_POINTS = 32;
private static Vector2[] ellipseVertices = new Vector2[ELLIPSE_APPROX_POINTS];

private static ChainShape getEllipse(EllipseMapObject ellipseMapObject) {
    for (int idx = 0; idx < ELLIPSE_APPROX_POINTS; idx++) {
        float percentDone = (float) idx / (float) ELLIPSE_APPROX_POINTS;
        float currentEllipseAngle = percentDone * 2 * MathUtils.PI;
        Vector2 newPoint = calculatePointOnEllipseForAngle(currentEllipseAngle, ellipseMapObject.getEllipse());
        ellipseVertices[idx] = newPoint;
    }

    ChainShape chainShape = new ChainShape();
    chainShape.createChain(ellipseVertices);
    return chainShape;
}

private static Vector2 calculatePointOnEllipseForAngle(float currentEllipseAngle, Ellipse ellipse) {
    Vector2 newPoint = new Vector2();
    float radiusX = ellipse.width / 2f;
    float radiusY = ellipse.height / 2f;

    newPoint.x = (radiusX * (float) Math.cos(currentEllipseAngle) + (ellipse.x + radiusX)) / ppt;
    newPoint.y = (radiusY * (float) Math.sin(currentEllipseAngle) + (ellipse.y + radiusY)) / ppt;

    return newPoint;
}

```

Code is based on https://stackoverflow.com/questions/22694850/approximating-an-ellipse-with-a-polygon. Hope this helps someone.
> 0 votes

---
Tags: box2d, libgdx, tilemap
---


# Question
Title: Unity & CSharp - Placing Instantiated Object in the Direction of Player
So, I am making a Minecraft ripoff.
I have a raycast that hits a block. It then places a block inside of that block. I am trying to make it place next to the block in the direction the user is facing.
I got some of that figured out. I use:
`Math.Round();`
to round up the floats. My problem is figuring out what axis to round on. I need it to depend on the direction the player is facing to figure it out.
I tried doing a complicated algorithm to figure out which face of the collider the player is facing, but that didn't work out that well....

How do I solve this? I can't figure it out.

# Answer
> 1 votes
You can base it off of the normal of the surface the Raycast hits. When performing a Raycast, there is an optional out parameter that supplies information about the resulting collision, including the aforementioned normal.

Here's a brief example of how you could do this:

```
RaycastHit hit;
if(Physics.Raycast(new Ray(transform.position, transform.forward), out hit) {
    objectToInstantiate.transform.position =
    hit.collider.gameObject.transform.position + hit.normal * blockSize;
}

```

The object will be translated from the source block by the normal of the face that is hit by the Raycast. In case you're unfamiliar, the normal is the vector perpendicular to a given face (basically, what direction it's facing)

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


# Question
Title: How to get plane geometry associated with primitive 3d plane in unity3d
I assume there should be a plane (struct) associated with a primitive 3d plane in unity3d, how to get that? Or if not associated, can we build plane struct object somehow using corner vertices of 3d plane. Can somebody help me how to get cornor vertices of 3d plane mesh.

Update: What I am trying to achieve is to use Plane.Raycast on a 3d Plane, but I am not certain whether there is any plane geometry component associated with it, or Is there any way to build a plane geometry which should be going through all the corners of the 3d plane, so that I'll be able to use Plane.Raycast from the normal direction of 3d plane towards itself.

# Answer
If you're asking about the built-in Plane primitive, it's a plane normal to the local up direction, passing through the local origin. So you can write:

```
Plane plane = new Plane(
                 planeObject.transform.up,
                 planeObject.transform.position
              );

```
> 1 votes

---
Tags: unity
---


# Question
Title: Unity, Object's vectors are not rotating with the object. what did i do wrong?
I found a youtube video (Sebastian Lague: Character Creation (E07: Unity character controller)) that has a really good movement script, I understood it and used it for my character.

When I started moving it, I noticed that the character rotates but his blue, red, green vectors are not rotating with him, his forward always stays the same, whereas in the youtube video his vectors rotated with the object, what could i have done wrong here?

```
 Vector2 input = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
    Vector2 inputDir = input.normalized;

    //if (inputDir==new Vector2 (0,1))
    //    transform.eulerAngles = new Vector3(0, Camera.main.transform.eulerAngles.y, 0);
    //Debug.Log(Input.GetAxis("Mouse X"));

    if (inputDir != Vector2.zero)
    {

        float TargetRot = Mathf.Atan2(inputDir.x, inputDir.y) * Mathf.Rad2Deg;
        transform.eulerAngles = Vector3.up * Mathf.SmoothDampAngle(transform.eulerAngles.y, TargetRot, ref TurnSmoothVelocity, TurnSmoothTime);

    }

    bool running = Input.GetKey(KeyCode.LeftShift);
    float TargetSpeed;
    if (running == true) TargetSpeed = RunSpeed * inputDir.magnitude;
    else TargetSpeed = WalkSpeed * inputDir.magnitude;
    CurrentSpeed = Mathf.SmoothDamp(CurrentSpeed, TargetSpeed, ref SpeedSmoothVelocity, SpeedSmoothTime);

    transform.Translate(transform.forward * CurrentSpeed * Time.deltaTime, Space.World);

}

```

# Answer
If I understood your question correctly, the problem is that the directional arrows in the scene view aren't rotating with your character. One problem that I can think of off the top of my head is that your coordinate system for the translation arrows is set to global. There's a button at the top of the scene tab that's split in half, clicking on the left half will switch between "pivot" and "center", and clicking the right half will switch between "local" and "global". Try switching the right half to local and see what happens.
> 1 votes

---
Tags: unity, 3d, vector, transformation
---


# Question
Title: Will TCP really affects UDP if used in different context?
I have read some questions about using both TCP and UDP in multiplayer game, such as Does it make sense to use both TCP and UDP at once? and Is UDP still better than TCP for data-heavy realtime games?.

Most answers recommend against using both at the same time, and maybe use a reliable UDP library, because of the TCP induces UDP packet loss argument stated in this paper for example.

But, if I don't use them both at the same time, e.g. using TCP when the players are still in the lobby/room and then sending data like who are in the room, players data, who just joined the room, etc. where everything must be reliable but also pretty infrequent and then as soon as the game started it switches to UDP to send data like movement, position, etc. where some packet drops is okay, is it okay to do this?

What about if the server is currently handling multiple games at once, like one game is currently playing (using UDP) and another one is still in the room (using TCP)? Will there be a massive packet loss for UDP?

Also about the simultaneous TCP and UDP packet loss, is it only happening if we use them in the same port or does it still happen regardless?

# Answer
> 2 votes
You need to always remember that **UDP and TCP are both just protocols on top of the IP layer**, which is **packet-based** like UDP. When you send data via UDP or TCP both will result in a number of IP packets being sent out (and also received back as acknowledgement in the case of TCP).

Look at layer 3 and 4 in this model: **Wikipedia - OSI Model**

This means that if you use your TCP stream recklessly it'll affect the UDP packet-loss because **both use the same shared network resources in the form of IP packets**.

---

Now here's the difference:

**Sending a single UDP** packet usually (depending on the payload size) **results in a single IP packet** being sent, it's very **deterministic**. This means you can control how much data you send per second accurately down to the byte level. Games need this since you want every client to get his dose of time-critical data just at the right time. Also server and client need to control how much they saturate their connection, otherwise packet loss happens on the IP level which translates into a slow-down (and build-up of data!) for TCP streams and loss of UDP packets.

With **TCP** you do **not have direct control over** how pushing out some bytes results in IP **packets being emitted**. This can lead to you accidentally saturating your connection when sending a large chunk of data or when many small pieces of data build up in the outgoing buffer.

**TCP is greedy: it'll try to send the data you put in as fast as possible** but will throttle back once it loses IP packets, resend the data, speed up again, rinse and repeat. You can surely see how this might strain your network for longer than a single UDP packet would.

---

BUT, this isn't something that just happens at random! **You are responsible** for how well UDP and TCP go together. **Control how much data you push into your TCP streams** at any given time, just like with the UDP side, as DMGregory already said in his comment. **Do not let large amounts of data build up in the outgoing TCP buffer, you cannot control how and when it get's pushed out**, it might eat your bandwidth at the wrong time as a result of trying to "catch-up".

You should be fine as long as you **leave some headroom for the overhead TCP creates** and **control the overall data rate**, meaning the combined bandwidth that TCP and UDP use.

---
Tags: networking, udp
---


title: How can I use OpenCL in libGDX?

text:
# Question
Title: How can I use OpenCL in libGDX?
Been looking for a way to implement some OpenCL stuff in my libGDX project. It's possible via LWJGL which libGDX is based on, but it's only for the Desktop environment.

I would like to have it cross platform as libGDX was meant to be used; how can I do that?

# Answer
OpenCL is not supported on all platforms, this means it's a platform dependent feature no matter what library/engine/whatever you throw at it.

The only way to use this in a platform independent way would be to query lwjgl for whether you are in an environment that supports OpenCL and use a CPU fallback solution in the case that it's not supported.

That's it for OpenCL basically. You could otherwise use Compute Shaders: https://stackoverflow.com/a/15874988

With them you are not dependent on OpenCL support but on the OpenGL version which is easier to fulfill on mobile. There are some differences between OpenGL ES and Desktop OpenGL though, i don't know how well lwjgl handles this. Compute shaders are generally supported though: https://github.com/LWJGL/lwjgl3-wiki/wiki/2.6.2.-Ray-tracing-with-OpenGL-Compute-Shaders-%28Part-II%29
> 1 votes

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


# Question
Title: Unity tilemap collider not colliding with rigidbody
In the wireframe you can see the tilemap collider for this hill. The red circle falls right through however. The circle has a 2D rigidbody attached. Everything is on the Default sorting layer and on layer order 0.

# Answer
I forgot to put a circle collider on the red circle. Leaving this up for others who might run into the same problem.
> 3 votes

---
Tags: unity, 2d, tilemap, rigidbody, collider
---


# Question
Title: mouseButton.y and mouseButton.x is -858993460 for every event except MouseButtonPressed
Using SFML, every event type will produce a large negative value for x and y of -858993460.

```
if (menuEvent.type == sf::Event::GainedFocus
    || menuEvent.type == sf::Event::LostFocus
    || menuEvent.type == sf::Event::KeyPressed
    || menuEvent.type == sf::Event::KeyReleased
    || menuEvent.type == sf::Event::MouseEntered
    || menuEvent.type == sf::Event::MouseMoved
    || menuEvent.type == sf::Event::MouseButtonReleased
    || menuEvent.type == sf::Event::MouseButtonPressed) {

    return HandleFindExit(menuEvent.mouseButton.x, menuEvent.mouseButton.y);
    // Except for when menuEvent.type is MouseButtonReleased
    // or MouseButtonPressed x and y will be -858993460
}

```

I am wondering if this is an intended result or am I attempting to use these events incorrectly?

It seems to me there is a use case for knowing the position of the mouse cursor on MouseMoved, for example so you can have a button change to a different sprite as if you are hovering over it.

# Answer
It would make sense that `mouseButton` won't have proper values except for events that involve the mouse button - MouseButtonReleased and MouseButtonPressed.

If for example you wanted the mouse position for MouseMoved events, you should be looking at the `mouseMove` member, which is of type `MouseMoveEvent`.

Always use the right event data for the event type. A mapping can be found in source code:

```
  221     union
  222     {
  223         SizeEvent             size;
  224         KeyEvent              key;
  225         TextEvent             text;
  226         MouseMoveEvent        mouseMove;
  227         MouseButtonEvent      mouseButton;
  228         MouseWheelEvent       mouseWheel;
  229         MouseWheelScrollEvent mouseWheelScroll;
  230         JoystickMoveEvent     joystickMove;
  231         JoystickButtonEvent   joystickButton;
  232         JoystickConnectEvent  joystickConnect;
  233         TouchEvent            touch;
  234         SensorEvent           sensor;
  235     };

```

FYI -858993460 in hexadecimal is CCCCCCCC. It is a garbage value used by microsoft compilers for uninitialised values.
> 1 votes

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


# Question
Title: I add a straight big plane over terrain(3d). Vibrations are happening when i move camera
I have this problem in my OpenGL project but i will show you the same thing over blender3d with video. So I believe that I will better explain the problem. it is just 30 seconds. Take a look. Youtube LINK

How can i fix these problem ?

# Answer
As others have already pointed out, it's called Z fighting, and happens when two or multiple polygons are close to eachother (depth-wise) and the framework has trouble distinguishing which should be drawn over which. At its core, this is caused by floating point inaccuracies.

All that is nice to know, but how do you fix it?

1. In your terrain shader, discard every pixel that is below a certain height (the height of your water.) This way, there's nothing for the water to fight over visibility with.
2. increase the distance of your camera's near plane. Try to get it as far away from the camera as possible without clipping objects that should be shown.
3. Decrease the distance of your camera's far plane (not as effective as step 2)
> 2 votes

---
Tags: opengl
---


# Question
Title: How would I create a multiplayer game owning a server?
I'm using gamemaker studio 2 to create an RPG, at the moment it's only single player but I would ideally like to make it multiplayer if possible.

I've done a bit of research but all the information seems to be more for using your PC like a server whereas I own an actually server that I'd like to use for it.

I have a website that the game is embedded on, the files for it are all stored on my server along with my website's files.

I want to make it so that the game is constantly running 24/7 and can handle quite a few people playing at once, I imagine that this may be difficult to achieve although not impossible.

I feel I have the resources available to make this happen but I'm not sure on the steps I'd take to get to where I want to be.

If there's any more information that would help, I will update my question for you.

# Answer
A server that you own is nothing more than another PC running somewhere in the world 24/7.

Make a "headless" version of your game, that acts as a server, and has no graphics, only calculates the game's state. Upload that game to your server and run it. Now make a normal version of your game and connect with your server. I have no experience with GameMaker, but by reading a few tutorials of how to connect with other players, it should become more obvious of how its done.

Start by making the server accept only 1 connection at a time. Experiment with it, how it feels to program with networking in mind. Once comfortable, start adding more players. Handling networking properly is not an easy task, and trying to support "unlimited" number of players should not be approached by someone who has no experience in it.

Keep in mind that multi-billion companies out there have problems with too many people connecting, and servers crashing.
> 2 votes

---
Tags: multiplayer, game-maker, rpg
---


# Question
Title: MMO sending player position to other players
When it comes to sending data to a player in MMOs, is this what the server is basically doing? (pseudo code)

```
every gametick:
    for each player connected:
        compile `string` of positions of all other players in range
        if `string` different `lastString`:
            send data to player
            set `lastString` to `string`

```

# Answer
It's really hard to have an answer like "Yes, that's how its done" because each game is different. I will assume you mean a "classic MMORPG" where you walk in an open world and you can interact with players if you are close to them.

* Basically the server makes sure that it doesn't waste cycles. If you are in one corner of the map, there is no reason for the server to bother sending you the position of a player on the other side of the map. That's why it keeps track of who player is near whom.
* The server tries to send the position to the right players as often as possible, but networking can be unstable, so the client will need to make "predictions" sometimes. For example if a player was walking north, but lost connection for 2 seconds, the game will assume the player keeps walking north, until it connects again and gives the correct location. This is how a lot of jokes about players suddenly "snapping" to other locations started.
* When the server sends data to a player, it makes sure **not** to pause until the player responds, so the game goes on even if a player loses connection for some time. This is most likely done with Threads, but it depends on language/platform/game.

But for the most part, I would say, what you described is a good starting point. You can try implementing that, and see if there is some problem you didn't think of.
> 2 votes

---
Tags: networking, mmo, online
---


# Question
Title: Why don't mobile games use tiny transactions like the orginal Candy Crush?
My understanding is that Candy Crush found its early success by letting users pay really small amounts of cash on a continual basis.

If that was successful then, why don't mobile app developers use that payment model now?

# Answer
> 1 votes
On average, a small fraction of users will make in-app purchases. On the other hand, everybody sees ads. Many freemium games will have a combination of both, but if your game’s design doesn’t call for a virtual economy, then forcing one into it is not going to get people to use it.

For example, a game may be simple enough that there is nothing the user needs to purchase. However, if it’s an infinite progression game, then if the user dies, almost nobody would pay $.99 to keep playing, even if they got really far. On the other hand, watching an incentivized video ad for 30 seconds is a much easier pill to swallow. Depending on the ad, it can pay around a few cents per view. If you can get many people to watch video ads multiple times a day, that adds up a lot faster than a small percentage of users paying money to buy a contrived virtual currency.

On the other hand, some games will offer both options. If you have more time than money, you take the ads route. If you view your time as more valuable, you might just pay money to remove or skip certain ads.

# Answer
> 1 votes
Very small transactions are used not for money source, but making player more willing to pay.

For example, at the very start player don't want pay money. Especially for 1000 crystals with price of 50$.

But after 1 hour of gameplay this game can give him a **special exclusive one time offer**: 500 crystals for 0.50%. **Wow! That's cheaper in 50 times!** So player make his first payment and now he is the player who spend some money. So in future he will be much easier to make decision to pay little more and more, and more.

# Answer
> 0 votes
The key to CC's success was that the game was not always winnable, and whether a level was winnable or not depended on the random setup of the level. Some levels had a much smaller chance of being winnable. These were followed by easily winnable levels.

So the player felt like they were doing ok, winning levels, then they got stuck. The game pushed the pay-ways to win: buy powerups, buy more turns, etc. If the player paid to get past that level, they were rewarded with a bunch of easy-to-win levels.

It is this addiction mechanic that made CC a massive hit.

I also suspect that many players can't tell the difference between the effect their skill has and the effect the random setup has on whether they win or not.

As A. Denis said in his answer, one tactic many games use is to overprice everything then run periodic massive discounts to make it seem like a good deal. Bejeweled Blitz did this. They would periodically run 90% off sales where you could buy a ton of coins for $1.

---
Tags: mobile, business
---


# Question
Title: What are constraints and how are they pluggable?
I have been reading this book called "Game Physics Engine Development" and Came across this image in the context of Collision Resolution.

See the contact Generator part. Can someone tell me what are constraints and how there can be different types of them? Thank you.

# Answer
> 1 votes
It's a bit of an educated guess without having the book to double check their context. In general, a constraint is something that must hold true for a given situation. In this specific instance, I would presume they are talking about situations where not all bodies generate collisions with each other.

For instance, you might have a portal that only interacts with the player and not other game objects. So the concept of `isPlayerBody` could be seen as a constraint (something that must be necessarily observed) in order to generate contact & collision data. By ignoring things that don't meet your constraints with (ideally) inexpensive calculations at an early stage you can save the trouble of doing more expensive calculations (computing contacts) later on.

As to the different types of constraints, they would be game specific and could represent a variety of things, but would ultimately need to represent some sort of boolean as either the constraint is observed or it is not.

Side note: in some situations there is the idea of a soft constraint which is something that you try to enforce if at all possible, but can relax to some degree (for instance if it is preempted by other constraints); I would be surprised if the book was referencing those as well, but given that the terminology can get mixed up, I thought they were worth mentioning.

---
Tags: physics, rigidbody
---


# Question
Title: Link CSS file with HTML file in Unity Power UI
I want to link css file with html in Unity with the help of Power UI. I already converted css file into bytes format but it not still worked. Here is the code

```
<head>
    <link href="Resources/bootstrapUnity.css.bytes"/>
</head>
<body>
    <h1>Hello Game</h1>
    <button type="button" class="btn btn-success btn-lg">Play</button>
    <button class="btn btn-info">Test</button>
</body>

```

# Answer
The default href with PowerUI is `resources://` so you don't need `Resources/` just `/bootstrapUnity.css`.

(If you have the .bytes extension added, this means you don't need it mentioned in the HTML file, as Unity will 'name' it without .bytes so that .css/.js links work normally..)..

Assuming `bootstrapUnity.css.bytes` is in the root of a 'resources' folder, try: `<link href="/bootstrapUnity.css"/>`
> 1 votes

---
Tags: html, css
---


title: Convert coroutine into void

text:
# Question
Title: Convert coroutine into void
I want to get rid of a co-routine and do this with a void.

How could I convert his IEnumerator into a void?

```
private IEnumerator pChangeFoV()
{
    float zValue =70f;

    for (float t = 0f; t < FoVDuration; t += Time.deltaTime)
    {
        float fNew = Mathf.Lerp(_camera.fieldOfView, zValue, t / FoVDuration);
        _camera.fieldOfView = fNew;
        yield return 0;
    }
    _camera.fieldOfView = zValue;
}

```

Thank you for the help!

# Answer
> 2 votes
Short answer:

```
private void pChangeFoV()
{
    float zValue =70f;

    for (float t = 0f; t < FoVDuration; t += Time.deltaTime)
    {
        float fNew = Mathf.Lerp(_camera.fieldOfView, zValue, t / FoVDuration);
        _camera.fieldOfView = fNew;
    }
    _camera.fieldOfView = zValue;
}

```

I just removed the **yield** keyword, since it is a special keyword that states that the statement, this case a method, is an iterator (IEnumerator, or T Generic IEnumerator).

Nonetheless, by turning it into void, you are losing the smooth FOV change you wanted to achieve. To turn the functionality into a void, I'd do something like this:

```
private bool smoothChange = true;
private float zValue = 70f;
private float t = 0.0f;

private void Update()
{
    if(smoothChange) pChangeFoV();
}

private void pChangeFoV()
{
    _camera.fieldOfView = Mathf.Lerp(_camera.fieldOfView, zValue, t);
    t += Time.deltaTime / FoVDuration;

    if(t >= 1.0f)
    {
        _camera.fieldOfView = zValue;
        smoothChange = false;
    }
}

```

Although I'd rather use coroutines for these kinds of functionalities.

---
Tags: unity
---


# Question
Title: How to extract a point in LibGdx from Tiled map?
Tiled has a feature to insert a point in to an Object layer. But there doesn't seem to be a "PointMapObject" implementation in Libgdx on the doc. currently i am being forced to use a PolylineMap Object with two vertices but all i want is only the x or y of the first vertex.

# Answer
Actually points in LibGDX are treated as RectangleMapObject with height=0.0 and width=0.0.

Below debbuger output of object that is point on the tiled side:
> 3 votes

---
Tags: libgdx, tiled
---


# Question
Title: Parabolic Jump Libgdx Without Box2D and With Vectors
I have tried to write a jump method that sketches out a parabolic jump but it results in either no movement, or a jerky upward movement when I try to scale up dt. I have the following things defined:

```
    x = 0;
    y = 250;
    pos.set(x, y); // position of player
    velocity.set(2, 12); // player velocity
    gravity.set(0, -2); // player gravity

```

Then I have the key input processor:

```
private void handleInput(float dt)
{
    if(Gdx.input.isKeyPressed(Keys.D))
        x += velocity.x;

    if(Gdx.input.isKeyPressed(Keys.A))
        x -= velocity.x;

    if(Gdx.input.isKeyJustPressed(Keys.W))
        jump(dt);

    pos.set(x, y);
    bound.setPosition(pos);
}

```

This is the jump method which takes in a Gdx delta time method:

```
private void jump(float dt)
{
    y += velocity.y * dt;
    velocity.set(velocity.x, velocity.y + gravity.y);

    pos.set(x, y);
    bound.setPosition(pos);
}

```

This is all called in the update method which is called once per frame in the render method:

```
public void update(float dt)
{
    handleInput(dt);
    movement(dt);
    collision(dt);
}

```

# Answer
Here I created jump function which increases velocity toward upwards. Movement function, on the other hand, updates sprite(the player)'s position each frame. Trick is movement function uses velocity multiplied with Time Delta (seconds between each frame) to calculate position on the next frame.

* movement function runs every frame, so it goes in main loop.
* jump is called once (and must be only once) key is pressed, not each frame while key is pressed.

Gravity is there always, decreases vertical velocity each frame.

Code with inline comments:

```
private void jump(float dt)
{
    velocity.set(velocity.x, velocity.y + jumpPower);//define   jumpPower in your code
}

public void movement(float dt) //I believe should you have this
{
    pos.set(x + (velocity.x * dt), y + (velocity.y * dt));//set position every frame
    bound.setPosition(pos); //?set sprite position (not sure)
    velocity.set(velocity.x, velocity.y * dt * gravityPower)//decrease vertical velocity every frame
}

```
> 1 votes

# Answer
It could be that you only update the 'y' velocity when you call jump. Try updating 'y' every frame. Then when you call jump just increase the 'y' velocity.
> 0 votes

---
Tags: java, libgdx, platformer, jumping
---


# Question
Title: Is it possible to add a sprite to a joint?
I want to have a joint between two objects, but I also want to highlight to the user that these two objects are connected together.

I am assuming this isn't the correct method, as a joint is just a component.

Note: I am a total Unity newbie.

I just want some method to indicate to a user which items are jointed together.

A code solution is totally fine - I am very comfortable programming. Maybe extending the joint class and adding a sprite selector?

# Answer
This link seems to indicate that the proper way to do this is via a script that links two objects with a line.

https://www.raywenderlich.com/1766-physics-joints-in-unity-2d

EDIT:

The code for the line script is here (writing it to preserve it in case anyone needs it):

```
public class Line : MonoBehaviour {

    public GameObject gameObject1;          // Reference to the first GameObject
    public GameObject gameObject2;          // Reference to the second GameObject

    private LineRenderer line;                           // Line Renderer

    // Use this for initialization
    void Start () {
        // Add a Line Renderer to the GameObject
        line = this.gameObject.AddComponent<LineRenderer>();
        // Set the width of the Line Renderer
        line.SetWidth(0.05F, 0.05F);
        // Set the number of vertex fo the Line Renderer
        line.SetVertexCount(2);
    }

    // Update is called once per frame
    void Update () {
        // Check if the GameObjects are not null
        if (gameObject1 != null && gameObject2 != null)
        {
            // Update position of the two vertex of the Line Renderer
            line.SetPosition(0, gameObject1.transform.position);
            line.SetPosition(1, gameObject2.transform.position);
        }
    }
}

```

Then you just set the two game objects of the script, either programmatically or in the IDE. After that, a line render component will generate, and all you have to do here is set a material for the line render component.

This very nicely and neatly rendered a line between my two objects.
> 1 votes

# Answer
You can add sprite via material. It is good and with great control.
> -3 votes

---
Tags: unity
---