title: Detect Triple click

text:
# Question
Title: Detect Triple click
I need a triple click detection on my 2d game.

I have a Canvas with a fire button inside and I'm searching a way to trigger 3 different actions on the player's script when I press this button once, twice, or three times.

There's a similar question about detecting double-clicks in Unity, but it wasn't clear which of the seven different answers would be appropriate for this situation, or how to extend them to handle three clicks.

# Answer
> 3 votes
The basic strategy here is to set up our script to **remember it was clicked** (some number of times), but **delay acting on that information** for a short period of time, in case another click immediately follows.

For UI elements in a Canvas, the most robust method is probably to use a variation on Norb's answer for the double-click case. This leverages the Unity UI event system to give a lot of flexibility.

For this, we put a custom `ClickController` script on each UI object we want to be able to react to multiple click types - make sure they have their "Raycast Target" box checked so they're visible to mouse events:

```
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using System.Collections;

public class ClickController : MonoBehaviour
{
    // Configure how we listen for clicks (how fast, which button).

    [Tooltip("Seconds after each click to wait for a follow-up")]
    public float timeLimit = 0.25f;

    [Tooltip("Which mouse/stylus button to react to")]
    public PointerEventData.InputButton button;

    // Expose events we can wire-up in the inspector to our desired handlers.

    // I added this so we can use it to show visible feedback immediately
    // on the first click, to minimize perceived latency.
    public UnityEvent onAtLeastOneClick;

    public UnityEvent onSingleClick;

    public UnityEvent onDoubleClick;

    public UnityEvent onTripleClick;

    // Internal state for keeping track of clicks.

    private int clickCount;
    private Coroutine delayedClick;

    // Auto-configure on Start.
    // I added this to reduce fiddly inspector setup - we'll use an existing
    // EventTrigger component if it's there, or add one & wire it up if not.
    void Start()
    {
        EventTrigger trigger = GetComponent<EventTrigger>();
        if (trigger == null)
            trigger = gameObject.AddComponent<EventTrigger>();

        var entry = new EventTrigger.Entry();
        entry.eventID = EventTriggerType.PointerClick;
        entry.callback.AddListener(onClick);

        trigger.triggers.Add(entry);
    }

    // Main click handler - this is where the magic happens.
    public void onClick(BaseEventData data)
    {
        PointerEventData pointerData = data as PointerEventData;

        // Ignore clicks on buttons we're not watching.
        if (this.button != pointerData.button)
            return;

        // Count up the clicks.
        clickCount++;

        // React accordingly.
        switch(clickCount)
        {
            // First click: fire OnAtLeastOneClick and wait to see if a second comes in.
            case 1:
                delayedClick = StartCoroutine(DelayClick(onSingleClick, timeLimit));
                onAtLeastOneClick.Invoke();
                break;
            // Second click: cancel single-click and wait to see if a third comes in.
            case 2:
                StopCoroutine(delayedClick);
                delayedClick = StartCoroutine(DelayClick(onDoubleClick, timeLimit));
                break;
            // Third click: cancel double-click fire OnTripleClick immediately.
            case 3:
                StopCoroutine(delayedClick);
                delayedClick = null;
                onTripleClick.Invoke();
                clickCount = 0;
                break;
        }
    }

    // This handles firing off the click after a delay.
    // We cancel it if a new click comes in sooner.
    private IEnumerator DelayClick(UnityEvent clickEvent, float delay)
    {
        yield return new WaitForSeconds(delay);
        // This coroutine didn't get stopped, so no new click came in.
        // Fire off the corresponding click event and reset.
        clickEvent.Invoke();
        clickCount = 0;
        delayedClick = null;
    }
}

```

The script looks like this when attached, with four events you can link-up to call public methods on any component in your scene:

As described in the comments above, I added the `OnAtLeastOneClick` method so we have something we can call right away as soon as the player interacts (triggering this OnPress would also work if you need it even sooner). Firing off some visual and audio feedback at that moment can help cover the waiting period for the next click to come in, helping the interaction feel snappy & responsive. Since at this moment we don't yet know whether this will be a single-, double-, or triple-click, the feedback has to work for all three, and more specialized feedback can be triggered a fraction of a second later once we know for sure what input action we're dealing with.

---
Tags: unity
---


title: How to draw textured tile map in opengl

text:
# Question
Title: How to draw textured tile map in opengl
I am trying to create a textured hexagonal tile map in opengl. I have the VBO and respective index buffer. Additionally I have a texture atlas for texturing individual tiles. I'm attempting to create a distinct texture for each hex without mixing the textures.

I understood that one should use a pair of (U,V) texture coordinates for each vertex. Now if the tile map would not be indexed and have the overlapping vertices, I could just set the texture coordinates for each vertex and get each hex rendering the correct texture. However, with indexing the overlapping vertices are gone and I can only set single pair of texture coordinates for each vertex which results in the textures mixing inside the hexes. Is there a way to texture tiles with indexing or another alternative approach to creating hex maps with different textures?

# Answer
> 1 votes
Vertices can only be merged when every single attributes are the same.

A vertex can have the same position as another without having the same UV, color, or differ in other attributes.

You can still use an index buffer to merge the vertices of triangles making up each individual hexagons (7 vertex instead of 18 to make a nice pie with a center, or 6 (instead of 15) if you don't mind long triangles) but no two tiles will share vertices.

---
Tags: opengl, textures, tilemap, index-buffer
---


# Question
Title: Can I use models of real cars with logos removed to avoid copyright infringement?
My friends and I have recently started making a video game. We were going to make it an open world simulator, but can't figure out if using real cars with the real logos is copyright infringement. How can we stay on the right side of the law here?

# Answer
> 7 votes
I'm not an expert, but I think that it's still copyright infringement on the design of the car. If you make a similar style of car, but not the same model, that's okay. There's tons of creative commons models of cars online, so I recommend using those.

# Answer
> 2 votes
Have a look into Grand Theft Auto by DMA Design.

Here you see an example of a selection of cars that were based upon real cars closely enough that they were instantly recognisable. They used names similar but not the same as the real names, in many cases using the car model's nicknames (Such as "Cossie" for the Ford Sierra Cosworth.

This game was immensely popular and spawned one of the best selling driving simulation game series of all time.

I've done some googling and found them to be the subject of many court cases, however none of them seemed to relate to any copyright claims by any car manufacturers or designers.

I'd be quite confident in following their lead, but of course ***I am not a lawyer***

Do keep away from using brand names without permission though, that's just asking for trouble.

# Answer
> 2 votes
Mass produced functional items like cars aren't subject to copyright. What could get you in trouble is violating trademarks. It's not just name and logos the are trademarked, but also distinctive non-functional details like the front grill. Harley-Davidson even once tried to trademark the sound of their engines. A number of years ago Hummer ran advertisements in game magazines threating developers if they violated their trademarks. Cars can also be protected by design patents, but I don't know if such protection would extend to a depiction of a car in a video game.

I don't think there's any case law on this, and while my belief is that you would ultimately prevail in the courts if you, say, put a Ford Focus in your video game without permission, it would only be after a long and expensive battle. Regardless, the video game industry either thinks differently or has decided its not worth fighting these battles and either obtains permission to use real cars in their games (eg. most racing games), or makes up fake ones to include (eg. Grand Theft Auto and its various clones).

# Answer
> 0 votes
It is a risky endeavor, and I wouldn't want to try my luck. Rather, make something that is at best remotely similar, but not immediately recognizable.

There exist design patents, and the possibility that the owners enforce it is very real. If you make something that is at first look recognizable as XYZ, then you are heading for trouble. With some luck, nothing happens, but you don't know that.
Depending on how serious the owners of the design patents are, this can get very expensive for you (but even a simple C&D may easily cost you a couple of grands).

Remember the 1980s TV series Miami Vice with the black Ferrari Daytona? Turned out they didn't buy a Ferrari, but used a kit car which looked very similar. That worked well until the day Enzo came up with a lawsuit.

---
Tags: legal, copyright, vehicle
---


# Question
Title: Fast, simple procedural 2d island generation
I need to generate tile data for an island based rpg, my goal is have something that looks like this (mountains not required):

For the past few days I have been trying to figure out a satisfactory way to generate tile data that will give me varied and natural islands, such as in the example above.

I've tried using Unity's Mathf.PerlinNoise but the results are far too random, and I can't see a way to get it to generate a single island.

Using LibNoise I was able to get slightly better results, although the generation seems to be significantly slower and perhaps better suited to 3d terrain. Similarly however, I can't see a way to set the Octaves/Frequency/etc, so that I get a nice single island each time.

While there are a fair amount of resources online for perlin/noise in general, it mostly seems to be aimed at 3d terrain and height, where I simply have a 2d array of int for my tile data, that maps to either water, sand or grass and needs to be generated in such a way that sand/grass are grouped together logically to form an island.

Any help would be greatly appreciated!

# Answer
One thing I've done in the past for island shapes is to use perlin noise *minus* a circular shape. It usually produces one big island and some little things off on the side. You can use flood fill or smoothing to remove any small noise.

Here's a demo (flash) that I wrote for this question.

For each location `(x, y)` in the noise bitmap, compute the distance from the center, normalized so that the bitmap is 2x2:

```
function distance_squared(x, y):
    dx = 2 * x / width - 1
    dy = 2 * y / height - 1
    # at this point 0 <= dx <= 1 and 0 <= dy <= 1
    return dx*dx + dy*dy

```

Location `(x, y)` is part of the island if `perlin_noise(x, y) > 0.3 + 0.4 * distance_squared(x,y)`. In the demo you can vary the two constants to see the effects you can get.

I don't think these islands look quite the way you want but this technique might be useful for you in combination with other techniques you're using.
> 12 votes

# Answer
I don't do a lot of 2d in Unity, but I can still make this pretty easily. So, first you start with a minimum and maximum (x,y) then generate a random. From here you need a basic island tileset (full islands) then you will find a random island in code and instantiate it. Henceforth, you now have a island. TRUELY random generation is much harder.
> -2 votes

---
Tags: c#, unity, tiles, procedural-generation
---


# Question
Title: How do you save the rendering of a tiled map to an image?
Im currently using LibGDX and drawing a tiledmap with the OrthogonalTiledMapRenderer. Is there a way to save one rendering and put it into some file as an image? If you know of a method that doesnt use OrthogonalTiledMapRenderer, thats ok too.

# Answer
Try this:

https://github.com/libgdx/libgdx/wiki/Taking-a-Screenshot

You might also want to try FrameBufferObjects

https://github.com/mattdesl/lwjgl-basics/wiki/FrameBufferObjects

(Note the link near the top of this article to the LibGDX version)

Good luck!
> 0 votes

---
Tags: java, libgdx, file, tiles
---


# Question
Title: unable to create a IDXGIDevice with D3D12CreateDevice()
I was trying to do a bare bones simple build similar to some Directx samples. First I have to use `__uuid()` instead of `IID_PPV_ARGS()` in `D3D12CreateDevice()` in order to get an `HRESULT=S_OK`. But then when I try to create a command queue with `CreateCommandQueue` visual studio says that the device object which is really a com pointer `ComPtr<IDXGIDevice>` doesn't have a member function `CreateCommandQueue`, even though when I look through the `D3D12.h` header I can see it declare it as a public member.

# Answer
A bare-minimum would be:

```
ComPtr<ID3D12Device> device;
HRESULT hr = D3D12CreateDevice(nullptr, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&device));
if (FAILED(hr))
    // Error!

```

This will fail if the default device doesn't have an updated WDDM 2.0 driver that supports DirectX 12.

> This program would also fail to run/bind on a system older than Windows 10 because `D3D12CreateDevice` in `d3d12.dll` only exists on Windows 10 systems.

You cannot `QueryInterface` a `IDXIGDevice` from a `ID3D12Device`, nor can you create a `IDXGIDevice` using `D3D12CreateDevice`. This is not supported for Direct3D 12. DXGI is strictly for dealing with adapters, outputs, and swap chains, not Direct3D devices.

See Anatomy of Direct3D 12 Create Device
> 0 votes

---
Tags: directx12
---


# Question
Title: LibGDX: How do I manage Player position?
I'm making a 2D isometric tiled game using LibGDX. In my Player class, I created a vector2 that I named 'pos' to manage the player position, then I draw my Player with:

```
    batch.begin();
    batch.draw(localPlayer.texture,LocalPlayer.pos.x,LocalPlayer.pos.y);
    batch.end();

```

Let's say pos = (0,0), then the Player will be rendered at the bottom left corner of my screen.

When I translate the camera, the (0,0) still correspond with the bottom left of my screen, so the pos Vector2 is about my screen, not my map...

What should I do to get a Coordinate System based on the map and not on my screen? I would not prefer using the Sprite Class...

Thank you :)

