title: Changing the camera movement in unity

text:
# Question
Title: Changing the camera movement in unity
I have a code that allows me to move the camera on the x-axis. I need it to move on the y-axis as well as the x.

```
    using UnityEngine;
using System.Collections;

public class orbit : MonoBehaviour {

    public float turnSpeed = 4.0f;
    public Transform player;

    private Vector3 offset;

    void Start () {
        offset = new Vector3(player.position.x, player.position.y + 8.0f, player.position.z + 7.0f);
    }

    void LateUpdate()
    {
        offset = Quaternion.AngleAxis (Input.GetAxis("Mouse X") * turnSpeed, Vector3.up) * offset;
        transform.position = player.position + offset;
        transform.LookAt(player.position);
    }
}

```

# Answer
> 2 votes
You could just do the same thing on the Y axes, like so:

```
void LateUpdate()
{
    offset = Quaternion.AngleAxis (Input.GetAxis("Mouse X") * turnSpeed, Vector3.up) * offset;
    offset = Quaternion.AngleAxis (Input.GetAxis("Mouse Y") * turnSpeed, Vector3.left) * offset;
    transform.position = player.position + offset;
    transform.LookAt(player.position);
}

```

Or perhaps even simpler like so:

```
void LateUpdate()
{
    player.transform.rotation *= Quaternion.Euler(Input.GetAxis("Mouse X") * turnSpeed, Input.GetAxis("Mouse Y") * turnSpeed, 0);
}

```

However, those two ways 'rotate based on the current orientation/rotation' of the player.

This next one will rotate the same way, no matter how the player is orientated:

```
void LateUpdate()
{
    player.transform.Rotate(Vector3.up, Input.GetAxis( "Mouse X" ), Space.World);
    player.transform.Rotate(Vector3.left, Input.GetAxis( "Mouse Y" ), Space.World);
}

```

Hope that helps!

---
Tags: unity
---


title: Drawing Chess Board vs Using Picture

text:
# Question
Title: Drawing Chess Board vs Using Picture
Would it be better to actually draw the board in a script and attach colliders to each piece or get a picture and add the colliders before the game starts? Is the difference in processing power needed significant?

Which way would be the easiest for figuring out where a specific piece is?

# Answer
> 6 votes
> Which way would be the easiest for figuring out where a specific piece is?

DO NOT use the scene for working out where stuff is. That is absurd and backwards.

Have some internal logic (like a `ChessBoardRepresentation` class) that stores an 8x8 grid and tells you what pieces are there. like `.getPieceAt(x,y)` say. You can have other methods like `.getPossibleMovesFor(x,y)` that returns a `PossibleMoves` that has things like `isPinned()` and so forth. This is your 'internal logic'

To make a move you tell the internal logic to make a move. Which could throw if the move is illegal (say) and if that move is valid, updates the internal representation AND tells the bit doing graphics the new positions of some objects.

Remember what you draw on screen REPRESENTS the state, you should never work out the state by looking at the scene graph or other structures managing the drawing process

---
Tags: unity
---


# Question
Title: Error in projecting coordinates from FitViewport to screen in LibGDX
i'm using a FitViewport to render my "game world". Viewport virtual dimensions are fixed 400x240. I use `viewport.unproject` method to scale input touches from screen coordinates to world coordinates, and the values are good.

The problem begins when i use the opposite (`viewport.project` method). I have to use it for drawing a sprite that is scaled for screen dimensions but i have X and Y positions in "game" coordinates.

```
Vector2 screenCoords = new Vector2();
screenCoords = (viewport.project(new Vector2(gameX, gameY)));

```

When i use `viewport.project` i only have the result i expect if the screen aspect ratio matches my game aspect ratio (so the viewport fits the whole screen).

I noticed that if screen height is higher (so my viewport is fitted horizontally and black bars appear below and above it) the X coordinate is fine, but Y coordinate varies slightly depending if the "game" Y coordinate is near upper or lower side.

Based on my knowledge and on javadoc comments i've red, the method must automatically recognize if the viewport is not full-screen or if it is not, and add an offset based on how tall the black bars are.

Am i doing something wrong???

# Answer
> 1 votes
Use camera projection instead of the viewport projection. And use the cameras viewport instead of your virtual viewport. The stuff on your screen is rendered using the cameras projection and the cameras viewport, so if you want world coordinates to end up in the same place, then this should solve your problem:

```
cam.project(new Vector2(gameX, gameY), 0, 0, cam.viewportWidth, cam.viewportHeight);

```

---
Tags: libgdx, camera, coordinates, viewport, aspect-ratio
---


# Question
Title: Tween animation with Universal Tween Engine LIbGDX
Let me preface by saying that I'm new to libgdx...

I have an animation that I'm currently drawing to the screen using:

```
game.batch.draw(flyAnimation2.getKeyFrame(elapsedTime, true), 200,200,0, 0, 124, 90, 1.0f, 1.0f, 90);

```

Where flyAnimation2 is: `Animation flyAnimation2;`

This works correctly. I now want to use UniversalTweenEngine to tween it from one side of the screen to the other.

I can't find any decent documentation on how to achieve this affect using an Animation. Any help would be appreciated!!

# Answer
> 2 votes
I would recommend representing the position of the animated sprite as a `Vector2`, then to use the universal tween engine you would first have to implement a `TweenAccessor` for that type;

```
public class Vector2Accessor implements TweenAccessor<Vector2> {
    public static final int TYPE_XY = 1;

    @Override
    public int getValues(Vector2 target, int tweenType, float[] returnValues) {
        switch (tweenType) {
            case TYPE_XY:
        returnValues[0] = target.x;
            returnValues[1] = target.y;
            return 2;

            default:
        assert false;
        return -1;
        }
    }

    @Override
    public void setValues(Vector2 target, int tweenType, float[] newValues) {
        switch (tweenType) {
            case TYPE_XY:
        target.x = newValues[0];
            target.y = newValues[1];
        break;
            default:
        assert false;
        break;
        }
    }
}

```

After that it's a matter of registering the accessor, and updating the `TweenManager` with the delta time before rendering the `Animation` at the `Vector2` position;

```
public class MyApplication extends ApplicationAdapter {

    private TweenManager manager = new TweenManager();
    private Vector2 position = new Vector2();

    public MyApplication() {
        Tween.registerAccessor(Vector2.class, new Vector2Accessor());
    }

    public void create() {
        // Set the position to the left hand side of the screen, center vertically
        position.set(0, Gdx.graphics.getHeight() / 2.0f);
        Tween.to(position, Vector2Accessor.TYPE_XY, 5.0f).target(Gdx.graphics.getWidth(), Gdx.graphics.getHeight() / 2.0f).start(manager);
    }

    public void render() {
       manager.update(Gdx.graphics.getDeltaTime());
       // For brevity I'll just pretend batch and flyAnimation and elapsedTime exists here
       batch.draw(flyAnimation2.getKeyFrame(elapsedTime, true), position.x,position.y, 0, 0, 124, 90, 1.0f, 1.0f, 90);
    }
}

```

---
Tags: libgdx, tweening
---


# Question
Title: DirectX11 - AlphaBlending Rendering problem
So.. I completed this tutorial on the following site rastertek.com/dx11tut12.html. The tutorial is all about rendering Text in an orthographic space. Basically just 2D rendering on DirectX 11.

Now that I finished i wanted to experiment with it. In the original tutorial he uses a Black background texture with the different letters in white, then he uses AlphaBlending to make the pipeline omit the background when drawing to the backbuffer saying that the alpha value for when the sample color is black is 0.

```
//Initializing the AlphaEnabledBlendingState
D3D11_BLEND_DESC blendStateDescription;
ZeroMemory(&blendStateDescription, sizeof(D3D11_BLEND_DESC));

blendStateDescription.RenderTarget[0].BlendEnable = TRUE;
blendStateDescription.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
blendStateDescription.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
blendStateDescription.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
blendStateDescription.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO;
blendStateDescription.RenderTarget[0].RenderTargetWriteMask = 0x0f;
blendStateDescription.RenderTarget[0].SrcBlend = D3D11_BLEND_ONE;
blendStateDescription.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE;

result = this->m_device->CreateBlendState(&blendStateDescription, &this->m_alphaEnableBlendingState);
if (FAILED(result))
{
    return false;
}

```

_

```
//Setting the AlphaEnabledBlendingState as the active AlphaBlendState
float blendFactor[4];

blendFactor[0] = 0.0f;
blendFactor[1] = 0.0f;
blendFactor[2] = 0.0f;
blendFactor[3] = 0.0f;

this->m_deviceContext->OMSetBlendState(this->m_alphaEnableBlendingState, blendFactor, 0xffffffff);

```

And the PixelShader I'm using to render the Text.

```
Texture2D shaderTexture;
SamplerState SampleType;

cbuffer PixelBuffer
{
    float4 pixelColor;
};

struct PixelInputType
{
    float4 position : SV_POSITION;
    float2 tex : TEXCOORD0;
};

float4 main(PixelInputType input) : SV_TARGET
{
    float4 color;

    color = shaderTexture.Sample(SampleType, input.tex);

    //If the color is black on the texture then treat this pixel as transparent
    if (color.r == 0.0f)
    {
        color.a = 0.0f;
    }
    //If the color is other than black on the texture then this is a pixel in the font so draw it using the font pixel color
    else
    {
        color.a = 1.0f;
        color *= pixelColor;
    }

    return color;
}

```

This is the result

So i said, let's change the background of the texture to green, (0, 255, 0). So i did and changed the shader to look for a green color to set his alpha value to 0.

Looking for Green instead of black

```
//If the color is green on the texture then treat this pixel as transparent
if (color.r == 0.0f && color.g == 1.0f && color.b == 0.0f)
{
    color.a = 0.0f;
}

```

But the result is not what i expected. There's also the prove that the texture background is green.

This is the result

So, the question is... What am I doing wrong? what step am I skiping? I see that the color is totally transparent, as it should be.

Thank you for the time and help you can provide!

# Answer
The problem here is the blendstate, which leads the font background to be added to the screen background. So if the font background is black, everything is ok, but if you're using green it will be added to the blue background resulting in cyan.

You blendstate resulting in following blendoperation:

```
ResultColor = SrcColor * 1 + DestColor * (1-SrcAlpha)

```

This adds your transparent font background (Alpha = 0) to the full screen background (in this case 1-Alpha = 1)

But to hide your green background with transparency, so you need

```
ResultColor = SrcColor * SrcAlpha + DestColor * (1-SrcAlpha)

```

This will hide your font background, as it will be multiplied with 0, so the result is the remaining screen background.

Leading to the following changes:

```
blendStateDescription.RenderTarget[0].BlendEnable = TRUE;
blendStateDescription.RenderTarget[0].RenderTargetWriteMask = 0x0f;

blendStateDescription.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
blendStateDescription.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA;
blendStateDescription.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;

blendStateDescription.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
blendStateDescription.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO;
blendStateDescription.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE;

```
> 1 votes

---
Tags: directx, hlsl
---


title: How to fill in crevices on a height map

text:
# Question
Title: How to fill in crevices on a height map
I am a very experienced iOS Developer, but I am beginning my very first foray into 3D graphics (specifically with SceneKit). I'm trying to model a planet, and I have it working with a height map giving mountains and valleys to a simple sphere.

What I'm wondering now is, how might I have a variable sea level? As I understand it, a height map only affects how the image is rendered, but it doesn't actually change the geometry of the object, correct? So my first idea, to have a smaller sphere and scale it up or down relative to the planet so that it shows through in the lower-elevation areas, wouldn't work?