# Answer
> 0 votes
Have a look at model view protection matrix (matrix transformations): http://www.opengl-tutorial.org/beginners-tutorials/tutorial-3-matrices/

This is related to OpenGL, but the operations are similar in any library.

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


title: how to make my character jump

text:
# Question
Title: how to make my character jump
I want my player to jump and i tried my best to do it and i couldn't. Basicaly my class are splitted(i have speparate player class and keyboard class) which i thought would make my life easier but didnt.

I made it so that if i press space bar, then i would fly(this is for temporarily and i wanted it to jump) and also i added gravity.

It would be great if you guys posted what to add on what class and explain what it does cause im a noob at java.

Thnx

My Player Class

```
package com.vescorspel.game.MyFirstGame.entities.creatures;

import java.awt.Graphics;
import java.awt.image.BufferedImage;

import com.vescorspel.game.MyFirstGame.Handler;
import com.vescorspel.game.MyFirstGame.gfx.Animation;
import com.vescorspel.game.MyFirstGame.gfx.Assets;

public class Player extends Creatures{

//Animations
private Animation animRight, animLeft;

public Player(Handler handler, float x, float y) {
    super(handler, x, y, Creatures.DEFAULT_CREATURE_WIDTH, Creatures.DEFAULT_CREATURE_HEIGHT);

    bounds.x = 32;
    bounds.y = 32;
    bounds.width = 92;
    bounds.height = 96;

    //Animations
    animRight = new Animation(100, Assets.DerpDino_right);
    animLeft  = new Animation(100, Assets.DerpDino_left);
}

@Override
public void tick() {

    //Animations
    animRight.tick();
    animLeft.tick();
    //Movement
    getInput();
    move();
    handler.getGameCamera().centerOnEntity(this);
}

private void getInput(){
    xMove = 0;
    //Gravity
    yMove = 5;

    if(handler.getKeyManager().left)
        xMove = -speed;
    if(handler.getKeyManager().right)
        xMove = speed;
    if(handler.getKeyManager().jumping)
        //this makes my player fly
        yMove = -speed;
}

@Override
public void render(Graphics g) {
    g.drawImage(getCurrentAnimationFrame(), (int) (x - handler.getGameCamera().getxOffset()), (int) (y - handler.getGameCamera().getyOffset()), width, height, null);

private BufferedImage getCurrentAnimationFrame(){
    if(xMove < 0){
        return animLeft.getCurrentFrame();
    }else{
        return animRight.getCurrentFrame();
    }
}

}

```

My KeyManager Class

```
package com.vescorspel.game.MyFirstGame.input;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class KeyManager implements KeyListener{

private boolean[] keys;
public boolean left, right, jumping;

public KeyManager(){
    keys = new boolean[256];
}

public void tick(){
    left = keys[KeyEvent.VK_A];
    right = keys[KeyEvent.VK_D];
    jumping = keys[KeyEvent.VK_SPACE];
}

@Override
public void keyPressed(KeyEvent e) {
    keys[e.getKeyCode()] = true;
    System.out.println("Pressed!");
}

@Override
public void keyReleased(KeyEvent e) {
    keys[e.getKeyCode()] = false;
}

@Override
public void keyTyped(KeyEvent arg0) {
}

}

```

# Answer
You need to implement Kinematics - Movement Obliquely in his game. Of course, if you want to simulate our world. Remind your world your rules. Or if you prefer to use a ready-made physical engine like JBox2D.

The explanation is very long and I'm not in the area of physics, so I'm being corrected if I'm wrong about anything, please.

First define the real-world scale in your game. How many pixels are equal to one meter? This is important for calculations, it is called discretization. Define a constant in the code, for example:

```
private final double PIXELS_POR_METER = 10.0;

```

Second, all objects with mass will be actively acting on gravity in your game and make contact with the ground, simple example:

```
// Game gravity
private final GRAVITY = -10; // 10 m / s²

// Initial velocity in leap angle factor
// Example angle definition: jump only - 90 degrees, jump + right / left - 45 degrees
V0y = v0 + Math.sin (angle);
// Where v0 is the initial velocity of the body, usually velocity of the character

Double time = 1.0 / getFps (); // search about this getFps () function, it returns how many frames are redrawn every second in your game.
y + = v0y * time + GRAVITY * time * time / 2; // displacement to each frame

// Contact with the floor
If y <= y_floor {y = y_floor};

```

This operation is only for the Y axis. Usually in a 2D game is enough because the offset on the X axis is controlled by the user. What does not happen in the real world.

These calculations are in real world scale. Finally, make it into game coordinates before you draw.

```
// Position in pixels unit
Double x_real = x / PIXELS_POR_METER;
Double y_real = y / PIXELS_POR_METER;

```

That's it, remembering that any mistake warn me so I can fix it.

Study for understand more: kinematics formulas
> 1 votes

# Answer
I will tell my logic that would work with any type of framework with little modifications.

```
Void jump()
{
    static bool j=false;// is jumping
    If( key ==' ' && j == false)
          J = true;
    If (j && obj.y < maxheight)
        Obj.y ++;
    If(obj.y > maxheight)
        Obj--;
    If ( obj.y< minheight)
        J = false;
}

```

Basically it set the signal variable to false initially. It means the ball is on the ground

If we hit a space the variable is set to true, obj will rise and get the max height...after that it will decrease..once it touched the ground the control variable is set to false..

This should be called in a game loop to make it work..

this Is all about jumping...you have to transform this code to make it work in java
> 0 votes

---
Tags: java, jumping
---


# Question
Title: Creating chat bubble using 9-patch and Glyphlayout
I'm trying to create a chat bubble using 9patch as my background and text in the front.It is not drawing anything and I am unable to find the mistake in my code.

PS: I've taken some help from prev answers to write this code

Here is my code

```
 public void render(SpriteBatch sb) {

        chatBubble.drawSpeech(str,(int)Gdx.graphics.getWidth()/2,(int)Gdx.graphics.getHeight()/2,sb);

```

}

and ChatBubble class is given below:

```
public class ChatBubble {

    private NinePatch ninePatch;
    private Texture bubble;

    private Random rand = new Random();

    BitmapFont font = new BitmapFont();

   public ChatBubble() {

        bubble = new Texture("bubble.png");
        ninePatch = new NinePatch(new TextureRegion(bubble, 1, 1, bubble.getWidth() - 2, bubble.getHeight() - 2), 10, 10, 10, 10);

    }
    int textBoxBuffer = 5; // Allow for box to surround the text
    int textBoxWidth = 80; // the default width of the textbox
    public void drawSpeech(String str, int x, int y,SpriteBatch sb){
        sb.begin();
        GlyphLayout layout = new GlyphLayout(font,str, Color.BLACK, textBoxWidth , Align.left, true);
        ninePatch.draw(sb,x - textBoxBuffer, y - textBoxBuffer,
                layout.width + textBoxBuffer, layout.height + textBoxBuffer);
        font.draw(sb, layout, x, y);
        sb.end();
    }

}

```

# Answer
> 0 votes
I can't see where you are loading your `font` from the code you posted, but you need to load it with a `.fnt` file and an atlas. Or, you can load it from a `Skin`.

One way of achieving the bubble would be something like this;

```
package com.bornander.androidstudiosandbox;

import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.GlyphLayout;
import com.badlogic.gdx.graphics.g2d.NinePatch;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.utils.Align;

public class MyAndroidStudioSandboxGame extends Game {
    private SpriteBatch batch;
    private OrthographicCamera camera;

    private Texture bubble;
    private NinePatch ninePatch;
    private BitmapFont font;
    private GlyphLayout dialogGlyphLayout = new GlyphLayout();

    @Override
    public void create () {
        batch = new SpriteBatch();

        // Set up a camera that is the same size as the window and set the lower left corner to be 0,0
        camera = new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
        camera.position.set(Gdx.graphics.getWidth() / 2.0f, Gdx.graphics.getHeight() / 2.0f, 0);

        // Load the skin that has the bitmap font
        Skin skin = new Skin(Gdx.files.internal("uiskin.json"));

        // Get the font from the skin
        font = skin.get("default-font", BitmapFont.class);
        bubble = new Texture("bubble.png");

        // Create the bubble nine-patch, this one has a margin of 5 pixels
        ninePatch = new NinePatch(new TextureRegion(bubble, 0, 0, bubble.getWidth(), bubble.getHeight()), 5, 5, 5, 5);
    }

    @Override
    public void render () {
        Gdx.gl.glClearColor(0, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        camera.update();
        batch.begin();
        batch.setProjectionMatrix(camera.combined);
        renderBubble("Hello, world!\nHello, again!");
        batch.end();
    }

    private void renderBubble(String text) {
        // 0.75 to make the dialog max 75% the width of the screen
        dialogGlyphLayout.setText(font, text, Color.WHITE, Gdx.graphics.getWidth() * 0.75f, Align.topLeft, true);

        float tw = dialogGlyphLayout.width;
        float th = dialogGlyphLayout.height;

        // 0.05 for 5% margin, dw and dh are the width of the bubble
        // bo the bubble is the size of the text, plus a 5% margin (of the window size)
        float dw = tw + 0.05f * Gdx.graphics.getWidth();
        float dh = th + 0.05f * Gdx.graphics.getHeight();

        // bx, bh is the position of the buggle
        float bx = (Gdx.graphics.getWidth() - dw) / 2.0f;
        float by = Gdx.graphics.getHeight() - dh * 1.2f;

        ninePatch.draw(batch, bx, by, dw, dh);

        font.draw(batch,  dialogGlyphLayout, bx + (dw-tw) / 2.0f, by + dh - (dh-th) / 2.0f);
    }
}

```

In this case I am loading an image for the bubble that looks like this;

I also using the *uiskin* from **libgdx** tests; LibGdx tests at GitHub

The important files in there are;

* uiskin.json (This is the json definition that describes the skin)
* uiskin.png (This is the graphics)
* uiskin.atlas (This is the texture atlas that defines the texture regions the graphics, including the bitmap for the font)
* default.fnt (This is the file that describes where each letter is in the bitmap font).

Given all that, the example above creates a horizontally centered, top-aligned bubble that is sized to hold the text plus a little margin.

---
Tags: android, libgdx
---


# Question
Title: C# What is the advantage of using interfaces for simulating multiple inheritance?
Interfaces are a feature of C# that I've never quite been able to see the purpose of. I see them used all the time in professional code, but for the life of me I can't work out the reasoning.

My question here is specifically about interfaces to simulate multiple inheritance. In reading around the subject, I'll often come up on an example like this:

```
interface IAddition
{
    int add(int a, int b);
}

interface ISubtraction
{
    int sub(int a, int b);
}

class Calculation : IAddition, ISubtraction
{
    public int add(int a, int b)
    {
        return result1 = a + b;
    }

    public int sub(int a, int b)
    {
        return result1 = a - b;
    }
}

```

What I don't understand is - what benefit do the interfaces bring here? It looks to me like you could remove them completely, and the Calculation class would still work exactly the same. What am I missing here?

Any help would be appreciated - I've been looking for something to make interfaces 'click' in my head for quite a while now.

The reason I look for the solution to this is for making games. Multiple inheritance seems to be a good solution for making flexible game objects, but I've haven't quite got a proper grasp of it yet.

# Answer
> 2 votes
An interface represents a *contract*, they're used to allow a method to state that it needs something that fulfills that contract, when the actual details of that contract aren't known.

You example is a bit weird because things aren't usually **both** an addition and a subtraction, it might make more sense for it to be something like this;

```
public interface ICalculation {
    int DoOperation(int a, int b);
}

public class Addition : ICalculation {
    public int DoOperation(int a, int b) {
        return a + b;
    }
}

public class Subtraction : ICalculation {
    public int DoOperation(int a, int b) {
        return a - b;
    }
}

public class Calculator {
    int GetResult(ICalculation calculation, int a, int b) {
        return calculation.DoOperation(a, b);
    }
}

```

The `Calculator` does not need to know how to add now, only that it needs to use the `Addition` implementation of the `ICalculator` contract.

---
Tags: c#, inheritance
---


# Question
Title: Vector3 Array serialization ReorderableList
I've been working on a ReorderableList, but it's given me quite the headache. I've come to the point where I want to define a "drawElementCallback" -callback, which looks like this:

```
list.drawElementCallback = (rect, index, active, focused) => {
    EditorGUI.PropertyField(rect, list.serializedProperty.GetArrayElementAtIndex(index), GUIContent.none);
};

```

What it's supposed to draw is one Vector3 object from an array of Vector3 objects. I get this property like this: ("property" is a SerializedProperty that contains the property that I need)

```
SerializedProperty locationsProperty = property.FindPropertyRelative("locations");

```

The array is declared as follows:

```
public Vector3[] locations;

```

Inside a container class that is marked as "Serializable".

The problem I kept getting with different code is that the ReorderableList shows all the Vectors correctly but it doesn't allow me to reorder any of the items, nor delete them (I can add new Vector3 objects and change them as expected).

With this code, I wanted to fix that issue. However, now I keep getting the following error:

***"InvalidOperationException: The operation is not possible when moved past all properties (Next returned false)"***

I wanted to make a reorderable list because it seemed easy, but I can't figure out the problem and I honestly wish I hadn't started working on it. It's taken up most of the past 3 days.

If anyone knows how to fix this, I would be very grateful.

**To clarify, this code shows the array properly:**

```
list.drawElementCallback = (rect, index, active, focused) => {
    SerializedProperty item = locationsProperty.GetArrayElementAtIndex(index);

    EditorGUI.BeginChangeCheck();
    item.vector3Value = EditorGUI.Vector3Field(rect, string.Empty, item.vector3Value);
};

```

But doesn't allow me to remove or reorder items. I thought I should show the code to demonstrate that there are indeed array items.

# Answer
> 0 votes
I couldn't find the right solution at first, so what I did to solve the problem was make two scripts.

The first was the script that previously contained a bunch of properties, including the array that I wanted to show in the editor. (**SerializedObject**-\> SerializedObject-\> Array of Vector3 Objects)

The editor script linked to this added a button to add a script as component, which was the script that previously contained the array of Vector3 objects that I wanted to show in the editor. (SerializedObject -\> **SerializedObject-\> Array of Vector3 Objects**)

This allowed me to make two seperate editor scripts; One for the parent object, and one for the child object that contained the list of Vector3's that I wanted to serialize. This made it a lot easier to obtain the SerializedProperty that I needed to create the ReorderableList.

I simply copied the following script and changed it to my needs afterwards, and it was fine: http://va.lent.in/unity-make-your-lists-functional-with-reorderablelist/

*I tried to make it as clear as possible, feel free to ask me to clear something up if I didn't manage to do so!*

I think the problem was that I didn't get how I paths worked in serializedobjects. It would have looked something like this, to get the list of Vector3 objects inside the child object of the parent object: *parentobject.array.data\[index\].childobjectname.array.data\[index\].vector3arrayname.array.data\[index\]*

Simply put, if you're in a situation where you're working with nested objects make sure you know how relative paths work!

---
Tags: unity, serialization
---


# Question
Title: Greenfoot java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
When an enemy comes into contact with the hero the hero class is supposed to remove the enemy class with the same X and Y. It works the first time but throws an error immediately after that:

> java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
> at java.util.ArrayList.rangeCheck(ArrayList.java:653) at java.util.ArrayList.get(ArrayList.java:429)
> at Hero.checkCollision(Hero.java:39)
> at Hero.act(Hero.java:23)

```
public void act()
{
    ...
    checkCollision();
    ...
}
private void checkCollision()
{
    Actor 2 = (Actor)getWorld().getObjects(2.class).get(0);
    if(2.getX() == getX() & 2.getY() == getY()) {
        getWorld().removeObject(2);
    }
    Actor 1 = (Actor)getWorld().getObjects(1.class).get(0);
    if(1.getX() == getX() & 1.getY() == getY()) {
        getWorld().removeObject(1);
    }
    Actor 3 = (Actor)getWorld().getObjects(3.class).get(0);
    if(3.getX() == getX() & 3.getY() == getY()) {
        getWorld().removeObject(3);
    }
      if (Room.totalPeeps == 0) {
          setLocation(250,250);
          GreenfootImage img = getImage();
          img.setFont(img.getFont().deriveFont(30f));
          setImage(new GreenfootImage("YOU WIN!!" , 75, Color.WHITE, Color.BLACK));
          Greenfoot.stop();
    }
}

```

# Answer
> 0 votes
After a `getWorld().removeObject();` there will be no instances of the classes anymore in the container, and hence trying to access the first element at index 0 will throw that exception. You need to add in size checks.

So you would want to write something like

```
if (getWorld().getObjects(2.class).size() > 0)
{
    Actor 2 = (Actor)getWorld().getObjects(2.class).get(0);
    if(2.getX() == getX() & 2.getY() == getY()) {
        getWorld().removeObject(2);
    }
}
... same for the other two

```

---
Tags: java, greenfoot-engine
---


title: Do I need an Indie Studio Name?

text:
# Question
Title: Do I need an Indie Studio Name?
I've recently been making a mobile game which I'm going to publish to Google Play. Google Play requires a Developer Name. Most Google Play Developer use their game studio name like Gameloft, Supercell, etc. But some indies use their names as the developer name like Scott Cowthon, FNAF Developer. I was wondering what are the advantages and disadvantages of each type to me as the only developer of my game?

# Answer
The name is the centre focus of your entire brand, so it's something to think over carefully before you publish your first product.

Using your real name can show that personable touch you apply to your software but also has the increased risk of exposing your identity in a way that gives new meaning to the word public. I favour real names because it tends to be a lot more sensible/coherent than "Deadly Dinosaur Designs", "Banana BreadBox Banana Boom Games Bah!" or any of the other usual indie dev studio names. The most important thing though is **if your real name alliterates then you have to use it.** Scott Scotty is the kind of branding I want to see at the top of the app store tomorrow.

At the end of the day it's your call and although it represents the flag your games hoist it's not going to make or break you as a dev. The pain and permanence of naming things is why most major studios adopt a codename for their next title so they don't have to weep over what they're going to call the Unity Project for a week.
> 47 votes

# Answer
Use your real name, or a nickname, because you're not a studio right now.

* Players have higher expectations if it looks like the game is written by a studio, and are less forgiving of rough edges.
* Interactions with your players are more friendly if they think you're a real person, and not a faceless corporate brand.
* Creating a brand is work, and you don't need to do that now. Focus on the game.
* If your game is a success, **you want your name attached to it.**

I used a brand when I started making indie games, but I wish I hadn't now. Present yourself as you really are.
> 38 votes

# Answer
Well having your own name as the sole developer should only be used if you are the only one who made the game. If an artist or writer were used then you should use a studio name because that means everyone is involved. If you plan to expand and hire staff use a studio name to save on google play license costs.

So I recommend using a Studio name so later you can expand in your studio and possibly hire other people to help you create games.
> 6 votes

---
Tags: google-play
---


# Question
Title: How do I get my iOS game to have custom background
Sometimes when you go on the App Store to look at games, some have a custom background, instead of the default white. Does this cost extra money to do? Or do certain conditions for the game have to be met?

# Answer
Unless Apple has changed something in the policy your app has to be featured to have a custom background.

That means this is not something that you can just set as a developer, your game has be be selected to be featured for this.
> 2 votes

---
Tags: appstore
---


title: How do Inventories work?