If that's the case, how else might I approach this? I'd love a code sample if it's simple or ready-made, but mostly I'm just looking for a conceptual answer that I can go off and implement. How might I take a height-mapped planet surface, and have an adjustable sea level that fills in the lower-elevation areas first? For simplicity, I'm treating sea level as purely altitude-based (i.e. I don't need to factor in dams or obstacles, and maintaining a consistent volume of water isn't important).

# Answer
> 1 votes
You need a 3d noise function (perlin,simplex,..). Call it f(x,y,z). Usualy this function returns a 0..1 float value. You simply decide your sea level float k in 0..1 and :

```
Foreach point of the sphere

If f(x,y,z) < k

 k is your heigth in that point

Else

 f(x,y,z) is your heigth in that point

```

# Answer
> 1 votes
You should be able to animate the height using u\_time in your shader. Example usage of u\_time code in Xcode project download here - https://developer.apple.com/library/mac/samplecode/SceneKit\_Slides\_WWDC2013/Introduction/Intro.html (compiles to slide show, use -\> key to goto slide 40-something)

Can you help me out? I've been trying to do a height map with SceneKit's SCNShaderModifierEntryPointGeometry and can't seem to get my (UIImage\*)heightMap passed to a sampler2D variable in the shaderModifier. How are you passing your image? Thanks in advance.

# Answer
> 1 votes
What you explain sounds reasonable. Generate a smaller sphere with the radius set for an appropriate sea level.

Alternativly generate a sphere and alter its scale. This'd be quicker than regenerating a new one.

---
Tags: ios, heightmap, planet, scenekit
---


# Question
Title: How to create in game menu attached to unit
I'm creating a game similar to Banner Saga, except my game will be in 3D, with a camera that can move around and zoom in and out. What I want is for a menu to appear after the user clicks on a unit. This menu must always be visible and facing the camera.

The menu that has the foot and sword symbols is what I want.

How can I get a similar result in 3D? The new Unity UI canvas isn't really suitable, since the camera will move around, and the menu must stay next to the unit. The menu elements can't be covered up by things in front of it, like other units. Thanks

# Answer
> 1 votes
I can suggest:

1.make menu objects using gameObjects (like quads with textures (EDIT) or better as stated by Philipp in his comment and Exerion in his answer: "using Unity5 UI system: Canvas component, which is the base of the new UI system, can be set to "World Space" to make it appear as a diegetic interface with a 3d position in the scene.") and assign them a layer.

2.use a second camera child of main camera and with all the same properties except Culling Mask setted to render only menu objects(1).

3.set the "menuCamera" Depth higher than ManiCamera so that it render menu objects on top of other stuff. EDIT (as DeeCeptor said in comment) : The clear flags on the foreground (menu camera) must be set to 'Depth only'.

4.You can regroup all menu objects under a "rootMenu" (empty gameobject). Put a script into rootMenu to make it rotate always to menuCamera

```
void Update() {
    // Rotate the camera every frame so it keeps looking at the target
    transform.LookAt(menuCamera);
}

```

# Answer
> 2 votes
It looks like you need UI with render mode `World Space`. In that case all UI elements will be placed in world's coordinates as such other GameObjects. What you should try is:

* Create UI Canvas, reset it's transform and set it as child of a unit you want to show
* In that canvas create, for example, a Button and reset it's transform
* Create simple script to make new UI behave like a billboard:

```
public class LookAtCamera : MonoBehaviour
{
    public Camera target;

    void Update()
    {
        if (target != null)
        {
            transform.rotation = target.transform.rotation;
        }
    }
}

```

To fix possible mirror effect, you can try this variation of `Update` method:

```
void Update()
{
    transform.LookAt(transform.position + target.transform.rotation * Vector3.back, target.transform.rotation * Vector3.up);
}

```
* As it done, attach this script to UI Button and set `target` to your UI camera (probably main camera)

At this point your button should appear near/inside your unit and may be relatively big. Adjust scale of a Button and it's position. With script work fine you should see a button near unit that always facing target camera and moving along with unit.

# Answer
> 0 votes
You could create the GUI and disable it. After position the GUI by usin ScreenPointToRay(MOUSE POSITION) to spawn it at the position of the mouse and then enable it. Read more here: http://docs.unity3d.com/ScriptReference/Camera.ScreenPointToRay.html

---
Tags: unity, gui
---


# Question
Title: How to get the directional vector (for IrrKlang) from pitch and yaw?
Currently my game engine allows the player/camera to pitch and yaw, so there's no roll.

The pitch angle starts at 0°, which means the camera is facing straight ahead. From here it can go up to +85° (looking almost straight up) or down to -85° (looking almost straight down).

The yaw angle starts at 0°, which means the camera is facing east. The rotation is clockwise so 90° is south, 180° is west and 270° north. What would be 360° is 0° again obviously.

How do I get from this to the direction vector (`lookdir`) IrrKlang's `SetListenerPosition` requires to get directional audio working?

PS: x and z are my horizontal axis, y is the vertical one.

# Answer
> 1 votes
x = cos(yaw)

y = sin(pitch)

z = sin(yaw)

(Depending on the orientation of you coordinate system you could have to put a "-" somewhere)

Roll is irrelevant for the lookDir Vector, as it just changes the Up-Vector. Remember that there are theoretically infinite "correct" lookDir Vectors, the one above has the length 1.

---
Tags: c++, physics, mathematics, sound, audio
---


# Question
Title: Simple mobile multiplayer game. TCP/UDP?
I'm tying to dive into multiplayer game programming.

The game is quite simple, it's a 2D scroller mobile game, the player need to touch the screen in order to move 1 step and it could contain up to 4 players at max. 1 of the player could create a room for other players to join.

I was thinking that I would use TCP for this and will only send packets when 1 of the player trigger an event like moving or exiting the game. Is my approach is correct? Since from what I've read, many games are created in UDP instead of TCP.

In case of UDP, what is sent between the clients and the server? The position of each entity in the game at a fix time interval?

I'm really new multiplayer programming. I'd appreciate if someone would share their story.

Thank you.

# Answer
UDP packets are not guaranteed to arrive. Use them for things like position updates, where it doesn't matter if some of them are missed. They don't necessarily arrive in the order that you sent them.

TCP packets are guaranteed to arrive, no matter how many retries this may take. They always arrive in the correct order, too.

For such a small game, you could get away with using TCP. It sounds as if the packets will be small, so the noticeable difference shouldn't be huge.

Also bear in mind that TCP will almost certainly be more efficient than your system of guaranteeing packet delivery, since it has been designed carefully by professionals.

The packets that are sent depend on your game. For what you're making, I imagine that it'll consist of: player joining, player movement, world data etc. Bear in mind that out of these three examples, two have to be delivered every time (and TCP does this for you).
> 1 votes

# Answer
Lolums explained the differences well, so I'll just add that if you're game is turn based, you'll need to have all players see each others moves, so missing packets of information is not allowed and TCP should be used. Alternately if your game uses realtime gameplay, you need to ensure that all players have the latest information so waiting for a late packet with outdated information is unacceptable. you'll want to use UDP in that scenario and throw away older packets that may come out of order. for example, if you get 2 packets of position information for the same player, but the older one comes later due to some network latency somewhere you need to know to ignore it in favor of the newer information.
> 1 votes

---
Tags: multiplayer, mobile, udp
---


# Question
Title: Sounds and buttons show up in simulator, not in an Android device
I'm a noob in android game development, started with corona sdk and outlaw. My project runs just fine with the corona simulator on my win8, however, when building it to my android device (galaxy s3) and running it - it behaves differently than in the simulator:

First thing: in my project I have wav sound files that work just fine in the corona simulator, but on my android device the sound files do not play (I use the audio.play api).

Second thing: I have 2 buttons created with the widget.newButton api, which are displayed on a lua screen. The buttons do show in the simulator, but are not shown on the android app.

Any help will be appreciated!

# Answer
> 0 votes
**Audio**

I find that for audio playback it's faster, smaller and more reliable to have two versions of the same audio and select different filetypes for iOS and Android. *m4a* for iOS and *ogg* for Android seem to work consistently.

If you are just building for Android then use .ogg files. If you're building for both iOS and Android you could use `device.lua` added down there to detect device and serve the appropriate audio file extensions.

```
--// Platform specific audio file extensions
local audioFileExtension = '.m4a'
if device.isAndroid then audioFileExtension = '.ogg' end

--// Then load the audio like this
local soundFile = 'soundFileName'
audio.loadSound(soundFile..audioFileExtension )

```

I would then add a condition in build.settings to exclude the unnecessary audio files depending on the platform

```
settings.excludeFiles = {
    iphone =
    {
    "audio/*.ogg",
    },

    android =
    {
    "audio/*.m4a",
    }
}

```

**Widget Buttons**

For your buttons, have you tried setting the widget theme using widget.setTheme() ?

```
local widget = require( "widget" )

widget.setTheme( "widget_theme_android" )

```

**device.lua**

```
-- Project: Simple device detection flags
--
-- File name: main.lua
--
-- Author: Corona Labs
--
-- Abstract: Sets up some simple boolean flags that lets us do various device tests.
--
--
-- Target devices: simulator, device
--
-- Sample code is MIT licensed, see http://www.coronalabs.com/links/code/license
-- Copyright (C) 2012 Corona Labs Inc. All Rights Reserved.
---------------------------------------------------------------------------------------
local M = {}

--
-- Set up some defaults
--

M.isApple = false
M.isAndroid = false
M.isGoogle = false
M.isKindleFire = false
M.isNook = false
M.is_iPad = false
M.isTall = false
M.isSimulator = false

local model = system.getInfo("model")

-- Are we on the simulator?

if "simulator" == system.getInfo("environment") then
    M.isSimulator = true
end

-- lets see if we are a tall device

M.isTall = false
if (display.pixelHeight/display.pixelWidth) > 1.5 then
    M.isTall = true
end

-- first, look to see if we are on some Apple platform.
-- All models start with iP, so we can check that.

if string.sub(model,1,2) == "iP" then
     -- We are an iOS device of some sort
     M.isApple = true

     if string.sub(model, 1, 4) == "iPad" then
         M.is_iPad = true
     end
else
    -- Not Apple, then we must be one of the Android devices
    M.isAndroid = true

    -- lets assume we are Google for the moment
    M.isGoogle = true

    -- All the Kindles start with K, though Corona SDK before build 976's Kindle Fire 9 returned "WFJWI" instead of "KFJWI"

    if model == "Kindle Fire" or model == "WFJWI" or string.sub(model,1,2) == "KF" then
        M.isKindleFire = true
        M.isGoogle = false
    end

    -- Are we a nook?

    if string.sub(model,1,4) == "Nook" or string.sub(model,1,4) == "BNRV" then
        M.isNook = true
        M.isGoogle = false
    end
end

return M

```

# Answer
> -1 votes
first of all please load the sound you wanna play like this:

```
local testSound = audio.loadSound( "sample.wav" )
audio.play( testSound )

```

then make sure your coordinates on those buttons are correct. maybe buttons are off the screen. I don't have much to say because I have nothing from your code. please upload your code

# Answer
> -3 votes
man try using the exact capital or small letters from the sound file in the text script.

---
Tags: android, sound, corona-sdk
---


# Question
Title: Unity3D - override main camera rendering for compositing effect
I'm fairly new to Unity and am having a bit of trouble understanding the rendering pipeline.

I need to render the scene to four "windows," so that the viewport shows a 2x2 grid of the scene, each with a slightly different projection matrix.

My first thought was to have a component that would create four `RenderTextures`, and, in `OnPreRender()`, iterate through them, setting the main camera's `targetTexture` property to each texture in turn and rendering the camera's view to that texture:

(Pseudocode)

```
public class CompositiongEffect : MonoBehaviour
{
    private Material m_material;
    private List<RenderTexture> m_textures;

    void OnEnable()
    {
        if (null == m_textures)
        {
            m_textures = new List<RenderTexture>();

            for (var i = 0; i < 4; ++i)
            {
                m_textures.Add(new RenderTexture(512, 512, 24));
            }
        }

        if (null == m_material)
        {
            m_material = new Material(Shader.Find("Custom/CompositingEffectShader"));
        }

    }

    void OnPreRender()
    {
        var cam = Camera.current;

        foreach (var texture in m_textures)
        {
            /// adjust cam projection matrix here...

            cam.targetTexture = texture;
            cam.Render();
        }
    }

    void OnRenderImage(RenderTexture source, RenderTexture destination)
    {
        Debug.Assert(
            null != m_material
            && null != m_textures
            && m_textures.Count == 4, "Texture list not initialized"
            );

        for(var i = 0; i < m_textures.Count; ++i)
        {
            var x = i % 2;
            var y = i / 2;

            var uniformName = string.Format("Texture{0}{1}", x, y);

            m_material.SetTexture(name, m_textures[i]);
        }

        Graphics.Blit(source, destination, m_material);
    }

}

```

The Image Effect `m_material` would then draw the 2x2 grid to the frame buffer in a single pass.

Is this a good approach? I suspect (perhaps incorrectly) that using an image effect for the last step would actually cause an additional scene render that never gets used.

The reason for this is the signature for `OnRenderImage()`

```
void OnRenderImage(RenderTexture source, RenderTexture destination)

```

implies that `source` is already a valid image when this is called. That image has to come from *somewhere,* and it seems that it would contain the full-resolution rendered scene already. Since I am already rendering the scene in the previous step, I'd like to avoid this additional render.

Am I interpreting the pipeline correctly? If so, how can I address this?

Thanks!

**Edit**

Can I disable the main camera, then do everything manually in my component as mentioned above? If the camera is disabled, to what should I attach my component? Perhaps the camera's parent `gameObject`?

# Answer
I do that way:

* Create several cameras attached to the same parent gameobject. Then create RenderTexture in editor for each camera. Put RenderTextures to cameras' Target Texture property;
* When we want to move Main Camera, we move the parent object instead;
* Main Camera is left near other cameras, but Target Texture is null;
* Next, create a shader which takes all textures as uniforms and mixes them;
* Create a new material and specify our shader for it, then put RenderTextures in uniforms of the shader;
* Create a script in Main Camera and put the code like this in it:

public Material effectMaterial;

void OnRenderImage(RenderTexture source, RenderTexture destination)

{

Graphics.Blit(null, destination, effectMaterial);

}
* Attach our material to effectMaterial property in script component.

Hope that helps!
> 1 votes

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


# Question
Title: An Object is moving but its velocity is 0
In Unity 5 I have an object move when I press a button, force is added as seen by the code below. Then once this force is added I print out its velocity. The problem is that in the console my first print out with the first button press is "velocity(0.0,0.0)" then the second button press gives the printout "velocity(2.0,0.0)". Why is it that i get a velocity of 0 on the first button press even though my object is moving on the screen?

```
if (isPressed == true) {
            moveableBarrel.GetComponent<Rigidbody2D> ().AddForce (new Vector2 (100, 0));

            Debug.Log ("velocity" + moveableBarrel.GetComponent<Rigidbody2D> ().velocity);

            isPressed = false;
        }

```

Edit \**Incase anyone else asks, the code is within a FixedUpdate Method

# Answer
> 2 votes
You are changing its velocity using the `AddForce` method. This adds a *force*, not a *velocity* to the body. The change of velocity happens the next time the rigidbody physics are processed by the game engine, which happens during the next FixedUpdate.

---
Tags: c#, unity, rigid-body-dynamics
---


# Question
Title: precedurally generate blob-like surface?
Just looking for some direction, I'm making a 2d top-down game and need to make some random shapes for an asteroid surface. I want to have so control so I can have not too-circle-ish but not too-complicated shapes.

# Answer
> 1 votes
You could generate random ellipses, this answer gives you required equation. You just need to give it appropriate random inputs:

1. **Center:** to avoid overlapping between generated ellipses I suggest using blue noise \[1\] \[2\]. In the linked answer as vector *x\_0*.
2. **Size:** picking min and max size would suffice. To constrain the deformation, you could generate single size *h* and its scale *s*, `k = s * h` instead. In the linked answer as *k* and *h*.
3. **Rotation:** the easiest input to generate, its just a random number between 0 and 2pi rad (0 and 360 deg). In the linked answer as theta.

you could also play with the distribution to get more natural looks.
From here(actual rendering) you can continue as you were rendering a circle, just use the linked equation. For rendering craters you will be likely rendering a smaller ellipse inside larger one or displacing copy of larger one for shadow.

---
Tags: java, 2d, libgdx
---


# Question
Title: OpenGL 3.3+ Problem with ortho projection for UI/HUD
I have to a little bit of a problem with drawing HUD elements on top of my 3d world using a ortho projection. My 3D world keep getting render but there is nothing showing of my UI.

I wrap the code into a shorter version of my program. But I still have the same problem here.

I think i'm missing something for this to work. First this is a the struct for the game obj

```
struct GameObject
{

    GLuint Id;
    GLuint Shader;
    GLuint uniformMVP;
    GLuint VBO;
    GLuint VAO;
    GLubyte VertexCpt;
    vec3 WorldPossition;
    float Angle;
    float XScale;
    float YScale;
};

void RenderObject(GameObject *obj, mat4 Projection, mat4 View)
{

    glUseProgram(obj->Shader);

    //Calculate The MVP
    mat4 Model = glm::translate(glm::mat4(1.f), obj->WorldPossition)*glm::rotate(glm::mat4(1.f), obj->Angle, glm::vec3(0.0f, 0.0f, 1.0f))*glm::scale(glm::mat4(1.f), glm::vec3(obj->XScale, obj->YScale, 1.0f));
    mat4 MVP = Projection * View * Model;

    //Set the MVP into the current shader's MVP varaible
    glUniformMatrix4fv(obj->uniformMVP, 1, GL_FALSE, &MVP[0][0]);

    // 1rst attribute buffer : vertices
    glEnableVertexAttribArray(0);
    glBindBuffer(GL_ARRAY_BUFFER, obj->VBO);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);

    // 2nd attribute buffer : colors
    glEnableVertexAttribArray(1);
    glBindBuffer(GL_ARRAY_BUFFER, obj->VAO);
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);

    glDrawArrays(GL_TRIANGLES, 0, obj->VertexCpt);

    glDisableVertexAttribArray(0);
    glDisableVertexAttribArray(1);
}

```

This is the main loop and the matrices

```
glm::mat4 ProjectionP = glm::perspective(45.0f, 4.0f / 3.0f, 0.1f, 100.0f);
glm::mat4 projectionO = glm::ortho(0.0f, 1024.f, 0.0f, 768.f, 0.1f, 100.0f);
glm::mat4 View = glm::lookAt(
    glm::vec3(5, 5, 5), // Camera is at (4,3,3), in World Space
    glm::vec3(0, 0, 0), // and looks at the origin
    glm::vec3(0, 1, 0)  // Head is up (set to 0,-1,0 to look upside-down)
    );

GameObject obj1 = { 1, SimpleShaderProg, uniformMVP, SquareVBO, orangeVAO, 6, vec3(200, 200, 1), 0.f, 100.f, 200.f };
GameObject obj2 = { 2, SimpleShaderProg, uniformMVP, SquareVBO, orangeVAO, 6, vec3(0, 0, -2), 0.f, 1.f, 1.f };
GameObject obj3 = { 3, SimpleShaderProg, uniformMVP, SquareVBO, orangeVAO, 6, vec3(0, 0, 0), 0.f, 1.f, 1.f };
GameObject obj4 = { 4, SimpleShaderProg, uniformMVP, SquareVBO, orangeVAO, 6, vec3(0, 0, 2), 0.f, 1.f, 1.f };

//Main render loop
double lastTime = glfwGetTime();
while ((glfwGetKey(window, GLFW_KEY_ESCAPE) != GLFW_PRESS && glfwWindowShouldClose(window) == 0))
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glfwPollEvents();

    RenderObject(&obj1, projectionO, mat4(1.f)); //<- This object will be render to the screen
    RenderObject(&obj2, ProjectionP, View);
    RenderObject(&obj3, ProjectionP, View);
    RenderObject(&obj4, ProjectionP, View);

    double currentTime = glfwGetTime();
    if (currentTime - lastTime >= 0.02){

        lastTime += 0.02;
    }
    glfwSwapBuffers(window);
}

```

This is the current configuration

```
glViewport(0, 0, windowWidth, windowHeight);
glClearColor(0.2f, 0.4f, 0.1f,1.f);

glEnable(GL_CULL_FACE);                                 //Enable culling
glCullFace(GL_FRONT);                                   //

glEnable(GL_BLEND);                                     //Enable blending for all obj
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

glEnable(GL_DEPTH_TEST);                                //Enable depth test for all obj
glDepthFunc(GL_LESS);

```

Vertex shader

```
#version 330 core
layout(location = 0) in vec3 vertexPosition_modelspace;
layout(location = 1) in vec3 vertexColor;

uniform mat4 MVP;
out vec3 fragmentColor;

void main(){
    gl_Position =  MVP * vec4(vertexPosition_modelspace,1);
    fragmentColor = vertexColor;
}

```

Fragment shader

```
#version 330 core
in vec3 fragmentColor;
out vec4 color;

void main()
{
    color.rgb =  fragmentColor;
    color.a =  1.f;
}

```

I hope someone can help me with that , and if you need more information feel free to ask. Thanks. NB: English is not my first language, sry about that.

# Answer
> 4 votes
One way is to disable GL\_DEPTH\_TEST for rendering 2D stuff. So draw everything of the 3D world like normal, then disable depth testing and then draw your UI at last. Another approach would make use of the depth test by setting the z-component of the vertices for the 2D stuff to 0 (and the near plane in the prohection matrix to something greater than 0) to always pass the depth test as the topmost object on screen, however you would need to pass another coordinate per vertex or set it as a constant in the shader. Generally i find method 1 easier as you don't need to worry about the third coordinate. And simply "first render 3D, then render 2D" is not that much of a sorting task to do.

---
Tags: opengl, glsl, glm
---


# Question
Title: libgdx: 2nd var of myClass()'s values saving to/overriding 1st var of myClass()
I'm using libgdx with Eclipse.

---

PROBLEM:

In the class **inputHandler** I have a list of buttons, menuButtons, composed of 2 buttons: playButton and retryButton. They both belong to the class **simpleButton**:

```
public static simpleButton playButton, retryButton;

```

I declared them as:

```
retryButton = new simpleButton(100, 100, 40, 10, retryRegion, retryRegion);
playButton = new simpleButton(80, 80, 20, 20, assetLoader.playButtonUp, assetLoader.playButtonDown);

```

---

*(see note at end of question)*

---

But when I run the game only the 2nd button runs (in the above case, playButton).

So I went to the class **gameRenderer** and used shapeRenderer to clearly see what was going on.

```
shapeRenderer.rect(inputHandler.retryButton.bounds.x, inputHandler.retryButton.bounds.y,
    inputHandler.retryButton.bounds.width, inputHandler.retryButton.bounds.height);

shapeRenderer.rect(inputHandler.playButton.bounds.x, inputHandler.playButton.bounds.y,
        inputHandler.playButton.bounds.width, inputHandler.playButton.bounds.height);

```

Although only the 2nd button was displaying, the 2nd button now adopted the code for both the buttons. i.e. the 2nd button was now both the play and retry (replay) buttons and worked perfectly.

---

***note from before:*** *These aren't their actual sizes (the actual sizes are equal to the sizes of the texture regions of their art graphics) but for the sake of simplicity and legibility I changed them to simpler values.*

---

Pictures:

**playButton on bottom (playButton working):**

---

**retryButton on bottom (retryButton working):**

---

The **simpleButton** class:

```
public class simpleButton {

    private float x, y, width, height;

    private TextureRegion buttonUp;
    private TextureRegion buttonDown;

    public static Rectangle bounds;

    public static boolean isPressed;

    public simpleButton(float x, float y, float width, float height,
            TextureRegion buttonUp, TextureRegion buttonDown) {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
        this.buttonUp = buttonUp;
        this.buttonDown = buttonDown;

        bounds = new Rectangle(x, y, width, height);
    }

```

# Answer
> 2 votes
not a java developer but:

```
public static Rectangle bounds;

```

is no good. Static members belongs to class not to objects (class references). So when you change bounds

```
 bounds = new Rectangle(x, y, width, height);

```

you set it for all simpleButton objects . And the last instantiated goes in top of the others.

---
Tags: libgdx, game-mechanics, eclipse
---


# Question
Title: Is locking required to implement a seperate rendering thread?
I have been reading a lot about this, but still not sure about a proper way to implement an independent render thread, using a variable time step and running in parallel to a physics thread, which uses a smaller, fixed time step. I'm familiar with the mechanics of mutexes and locking, when it comes to concurrent write access, but a render function would only read, and never modify.

Would a locking mechanism be required, at all, for using two buffers - a read buffer that is used by the renderer, while the physics engine modified the write buffer, and swapping after it's finished?

Even with only one buffer, I could imagine that you wouldn't even notice when some objects are updated, while rendering, having interpolation anyway and the much higher render frame rate. The only problem I see, with one buffer, is when objects would be deleted from physics and the renderer still trys to access them.

What is the main problem there? I am not talking about, for example, a concurrent physics and AI that both modify - only one additional render thread.

# Answer
Technically reading a value that another thread is writing to is undefined behavior. This means that *anything* is allowed to happen up to and including nasal demons or getting your harddrive formatted.

In reality it usually means the reading thread gets a *corrupt* value. This can cause visual artifacts like flickering models. Or if the value read is a pointer or pointer offset (and you don't do a bounds check) then a segfault is possible. Also the optimizer is allowed to reorder your memory accesses unless you explicitly prevent it and doing that screws with the optimizer.

To fully fix it you need 3 buffers.

* The physics thread uses 2. One as read-only for the current state and one in write for the next state. When the physics pass is complete the buffer in write state becomes read-only and it then picks the remaining buffer that the render thread *isn't* currently reading for the write buffer. At this point all 3 buffers will be in use.
* The render thread uses a read-only buffer to render and when the render pass is done, it will pick the buffer the physics thread is reading from. This may be the same as the previous render buffer if rendering is outspeeding the physics thread.

In my limited experience with atomics I haven't found a way to have the threads pick their buffers without needing a lock. But the critical section is only a few memory operations so it's not a huge deal (a busy-wait lock would suffice most of the time).
> 4 votes

---
Tags: multithreading
---


title: Continuous Collision Detection

text:
# Question
Title: Continuous Collision Detection
So I'm playing around with the separating axis theorem and collision. Obviously the problem of what face it collided with arose. I need the unit normal which is tangent to that face it collided with to resolve depth penetration. For rectangles it's easy.

```
Update Y velocity
If collision
    collision happened on the y axis.
Update X velocity
If collision
    collision happened on the x axis.

```

But I wanted a more general that would work with all cases. I came up with two solutions

1.) So I thought about the solution above with a triangle. Obviously it wouldn't work because the rectangles faces are axis aligned and a triangles faces are not. So I figured I could just project the face and velocity using the dot product to solve it like the rectangle but for every face with its own axis. This would of course involve checking collision with the whole shape again for each face.

2.) I also figured I could do Polygon v Ray collision detection to figure out what face it collided with.

My question is: Which solution is faster? Or is there a better one that hasn't come to my mind?

I don't know how to do Polygon v Ray collision but I would guess that foreach face, find intersection point between ray and segment of face.

# Answer
> 1 votes
Separating axis theorem on x and y is often only used for a quick pre-test if more accurate collision tests are necessary. These usually include accurate ray/polygon tests etc.. Keep in mind that the general approach of finding a separating axis/hyperplane works only for convex objects! See Wiki.

Generally, it is not a good idea to update positions on the axis separately - if you find a collision, you might still want to update the other axis depending on your resolve strategy. Instead you should just check all objects that have moved since the last simulation step.

**Polygon vs Ray 2D:**
As you suggested, just test the ray vs every edge. Only if a single polygon is extremely complicated (\>100 edges) you may need to think about more involved data-structures for this task.

**Polygon vs Ray 3D:**
Polygon vs ray works by first intersecting the ray with the polygon's plane (early out if no hit). This reduces the problem to two dimensions: For triangles you need to determine the barycentric coordinates and check weather they're inside. For more complex polygons you can check for every edge if the point lies inside or outside - only if the tests return "inside" for every edge, the ray has hit the polygon.

---
Tags: collision-detection, collision-resolution, raycasting
---


# Question
Title: 3D mesh culling issue, further faces showing through closer faces
I'm trying to render a generated mesh using libGDX which acts as a java wrapper for openGL. The issue i'm having can be seen in the screenshot below. The faces of the mesh that should be hidden by closer faces are being drawn on top of the closer faces.

There is probably something really obvious that i'm missing but i cant quite work out what it is. How do i get the draw order/culling to be correct.

The methods that generate my indices, vertices and normals can be found below.

```
public TerrainChunk(int width, int height, int vertexSize, String heightMapTexture) {

    if ((width + 1) * (height + 1) > Short.MAX_VALUE) {
        throw new IllegalArgumentException(
                "Chunk size too big, (width + 1)*(height+1) must be <= 32767");
    }

    this.heightMap = new float[(width + 1) * (height + 1)];
    this.width = (short) width;
    this.height = (short) height;
    this.vertices = new float[heightMap.length * vertexSize];
    this.indices = new short[width * height * 6];
    this.vertexSize = vertexSize;

    buildHeightmap(heightMapTexture);

    buildIndices();
    buildVertices();

    calcNormals(indices, vertices);

}

public void buildHeightmap(String pathToHeightMap) {

    FileHandle handle = Gdx.files.internal(pathToHeightMap);
    Pixmap heightmapImage = new Pixmap(handle);
    Color color = new Color();
    int idh = 0;

    for (int x = 0; x < this.width + 1; x++) {
        for (int y = 0; y < this.height + 1; y++) {
            Color.rgba8888ToColor(color, heightmapImage.getPixel(x, y));
            this.heightMap[idh++] = color.r;
        }
    }
}

public void buildVertices() {
    int heightPitch = height + 1;
    int widthPitch = width + 1;

    int idx = 0;
    int hIdx = 0;
    int strength = 100; // multiplier for height map

    float scale = 4f;

    for (int z = 0; z < heightPitch; z++) {
        for (int x = 0; x < widthPitch; x++) {

            // POSITION
            vertices[idx++] = scale * x;
            vertices[idx++] = heightMap[hIdx++] * strength;
            vertices[idx++] = scale * z;

            // NORMAL, skip these for now
            idx += 3;

            // COLOR
            vertices[idx++] = Color.WHITE.toFloatBits();

            // TEXTURE
            vertices[idx++] = (x / (float) width);
            vertices[idx++] = (z / (float) height);

        }
    }
}

private void buildIndices() {
    int idx = 0;
    short pitch = (short) (width + 1);
    short i1 = 0;
    short i2 = 1;
    short i3 = (short) (1 + pitch);
    short i4 = pitch;

    short row = 0;

    for (int z = 0; z < height; z++) {
        for (int x = 0; x < width; x++) {
            indices[idx++] = i1;
            indices[idx++] = i2;
            indices[idx++] = i3;

            indices[idx++] = i3;
            indices[idx++] = i4;
            indices[idx++] = i1;

            i1++;
            i2++;
            i3++;
            i4++;
        }

        row += pitch;
        i1 = row;
        i2 = (short) (row + 1);
        i3 = (short) (i2 + pitch);
        i4 = (short) (row + pitch);
    }
}

// Gets the index of the first float of a normal for a specific vertex
private int getNormalStart(int vertIndex) {
    return vertIndex * vertexSize + positionSize;
}

// Gets the index of the first float of a specific vertex
private int getPositionStart(int vertIndex) {
    return vertIndex * vertexSize;
}

// Adds the provided value to the normal
private void addNormal(int vertIndex, float[] verts, float x, float y, float z) {

    int i = getNormalStart(vertIndex);

    verts[i] += x;
    verts[i + 1] += y;
    verts[i + 2] += z;
}

/*
 * Normalizes normals
 */
private void normalizeNormal(int vertIndex, float[] verts) {

    int i = getNormalStart(vertIndex);

    float x = verts[i];
    float y = verts[i + 1];
    float z = verts[i + 2];

    float num2 = ((x * x) + (y * y)) + (z * z);
    float num = 1f / (float) Math.sqrt(num2);
    x *= num;
    y *= num;
    z *= num;

    verts[i] = x;
    verts[i + 1] = y;
    verts[i + 2] = z;
}

/*
 * Calculates the normals
 */
private void calcNormals(short[] indices, float[] verts) {

    for (int i = 0; i < indices.length; i += 3) {
        int i1 = getPositionStart(indices[i]);
        int i2 = getPositionStart(indices[i + 1]);
        int i3 = getPositionStart(indices[i + 2]);

        // p1
        float x1 = verts[i1];
        float y1 = verts[i1 + 1];
        float z1 = verts[i1 + 2];

        // p2
        float x2 = verts[i2];
        float y2 = verts[i2 + 1];
        float z2 = verts[i2 + 2];

        // p3
        float x3 = verts[i3];
        float y3 = verts[i3 + 1];
        float z3 = verts[i3 + 2];

        // u = p3 - p1
        float ux = x3 - x1;
        float uy = y3 - y1;
        float uz = z3 - z1;

        // v = p2 - p1
        float vx = x2 - x1;
        float vy = y2 - y1;
        float vz = z2 - z1;

        // n = cross(v, u)
        float nx = (vy * uz) - (vz * uy);
        float ny = (vz * ux) - (vx * uz);
        float nz = (vx * uy) - (vy * ux);

        // normalize(n)
        float num2 = ((nx * nx) + (ny * ny)) + (nz * nz);
        float num = 1f / (float) Math.sqrt(num2);
        nx *= num;
        ny *= num;
        nz *= num;

        addNormal(indices[i], verts, nx, ny, nz);
        addNormal(indices[i + 1], verts, nx, ny, nz);
        addNormal(indices[i + 2], verts, nx, ny, nz);
    }

    for (int i = 0; i < (verts.length / vertexSize); i++) {
        normalizeNormal(i, verts);
    }
}

```

The draw method can also be found below:

```
modelView.set(camera.view);

    terrainTexture.bind();

    shader.begin();

    //Gdx.gl.glEnable(GL20.GL_CULL_FACE);
    //Gdx.gl.glCullFace(GL20.GL_BACK);
    Gdx.gl.glDepthFunc(GL20.GL_LESS);

    shader.setUniformMatrix("u_MVPMatrix", camera.combined);
    shader.setUniformMatrix("u_normalMatrix", normalMatrix.set(modelView).inv().transpose());

    shader.setUniform3fv("u_lightPosition", new float[]{0,100,0}, 0, 3);
    shader.setUniform4fv("u_ambientColor", new float[]{1,1,1,1}, 0, 4);
    shader.setUniform4fv("u_diffuseColor", new float[]{1,1,1,1}, 0, 4);
    shader.setUniform4fv("u_specularColor", new float[]{1,1,1,1}, 0, 4);

    shader.setUniformi("u_texture", 0);

    mesh.render(shader, GL20.GL_TRIANGLES);

    shader.end();

```

Vertex Shader:

```
attribute vec4 a_position;  +
attribute vec3 a_normal;
attribute vec2 a_texCoord;
attribute vec4 a_color;

uniform mat4 u_MVPMatrix;
uniform mat3 u_normalMatrix;

uniform vec3 u_lightPosition;

varying float intensity;
varying vec2 texCoords;
varying vec4 v_color;

void main() {
vec3 normal = normalize(u_normalMatrix * a_normal);
vec3 light = normalize(u_lightPosition);
intensity = max( dot(normal, light) , 0.0);

v_color = a_color;
texCoords = a_texCoord;

gl_Position = u_MVPMatrix * a_position;
};

```

Fragment Shader:

```
#ifdef GL_ES
precision mediump float;
#endif

uniform vec4 u_ambientColor;
uniform vec4 u_diffuseColor;
uniform vec4 u_specularColor;

uniform sampler2D u_texture;
varying vec2 texCoords;
varying vec4 v_color;

varying float intensity;

void main() {
    gl_FragColor = v_color * intensity * texture2D(u_texture, texCoords);
};

```

# Answer
I'd comment but I dont have the rep yet. I've not worked with libGDX but I presume somewhere that you have to enable Z writes on your terrain draw.
> -1 votes

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


# Question
Title: Arrow key control on winforms RichTextBox
I am making a faux console using winforms for the game I am working on. Right now I am moving a '0' across the screen using the arrow keys.

In order to provide fine grain formatting on the text, I am using a richTextBox for the console display. The background for this box is black.

Problem: If the richTextBox is set to Enabled = false I can use the arrow keys without a problem but the box background color is grey and will not change. If I set it to read-only, when using the arrow keys it will just move the cursor and my arrow key events will not fire.

I am fine with setting the text to read-only and getting my black control color. So my question would be, is there a way to set the control to read-only and still allow for my arrow key events (and not move the cursor)?

# Answer
> 1 votes
As Ausa mentioned, you can use `KeyPreview` **and** `SupressKeyPress`.

```
public MainForm()
{
    InitializeComponent();
    this.KeyPreview = true;
    this.KeyDown += new KeyEventHandler(MainForm_KeyDown);
}

void MainForm_KeyDown(object sender, KeyEventArgs e)
{
    e.SuppressKeyPress = true; // cancel key press
    if (e.KeyCode == Keys.Right) // do whatever you want with your user input
    {
        MoveRight(); // for example
    }
}

```

# Answer
> 0 votes
One way could be to make it so whenever the text box got focus (watch for the event), set the focus to a different control instead (maybe the main window).

In that other control, you could watch for arrow key events and act on them by running the code that does whatever you want to do to the contents of the rich text box.

To the user, things would seem like you want them to, even though in reality there are a few more moving parts.

# Answer
> 0 votes
If you're raising the key press event from your main form then you should be able to simply set the KeyPreview property to true on your main form and it will register the key press first, befor the Rich Text Box does.

---
Tags: c#, windows-forms
---


# Question
Title: Libgdx Networking (http requests) - Login
I am new to Networking and Databases, but im trying to learn MySQL and HTTP Requests to create a user Login for a game.

My goal is to let users create accounts and login to them etc (for Highscores etc). I discovered the Libgdx Net Module and also got my server running with MySQL, Apache and PHP. I want to use php files to communicate with the Database on the Server.

But my question is (since there is not a big documention for libgdx Network Module): Where and how can i learn how to create proper HTTP Requests in LibGDX and should i use JSON? Just give me a hint how to start.

Thanks ;)

# Answer
This is somewhat what I am doing now. I use the KryoNet library also created by Nathan of LibGDX. I have a KryoNet server that my LibGDX app connects to and that server uses the `jdbc` to connect to a MySQL server locally. So actually without webrequests since my server is local to the DB.

Having a server between the database and your clients is not really necessary though. But I want multiplayer game mechanics that need to be handled on the server. And a TCP connection is a lot faster then webrequests.

Now for your actual question, if you want to use webrequests to run a php script for working with your database then look at the following code.

```
builder = new HttpRequestBuilder();
        request = builder.newRequest().method(Net.HttpMethods.GET).url("http://yourdomain.com/script.php").build();
        request.setHeader("Content-Type", "application/x-www-form-urlencoded");

final long start = System.nanoTime(); //for checking the time until response
        Gdx.net.sendHttpRequest(request, new Net.HttpResponseListener() {
            @Override
            public void handleHttpResponse(Net.HttpResponse httpResponse) {
                Gdx.app.log("WebRequest", "HTTP Response code: " + httpResponse.getStatus().getStatusCode());
                Gdx.app.log("WebRequest", "HTTP Response code: " + httpResponse.getResultAsString());
                Gdx.app.log("WebRequest", "Response time: " + ((System.nanoTime() - start) / 1000000) + "ms");
            }

            @Override
            public void failed(Throwable t) {
                Gdx.app.log("WebRequest", "HTTP request failed");
            }

            @Override
            public void cancelled() {
                Gdx.app.log("WebRequest", "HTTP request cancelled");
            }
        });

```

You can also send back XML and HTML if you supply the `content-type` in the header. Then just use your favorite parser to parse the data in your app. You can just grab it within the listeners `httpResponse.getResultAsString()` or `httpResponse.getResultAsStream()` if you like to work with a stream.

This is some php I wrote to receive XML when I wanted the same as you, then I switched over to the client -\> server -\> database architecture.

```
<?php
$link = mysqli_connect("127.0.0.1", "root", "", "test");
$xml = new SimpleXMLElement("<?xml version=\"1.0\" encoding=\"utf-8\" ?><mysql></mysql>");
if (!$link)
{
    $xml->addChild("error", "Error: Unable to connect to MySQL.");
    $xml->addChild("error", "Debugging errno: " . mysqli_connect_errno());
    $xml->addChild("error", "Debugging error: " . mysqli_connect_error());
    exit;
}

$xml->addChild("success", "Success: A proper connection to MySQL was made!");
$xml->addChild("success", "Host information: " . mysqli_get_host_info($link));

//To send the xml data back:
print($xml->asXML());

mysqli_close($link);
?>

```

Take note that you do have to change the header to receive xml data in your app.
> 1 votes

---
Tags: libgdx, networking, databases, mysql, http
---


# Question
Title: D3D12 ConstantBuffer - Shader receives wrong values
im having trouble with one constantbuffer:

```
struct CameraConstData
{
    urd::Matrix projection; // 64 ( 16 floats)
    urd::Matrix view;       // 64 ( 16 floats)
    urd::Vec3 viewPosition; // 12 ( 3 floats)
    urd::Vec3 viewDir;      // 12 ( 3 floats)

    // 104 bytes (26 * 4)
    float offset[26];
};

```

inside the shader its defined like:

```
// desc heap cbv
cbuffer CameraConstBuffer : register(b0)
{
    float4x4 projectionMatrix;
    float4x4 viewMatrix;
    float3 viewPos;
    float3 viewDir;

}

```

now viewdir is always filled with wrong buffer indices.

viewDir.x is the passed y value viewDir.y is the passed z value viewDir.z is 0.0

checked it in the shader like:

```
float3 vpos = normalize(float4(viewDir, 0.0)).xyz;
//float value = vpos.x; // uses the passed y value
//float value = vpos.y; // uses the passed z value
color = float4(vpos, 1.0);

```

GPU Debugging shows that the constant buffer looks fine:

i checked the vectors against the cpu side and they match.

**So why is the shader reading index 36-38 instead of 35-37?**

Its always affecting the 4th member of the struct. If i switch viewPosition with viewDir, viewPosition is false.

# Answer
> 0 votes
Aligning members should help. Either replace Vec3 and float3 with Vec4 and float4 or add a float after them.

---
Tags: shaders, directx, hlsl, directx12
---


title: Where am I obligated to put credits?

text:
# Question
Title: Where am I obligated to put credits?
First of all this is not a discussion for the *best* place to put credits, but rather where it's *allowed*.

So for instance is it fine if I just include a credits.txt file in the install directory, or will I have to make an in-game place where you can read them.

And is there any general rules, or is it up to the individual which need credit?

# Answer
You could follow the game crediting guide by the IGDA like many game studios do.

Its main bulk are several rules regarding who to credit, in what order and in what way. But page 10 also has rules regarding where to place the credits. To sumarize:

* The credits should appear in the game
* The credits should be easily accessible without having to beat the game.

General practice is to put a "credits" button on the main menu and also play the credits on completion of the game (if the game has a clear moment of completion).

However, this guide is only a recommendation. The only crediting requirements which you **must** follow are those which are part of the work contracts of those who contribute to the game (many work contracts in the game industry reference or quote the IGDA rules, though). When the contract you made with a staff member doesn't have a crediting clause, you are only morally obligated to give them credit, not legally.
> 18 votes

# Answer
It depends on the contracts you are bound by. If nothing is specified then you can put it wherever you want. That being said you probably want to give due credit.
> 5 votes

# Answer
It's up to the individual and whatever contract or agreement governs your use of whatever they did.

Some OSS licenses specify that credits have to be in particular places. IANAL, but I've seen cases where (when no location was specified) it was deemed correct by courts that the credit was in the application package (for a Mac app), which is not usually a place where people not reverse-engineering your app look. So you can probably get away with a lot as far as courts are involved.

That said, it's generally considered polite to put credits in an equivalent place to where you put the credits for your team/your main copyright notice. Not on the home screen, but your about screen or your Readme file are usually considered appropriate (the latter is the only sensible place for e.g. command line tools).

But when in doubt, ask whoever you're crediting where they want to be credited. Only way to be safe.
> 1 votes

---
Tags: assets, business
---


# Question
Title: Rotating a 3rd person camera toward a target
I have a 3rd person camera that doesn't look directly at the player but somewhere in front of him.

When the user enter shooting mode, I want the camera to turn around the player to face the target.