text:
# Question
Title: How do Inventories work?
I am trying to create a inventory screen / system for my game. And I don't know how it will work. I'm creating it in unity. I was thinking of making a database of all items and a database of items in inventory. However unity has no database function. Another problem would be using a web database. Every single player can't have their own database, it would be overkill.

I haven't started writing any code for the inventory but only planning for it. The type of inventory system I am planning is similar to skyrim. List on left and stats for items on the right.

# Answer
> 8 votes
I recommend that you do not "pass around Items" as an actual object, but instead, have each item stored in a `Dictionary<int,GameItem>`. Each item has it's own integer id, which you pass around and store in the inventory. So say Iron Ore has an id of 4, and you have 18 of them. In your inventory there would be a struct that says 18, 4. You then use the id to fetch the actual item from a Dictionary. Doing it this way will greatly reduce, if not completely eliminate, stressing out the garbage collector. You can also think of it like how instancing models in OpenGL or DirectX works, why would you initialize a tree model hundreds of times when you could just initialize it once and reuse it?

I also wanted to mention that this is how most, if not all, modern games handle their in game resources. A good example being Skyrim, which uses an id for literally everything. When a player opens up their inventory, they are simply querying the Dictionary with the integer ids in their inventory; which is then read and converted to a presentation layer, showing the item's name and attributes.

And as a final note, the only limitation to this is ((2^31)-1) items, which again can also be doubled if you use an unsigned integer. But let's be honest right now, not even MMO's like World of Warcraft have anywhere close integer max number of items. (Wowhead says 100,458 total items)

Here is a brief example of what your inventory should actually be holding.

```
using System;

namespace Your.Game.Framework.Namespace
{
    public struct ItemStack : IEquatable<ItemStack>
    {

        public int ID { get; }
        public int Quantity { get; }
        public const int MinimumItemQuantity = 0;

        public ItemStack(int id, int quantity)
        {
            this.ID = id;
            this.Quantity = quantity;
        }

        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public ItemStack ToEmptyQuantity()
        {
            return new ItemStack(this.ID, 0);
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj)) return false;
            return obj is ItemStack && Equals((ItemStack)obj);
        }

        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public override int GetHashCode()
        {
            unchecked
            {
                return (ID * 397) ^ Quantity;
            }
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="a"></param>
        /// <param name="b"></param>
        /// <returns></returns>
        public static bool operator ==(ItemStack a, ItemStack b)
        {
            return a.Equals(b);
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="a"></param>
        /// <param name="b"></param>
        /// <returns></returns>
        public static bool operator !=(ItemStack a, ItemStack b)
        {
            return !(a == b);
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="other"></param>
        /// <returns></returns>
        public bool Equals(ItemStack other)
        {
            return this.ID == other.ID && this.Quantity == other.Quantity;
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="packet"></param>
        /// <param name="quantity"></param>
        /// <returns></returns>
        public static ItemStack operator +(ItemStack packet, int quantity)
        {
            return new ItemStack(packet.ID, packet.Quantity + quantity);
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="packet"></param>
        /// <param name="multiplier"></param>
        /// <returns></returns>
        public static ItemStack operator *(ItemStack packet, int multiplier)
        {
            return new ItemStack(packet.ID, packet.Quantity * multiplier);
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="packet"></param>
        /// <param name="divisor"></param>
        /// <returns></returns>
        public static ItemStack operator /(ItemStack packet, int divisor)
        {
            return new ItemStack(packet.ID, ClampMinimum(packet.Quantity / divisor, MinimumItemQuantity));
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="packet"></param>
        /// <param name="quantity"></param>
        /// <returns></returns>
        public static ItemStack operator -(ItemStack packet, int quantity)
        {
            return new ItemStack(packet.ID, ClampMinimum(packet.Quantity - quantity, MinimumItemQuantity));
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="value"></param>
        /// <param name="minimum"></param>
        /// <returns></returns>
        private static int ClampMinimum(int value, int minimum)
        {
            return value < minimum ? minimum : value;
        }
    }
}

```

As a sort of update, I also wanted to express that this implementation doesn't *need* to be a struct. If you want optimal performance in terms of avoiding garbage collection, a struct is the way to go. However, depending on the scale of your game, you could easily use a class, and further, a string ID instead of an integer ID. It all depends on the kind of game you're making; there is no clear cut answer. Look at your game, prototype both implementations, and see which one works better for you.

# Answer
> -3 votes
You can use C# Arrays or Lists and Classes; Make an `Item` class/struct which has all the properties and stats of the item; Name, Quantity, Weight, etc. Then for each item in the game, make an object of the class/struct with the items properties. Store all game items in an *Global* list, each player should have their own list of their inventory items. When the player collects an item, you will add that item to the player's inventory list using `List.Add` function and when the player removes an item, you remove it using `List.Remove`. You can use the unity's newly introduced UI system to show the player's items and their corresponding stats.

---
Tags: unity, 3d, inventory, skyrim-modding
---


title: GET and POST requests in gdscript

text:
# Question
Title: GET and POST requests in gdscript
How do I perform get and post requests from Gdscript in Godot? I am trying to get a map API and use it in the game.

# Answer
As someone else said, check out the HTTPClient class.

It's nonblocking, so you'll need to check for when it's finished.

A barebones example with no error checking would be the following:

```
var http = HTTPClient.new()
http.connect("www.myapi.net",80)
var headers=[
    "User-Agent: Pirulo/1.0 (Godot)",
    "Accept: */*"
]
http.request(HTTPClient.METHOD_GET,"/myendpoint",headers)
if (http.has_response()):
    #read through the chunks...

```

Really, this is just pseudo-code. The docs have a really complete code example. http://docs.godotengine.org/en/latest/tutorials/http\_client\_class.html
> 7 votes

---
Tags: godot
---


# Question
Title: Using L-Systems to procedurally generate cities
I'm currently making an app that focuses a lot on procedurally generated content. So far, I've successfully implemented the procedural generation of the terrain and shape of a map using simplex noise. I'm really pleased with how it looks. Now I'm trying to do the same for cities. I just need to generate a 2D layout of the streets and buildings. I've looked into it and it seems most people suggest using L-Systems. However I can't seem to wrap my head around them. I get the concept, but not the implementation into code. Does anyone have any code examples of L-Systems for procedurally generated cities, or suggestions on other ways to handle the cities?

# Answer
> 20 votes
L-Systems, from what I can tell\*, are a set of grammar-like substitution rules that you can apply recursively to get interesting, "organic" results.

Plants are where L-Systems are often used, as they show a lot of recursive growth (i.e. branch splits off into more branches). For a simple example, I'll show a "lollipop" tree generated using an L-System:

```
variables : | o              (these are the things that will grow)
start  : o
         |                   (this is what we start with)
rules  : (o → o   o)         (these are the substitution rules that we apply
               \ /            one step at a time)

```

So at generation 1, we just have the start:

```
o
|

```

At generation 2, we follow each of the rules and substitute the existing parts according to the rules. We replace the "balls" with "two-sticks-and-balls":

```
o   o
 \ /
  |

```

Generation 3:

```
o o   o o
 \|   |/
   \ /
    |

```

Soon we'll have a pretty (crappy) big tree!

To do this in code, you can either do this recursively (i.e. DFS), continually applying the rules on the same parts until you reach some arbitrary end, or you can do this iteratively (i.e. BFS) as we've done in this example, performing one rule "pass" on all the elements and repeating a number of steps. That is:

**Recursively:**

```
tree = start
grow(tree, start)

func grow(tree, part)
    if this part of the tree is big enough
        stop
    if part is 'o'
        replace part with 'o\/o'
        grow(tree, the left 'o')
        grow(tree, the right 'o')

```

**Iteratively:**

```
tree = start
for a number of iterations
    for each part in tree
        if part is 'o':
            replace with 'o\/o'

```

A lot of uses of L-Systems perform the "grow" step using subdivision - that is, the parts keep getting smaller as they are "grown", the bigger parts just get divided. Otherwise your growing system may start to overlap on top of itself. You'll see in my lollipop tree example, I've magically ensured the two branches don't overlap in the middle by changing the shape of the new branches. Let's do the **city** example using subdivision:

```
variables: block_vertical block_horizontal road_vertical road_horizontal
start: block_vertical
rules: (block_vertical → block_horizontal road_vertical block_horizontal)
       (block_horizontal → block_vertical road_horizontal block_vertical)

```

This will make sense in a minute.

Generation 1:

```
+--------------------+
|                    |
|                    |
|                    |
|        V           |
|                    |
|                    |
|                    |
+--------------------+

```

A single, boring vertical block. (The V stands for vertical.)

Generation 2: we replace the vertical block with horizontal blocks with a vertical road in the middle

```
+--------------------+
|       r            |
|       r            |
|       r            |
|   H   r      H     |
|       r            |
|       r            |
|       r            |
+--------------------+

```

The r stands for road! I've randomly spaced out the split, we don't want boring regular parts in PCG.

Generation 3: we replace the horizontal blocks with vertical blocks split apart with horizontal roads. The existing roads stay; there are no rules for them.

```
+--------------------+
|   V   r            |
|       r            |
|rrrrrrrr            |
|       r      V     |
|   V   r            |
|       rrrrrrrrrrrrr|
|       r      V     |
+--------------------+

```

Notice how the roads connect to each other, which is nice. Repeat this enough times and you'll end up with something like this (blatantly ripped off a related answer):

Notice that there are a lot of details I haven't covered, and that this result looks "obviously" generated - real cities look somewhat different. That's what makes PCG fun/hard. There are endless things you can do to tweak and improve your results, but being unrelated to L-Systems, I'll leave this answer here; hope this helps you get started.

<sub>\*- I haven't studied L-Systems formally, although I have encountered specific types like grammars and PCG vegetation; please correct me if I get any definitions or concepts wrong</sub>

# Answer
> 1 votes
@congusbongus answer is excellent, let me add a few things.

Blocks needs to be splitted into building areas according to all the roads that border them. When you have road all around, the overall pattern is a ring. See this link for example : http://oldurbanist.blogspot.fr/2012/01/city-blocks-spaces-in-between.html

( Depending on the density, there might be no space in the ring center, see kowloon ).

Once you have done the blocks, you need to generate the buildings. They are a bit tricky and require a two pass generation. They are partially interdependent : your generator should not create a window that is in front of the next building side wall.

And to add life to this, you may want to influence the generation with the environments like the terrain or an economic map : Roads (except in San Francisco) tends to go around big hills, instead of going straight and the types of houses are heavily influenced by the part of the city they are in.

have fun.

---
Tags: 2d, ios, game-mechanics, procedural-generation
---


title: Multithreading problem in openGL?

text:
# Question
Title: Multithreading problem in openGL?
Let's say that I have two threads.

Both of them generates and binds to a vbo separately.

If I join and run these threads the behavior will be undefined obviously.