In the image above. "O" is the player (Origin), "L" is the lookat, "C" is the camera position and "T" is the target. I want to rotate the lookat line C-\>L so that it passes by T (C'-\>L'-\>T') around the Origin ("O").

Basically I need to find the angle alpha that I put in red in the picture.

I store my camera position in a structure like such :

```
struct CameraTarget {
     Quaternion absoluteRotation;
     Vec3 absolutePosition;
     Vec3 cameraOffset;
     Vec3 lookatOffset;
     float FOV;
}

```

So if I could find the angle I'm looking for I could do something like :

```
cam->absoluteRotation = cam->absoluteRotation * alpha;

```

To get the player to always look at the target.

If the lookat was passing by the Origin I could simply do

```
Vec3 origDir = cam->lookAtOffset - cam->absolutePosition;
origDir.normalize();
Vec3 newDir = cam->target - cam->absolutePosition;
newDir.normalize();
Quaternion q(origDir, newDir); // from->to
cam->absoluteRotation = cam->absoluteRotation * q;

```

However in the diagram above this doesn't quite work since the rotation is offset from the Origin.

# Answer
> 1 votes
Answering to myself if it helps someone else one day :

SFDKT has the right idea about projecting the target point into the current camera look direction.

However, my biggest problem was finding this point P. Turned out that a bit of trigonometry managed to solve it.

Considering the triangle formed by the three points CPO :

1. Since I know the lengths LO, OC and CL I can calculate the angle at C.
2. Now I know the angle C and the length of OC and PO. Using the law of sines you can find the angle at O. (I found this website very useful for finding the missing angles)
3. Then I can find the last missing angle P and use again the law of Sines to find the length CP.
4. Take the look direction posC + normalized(CL) * lengthCP gives me the position of P.
5. Once I have P I can calculate the shortest rotation between OP and OT which gives me the quaternion I need to rotate my camera.

I did have a bit of trouble with unwanted roll in 3D but I just solved the problem with Z = 0 then calculated the missing pitch rotation to keep the camera's up vector straight.

# Answer
> 0 votes
this picture adds the symmetry needed to solve the question easier.

Just project `L` along the vector `CL` so that `|P-O|=|T-O|`.

Now it's obviously just two identical triangles (`CPO` and `C'TO`) rotated by your desired angle. I.E. `ang(OT)-ang(OP)`

`C'` and `L'` are both the same as `C` and `L` after rotating, about `O`, by the same amount.

---
Tags: c++, 3d, mathematics, camera, software-engineering
---


# Question
Title: How to achieve a dynamic soft see-through hole effect in a wall with shaders?
I'm looking for a way to create a dynamic soft see-through hole effect for room walls. I know a few ways how to do it (for example multitexturing with second layer being the hole mask in screenspace), but all involve rendering walls with blending on which is too expensive for the mobile project I'm working on. Is there any way to do this without using blending on the whole geometry (the hole can appear in any place on any wall). Please see the attached image for a better illustration of the effect:

Also, I'm very open to any links to papers/tutorials that might not be solving the exact problem but doing something close that might get me on the right tracks. Thank you!

# Answer
> 1 votes
You could add another camera which has only one specific layer that it can view. This layer should be the layer of your special object, so then you enable the second camera whenever you want to see the object through other objects.

# Answer
> 0 votes
Using two materials for walls. Solid one and trasparent one. Whe you decide to activate trasparency :

```
gameObject.renderer.material = transparentMaterial;

```

You can script some conditions, like to activate trasparancy when some interesting object is inside a particular range from camera..

---
Tags: unity, opengl, shaders, directx, graphics-programming
---


# Question
Title: How to project a foam trail on dynamically changing mesh
I am trying to create water, and right now I got it through dynamically generating waves on a mesh. But now I want to make my boat manipulate these waves, and cause a Kelvin Wake on top of this.

Fact is I generate the water using different tiles, repeating the same pattern dynamically. So How would I generate this on top of a dynamically generated mesh(plane)? Without also manipulating the other tiles (planes)?

# Answer
> 1 votes
How I would go about something like this is to make a grid, like a sort of heightmap. And if a mesh is in the grid try to calculate (on a 2d plane) how deep it will be in the water, then, based on this heightmap, generate the waves in the water.

# Answer
> 0 votes
I have 3 suggestions. first: You might try and create the effect using a particle system. second: You can try and use TrailRenderer for a trail. third: You could try and create a mesh with such trail shape, parent it to the boat and depending on the speed/distance to increase the size of it on one/two axes.

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


# Question
Title: spritekit sidescroller how to move hero through the level
I am trying to learn spritekit by working my way through developing a simple side scrolling game, but I cannot find a clear answer on how to move the hero through the level.

The width of my ground far exceeds the width of the view and I have always thought it was best to move the ground not the hero, but my enemies (who pace back and forth) tend to move much more quickly as the hero moves and to the wrong spot. I am guessing this is because the ground is moving and changing their destination during the move action.

Is moving the ground (not the hero) the best way to create a sidescroller without a repeating landscape. If so, how do I create enemies that move in a restricted area like mario?

Here is a portion of my code:

```
let enemy = SKSpriteNode(imageNamed: "enemyWalk1.png")

override func didMoveToView(view: SKView) {

    enemy.physicsBody = SKPhysicsBody(texture: SKTexture(imageNamed: "enemyWalk1.png"), size: enemy.size)
    enemy.physicsBody = SKPhysicsBody(rectangleOfSize: enemy.size)
    enemy.physicsBody!.affectedByGravity = true
    enemy.physicsBody!.allowsRotation = false
    enemy.physicsBody!.dynamic = true

    enemy.position = CGPoint(x:CGRectGetMinX(self.frame) + enemy.size.width + 800, y:CGRectGetMinY(self.frame) + ground!.frame.size.height + enemy.size.height)
    self.addChild(enemy)

    var enemyGoTo1 = enemy.position.x + 100
    var enemyGoTo2 = enemy.position.x - 100

    var enemyXScale1 = SKAction.scaleXBy(1, y: 1, duration: 0.0)
    var enemyXScale2 = SKAction.scaleXBy(-1, y: 1, duration: 0.0)

 enemy.runAction(SKAction.repeatActionForever(SKAction.animateWithTextures(enemyTextureArray, timePerFrame: 0.15)), withKey: "enemyWalk")
    enemy.runAction(SKAction.repeatActionForever(SKAction.sequence([enemyXScale1, SKAction.moveToX(enemy.position.x + 100,duration: 1.5), enemyXScale2, SKAction.moveToX(enemy.position.x - 100,duration: 1.5), enemyXScale1, enemyXScale2])))

}

override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
    for touch in (touches as! Set<UITouch>) {
        let location = touch.locationInNode(self)

        if nodeAtPoint(location) == rightArrow {
                rightTouched = true

            }
        }
}

override func update(currentTime: CFTimeInterval) {
        if rightTouched == true {
            childNodeWithName("ground")!.position.x = childNodeWithName("ground")!.position.x - 8
        }
}

```

# Answer
> 0 votes
You need to define some classes first

* Background
* Enemy
* Player (your hero)
* Life Bonus (for example or power up or ….)
* GameScene,ViewController,appDelegate

and you should define some essential method on them like generating a background for your game on class Background something like this (from the below book)

```
+ (ERGBackground *)generateNewBackground
{
    ERGBackground *background = [[ERGBackground alloc]initWithImageNamed:@"background.png"];
    background.anchorPoint = CGPointMake(0, 0);
    background.name = backgroundName;
    background.position = CGPointMake(0, 0);
    background.zPosition = 5;
    background.physicsBody = [SKPhysicsBody bodyWithEdgeFromPoint:CGPointMake(0, 34) toPoint:CGPointMake(background.size.width, 34)];
    background.physicsBody.collisionBitMask = playerCollisionBitmask;
    SKNode *topCollider = [SKNode node];
    topCollider.position = CGPointMake(0, 0);
    topCollider.physicsBody = [SKPhysicsBodybodyWithEdgeFromPoint:CGPointMake(0, background.size.height - 30) toPoint:CGPointMake(background.size.width, background.size.height - 30)];
    topCollider.physicsBody.collisionBitMask = 1;
    [background addChild:topCollider];
    return background;
}

```

In background moving you need to create just two set of background in a moment and switch the first to the secound, one when it reaches to the end.

Paralax should also be created in background class

```
(ERGBackground *)generateNewParallax
{
    ERGBackground *background = [[ERGBackground alloc] initWithImageNamed:@"parallax.png"];
    background.anchorPoint = CGPointMake(0, 0);
    background.name = parallaxName;
    background.position = CGPointMake(0, 0);
    background.zPosition = 4;
    return background;
}

```

Unfortunately the codes are in objective C you have to change them to swift which I that would be very easy.

Please read the following book which is totaly about how to create an endless runner game. It also has some example that you can download and start to change it to have your own. as I see, you hav’t started to code yet, so I think this is a good start for you :

Read This Book

> I read this book, it is really a good one and will push you into endless runner games.

---
Tags: ios, spritekit, swift
---


title: Drawing the box2D rectangles

text:
# Question
Title: Drawing the box2D rectangles
i'm using SDL2.0/OpenGL + Box2D with C++ to learn some stuff about games, so i created two rectangles bodies: a small box(dynamic) wich will fall into the second body: the ground(static), i draw them on the screen with OpenGL primitives, as recomended i'm not using "pixel thinking", i'm using meters to represent everything, well, the problem is that i can't get a good physic simulation, just almost, when rendering i can see the small box falling into the ground but it don't touch the ground, it gets real close but don't touch, i really can't understand why, so i came here to see if can get some help:

Here we create the bodies(and do other things):

```
void MyLoop::onCreate(){
world = new b2World(b2Vec2(0, -10));

player = new Player(world);
//creates the player body
player->create();

//Creates the ground
b2BodyDef bdef;
b2PolygonShape* pshape = new b2PolygonShape();
b2FixtureDef fdef;

bdef.type = b2_staticBody;
ground = world->CreateBody(&bdef);

pshape->SetAsBox(40.0f, 1.0f);
fdef.shape = pshape;

ground->CreateFixture(&fdef);
ground->SetTransform(b2Vec2(20.0f, 0.5f), 0);

glMatrixMode(GL_MATRIX_MODE);
glLoadIdentity();
//configurating the apropriate scale
glOrtho(0, 40, 0, 20, 1, -1);

delete pshape;
}

```

The most important here is the bodies creation and the glOrtho call wich will set the camera to our coordinate system.

The creation of the player body:

```
b2BodyDef bdef;
bdef.type = b2_dynamicBody;

pbody = world->CreateBody(&bdef);

b2PolygonShape* pshape = new b2PolygonShape();
pshape->SetAsBox(0.5f, 1.0f);

b2FixtureDef fdef;
fdef.shape = pshape;
pbody->CreateFixture(&fdef);
pbody->SetTransform(b2Vec2(19.0f, 10.0f), 0);

```

So now we go to the render loop: i get the bodies position with getPosition() method and use them to draw the bodies:

```
glClearColor(1.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);

player->render();

float x = ground->GetPosition().x;
float y = ground->GetPosition().y;

renderer.begin(GL_QUADS);
renderer.setColor(0.0f, 0.0f, 1.0f);
renderer.drawRectangle(x - 20.0f, y + 0.5f, 40.0f, 1.0f);
renderer.end();

SDL_GL_SwapWindow(window);

world->Step(1 / 20.0f, 8, 3);

```

The player render:

```
float x = pbody->GetPosition().x;
float y = pbody->GetPosition().y;

renderer.begin(GL_QUADS);
renderer.setColor(0.0f, 1.0f, 0.0f);
renderer.drawRectangle(x - 0.25f, y + 0.5f, 0.5f, 1.0f);
renderer.end();

```

# Answer
> 1 votes
I think that there is no problem with your code. It's Box2D's thing, that it creates a little bit of skin around the polygons.

According to the Box2D manual, a little gap between polygons is being intentionally created to make continuous collision resolution more stable by preventing tunneling, eg. in stacking scenarios. Manual also says one can make their visual shapes slightly bigger to make up for this artificial gap. I think you could go with that.

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


title: Dealing with Spritesheets - resizing

text:
# Question
Title: Dealing with Spritesheets - resizing
Let's say that I have a spritesheet with 4 sprites (standing, breathing player).

When I load it with

```
player_bitmap = BitmapFactory.decodeResource(resources, R.drawable.player_standing);

```

it sets it's width and height to for example 100/50 and I have to divide it by 4 and I get four sprites 25x50.

Problem is here that when I switch the app to tablet (I was on phone) sprites have different sizes when loaded.

How to solve issues like this?

Thank you

# Answer
> 0 votes
It seems as though the pixel density for your phone and tablet are different.

If so a few of options are,

1) Have a set of spritesheets created for varying pixel density displays and pick the closest one that matches the pixel density it was created for. You could end up with a lot of spritesheets

2) Scale your sprites when you draw them.

You can use a mixture of both techniques.

If your phone has a pixel density of 100, and your tablet has a pixel density of 200, then your sprites would seem half the size on the tablet. In this case if you chose option 2 then you'd need to double the scale

You can find a handy PPI list for various devices here

---
Tags: java
---


# Question
Title: What is a viable way of finding the minimum swaps to sort numbers in pyramid?
I have made a game that consists of a pyramid of hexagons with numbers from 00 to 99 randomly positioned in groups of 6, 10 or 15 elements. Now, I'm working to create an auto-solver but for the last 2 weeks, I have got nothing really worth produced, and would like your help. My objective is to determine the minimum swaps need to turn the left pyramid into the right pyramid:

Obviously, there's a catch: every cell can be exchanged only with it's neighbors cells, as below:

I've tried a lot of approaches with binary heap, BST and others, but I can't seems to find a proper answer. What would be the best algorithm choice to determine the minimum swaps needed to sort this hive?

Thanks in advance for any help,

Marcelo

# Answer
> 5 votes
This is very nice example of problem suited for A\* algorithm. I will not go into details how to implement A\* here as it has been done better before and this very easy to find, however this is how I would apply A\* for your problem:
As you can see, there is only a limited number of states that you can "move" to using single swap (14 for this case if I am not mistaken), you can think of them as a nodes in the (pathfinding)graph searched by A\*. Naturally, you can only move to adjacent nodes and the distance from start node is the number of swaps made to reach "current" node.
What you also need for A\* is function estimating the distance to goal state. Choosing good one is the key to speed of the algorithm, however pretty much any decent one will lead to the solution. I suggest using the sum of distances to goal postion, e.g. "1" is 1 swap away from its place, similarly "3" is two swaps away, all summing up to `distance = 8` for the state in your example.

---
Tags: algorithm, data-structure, tree, sorting
---


# Question
Title: Is restitution the wrong value, to make bouncing objects?
I have been experimenting with Bullet. Specifically I was modifying the Hello World tutorial, to make the ball bouncing.

The first thing I noticed is, that I need to set both the restitution of the ball and the ground above 0 to make the ball bouncing.

For a simple setup, with two objects, this seems fine. However, for larger simulations I fell like, restitution is the wrong way, to make bouncy objects. Here are my reasons:

# Reason 1

Consider three objects: `ball`, `box` and `ground`. `ground` is just some plane. `box` is a box, which is not supposed to be very bouncy, thus its restitution is near or equals zero. `ball` is supposed to be bouncy, so I give it a restitution of `0.5`.

If now the ball collides with the ground, it only actually bounces, if the ground also has a restitution higher than `0`, so let's give it a restitution of `1`. So our ball is bouncy as expected, when colliding with the ground.

When it collides with `box` it won't bounce, because the box has a restitution of `0`. If we give `box` a higher restitution, the ball will bounce from it. But now we have a different problem. If the `box` collides with the ground, it will bounce off, but it isn't supposed to.

I see no way, with restitution only, to make this scenario work.

# Reason 2

Restitution describes the amount of energy, that remains as impulse after a collision. The rest of the energy goes into deforming the colliding bodies and other side effects.

If we now look at a typical bouncy object, like a rubber ball, we see that they are easily deformable (compared to less bouncy objects). When the rubber ball collides with something, it takes up energy from the collision, by being deformed **and then** goes back into its original form, thus releasing the energy taken up during the collision and bouncing back off.

# The solution (?)

Reason 2 suggests, that a bouncy ball (like a rubber ball) shouldn't have a restitution close to 1, but rather be elastic (thus being deformed and then going back to its original form), to model bouncy objects as expected.

The way to model this in Bullet, would be a soft-body and I think it would be the way to go, in such a scenario.

# The actual question

The text above looks more like an answer than a question, so here's the question I'm trying to ask:

I'm really unsure, whether this is right. Are soft-bodies really the better way for bouncy stuff or am I just mistaking the principle of restitution?

# Answer
You're mistaking restitution. Or more specifically, it depends upon Bullet's chosen restitution implementation.

Ideally you would be able to define \[ball, plane\].restitution as 0.9 and \[box, plane\].restitution as 0.1, for example.

The total coefficient of restitution, in real life, is almost always \>0.0 and \<1.0.

Thus, when generating your restitution from two separate object materials, depending on the method\*, ensure that your coefficients are between 0.0 and 0.5.

\*The example above assumes that the two materials' restitutions are added together. I am not sure about whether Bullet adds them together, multiplies them or performs some form of min/max.

Further investigation:

1. Looking at bullet's constraint solver you can see that it gets the contact manifold
2. Once it has the manifold it gets a specific contact point
3. Once it has the contact point it requests its "m\_combinedRestitution"

However, I do not have the time right now to download the source and investigate where the m\_combinedRestitution is set. If you were to investigate, I'd look into the NarrowPhaseCollision section of Bullet.
> 1 votes

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


# Question
Title: How can I test DXGI_ERROR_DEVICE_REMOVED error handling?
My application uses DX11 and it periodically gets a `DXGI_ERROR_DEVICE_REMOVED` error on startup. It is an infrequent thing (I can go days or weeks without seeing it) but according to the documentation here it should be expected and handled smoothly.

Because it is so infrequent I cannot debug or test this scenario. I have tried changing video card settings while the app is running, switching users, etc. I cannot seem to trigger it. What can I do?

# Answer
The documentation you linked calls out the four most common reasons for a device reset:

* the device is physically removed from the system
* the device gets into a bad state and must reset
* the system switches between two onboard GPUs (low to high power, for example)
* the drivers are upgraded

You probably don't want to physically remove the device to stimulate the error, as most consumer PCs are not set up to safely hot-swap that way. Similarly it's not that easy to make the device crash and have to reset. Toggling GPUs is easy enough, usually, if you have them and have the ability to force the machine to use one or the other, but that's pretty hardware-dependent.

So you should update your drivers to trigger the error. Downgrading drivers should work as well, so you can just toggle between two driver versions while your code is executing to make sure you react correctly.

---

Note that you *can* just wrap the calls that might return `DXGI_ERROR_DEVICE_REMOVED`, ignore their actual return value, and pretend it was `DXGI_ERROR_DEVICE_REMOVED` on a temporary basis. This can be a quick way to test that the code path for handling the error works at the most basic level, although it is still good to check by stimulating the error for real, because the real error will come with side-effects that are much harder for you to simulate.
> 1 votes

# Answer
One reliable way to cause device-removed is to intentionally trigger the TDR mechanism from another process in the system. You can do this by dispatching a compute shader containing an infinite loop, such as the following:

**cs.hlsl**

```
RWBuffer<uint> dummyUAV;
cbuffer dummyCB {uint zero;}
[numthreads(256, 1, 1)]
void main(uint3 id : SV_DispatchThreadID)
{
    [loop] while (zero == 0) dummyUAV[id.x] = zero;
}

```

**main.cpp**

```
#include <d3d11.h>
#include "cs.h"

int main(int argc, char* argv[])
{
    ID3D11Device* dev = nullptr;
    ID3D11DeviceContext* con = nullptr;
    D3D11CreateDevice(nullptr, D3D_DRIVER_TYPE_HARDWARE, nullptr, 0, nullptr, 0, D3D11_SDK_VERSION, &dev, nullptr, &con);
    ID3D11ComputeShader* cs = nullptr;
    dev->CreateComputeShader(g_main, sizeof(g_main), nullptr, &cs); // from compiled cs.h
    con->CSSetShader(cs, nullptr, 0);
    con->Dispatch(256, 1, 1);
    con->Flush(); // hangs then TDRs
    return 0;
}

```
> 4 votes

---
Tags: directx, directx11
---


# Question
Title: Can i use shaders in allegro without opengl?
I'm currently learning opengl but it seems quite complicated so i considered using some library like sdl or allegro. I noticed that allegro has some built in functions to create and attach shaders.

But my question is: do my shaders "shade" everything i render with allegro or they are only functions to ease the work of loading shaders with opengl/directx?

Any help apreciated!

# Answer
> 2 votes
They work in a similar, if not identical, way as in openGL/DirectX shaders... The only difference is that an `ALLEGRO_SHADER` needs to contain both a fragment and vertex shader for rendering to work.

The way they work is that you attach a shader program to the device or display and then all drawings done in it will pass through the shader, so to achieve different effects you can detach the previous shader and then attach the new one on run-time as necessary.

---
Tags: shaders, glsl, allegro
---


title: Tiled deferred rendering light culling

text:
# Question
Title: Tiled deferred rendering light culling
I'm trying to implement tile based light culling in opengl using a compute shader. I am using this as a guide. The lighting calculations work fine but the point light culling doesn't seem to work any where near correctly. I can't tell if my planes are calculated wrong or its my culling loop. To test what tile has a light affecting it I draw it in gray, as i move the camera away the gray tiles fade to the right no matter where the light is placed.

Compute shader:

```
#version 430

#define MAX_POINT_LIGHTS 1024
#define MAX_LIGHTS_PER_TILE 40
#define WORK_GROUP_SIZE 16

struct Attenuation
{
    float constant;
    float linear;
    float exponent;
};

struct Light
{
    vec3 color;
    float intensity;
};

struct DirectionalLight
{
    Light light;
    vec3 direction;
};

struct PointLight
{
    Light light;
    Attenuation atten;
    vec3 position;
    float radius;
};

vec4 calcLight(Light light, vec3 direction, vec3 normal, vec3 fragPos, vec3 specular, vec3 camPos)
{
    float diffuseFactor = dot(normal, -direction);

    vec4 diffuseColor = vec4(0.0, 0.0, 0.0, 0.0);
    vec4 specularColor = vec4(0.0, 0.0, 0.0, 0.0);

    if (diffuseFactor > 0)
    {
        // might need to be 0.0----------| |
        diffuseColor = vec4(light.color, 1.0) * light.intensity * diffuseFactor;

        vec3 directionToEye = normalize(camPos - fragPos);
        vec3 halfDirection = normalize(directionToEye - direction);

        float specularFactor = dot(halfDirection, normal);
        // maybe not 32?
        specularFactor = pow(specularFactor, 32);

        if (specularFactor > 0)
        {
            // maybe 0.0 again
            specularColor = vec4(light.color, 1.0) * vec4(specular, 1.0) * specularFactor;
        }
    }

    return diffuseColor + specularColor;
}

vec4 calcDirectionalLight(DirectionalLight dirLight, vec3 pos, vec3 normal, vec3 specular, vec3 camPos)
{
    return calcLight(dirLight.light, dirLight.direction, normal, pos, specular, camPos);
}

vec4 calcPointLight(PointLight pointLight, vec3 pos, vec3 normal, vec3 specular, vec3 camPos)
{
    vec3 lightDirection = pos - pointLight.position;
    float distanceToPoint = length(lightDirection);

    lightDirection = normalize(lightDirection);

    vec4 color = calcLight(pointLight.light, lightDirection, normal, pos, specular, camPos);

    float atten = pointLight.atten.constant + pointLight.atten.linear * distanceToPoint + pointLight.atten.exponent * distanceToPoint * distanceToPoint + 0.0001;

    return color / atten;
}