Because one may generate the vbo and one may Bind the vbo.

So how do AAA games like doom resolve this problem.

I chose that game because it most likely to be run in multiple threads. Thank you

# Answer
> 2 votes
There are a number of ways to handle this cleanly, but the simplest way is to **use an API that's actually designed to work well with multithreading**.

That means not using OpenGL, because OpenGL's global state, implied context, and bind-to-modify makes it work poorly with multithreading.

Most AAA games actually don't use OpenGL so this isn't a problem for them.

If you must use OpenGL there are of course solutions, including using wglShareLists (or equivalent) to share objects between contexts (and then being very very careful about how threads use objects), or restricting all GL calls to a single thread.

---
Tags: opengl, multithreading
---


title: Libgdx scene2d not erasing old texture

text:
# Question
Title: Libgdx scene2d not erasing old texture
I've been having trouble with getting scene2d to erase my old texture when I switch screens, and also when I change my label the old label string is still drawn underneath.

```
public StartScreen(MainGame game){
    this.mainGame = game;

    viewport = new FitViewport(640, 360, new OrthographicCamera());
    stage = new Stage(viewport, game.batch);

    Texture button = new Texture("playButton.png");
    Button.ButtonStyle bs = new Button.ButtonStyle();
    bs.up = new TextureRegionDrawable(new TextureRegion(button));
    startGameButton = new Button(bs);

    Table table = new Table();
    table.top();
    table.setFillParent(true);

    table.add(startGameButton).expandX().padTop(10);

    stage.addActor(table);

    startGameButton.addListener(new ClickListener(){
        @Override
        public void clicked(InputEvent event, float x, float y) {
            mainGame.SetClassScreen();
        }
    });

    Gdx.input.setInputProcessor(stage);
}

public void render(float delta) {
    mainGame.batch.setProjectionMatrix(stage.getCamera().combined);
    stage.act(Gdx.graphics.getDeltaTime());
    stage.draw();
}

```

In the constructor I have tried using Dispose() when changing the screen and it doesn't work.

When the screens are changed, The playButton still shows in the next screen. I also have a Label which displays text depending on a button pressed, but when it's pressed it writes the string over the old string to look like a jumbled mess.

I have a feeling I'm not updating something to be redrawn somewhere but I can't find it.

```
public PickClassScreen(MainGame game){
    this.mainGame = game;

    viewport = new FitViewport(640, 360, new OrthographicCamera());
    stage = new Stage(viewport, game.batch);

    //All initialization of Scene2d stuff.

    stage.addActor(table);

    Gdx.input.setInputProcessor(stage);
}

@Override
public void show() {

}

@Override
public void render(float delta) {
    mainGame.batch.setProjectionMatrix(stage.getCamera().combined);
    stage.act(Gdx.graphics.getDeltaTime());
    stage.draw();

}

```

The screen that I am switching to. ^

# Answer
Try changing your `render` methods to this;

For `StartScreen`:

```
public void render(float delta) {
  // Clear the buffer
  Gdx.gl.glClearColor(0, 0, 0, 1);
  Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

  mainGame.batch.setProjectionMatrix(stage.getCamera().combined);
  stage.act(Gdx.graphics.getDeltaTime());
  stage.draw();
}

```

For `PickClassScreen`

```
public void render(float delta) {
  // Clear the buffer
  Gdx.gl.glClearColor(0, 0, 0, 1);
  Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

  mainGame.batch.setProjectionMatrix(stage.getCamera().combined);
  stage.act(Gdx.graphics.getDeltaTime());
  stage.draw();
}

```

I think you're seeing old stuff on the render buffer, by clearing the buffer before every draw you wont have this issue.
> 1 votes

---
Tags: java, libgdx, scene2d
---


title: pygame on windows doesn't load sounds

text:
# Question
Title: pygame on windows doesn't load sounds
I had written a program using PyGame that should play sounds. I created sounds in Audacity, saved it as WAV (Microsost) signed 16 bit PCM. They are played well on Linux, but aren't loaded in Windows. There is exception:

```
    self.start_signal = pygame.mixer.Sound(open('start.wav'))
pygame.error: Unrecognized file type (not WAVE)

```

Same error if I try to use Ogg Vorbis:

```
    self.start_signal = pygame.mixer.Sound(open('start.ogg'))
pygame.error: OGG bitstream is not valid Vorbis stream!

```

But I can play sounds in both formats in Windows Media Player.

pygame-1.9.1.win32-py2.7.msi

# Answer
I found out my mistake:

One should use

```
pygame.mixer.Sound('start.ogg')

```

instead of

```
pygame.mixer.Sound(open('start.ogg'))

```
> -1 votes

---
Tags: pygame, windows
---


# Question
Title: OpenGL tesselation doesn't change geometry shape
I implemented tessellation control and evaluation shaders in OpenGL, but the effect it has on my terrain was not what I expected.

I expected that the low poly-count curves and shapes on the terrain would be smoothed out with new vertices between the old ones but instead I get the effect shown below.

This tessellation seems to simply create a high poly-count version of the exact same model with no difference in shape.

How do I remedy this, or am I misunderstanding the purpose of tessellation?

**Without Tessellation**

**With Tessellation**

**Tessellation Control Shader**

```
#version 450

layout(vertices = 3) out;

in VS_OUT {
    vec3 normal;
} tesc_in[];

out TESC_OUT {
    vec3 normal;
} tesc_out[];

uniform vec3 view_position;

/* Return level of tessellation based on distance */
float tess_level(vec4 pos1, vec4 pos2) {
    const float d = distance(pos1, pos2);
    if(d < 0.5) { return 25; }
    if(d < 1.0) { return 20; }
    if(d < 1.5) { return 15; }
    if(d < 2.0) { return 10; }
    if(d < 2) { return 5; }
    if(d < 3) { return 2; }
    return 1;
}
float tess_level(vec3 pos1, vec3 pos2) {
    return tess_level(vec4(pos1, 1.0), vec4(pos2, 1.0));
}

/* Sets tessellation levels */
void set_LoD() {
    vec4 d1 = vec4(gl_in[1].gl_Position.xyz + (gl_in[2].gl_Position.xyz - gl_in[1].gl_Position.xyz) / 2, 1.0);
    vec4 d2 = vec4(gl_in[0].gl_Position.xyz + (gl_in[2].gl_Position.xyz - gl_in[0].gl_Position.xyz) / 2, 1.0);
    vec4 d3 = vec4(gl_in[0].gl_Position.xyz + (gl_in[1].gl_Position.xyz - gl_in[0].gl_Position.xyz) / 2, 1.0);

    vec4 view_position_v4 = vec4(view_position, 1.0);
    float e0 = tess_level(d1, view_position_v4);
    float e1 = tess_level(d2, view_position_v4);
    float e2 = tess_level(d3, view_position_v4);
    float m = min(e0, min(e1, e2));

    gl_TessLevelInner[0] = floor((min(e0, min(e1, e2)) + max(e0, max(e1, e2))) / 2);
    gl_TessLevelOuter[0] = e0;
    gl_TessLevelOuter[1] = e1;
    gl_TessLevelOuter[2] = e2;
}

void main() {
    if(gl_InvocationID == 0) {
        set_LoD();
    }

    tesc_out[gl_InvocationID].normal = tesc_in[gl_InvocationID].normal;
    gl_out[gl_InvocationID].gl_Position = gl_in[gl_InvocationID].gl_Position;
}

```

**Tessellation Evaluation Shader**

```
#version 450

layout(triangles, fractional_even_spacing, ccw) in;

in TESC_OUT {
    vec3 normal;
} tesc_in[];

out TESE_OUT {
    vec3 normal;
    float height;
    vec4 shadow_position;
} tesc_out;

uniform mat4 model_view;
uniform mat4 model_view_perspective;
uniform mat3 normal_matrix;
uniform mat4 depth_matrix;

vec3 lerp(vec3 v0, vec3 v1, vec3 v2) {
    return (
        (vec3(gl_TessCoord.x) * v0) +
        (vec3(gl_TessCoord.y) * v1) +
        (vec3(gl_TessCoord.z) * v2)
    );
}

vec4 lerp(vec4 v0, vec4 v1, vec4 v2) {
    return (
        (vec4(gl_TessCoord.x) * v0) +
        (vec4(gl_TessCoord.y) * v1) +
        (vec4(gl_TessCoord.z) * v2)
    );
}

void main() {
    gl_Position = lerp(
        gl_in[0].gl_Position,
        gl_in[1].gl_Position,
        gl_in[2].gl_Position
    );

    tesc_out.normal = normal_matrix * lerp(
        tesc_in[0].normal,
        tesc_in[1].normal,
        tesc_in[2].normal
    );

    tesc_out.height = gl_Position.y;

    tesc_out.shadow_position = depth_matrix * gl_Position;
    gl_Position = model_view_perspective * gl_Position;
}

```

# Answer
Tessellation does just that - tessellates. That means generating more triangles, typically on the interior of the original triangle / primitive.

If you're looking to smooth your result, rather than just creating a higher-resolution version with the same shape, you're going to have to get fancy.

If your terrain is defined via a height map, you'll want to resample your height map and set the vertical component of each new vertex in the same way that you're doing the original vertices.

If your terrain is functionally defined - say, via Perlin or simplex noise - just resample that function and, again, set the vertical component of each new vertex accordingly.

Basically, however you're getting the Y offset of your non-tessellated vertices, apply that method to the new vertices and you'll get a higher-frequency (smoother in this case) result.

Tessellation isn't designed to be an easy path to level-of-detail on its own. You'll have to handle this part yourself.

**EDIT**

That mesh looks suspiciously like it came out of a modeling program.

If that's the case, things are more complicated. One way would be to include "control point" data with your exported model, and use that to calculate a new vertex position by interpolating between adjacent control values - likely a Bezier patch or similar arrangement. Less easy than sampling, but it works.

**UPDATE**

Here's the reference Perlin noise implementation Translating this to GLSL should be straightforward.

```
// JAVA REFERENCE IMPLEMENTATION OF IMPROVED NOISE - COPYRIGHT 2002 KEN PERLIN.

public final class ImprovedNoise {
   static public double noise(double x, double y, double z) {
      int X = (int)Math.floor(x) & 255,                  // FIND UNIT CUBE THAT
          Y = (int)Math.floor(y) & 255,                  // CONTAINS POINT.
          Z = (int)Math.floor(z) & 255;
      x -= Math.floor(x);                                // FIND RELATIVE X,Y,Z
      y -= Math.floor(y);                                // OF POINT IN CUBE.
      z -= Math.floor(z);
      double u = fade(x),                                // COMPUTE FADE CURVES
             v = fade(y),                                // FOR EACH OF X,Y,Z.
             w = fade(z);
      int A = p[X  ]+Y, AA = p[A]+Z, AB = p[A+1]+Z,      // HASH COORDINATES OF
          B = p[X+1]+Y, BA = p[B]+Z, BB = p[B+1]+Z;      // THE 8 CUBE CORNERS,

      return lerp(w, lerp(v, lerp(u, grad(p[AA  ], x  , y  , z   ),  // AND ADD
                                     grad(p[BA  ], x-1, y  , z   )), // BLENDED
                             lerp(u, grad(p[AB  ], x  , y-1, z   ),  // RESULTS
                                     grad(p[BB  ], x-1, y-1, z   ))),// FROM  8
                     lerp(v, lerp(u, grad(p[AA+1], x  , y  , z-1 ),  // CORNERS
                                     grad(p[BA+1], x-1, y  , z-1 )), // OF CUBE
                             lerp(u, grad(p[AB+1], x  , y-1, z-1 ),
                                     grad(p[BB+1], x-1, y-1, z-1 ))));
   }
   static double fade(double t) { return t * t * t * (t * (t * 6 - 15) + 10); }
   static double lerp(double t, double a, double b) { return a + t * (b - a); }
   static double grad(int hash, double x, double y, double z) {
      int h = hash & 15;                      // CONVERT LO 4 BITS OF HASH CODE
      double u = h<8 ? x : y,                 // INTO 12 GRADIENT DIRECTIONS.
             v = h<4 ? y : h==12||h==14 ? x : z;
      return ((h&1) == 0 ? u : -u) + ((h&2) == 0 ? v : -v);
   }
   static final int p[] = new int[512], permutation[] = { 151,160,137,91,90,15,
   131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23,
   190, 6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33,
   88,237,149,56,87,174,20,125,136,171,168, 68,175,74,165,71,134,139,48,27,166,
   77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244,
   102,143,54, 65,25,63,161, 1,216,80,73,209,76,132,187,208, 89,18,169,200,196,
   135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,250,124,123,
   5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42,
   223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167, 43,172,9,
   129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218,246,97,228,
   251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107,
   49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254,
   138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180
   };
   static { for (int i=0; i < 256 ; i++) p[256+i] = p[i] = permutation[i]; }
}

```

For 2D (heightmap), just set `z` to zero (or another constant) and either use the result, or eliminate everything in function that relies on a varying `z`.
> 1 votes

---
Tags: opengl, c++, glsl, tessellation
---


# Question
Title: alpha test shader 'discard' operation not working - GLES2
I wrote this `shader` to illustare `alpha test` action in `GLES2` (Galaxy S6). I think is not working at all cause I don't see any change with or without it. Is there anything Im missing?
Any syntax error?
**I know its better not using `if` in `shader` but for now this is the solution I need.**

```
precision highp float;
precision highp int;
precision lowp sampler2D;
precision lowp samplerCube;

        //0 - CMPF_ALWAYS_FAIL,
        //1 - CMPF_ALWAYS_PASS,
        //2 - CMPF_LESS,
        //3 - CMPF_LESS_EQUAL,
        //4 - CMPF_EQUAL,
        //5 - CMPF_NOT_EQUAL,
        //6 - CMPF_GREATER_EQUAL,
        //7 - CMPF_GREATER

        bool Is_Alpha_Pass(int func,float alphaRef, float alphaValue)
        {
            bool result = true;
            if (func==0)
            {
                result = false;
                break;
            }

            if (func==1)
            {
                result = true;
                break;
            }
            if (func==2)
            {
                result = alphaValue < alphaRef;
                break;
            }
            if (func==3)
            {
                result = alphaValue <= alphaRef;
                break;
            }
            if (func==4)
            {
                result = alphaValue == alphaRef;
                break;
            }
            if (func==5)
            {
                result = alphaValue != alphaRef;
                break;
            }
            if (func==6)
            {
                result = alphaValue >= alphaRef;
                break;
            }
            if (func==7)
            {
                result = alphaValue > alphaRef;
                break;
            }
            return result;
        }

void FFP_Alpha_Test(in float func, in float alphaRef, in vec4 texel)
{
    if (!Is_Alpha_Pass(int(func), alphaRef, texel.a))
        discard;

}

```

# Answer
https://www.khronos.org/opengles/sdk/docs/man3/html/glBlendFunc.xhtml

Did you check the glblendfunc??

It is needed to be enabled in client state with gl\_alpha\_test

Without client state code it's difficult for me to solve the problem.
> 0 votes

---
Tags: opengl, android, shaders, opengl-es2, fragment-shader
---


title: Default color for 3D scene

text:
# Question
Title: Default color for 3D scene
I have webgl 3D scene with background image and few shapes with textures.
I want to add some lines and other shapes and apply on them default color which not affect the shapes with textures.
How can I do this?
this is what I have now:

```
gl.clearColor(0.0, 0.0, 0.0, 0.0); //alpha=0 for background img
gl.enable(gl.DEPTH_TEST);

```

# Answer
You have to use shaders to apply color to objects..

In fragment shader you can specify it with gl\_color = vec3(r,g,b,a);

Glcolor3f it's deprecated..
> 0 votes

---
Tags: opengl, javascript, webgl
---


title: lineStyle removed after colorTransform

text:
# Question
Title: lineStyle removed after colorTransform
I have these shapes with a lineStyle to outline the shapes, however, when I tried to do colorTransform, it will completely remove the outline of the shapes. Is there a way to make lineStyle constant? To permanently stay after the colorTransform? I don't quite understand as I thought colorTransform is just changing the color of the shape.

```
            char.graphics.lineStyle(0, 0x000000);
            char.graphics.beginFill(0xFFFFFF, 1);
            char.graphics.drawEllipse(x, y, 25, 25);
            char.graphics.endFill();

```

I have the outline as black and inside is all white.

```
            changeColor = char.transform.colorTransform;
            changeColor.color = 0xFFFFFF;
            char.transform.colorTransform = changeColor;

```

Once I change the shapes back to white to their original color, the lineStyle disappears. Is there a way to prevent this from happening?

# Answer
> -1 votes
take a look at this page

https://stackoverflow.com/a/796731/5862335

as there is explained you have to put your strokes in another DisplayObject.

---
Tags: actionscript-3, flashdevelop
---


# Question
Title: Unity / Rotate a point around an arbitrary axis and anchor
I'm trying to find out the point which is already rotated. To solve this I did a Rotation, save the position, set the previous position and return my position, like this:

```
Vector3 rotatePointAroundAxis(float angle ,Vector3 axis, Vector3 anchor)
{
Vector3 oldPosition = gameobject.transform.position;
gameobject.transform.RotateAround(gameobject.GetComponent<HingeJoint>().anchor, gameobject.GetComponent<HingeJoint>().axis, angle);

Vector3 newPosition = gameobject.transform.position;
gameobject.transform.position = oldPosition;
return newPosition;
}

```

I searched already. And I found very hard solutions. http://inside.mines.edu/fs\_home/gmurray/ArbitraryAxisRotation/ \- by the way i dont think I understand this, it seems like too much.

Is there any way to change that function to a "simple" one, so I don't need to rotate things forth and back to get the coordinates?

EDIT:

I believe tranform.RotateAround() takes the position and rotation from the transform parameters and calculates the solution and changes the current position and rotation of the gameobject.

So the solution should take 5 parameters:

1. current position of the unrotated Object
2. current rotation of the unrotated Object
3. the point the Object should be able to pass
4. the rotation axis
5. the angle

and return 2 parameters:

1. the rotated objects new rotation
2. the rotated objects new position

# Answer
The concept of a "rotation" is represented by a Quaternion. These are built into Unity and there's no need for you to understand the math in that link you posted.

To create a rotation from an angle & axis, use Quaternion.AngleAxis. Once you have it, you can simply multiply it by the `Vector3` you're trying to rotate. Your function would look like this:

```
Vector3 rotatePointAroundAxis(Vector3 point, float angle, Vector3 axis)
{
    Quaternion q = Quaternion.AngleAxis(angle, axis);
    return q * point; //Note: q must be first (point * q wouldn't compile)
}

```
> 4 votes

# Answer
Maybe this can help you:

After the rotating of parent:

```
foreach (Transform child in transform) {
  child.rotation = // reset value
}

```
> -3 votes

---
Tags: unity, rotation, transformation, axis
---


# Question
Title: Unity 5 - How to change Input Field 'Content Type' at runtime to toggle between asterisks and letters?
I have a password box set up in my project with the content type set to 'Password', so it shows asterisks when the user types in the box. However I would like a toggle switch so the user can click to show the password characters if they like, so effectively toggling between 'Password' and 'Standard' - is this possible? Any pointers would be appreciated.

Unity 5.3.5 - PC Standalone.

Thanks in advance.

# Answer
> 4 votes
Yes, it's possible. I assume you have a simple scene set up with a Toggle and an InputField like this:

Add a new Empty to your scene and name it `UIController`. Select your newly created object, head over to the Inspector and hit the `Add Component` button to create and attach a new custom component. Name the script `UIController` and paste the following code (I'm assuming C#):

```
using System;
using UnityEngine;
using UnityEngine.UI;

public class UIController : MonoBehaviour {

    public UnityEngine.UI.InputField passwordInput = null;

    public void ToggleInputType() {
        if (this.passwordInput != null) {
            if (this.passwordInput.contentType == InputField.ContentType.Password) {
                this.passwordInput.contentType = InputField.ContentType.Standard;
            } else {
                this.passwordInput.contentType = InputField.ContentType.Password;
            }

            this.passwordInput.ForceLabelUpdate ();
        }
    }
}

```

The script's public method is basically the answer to your question. Probably one thing to mention is the call to `forceLabelUpdate` after switching the InputField's contentType, otherwise the display-mode doesn't update immediately.

Just to be complete:

1. Of course you have to wire the reference to your specific InputField. To do this, select your UIController in the outline to have the UIController's properties visible in the Inspector. Then drag&drop the InputField to link it to the 'Password Field' member:

2. And finally, build the bridge from the Toggle to the UIController's `ToggleInputType()` method. Select the Toggle and scroll all the way down to the bottom:

From this section (outlined in blue) you can specify any object in your scene to be informed when the user interacts with the Toggle. Here you want to choose the UIController as the object (green) and its `ToggleInputType` method (red) to be invoked.

Wow. This got longer than expected but I hope it helps! :)

---
Tags: unity, input
---


# Question
Title: C# XNA colliders, physics, inclined plane/terrain/colliders
Currently I'm working on a project to learn game programming. But I'm not sure if I have the right approach on several things, and that's what I'm here for.

What I'm trying to create is a small world in 3d and simulate some simple physics. The world can be seen below.

The world is basically a box, note that I've left out the walls in the front and side view, but they will be there. The goal is to drop a ball somewhere in the green area and let physics do its work. Then the simulation will end once the ball falls into the hole. Later, once I got a better understanding of everything I want to create a pinball game out of it, but that's for a later stage.