layout (binding = 1, rgba32f) uniform image2D writeonly finalImage;
layout (binding = 2, rgba32f) uniform readonly image2D geometryPosition;
layout (binding = 3, rgba32f) uniform readonly image2D geometryDiffuse;
layout (binding = 4, rgba32f) uniform readonly image2D geometryNormal;

uniform int numActiveLights;
uniform PointLight pointLights[MAX_POINT_LIGHTS];
uniform Light ambientLight;
uniform DirectionalLight directionalLight;

uniform vec3 cameraPosition;
uniform vec2 resolution;

uniform mat4 projection;
uniform mat4 view;

shared uint minDepth;
shared uint maxDepth;
shared uint pointLightCount;
shared uint pointLightIndex[MAX_POINT_LIGHTS];

layout (local_size_x = WORK_GROUP_SIZE, local_size_y = WORK_GROUP_SIZE) in;

void main()
{
    minDepth = uint(0xFFFFFFFF);
    maxDepth = 0;
    pointLightCount = 0;
    barrier();

    ivec2 pixel = ivec2(gl_GlobalInvocationID.xy);

    vec3 position = imageLoad(geometryPosition, pixel).xyz;
    float d = position.z;
    uint depth = uint(d * uint(0xFFFFFFFF));

    atomicMin(minDepth, depth);
    atomicMax(maxDepth, depth);

    barrier();

    float minDepthZ = float(minDepth / float(0xFFFFFFFF));
    float maxDepthZ = float(maxDepth / float(0xFFFFFFFF));

    vec2 tileScale = vec2(resolution * (1.0 / float(2 * WORK_GROUP_SIZE)));
    vec2 tileBias = tileScale = vec2(gl_WorkGroupID.xy);

    vec4 col1 = vec4(-projection[0][0] * tileScale.x, projection[0][1], tileBias.x, projection[0][3]);
    vec4 col2 = vec4(projection[1][0], -projection[1][1] * tileScale.y, tileBias.y, projection[1][3]);
    vec4 col4 = vec4(projection[3][0], projection[3][1], -1.0, projection[3][3]);

    //vec4 col1 = vec4(-projection[0][0] * tileScale.x, 0.0f, tileBias.x, 0.0f);
    //vec4 col2 = vec4(0.0f, -projection[1][1] * tileScale.y, tileBias.y, 0.0f);
    //vec4 col4 = vec4(0.0, 0.0, 1.0, 0.0);

    vec4 frustumPlanes[6];
    frustumPlanes[0] = col4 + col1;
    frustumPlanes[1] = col4 - col1;
    frustumPlanes[2] = col4 - col2;
    frustumPlanes[3] = col4 + col2;
    frustumPlanes[4] = vec4(0.0, 0.0, -1.0, -minDepthZ);
    frustumPlanes[5] = vec4(0.0, 0.0, -1.0, maxDepth);

    for (int i = 0; i < 4; i++)
    {
        frustumPlanes[i] *= 1.0 / length(frustumPlanes[i].xyz);
    }

    uint threadCount = WORK_GROUP_SIZE * WORK_GROUP_SIZE;
    uint passCount = (numActiveLights + threadCount - 1) / threadCount;

    for (int passIt = 0; passIt < passCount; ++passIt)
    {
        uint lightIndex = passIt * threadCount + gl_LocalInvocationIndex;
        lightIndex = min(lightIndex, numActiveLights);

        PointLight p = pointLights[lightIndex];
        vec4 pos = view * vec4(p.position, 1.0);
        float rad = p.radius / pos.w;

        if (pointLightCount < MAX_LIGHTS_PER_TILE)
        {
            bool inFrustum = true;
            for (int i = 3; i >= 0 && inFrustum; i--)
            {
                float dist = dot(frustumPlanes[i], pos);
                inFrustum = (-rad <= dist);
            }

            if (inFrustum)
            {
                uint id = atomicAdd(pointLightCount, 1);
                pointLightIndex[id] = lightIndex;
            }
        }
    }

    barrier();

    vec3 normal = imageLoad(geometryNormal, pixel).xyz;
    vec4 diffuse = imageLoad(geometryDiffuse, pixel);
    vec3 specular = vec3(0.1, 0.1, 0.1);

    vec4 color = diffuse;
    color *= vec4((ambientLight.color * ambientLight.intensity), 1.0);
    color += calcDirectionalLight(directionalLight, position, normal, specular, cameraPosition);

    for (int i = 0; i < pointLightCount; i++)
    {
        //color += calcPointLight(pointLights[pointLightIndex[i]], position, normal, specular, cameraPosition);
        color = vec4(0.5);
    }

    barrier();

    imageStore(finalImage, pixel, color);
}

```

# Answer
Turns out it was just a stupid mistake on the line

```
vec2 tileBias = tileScale = vec2(gl_WorkGroupID.xy);

```

The second "=" should be "-". Whoops! Every thing works fine now.
> 1 votes

---
Tags: opengl, glsl
---


# Question
Title: How to change alpha of a sprite through script in Unity
I have 4 buttons and they each flash when the button is pressed. However if you were to press a button, then while the button is darker (flashing) click another one, that button then stays dark. I want to reset the color of the sprite before disabling them however it's not working. When the buttons are pressed they no longer flash....

Here is the code:

```
void Start () {
        easy.GetComponent<SpriteRenderer>().color = color;
    }

    void Update () {
        if(difficultySelected[0] == true){
            enemyBehavior.shotsPerSecond = 0.2f;
            //Enabling the selected button
            easy.enabled = true;

            //Reseting the colors
            normal.GetComponent<SpriteRenderer>().color = color;
            hard.GetComponent<SpriteRenderer>().color = color;
            expert.GetComponent<SpriteRenderer>().color = color;

            //Disabling the 'unselected' buttons
            normal.enabled = false;
            hard.enabled = false;
            expert.enabled = false;

            easy.Play("Difficulty");
        }else if(difficultySelected[1] == true){
            enemyBehavior.shotsPerSecond = 0.5f;
            normal.enabled = true;

            easy.GetComponent<SpriteRenderer>().color = color;
            hard.GetComponent<SpriteRenderer>().color = color;
            expert.GetComponent<SpriteRenderer>().color = color;

            easy.enabled = false;
            hard.enabled = false;
            expert.enabled = false;

            normal.Play("Difficulty");
        }else if(difficultySelected[2] == true){
            enemyBehavior.shotsPerSecond = 1;
            hard.enabled = true;

```

# Answer
Turns out I the easy, normal etc. variables were just the Animators, not the whole image. I just added another set of variables with the images in and it worked fine. Here is the final code:

```
    public EnemyBehavior enemyBehavior;
    public bool[] difficultySelected;

    public Animator easy;
    public Animator normal;
    public Animator hard;
    public Animator expert;

    public Image easyButton;
    public Image normalButton;
    public Image hardButton;
    public Image expertButton;

    private Color color;

    public void DifficultySelected(int name){
        difficultySelected[0] = false;
        difficultySelected[1] = false;
        difficultySelected[2] = false;
        difficultySelected[3] = false;
        difficultySelected[name] = true;
    }

    void Update () {
        if(difficultySelected[0] == true){
            enemyBehavior.shotsPerSecond = 0.2f;
            //Enabling the selected button
            easy.enabled = true;

            //Disabling the 'unselected' buttons
            normal.enabled = false;
            hard.enabled = false;
            expert.enabled = false;

            normalButton.color = new Color(1f, 1f, 1f, 1f);
            hardButton.color = new Color(1f, 1f, 1f, 1f);
            expertButton.color = new Color(1f, 1f, 1f, 1f);

            easy.Play("Difficulty");
        }else if(difficultySelected[1] == true){
            enemyBehavior.shotsPerSecond = 0.5f;
            normal.enabled = true;

            easy.enabled = false;
            hard.enabled = false;
            expert.enabled = false;

            easyButton.color = new Color(1f, 1f, 1f, 1f);
            hardButton.color = new Color(1f, 1f, 1f, 1f);
            expertButton.color = new Color(1f, 1f, 1f, 1f);

            normal.Play("Difficulty");
        }else if(difficultySelected[2] == true){
            enemyBehavior.shotsPerSecond = 1;
            hard.enabled = true;

            easy.enabled = false;
            normal.enabled = false;
            expert.enabled = false;

            easyButton.color = new Color(1f, 1f, 1f, 1f);
            normalButton.color = new Color(1f, 1f, 1f, 1f);
            expertButton.color = new Color(1f, 1f, 1f, 1f);

            hard.Play("Difficulty");
        }else if(difficultySelected[3] == true){
            enemyBehavior.shotsPerSecond = 2;
            expert.enabled = true;

            easy.enabled = false;
            normal.enabled = false;
            hard.enabled = false;

            easyButton.color = new Color(1f, 1f, 1f, 1f);
            normalButton.color = new Color(1f, 1f, 1f, 1f);
            hardButton.color = new Color(1f, 1f, 1f, 1f);

            expert.Play("Difficulty");
        }
    }

```
> 0 votes

# Answer
You can write:

```
color.a = 1f; // value between 0 and 1, where 1 is opaque

//Resetting the colors
normal.GetComponent<SpriteRenderer>().color = color;
hard.GetComponent<SpriteRenderer>().color = color;
expert.GetComponent<SpriteRenderer>().color = color;

```
> 1 votes

---
Tags: unity, c#, transparency, alpha
---


# Question
Title: How to draw a polygon with picture in libgdx?
I'm working around a simple rectangle game, It just split the rectangle in to a lot of polygon debris. I use `Pixmap` and `Texture` to draw the edges of each polygon.

```
...
 for (GraphEdge e: _edges) {
    pixmap.drawLine((int) e.x1, (int) e.y1, (int) e.x2, (int) e.y2);
 }
...
@Override//In an actor class
public void draw(Batch batch, float parentAlpha) {
    region = new TextureRegion(new Texture(pixmap));
    region.setRegionWidth((int)width+1);
    region.setRegionHeight((int)height+1);
    batch.draw(region, this.getX(), this.getY());
}

```

it works well,but I want to add some pictures to adjust those polygons to make it looks better than some tedious lines, how should I implement it?

# Answer
> 1 votes
Consider using `PolygonRegion`s, they're a way of mapping a `TextureRegion` onto a polygon. That way you can define the initial rectangle as a quad made up of two triangles, and then you can split that anyway you like across any number of fragments.

```
private Texture texture;
private PolygonRegion region;
private PolygonSpriteBatch batch;
private PolygonRegionDebugRenderer debugRenderer;

@Override
public void create () {
texture = new Texture(Gdx.files.internal("someimage.png"));

    // Define 4 vertices; (0, 0), (100, 100) (0, 100) and (100, 0)
    // Define 2 triangles; (0, 1, 2) and (0, 3, 2)
    // This will make up a quad
    region = new PolygonRegion(new TextureRegion(texture), new float[] {0, 0, 100, 100, 0, 100, 100, 0}, new short[] {0, 1, 2, 0, 3, 2});
    batch = new PolygonSpriteBatch();
    debugRenderer = new PolygonRegionDebugRenderer();
}

@Override
public void render () {
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    Gdx.gl.glClearColor(0f, 0f, 0f, 1f);

    // Setup camera, set camera onto batch etc, etc.

    batch.begin();

    batch.draw(region, 0, 0, 256, 256);

    batch.end();

    debugRenderer.setProjectionMatrix(camera.combined);
    debugRenderer.draw(region, 0, 0, 0, 0, 256, 256, 1, 1, 0);
}

```

It even comes with a handy `PolygonRegionDebugRenderer` for easy trouble shooting. There's an example in the github repository showing how to use them in more detail.

---
Tags: java, libgdx, graphics
---