Currently I'm creating this project in C# XNA/MonoDevelop and want to create everything from scratch. So I got my own physics engine, collider classes, math library, et cetera, which I find quite challenging, especially since I knew/know nothing about all of this, especially the math, but I am learning a lot from it, and I find it a lot of fun!

So what do I have now:

I got a GameObject class, which contains a position, a model, update and draw methods, etc. And a Physics Engine which uses PhysicsObjects and ModelObjects (both inheriting from the GameObject).

The PhysicsObject contains a mass, velocity, gravity, a collider update and draw method and the ModelObject just has a position and a collider and update and draw method.

The PhysicsEngine has a Run(deltatime) method which is being called in the update method and integrates through all the PhysicsObjects in step one, updating it's velocity, applying gravity, and finally position. In the next step the PhysicsEngine handles the collisions. It checks whether a collision was found between PhysicsObjects and PhysicsObjects and PhysicsObjects and ModelObjects and if a collision was detected it will handle the collision response.

So far I only have an Axis-Aligned Bounding Box, BoundingSphere and Plane class. And implemented the Sphere-Sphere collision, and Sphere-Plane collision.

I soon realized the AABB wouldn't be possible since I can't rotate them. So I tried creating planes, since as far as I understand, a Plane exists out of a normal vector to determine the 'up' side and a distance from the center/origin. The problem only is that there isn't a begin or end position so I can't have a hole in the terrain. So this is where I'm stuck, I have no idea on how to approach this and what to use and how most people would solve this problem. I'm not asking for code snippets or anything, but want to know if my general approach to all of this is 'correct' and how I should approach this problem for the terrain. What kind of collider should I use for the terrain to also make it possible to rotate it?

# Answer
You can have a hole in a plane. If you know the geometric center of the hole, simply place a condition on the ball/plane collision such that if that ball is on the plane but is within half width and half length of the center of the hole, then act as if the plane is not there.

You can set the edges of the structure on the plane in a similar fashion.
> 1 votes

---
Tags: c#, xna, collision-detection, physics
---


# Question
Title: Pathfinding on multiple grids connected through teleports
I try to create a "AI" that can move independently on a map structure where the individual maps are only connected by one directional teleport squares (links).
There are some map areas you can only traverse if you fulfill some requirements.
(for example you could be too heavy to swim.)
Movement is limited to 4 directions.

So far I use A\* to navigate on a single map.
For the shortest path across multiple maps I came up with a pre-generated graph.
I use the links as nodes and search with Dijkstra because I wasn't able to come up with a working heuristic for that (no spatial arrangement of the links).
I generate the graph by calculating the cost for every link target square to all other links on that map. (tons of A\* searches per map, takes 8-10 minutes to complete).

Then, for an actual search, I temporarily inject the start and end-point as links into the multi-map-graph (and do the cost calcing using A\* without persistently saving it) so I can find the fastest way to the goal.
I get a list of goals, one goal per map out of that and just need to do an A\* search for each goal on the corresponding map.

The tricky part in my approach is that the costly pre-calculated data isn't able to reflect the dynamic conditions for example swimming. (sometimes there is a completely different route necessary.)

**Now on to my question(s).**
Is there a known solution to this combination of problems that I'm just unable to find?
Has anyone already faced something similar?

There are some conditions that I want to meet. I'm already almost at the memory(ram) limit (that I'm willing to sacrifice) and I want to keep the disk IO as small as possible (multiple ai would be kill).
I thought about just pre-calculating path for every possible condition and at the moment that could actually work but I'm 99% sure that this wouldn't work in the future (because the size grows exponentially).

# Answer
For dynamic paths, the D\* family of algorithms is a good place to start. It is very similar to A\*, but whereas A\* must be completely recalculated whenever the shortest path changes, D\* can incrementally recalculate only those parts that are affected by the path change. It can still be very expensive, e.g. if the path becomes blocked requiring a very long detour, but for minor path changes it is efficient.

But I've found that for the best performance, it is better to take as much advantage of your specific situation and make some non-optimal assumptions. HPA\* is a great example; it is non-optimal but is responsive and very fast. Try to do the same, like producing a graph made up of all the teleport ends, and assuming all the teleports within the same map are accessible, falling back to D\* if they are not.
> 0 votes

# Answer
If you have a list of all available teleports per map containing information about their position and what map they link to, you could find out in a first step which teleport will bring you the closest to your target and then do a local A\*-search to that chosen teleport.
> 0 votes

---
Tags: path-finding
---


title: MultiSwipe in Libgdx

text:
# Question
Title: MultiSwipe in Libgdx
I have some trouble with my GestureListener class i think. I'm just trying to detect swipe on two half screen. I'm creating two InputListener but I can't add them to InputMultiplexer. Actually, I added with no trouble but it is not working as how I wanted. How can I detect two swipe(fling or pan whatever) events simultaneously ?

Maybe this picture will help you that you understand it.

EDIT : It's from my Player1 class and the other class' contents are the same. (Player2)

```
private void listenInputs() {

    inputProcessor = new InputProcessor() {

        @Override
        public boolean keyDown(int keycode) {
            return false;
        }

        @Override
        public boolean keyUp(int keycode) {
            return false;
        }

        @Override
        public boolean keyTyped(char character) {
            return false;
        }

        @Override
        public boolean touchDown(int screenX, int screenY, int pointer, int button) {
            if (canMove) {
                lastTouch.set(screenX, screenY);
                firstD = screenX;
            }
            return true;
        }

        @Override
        public boolean touchUp(int screenX, int screenY, int pointer, int button) {
            canMove = true;
            distance= 0;
            return true;
        }

        @Override
        public boolean touchDragged(int screenX, int screenY, int pointer) {

            Vector2 newTouch = new Vector2(screenX, screenY);
            distance = screenX - firstD;

            if (firstD < CarcleGame.HALF_SCREEN) {
                if (Math.abs(distance) > 20) {
                    if (canMove) {
                        canMove = false;
                        Vector2 delta = newTouch.cpy().sub(lastTouch);
                        if (delta.x > 0.7f)
                            move(true); // if it's true then go to the direction right, else go left
                        else if (delta.x < -0.7f)
                            move(false);

                        lastTouch = newTouch;
                    }
                }
            }
            return true;
        }

```

# Answer
> 2 votes
Use `touchDragged()` method the from `Screen` interface. Example taken from https://stackoverflow.com/questions/23731073/how-will-touchdragged-works-in-libgdx

```
private Vector2 lastTouch = new Vector2();

public boolean touchDown(int screenX, int screenY, int pointer, int button){
    lastTouch.set(screenX, screenY);
}

public boolean touchDragged(int screenX, int screenY, int pointer) {
    Vector2 newTouch = new Vector2(screenX, screenY);
    // delta will now hold the difference between the last and the current touch positions
    // delta.x > 0 means the touch moved to the right, delta.x < 0 means a move to the left
    Vector2 delta = newTouch.cpy().sub(lastTouch);
    lastTouch = newTouch;
}

```

Now if you want to detect which side made the 'drag', make some edits:

```
private final float HALF_SCREEN_WIDTH = Gdx.graphics.getWidth() / 2f;
private Vector2 lastTouch = new Vector2();

public boolean touchDown(int screenX, int screenY, int pointer, int button){
    lastTouch.set(screenX, screenY);
}

public boolean touchDragged(int screenX, int screenY, int pointer) {
    Vector2 newTouch = new Vector2(screenX, screenY);

    if(newTouch.x < HALF_SCREEN_WIDTH && lastTouch.x < HALF_SCREEN_WIDTH){
        // swipe on left side of the screen
    }else if(newTouch.x > HALF_SCREEN_WIDTH && lastTouch.x > HALF_SCREEN_WIDTH){
        // swipe on right side of the screen
    }else{
        // swipe made on both sides of the screen
    }
    Vector2 delta = newTouch.cpy().sub(lastTouch);
    lastTouch = newTouch;

}

```

# **Edited answer - supporting simultanousness**

I assume you have a class which implements Screen (cause you said that you don't have a stage). In `show()` method set the `InputProcessor` to `this` so the screen can receive touch events. If you have more things to receive events from - make a multiplexer (I assume you know how to do this cause you said you've tried!)

***How does it work?***

There's a method: `Gdx.input.isTouched()` which tells you if the screen is touched. There's also one more method with the same name, but with an additional parameter: `Gdx.input.isTouched(int pointer)`. This method was created to support multi-touch. If screen is touched it checks how many fingers are already touching it and it's incrementing the pointer and we can get each separate finger by passing a number to this method. Numbers start from 0, increment one by each finger and reset back to 0 when all fingers are released.

So if I touch the screen somewhere and check the 'pointer' variable in the `touchDown()` method (see below) - it will give me 0. If I hold the finger and put another one on the screen, pointer value will be 1, because I'm still touching the screen with the first finger (0 value is in use by the first touch).

So we have detected multiple screen touches. Now, let's write the support for the screen sides. We create 4 `Vectors` (vectors are just for storing touch coordinates here - x,y).

When we have a touchDown (see `touchDown()` method below) we make a loop to \<= pointer so we can get all the current touches with `Gdx.input.isTouched(pointer)`. Now, we check if the touch was made on the left or the right side of the screen.

If for instance left was touched - we set the `leftStart` vector to the touch position (we'll use this in `touchUp()` method). We also change `leftStarted` to `true` (you'll know why in a moment).

Now in the `touchUp()` method we iterate again so we can retrieve all the touchUp events. Again, for example, if we got a touchUp on the left side of the screen, we take the coordinates and set them to `leftEnd` vector.

Now, we can use a simple math to calculate the distance between `leftStart` and `leftEnd` points. We have the distance, we can check if it was longer than some value (`MIN_SWIPE_DISTANCE` in our case) and if it was - it was a left swipe. Right side works in the same manner.

Also, notice that after the successful touchUp we set `leftStarted`/`rightStarted` back to false.

Now, for the boolean `leftStarted` and `rightStarted` \- it's just a protection for a situation when screen is touched on the left side and released on the right.

Let's see:

If we touch the screen on the left side, `leftStarted` is true so `touchUp()` will know that this move was legit. But! Let's say that we touched the screen on the right side (touchDown) and swiped it to the left side. TouchUp fires and checks if '`leftStarted` is `true`' - it's false, which is correct cause we didn't start the swipe on the left side, but on the right side.

I hope you get the idea! :) If you have any questions, feel free.

```
// these are class fields!
private Vector2 leftStart = new Vector2(), leftEnd = new Vector2();
private Vector2 rightStart = new Vector2(), rightEnd = new Vector2();

private boolean leftStarted = false, rightStarted = false;

private final float MIN_SWIPE_DISTANCE = 50f;

@Override
public void show() {
    // or without multiplexer, do what you want there
    InputMultiplexer plex = new InputMultiplexer(this);
    Gdx.input.setInputProcessor(plex);
}

@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {

    for(int i=0;i<=pointer;i++){

        if(screenX < HALF_SCREEN_WIDTH) // left touched
        {
            leftStart.set(screenX, screenY);
            leftStarted = true;
        }

        if(screenX > HALF_SCREEN_WIDTH) // right touched
        {
            rightStart.set(screenX, screenY);
            rightStarted = true;
        }

    }
    return false;
}

@Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {

    for(int i=0;i<=pointer;i++){

        if(screenX < HALF_SCREEN_WIDTH && leftStarted) // left released
        {
            leftStarted = false;
            leftEnd.set(screenX, screenY);
            double distance = Math.sqrt((leftEnd.x - leftStart.x) * (leftEnd.x - leftStart.x) +
                    (leftEnd.y - leftStart.y) * (leftEnd.y - leftStart.y));

            if(distance > MIN_SWIPE_DISTANCE){
                // left swipe!
                System.out.println("Left swipe!");
            }

        }

        if(screenX > HALF_SCREEN_WIDTH && rightStarted) // right released
        {
            rightStarted = false;
            rightEnd.set(screenX, screenY);

            double distance = Math.sqrt((leftEnd.x - leftStart.x) * (leftEnd.x - leftStart.x) +
                    (leftEnd.y - leftStart.y) * (leftEnd.y - leftStart.y));

            if(distance > MIN_SWIPE_DISTANCE){
                // right swipe!
                System.out.println("Right swipe!");
            }
        }

    }
    return false;
}

```

For now it supports sides (left/right) but it doesn't support detection if the swipe was made 'up' or 'down' etc. It detects all directions. If you'd like to implement these, let me know and I'll add this ;)

---
Tags: libgdx
---


# Question
Title: Gdx.graphics.getWidth() vs cam.viewport width
I'm facing difficulty understanding the difference between Gdx.graphics.getWidth() vs cam.viewportwidth, What is the difference?

# Answer
`Gdx.graphics.getWidth()` returns the width (in pixels) of the window (or on mobile, the screen) that your application is running in.

`cam.viewportWidth` is the width of the view of the camera, in whatever unit is applicable for you.

Let's say your game world is 100 meters wide, but for some reason you only want to show a portion of that at the time, if you set your `cam.viewportWidth` to **10**, the you can see 1/10 of the world's width. The width that the camera is "seeing" is then mapped onto the screen/window, so on a 1024x768 pixel screen (assuming you're running full screen) those **10** units of camera viewport width is 1024 pixels wide on screen.

The `Camera` relates to where and how much of the game world you see, in world units. The `Gdx.graphics.getWidth()` is the physical pixels of the screen or window.
> 3 votes

---
Tags: java, libgdx, viewport
---


title: Gldraw call asynchronous or not

text:
# Question
Title: Gldraw call asynchronous or not
When i call gldrawarrays with a large set of data will the function return only after drawing all the vertices or will it happen asynchronously b/w cpu and gpu?

Also how does vsync work. Aren't they related?

# Answer
> 2 votes
By calling `glDrawArrays` you queue that action in the GPU. It will get executed the next time you call `glFlush` which is also executed by the platform dependent `SwapBuffers` function.

VSync is a completely different thing. It synchronizes `SwapBuffers` with your monitors refresh rate to avoid 'tearing' artifacts. Tearing is when half of the screen was displayed with one frame and half of the screen with the next frame. This is perceived by the eye and can become ugly and annoying.

# Answer
> 1 votes
When you give any draw command. The function returns its value immediately in next tick. You give "gldrawarrays" it tells gpu to draw all stuff. Cpu goes to the next command, while gpu is still drawing. note that cpu doesn't pause for the gpu to complete the drawing process.

That's one of the reason why we use delay function at end of code. We tell cpu to wait until gpu completes drawing ( I don't know which language you you are using so i cannot tell you exactly which command delays.)

---
Tags: opengl, vsync
---


# Question
Title: How costly is an OpenGL draw call, and how do I optimise them?
How costly is a draw call in OpenGL?

What are the ways to reduce the number of draw calls? I have seen people using `glMapBufferRange`, but I can't figure out how it improves the performance.

How much impact do draw calls have on the overall performance of a program?

# Answer
glDraw can cost a lot because it's the first place the driver actually knows what you want to draw.

The next glDraw call can cost anywhere from very little to a lot depending on how much render state you changed in between.

This means that for more efficient renders you need to group your objects into so that objects using the same state are rendered together. So the state changes between the glDraw calls are minimized. This is one thing that people can mean with batching.

You can also render more per draw call. This usually means instancing. This is the other meaning of batching.

`glMapBufferRange` is just a way of uploading data to the gpu and has little to do with

The final option to reduce cpu overhead is to move to the "next gen" graphics apis like Vulkan, DX12 or Metal. There the biggest cost in preparing for render is moved to creating the state objects that you then use for rendering. The win there is that the application code is responsible for not being stupid with destroying and recreating it.
> 1 votes

---
Tags: opengl, optimization
---


# Question
Title: How can I make my AI NPC's have a footstep sound?
I am making a horror game and I have NPCs roaming around the map.

How can I make it so the player can hear the NPCs' footsteps as they get closer?

# Answer
I'm not a UE programmer, so I can't help with code specifics.

That said, I've had this same requirement come up in one of my own projects, and figured out two approaches I'd use, depending on your actual needs:

Based on entity:

* Configure the loudness of a given entity (e.g, a larger creature like Tyrant from RE would make noise sooner than a lowly zombie)
* Query entities near the player using whatever means makes sense for your game (I'm currently using the spatial partitioning data for this), using the loudness as a threshold for the range of the query (similar to how I might implement a ranged non-projectile attack)
* If the entity is in range, play the footstep sounds at a loudness based on an appropriate conversion of 'distance from player' \<-\> 'actual sound volume'

Based on player:

* Have the player have some form of 'hearing range' configured
* Detect all entities within that range
* Have those entities play footsteps at a given volume based on their distance from the player (convert the range to a logarithmic representation of the audio volume you desire)

It's a fairly easy thing to implement, the only thing I've personally tripped over with doing it is realizing that volume is NOT a percentage in a lot of cases, and converting to the appropriate scale isn't always straightforward.
> 1 votes

# Answer
I would suggest adding some logic like this:

Let **D** be the distance between **Player** and **Entity** in UE units
Let **X** be an arbitrary multiplier to determine volume (suggesting a min of 0 and a max of 2), the higher **X**, the lower the overall volume
And let **V** be the volume of the entity's footsteps in (from 0 to 1)

**V** = 100 / (**D** * **X**)

**X** = 0.5:

```
D in units    V      X=0,5

100           2
200           1
300           0,666666667
400           0,5
500           0,4
600           0,333333333
700           0,285714286
800           0,25
1000          0,2
2000          0,1
3000          0,066666667
4000          0,05
5000          0,04

```

**X** = 1

```
D in units  V      X=1

100         1
200         0,5
300         0,333333333
400         0,25
500         0,2
600         0,166666667
700         0,142857143
800         0,125
1000        0,1
2000        0,05
3000        0,033333333
4000        0,025
5000        0,02

```

Etc.

**\[EDIT 1\]**

another suggest I came up with: Another way of doing this is to simply get the location of the entity and place a sound on it's location, you could do this in the blueprint, and would result in a much realistic sound, you only need to set the volume value of the sound and the engine should calculate it's volume and direction automatically
> 1 votes

# Answer
that's totally a "tons" of work , but i can give you list-to-do to make it

1. Detect area where the npc
2. Calculate the range from player to npc
3. set the volume based on range

i cannot give example sorry because its not just one or two , its THOUSAND OF WORK .
> -2 votes

---
Tags: game-design, unreal-4, sound, unreal
---


title: How to create image slider using unity

text:
# Question
Title: How to create image slider using unity
I have created one unity app with vuforia plugin. App contains image target to view an object and play video. I need one more feature to create gallery view from image target. I want to create something like this https://www.youtube.com/watch?v=LhwhELJgdX4&feature=youtu.be&t=85 Please give me some instruction how to make gallery view using vuforia. Please share any tutorial link or sample app with me.

# Answer
Its pretty simple stuff. You can use the following plugin. It's open source and there are video tutorial of how to use it. Download link: https://bitbucket.org/ddreaper/unity-ui-extensions Tutorial linkL: https://www.youtube.com/watch?v=KJlIlWHlfMo
> -1 votes

---
Tags: unity, image, vuforia
---


# Question
Title: How do I create a half-ortho half-perspective projection matrix
I've been trying to make a formula for the projection matrix where your vertical axis is projected orthographically but your horizontal axis will have perspective to it.

So the view frustum would look like this:

I studied how the formulae of orthographic projection and perspective projection and how they where achieved. And tried to modify those to try to reach projection I wanted. It seemed to me it wasn't possible to have one axis scale to Z and the other not (or to have them scale at a different factor).

It it possible to reach the perspective I want? If so what would the projection matrix look like?

# Answer
> 2 votes
This projection matrix should do the trick:

```
.tg  {border-collapse:collapse;border-spacing:0;}
.tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;}
.tg th{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;}
```

```
<table class="tg">
  <tr>
    <th class="tg-031e">1/r</th>
    <th class="tg-031e">0</th>
    <th class="tg-031e">0</th>
    <th class="tg-031e">0</th>
  </tr>
  <tr>
    <td class="tg-031e">0</td>
    <td class="tg-031e">1/t</td>
    <td class="tg-031e">0</td>
    <td class="tg-031e">0</td>
  </tr>
  <tr>
    <td class="tg-031e">0</td>
    <td class="tg-031e">0</td>
    <td class="tg-031e">-2/(f-n)</td>
    <td class="tg-031e">-(f+n)/(f-n)</td>
  </tr>
</table>
```

**r** = half the width of nearplane

**t** = half the height of nearplane

**f** = distance to farplane

**n** = distance to nearplane

So for example, try picking:

**r** = 0.1 (width will be 0.2)

**t** = 0.5 (height will be 1.0)

**f** = 1000 (far plane at distance 1000)

**n** = 1 (nearplane at distance 1)

# Answer
> 0 votes
Unfortunately, I don't think this is possible by just altering the projection matrix. After the projection matrix, the final screen coordinates are calculated by dividing (x, y, z) by w. For a perspective matrix, w is set to z. For a orthographic matrix, w is set to 1. You can't have a different w values for horizontal versus vertical. The other answer to this question is just a standard orthographic matrix.

If you have access to the shader itself and are willing to add another step, you could just use an orthographic projection but do the horizontal perspective correction manually.

---
Tags: 3d, rendering, projection-matrix
---