# Question
Title: If IDXGISwapChain::Present blocks, does that mean I'm GPU bound?
I updated my DirectX11 renderer to render on multiple threads using deferred contexts. Before my change, the `Present` method took a negligible amount of time (according to VTune analysis). After my change, `Present` now takes a significant amount of time (15-30ms or so). I've tried using double / triple buffering, disabling vsync, but that makes no difference. My scene runs at about 25 hz, and vtune shows my CPU at 100% up until i call `Present`, at which points it just waits for a good bit.

Does this mean that I'm GPU bound, or is this just an artifact of using deferred context rendering, since I'm not sending the GPU any work at all until the very last second? And if its the latter, is there anything I can do to get started on the next scene rather than waiting around on `Present`?

# Answer
> 5 votes
First, please use a real GPU profiling tool rather than inaccurate measurements. There is a good GPU and CPU profiler built into Visual Studio, so you don't have to hunt around to find decent tools. That out of the way...

Standard industry practice is to render *first*, then do game logic and physics, then finally call `Present`. That way you parallelize the GPU and CPU workloads.

```
# !! CORRECT !! game loop for non-trivial games
for N in 1..infinity:
  draw frame N
  prepare new frame N+1 # GOOD - GPU and CPU are working in parallel here!
  present N

```

The classic render loop you find in most books gets this horribly wrong.

```
# !! INCORRECT !! game loop from introductory learning materials
for N in 1..infinity:
  prepare new frame N # BAD - GPU is idle!
  draw frame N
  present N # BAD - CPU is idle!

```

More complex games have to intelligently intermingle the GPU commands and CPU work, since submitting a frame to the GPU by itself takes a considerable amount of time. This is often achieved with a threaded job system that uses a "shared nothing" approach to rendering. While the threading makes things more complicated, the game loop is similar to the first loop above: the difference is just that the "draw current frame" and "prepare next frame" are happening at the same time using separate copies of the game's state.

# Answer
> 0 votes
So I think I figured out whats going on here. If I `Sleep` at the beginning of my frame, then the frame rate slows down, which means I'm not strictly CPU bound.

If I sleep after I call `ExecuteCommandList` but before `Present`, my frame rate doesn't change (until I sleep for like 40ms). So I believe what is going on is that the driver needs time to translate the commands before I can continue, which is why `Present` is blocking.

---
Tags: c++, directx, directx11, multithreading
---


# Question
Title: Phong lighting - there is something very strange with specular lighting
I implemented Phong lighting. Everything seems to work - torus and spheres are lighted as expected, etc. But I notices something strange regarding specular lighting of directional light.

Here are two screenshots.

First:

Second:

As you can see more area has specular lighting when camera is far from an object.

Here are simplified vertex shader:

```
#version 330 core

layout(location = 0) in vec3 vertexPos;
layout(location = 1) in vec3 vertexNorm;
layout(location = 2) in vec2 vertexUV;

uniform mat4 MVP;
uniform mat4 M;

out vec2 fragmentUV;
out vec3 fragmentNormal;
out vec3 fragmentPos;

void main() {
  fragmentUV = vertexUV;
  fragmentNormal = (M * vec4(vertexNorm, 0)).xyz;
  fragmentPos = (M * vec4(vertexPos, 1)).xyz;

  gl_Position = MVP * vec4(vertexPos, 1);
}

```

... and fragment shader:

```
#version 330 core

in vec2 fragmentUV;
in vec3 fragmentNormal;
in vec3 fragmentPos;

struct DirectionalLight {
  vec3 Color;
  vec3 Direction;
  float AmbientIntensity;
  float DiffuseIntensity;
};

uniform sampler2D textureSampler;
uniform vec3 cameraPos;
uniform float materialSpecularFactor;
uniform float materialSpecularIntensity;
uniform DirectionalLight directionalLight;

out vec4 color;

void main() {
  vec3 normal = normalize(fragmentNormal); // should be normalized after interpolation

  vec4 ambientColor = vec4(directionalLight.Color, 1) * directionalLight.AmbientIntensity;

  float diffuseFactor = clamp(dot(normal, -directionalLight.Direction), 0, 1);
  vec4 diffuseColor = vec4(directionalLight.Color, 1) * directionalLight.DiffuseIntensity * diffuseFactor;

  vec3 vertexToCamera = normalize(cameraPos - fragmentPos);
  vec3 lightReflect = normalize(reflect(directionalLight.Direction, normal));
  float specularFactor = pow(clamp(dot(vertexToCamera, lightReflect), 0, 1), materialSpecularFactor);
  vec4 specularColor = vec4(directionalLight.Color, 1) * materialSpecularIntensity * specularFactor;

  color = texture(textureSampler, fragmentUV) * (ambientColor + diffuseColor + specularColor);
}

```

Full source code without any simplification could be found in this repository.

I wanted to know if I implemented something wrong. Or is it OK for Phong lighting?

# Answer
> 36 votes
> specular lighting of directional light
>
> more area has specular lighting when camera is far from an object

Yep, looks right to me.

The specular area for directional lights is supposed to be more or less constant w.r.t. the camera, given the same reflection surface. To compare, we can look at the phenomenon known as sunglint, which is basically specular reflection of the Sun on water, and since the Sun is approximately a directional light source for terrestrial purposes, and the reflection surface is the Earth which is approximately flat, this is a good analogue of your Phong lighting.

Example 1: area of sunglint roughly the same as a residential lot

> http://academic.emporia.edu/aberjame/remote/lec10/lec10.htm

Example 2: area of sunglint approximate to the Great Lakes

> http://earthobservatory.nasa.gov/IOTD/view.php?id=78617

In fact the sunglint area will just keep enlarging until you are far enough from the Earth for it to be more round than flat, from your perspective.

In terms of the Phong reflection model, the specular depends on three directions: the eye, the light, and the surface. Since your camera is looking at the same surface, just moving away, the eye stays the same; the surface stays the same by virtue of being flat, and the light stays the same by definition (it's a directional light), therefore the specular reflection will be the same - from the camera/screen's perspective, of course.

---
Tags: opengl, shaders, glsl, lighting, specular
---


# Question
Title: Getting child collider when collision occurs in compound object in unity3d?
I have a compound object. The parent of the compound object hierarchy has a script that is listening to the OnTrigerXXX callbacks of the children. When this compound object collides with other objects is there any way to get both colliders? I mean the "other" collider and the collider that belongs to the compound object itself that collided?

P.D: All rigid bodies must be kinematic, so, I can't use OnCollisionXXXX with the collision info param that has all the information I need in the contacts array.

Edit to add a bit more information as Savlon suggested:

When we are not using compound objects and we want to have a centralized place to handle children collision events, we could have something like this:

```
//In Children
void OnTriggerEnter(Collider c)
{
    (parent's script).TriggerHandler(this, c);
}

//In Parent
public void TriggerHandler(GameObject theChild, Collider c)
{
   // do stuff
}

```

This is ok and will work. The "problems" with this way are:

1. I could have a lot of children, so, using compound objects I would need to add just a rigid body component to the parent. This could be a pretty good memory reduction usage. However if I don't use compound objects I will have to add a rigid body to every child like in the previous code.
2. In my case children under a parent are always touching. Not intersecing but touching. Think about a set of blocks one beside the other. They do not intersect but there are no gaps between them. With compound objects I don't have to mess with it. It authomatically treats all the children as a whole and no collision callbacks will be fired among them.

On the other hand when using compund objects, you get all the advantages listed before but if you need information about what children collided with another collider you won't be able to get it because your script listening to callbacks is in the parent and you will only receive as parameter the "other" collider when unity calls you back through OnTriggerXXXX callback.

I was asking if there is any way to get both colliders using a compound object.

Hope everything is clearer now.

Cheers

# Answer
> 1 votes
You could, at runtime, assemble your children's colliders into one big collider that you add to the parent. In order for this to work the way I've done it below, the children would have to have Mesh Colliders, even if they were box-shaped:

```
// Use this for initialization
    void Start () {
        MeshCollider[] childMeshes = GetComponentsInChildren<MeshCollider>();

        CombineInstance[] combine = new CombineInstance[childMeshes.Length];

        for (int i = 0; i < childMeshes.Length; i++)
        {
            combine[i].mesh = childMeshes[i].sharedMesh;
            combine[i].transform = childMeshes[i].transform.localToWorldMatrix;
        }

        Mesh mesh = new Mesh();
        mesh.CombineMeshes(combine);

        MeshCollider parentMesh = gameObject.AddComponent<MeshCollider>();

        parentMesh.isTrigger = true;
        parentMesh.sharedMesh = mesh;
    }

```

After that, it would be up to you to disable the Mesh Colliders in the child components, or not, as your program requires.

See this documentation for more information:

docs.unity3d.com/ScriptReference/MeshCollider-sharedMesh.html docs.unity3d.com/ScriptReference/Mesh.CombineMeshes.html

---
Tags: unity, collision-detection, physics
---


# Question
Title: Efficient way to implement animation from spritesheet?
I'm actually trying to port a GBA game to SDL for educationnal purpose. The game has many sprites and tiles. Since the GBA screen size is 240x160px, I decided to scale it 2x. At first, it went okay creating spritesheet for animations, because typical animations had something around 2-8 frames.

However, I faced yesterday a problem that I had not seen coming. I got a 89-frame animation. Including the scale, each frame is around 480x320px. With 89 frames, it creates a huge image.

When I load it into a SDL\_Texture with IMG\_LoadTexture, the size of the test program goes from ~9MB to **56MB**. I find this huge considering the image weights at most **4MB** (without compression, PNG-32 bits I believe). No matter what compression I do, it still takes ~50MB.

Here's the code that loads the image:

```
m_frameDestRect = { 0, 0, 480, 320 };
m_frameSrcRect = { 0, 0, 480, 320 };
m_pTexSprite = IMG_LoadTexture(pRenderer, "image.png");

```

I keep the SDL\_Texture in a `SDL_Texture*` property of my class. It also never change.

Here's the code that "draws" the texture:

```
SDL_RenderCopy(m_pRenderer, m_pTexSprite, &m_frameSrcRect, &m_frameDestRect);

```

Here's the code that "update" the frame:

```
uint32_t frameX = (m_frame + 1) % 5;
uint32_t col = (m_frame + 1) / 5;

m_frameSrcRect = { frameX * 480, col * 320, 480, 320 };

```

I could live with that, but then I saw that I got an animation that has **489** frames...

Since I am no expert in video games programming, nor in imaging, I came here to ask this very question.

**1. Is the RAM consumption of SDL\_Texture (and whatever loaded behind) normal ?<br>2. Animation wise, are there other ways to implement them?**

I find it totally impressive all these sprites (got tons of them, in gif formats) actually loaded quite smoothly on the GBA, considering the number of frames.

Any advice / solutions / answers is more than welcomed.

Thanks

# Answer
> 0 votes
Just remember that unless you are using gpu compression (Which PNGs don't support), all of your images will be uncompressed in ram.

Also, your animation seems pretty standard. Remember that as long as everything fits into ram, you're only drawing what you see so performance shouldn't be an issue

# Answer
> 0 votes
With a standard setup you'll use 32 bit per pixel, that is 4 bytes. So each of your frames requires 614400bytes, 89 frames use 52MB.

You could reduce the amount by factor 2 if you switch to 16bit RGB565 for RGBA4444 format - that is not GPU dependent.

ETC1, PVRTC 2bbp/4bbp, DXTC are platform specific. Your software might not run on all kinds of GPUs.

8192x8192 might also not work on all devices.

I would recommend using a video codec to compress the images. They use the difference between frames and give you a way better compression ratio.

---
Tags: c++, animation, spritesheet, sdl2, compression
---


# Question
Title: Fixing strange artifacts in an HQX shader
I'm having an issue implementing an HQX filter that I found in the LibRetro GitHub repository.

* LUT texture was obtained here
* Shader file was obtained here (I converted it to compile in MonoGame with SM 5)

This is what I'm getting:

And this is what I'm expecting:

This is the relevant code:

```
// loading the effect
var effect = base.Content.Load<Effect>(@"Effects\hqx");
var lutTexture = base.Content.Load<Texture2D>(@"Effects\hq4x");
var projection = Matrix.CreateOrthographicOffCenter(0, 720, 480, 0, 0, 1);
var halfPixelOffset = Matrix.CreateTranslation(0.5f, 0.5f, 0);

effect.Parameters["modelViewProj"].SetValue(halfPixelOffset * projection);
effect.Parameters["texture_size"].SetValue(new Vector2(240f, 160f));
effect.Parameters["LutTexture"].SetValue(lutTexture);

this.effect = effect;

```

Here is how I've configured the required LUT image:

Here is where I draw a pre-rendered texture using the effect:

```
// renderTarget is a 240x160 texture that has the image draw to it first
// the scaling is done by drawing the renderTarget at the higher resolution
spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.NonPremultiplied,
                  SamplerState.PointClamp, null, null, this.Effect);
{
    spriteBatch.Draw(this.renderTarget, new Rectangle(0, 0, 720, 480),
                     this.renderTarget.Bounds, Color.White);
}
spriteBatch.End();

```

This is the contents of the hqx.fx file:

```
#define SCALE 4

#define trY 48.0
#define trU 7.0
#define trV 6.0

static float3 yuv_threshold = float3(trY/255.0, trU/255.0, trV/255.0);

const static float3x3 yuv = float3x3(0.299, 0.587, 0.114, -0.169, -0.331, 0.5, 0.5, -0.419, -0.081);
const static float3 yuv_offset = float3(0, 0.5, 0.5);

bool diff(float3 yuv1, float3 yuv2) {
    bool3 res = abs((yuv1 + yuv_offset) - (yuv2 + yuv_offset)) > yuv_threshold;
    return res.x || res.y || res.z;
}

struct out_vertex {
    float4 position : SV_POSITION;
    float4 color    : COLOR;
    float2 texCoord : TEXCOORD0;
    float4 t1       : TEXCOORD1;
    float4 t2       : TEXCOORD2;
    float4 t3       : TEXCOORD3;
};

sampler2D decal : register(s0);
sampler2D LUT : register(s1)
{
    Texture = (LutTexture);
    Filter = Linear;
    AddressU = clamp;
    AddressV = clamp;
};

float2 texture_size;
float4x4 modelViewProj;

out_vertex main_vertex
(
    float4 position : SV_POSITION,
    float4 color    : COLOR,
    float2 texCoord : TEXCOORD0
)
{
    out_vertex OUT;

    OUT.position = mul(position, modelViewProj);
    OUT.color = color;

    float2 ps = 1.0/texture_size;
    float dx = ps.x;
    float dy = ps.y;

    OUT.texCoord = texCoord;
    OUT.t1 = texCoord.xxxy + float4(-dx, 0, dx, -dy); //  w1 | w2 | w3
    OUT.t2 = texCoord.xxxy + float4(-dx, 0, dx,   0); //  w4 | w5 | w6
    OUT.t3 = texCoord.xxxy + float4(-dx, 0, dx,  dy); //  w7 | w8 | w9

    return OUT;
}
float4 main_fragment(in out_vertex VAR) : COLOR
{
    float2 fp = frac(VAR.texCoord*texture_size);
    float2 quad = sign(-0.5 + fp);
    float2 ps = 1.0/texture_size;

    float dx = ps.x;
    float dy = ps.y;
    float3 p1 = tex2D(decal, VAR.texCoord).rgb;
    float3 p2 = tex2D(decal, VAR.texCoord + float2(dx, dy) * quad).rgb;
    float3 p3 = tex2D(decal, VAR.texCoord + float2(dx, 0) * quad).rgb;
    float3 p4 = tex2D(decal, VAR.texCoord + float2(0, dy) * quad).rgb;
    float4x3 pixels = float4x3(p1, p2, p3, p4);

    float3 w1  = mul(yuv, tex2D(decal, VAR.t1.xw).rgb);
    float3 w2  = mul(yuv, tex2D(decal, VAR.t1.yw).rgb);
    float3 w3  = mul(yuv, tex2D(decal, VAR.t1.zw).rgb);

    float3 w4  = mul(yuv, tex2D(decal, VAR.t2.xw).rgb);
    float3 w5  = mul(yuv, p1);
    float3 w6  = mul(yuv, tex2D(decal, VAR.t2.zw).rgb);

    float3 w7  = mul(yuv, tex2D(decal, VAR.t3.xw).rgb);
    float3 w8  = mul(yuv, tex2D(decal, VAR.t3.yw).rgb);
    float3 w9  = mul(yuv, tex2D(decal, VAR.t3.zw).rgb);

    bool3x3 pattern = bool3x3(diff(w5, w1), diff(w5, w2), diff(w5, w3),
                              diff(w5, w4), false       , diff(w5, w6),
                              diff(w5, w7), diff(w5, w8), diff(w5, w9));
    bool4 cross = bool4(diff(w4, w2), diff(w2, w6), diff(w8, w4), diff(w6, w8));

    float2 index;
    index.x = dot(pattern[0], float3(1, 2, 4)) +
              dot(pattern[1], float3(8, 0, 16)) +
              dot(pattern[2], float3(32, 64, 128));
    index.y = dot(cross, float4(1, 2, 4, 8)) * (SCALE * SCALE) +
              dot(floor(fp * SCALE), float2(1, SCALE));

    float2 step = 1.0 / float2(256.0, 16.0 * (SCALE * SCALE));
    float2 offset = step / 2.0;
    float4 weights = tex2D(LUT, index * step + offset);
    float sum = dot(weights, float4(1,1,1,1));
    float3 res = mul(transpose(pixels), weights / sum);

    return float4(res, 1.0);
}

technique T0
{
    pass P0
    {
        VertexShader = compile vs_5_0 main_vertex();
        PixelShader = compile ps_5_0 main_fragment();
    }
}

```

Any help is greatly appreciated. If there are any other details you'd like me to provide please let me know.

# Answer
When configuring the LUT texture you must set the properties in the pipeline as follows:

```
GenerateMipmaps  = false
PremultiplyAlpha = false

// set this to false as it is redundant anyway (the scale 4 texture is 256x256)
ResizeToPowerOfTwo = false

```
> 0 votes

---
Tags: c#, shaders, monogame, graphic-effects
---


# Question
Title: Camera follows player but how to stop camera moving when player moves
The player is moving automatically diagonally down the screen, and I have the camera as a child on the player. I would like the camera to always be following the player (who sometimes slows down / speeds up) as they are automatically moving, but when the player moves left and right, I don't want the whole camera view to shift with this.

I am moving the player with this:

```
transform.Translate(xSpeed, ySpeed, 0);

```

And the player can move the character with this:

```
Vector2 direction = new Vector2(0.2f, 0.67f);

if (Input.GetKeyDown(KeyCode.LeftArrow))
{   //transform stores the position data of the playu
    transform.Translate(direction * -distance);
}

else if (Input.GetKeyDown(KeyCode.RightArrow))
{
    transform.Translate(direction * distance);
}

```

However when they move with this I would like not for the camera to shift with the movement, but still continue to follow them as they move across the 2D map.

@Hash Buoy I can't add comments yet, but the player is automatically moving at an angle, which the camera follows them. They can move left and right with the arrow keys, and I was just wondering how to stop the camera shifting left and right (also as a 45 degree angle) when they do this

# Answer
So first off, you'll want to separate the player and camera in the inspector. Typically you only want to parent in that fashion when you want ALL transforms to be transferred to the children--note that if you rotate your player, or if you scale your player, the same will happen to your camera in your current setup, and that's very limiting.

Instead, you'll want to write a script that you place on the camera that manually follows your player. Like so:

```
public class PlayerTracker: MonoBehaviour
{
  public Transform Player;

  private Vector3 lastPos;

  void Start()
  {
    if(Player == null)
      //You'll want to maybe search the tags or something more reasonable here.
      Debug.Log("You forgot to set the player, stupid!");

    lastPos = Player.position;
  }

  void Update()
  {
    //Get the distance the player has moved since last frame.
    Vector3 delta = Player.position - lastPos;
    //Adds this difference to the camera's transform.
    this.transform.position += delta;
    //Caches the player's current position for next frame.
    lastPos = Player.position;
  }

```

This will match your player's movement unit for unit, while preserving the original distance between the two. But since you want to limit which axes are being used, we'll change the `this.transform.position += delta;` line to this instead:

```
this.transform.position += new Vector3(0, delta.y, 0);

```

And now only the Y-axis is being followed.

This is assuming a Ski-Free-like movement. I'm not quite sure what you're definitions of "diagonal", "left", and "right" are, so you'll have to clarify that for us if this isn't what you're looking for.
> 2 votes

# Answer
I fell into the same problem last week.

The easy solution is grabbing the Camera2Dfollow script from the standard asset package and set the target as the player. If you choose to do so, Remove the camera from inside the player from the hierarchy screen

Here is the Script :

```
 using System;
  using UnityEngine;

         namespace UnityStandardAssets._2D
    {
          public class Camera2DFollow : MonoBehaviour
        {
    public Transform target;
    public float damping = 1;
    public float lookAheadFactor = 3;
    public float lookAheadReturnSpeed = 0.5f;
    public float lookAheadMoveThreshold = 0.1f;

    private float m_OffsetZ;
    private Vector3 m_LastTargetPosition;
    private Vector3 m_CurrentVelocity;
    private Vector3 m_LookAheadPos;

    // Use this for initialization
    private void Start()
    {
        m_LastTargetPosition = target.position;
        m_OffsetZ = (transform.position - target.position).z;
        transform.parent = null;
    }

    // Update is called once per frame
    private void Update()
    {
        // only update lookahead pos if accelerating or changed direction
        float xMoveDelta = (target.position - m_LastTargetPosition).x;

        bool updateLookAheadTarget = Mathf.Abs(xMoveDelta) > lookAheadMoveThreshold;

        if (updateLookAheadTarget)
        {
            m_LookAheadPos = lookAheadFactor*Vector3.right*Mathf.Sign(xMoveDelta);
        }
        else
        {
            m_LookAheadPos = Vector3.MoveTowards(m_LookAheadPos, Vector3.zero, Time.deltaTime*lookAheadReturnSpeed);
        }

        Vector3 aheadTargetPos = target.position + m_LookAheadPos + Vector3.forward*m_OffsetZ;
        Vector3 newPos = Vector3.SmoothDamp(transform.position, aheadTargetPos, ref m_CurrentVelocity, damping);

        transform.position = newPos;

        m_LastTargetPosition = target.position;
    }
}

```

}
> 2 votes

# Answer
Let your camera be positioned at point c and let your player be position at point p. Let v be a vector representing the velocity moving the player on a diagonal. For every tick c\_{next} = c + v, p\_{next} = p + v.

One also must consider if the player moves far enough horizontally that they are outside of the view port. One method to handle this is clamping the player to the screen now allowing them to run out of the view port.
> 1 votes

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


# Question
Title: Unity 5 C# - onClick.AddListener in a foreach loop using lambda expressions
I'm trying to dynamically create Unity 5 UI buttons that each set a global variable decision\_id to a different value when clicked.

The problem I'm having with this implementation is that they all set decision\_id to the exact same value right now. That value being the last one in my foreach loop.

Here's my code:

```
IEnumerator make_decision(XmlNode options_node) {
    // reset decision_id
    decision_id = "nothing";

    // spawn a button for each option_node in options_node
    int i = 1;
    var new_option_1 = Instantiate(option_1);
    var new_option_2 = Instantiate(option_2);
    var new_option_3 = Instantiate(option_3);
    var new_option_4 = Instantiate(option_4);
    foreach (XmlNode option_node in options_node) {
        XmlNode temp_option_node = option_node;
        string option_id = temp_option_node.Attributes["id"].Value;
        Debug.Log(option_id);
        switch (i) {
            case 1:
                new_option_1.GetComponentsInChildren<Text>()[0].text = option_node.InnerText;
                new_option_1.GetComponent<Button>().onClick.AddListener(() => set_decision_id(option_id));
                new_option_1.transform.SetParent(canvas.transform, false);
                break;
            case 2:
                new_option_2.GetComponentsInChildren<Text>()[0].text = option_node.InnerText;
                new_option_2.GetComponent<Button>().onClick.AddListener(() => set_decision_id(option_id));
                new_option_2.transform.SetParent(canvas.transform, false);
                break;
            case 3:
                new_option_3.GetComponentsInChildren<Text>()[0].text = option_node.InnerText;
                new_option_3.GetComponent<Button>().onClick.AddListener(() => set_decision_id(option_id));
                new_option_3.transform.SetParent(canvas.transform, false);
                break;
            case 4:
                new_option_4.GetComponentsInChildren<Text>()[0].text = option_node.InnerText;
                new_option_4.GetComponent<Button>().onClick.AddListener(() => set_decision_id(option_id));
                new_option_4.transform.SetParent(canvas.transform, false);
                break;
            default:
                Debug.Log("Too many option nodes! Should only be four per options section");
                break;
        }
        i++;
    }

    while (decision_id == "nothing") {
        yield return new WaitForSeconds(.5f);
        // the button will change decision_id for us eventually
        // decision_id = "monarchy";
    }

    // despawn each button spawned above
    Destroy(new_option_1);
    Destroy(new_option_2);
    Destroy(new_option_3);
    Destroy(new_option_4);

}

```

I've searched this issue and have found lots of talk about the lambda's capturing instances instead of values... but I've already gone out of my way to prevent this by capturing both the XmlNode itself AND the id string in local variables.

Is there something super obvious that I'm missing here?

# Answer
You could avoid this `switch` entirely. Just add a string property onto new\_option\_X objects and set it instead; you would not need lambdas at all.

```
switch (i) {
  case 1:
    new_option_1.GetComponent<OptionProperty>().Option = option_id;
    ...

```

where OptionProperty is simple script:

```
public class OptionProperty : MonoBehaviour {
  public string Option { get; set; }

  void Start()
  {
    /*"same" handler for all buttons, fetch the argument from property instead*/
    GetComponent<Button>().onClick.AddListener(set_decision());
  }

  /*not using anonymous functions allows you to unsubscribe later, preventing potential memory leaks*/
  private void set_decision()
  {
    set_decision_id(Option); /*or whatever function wherever it is*/
  }
}

```
> 1 votes

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


title: Monogame shader not working

text:
# Question
Title: Monogame shader not working
I'm trying to use this this tutorial in monogame, but the effect does not work, only renders a black screen. Everyhing by itself renders just fine, I looked at the render targets if they get drawn to, but when I try to apply the effect to them it only renders a black screen.

I converted the .fx file using 2MGFX, also tried loading it with the following code:

```
BinaryReader Reader = new BinaryReader(File.Open(@"Content\\Lighting.mgfx", FileMode.Open));
        lightingEffect = new Effect(GraphicsDevice, Reader.ReadBytes((int)Reader.BaseStream.Length));

```

also with

```
lightingEffect = content.Load<Effect>("Lighting.mgfx");

```

and also with

```
byte[] bytecode = File.ReadAllBytes("Content\\Lighting.mgfx");
        lightingEffect = new Effect(graphics.GraphicsDevice, bytecode);

```

They did not make a difference.

The .fx file contains the following:

```
sampler s0;
texture lightMask;
sampler lightSampler = sampler_state { Texture = <lightMask>; };

float4 PixelShaderFunction(float2 coords: TEXCOORD0) : COLOR0
{
    float4 color = tex2D(s0, coords);
    float4 lightColor = tex2D(lightSampler, coords);
    return color * lightColor;
}

technique Technique1
{
    pass Pass1
    {
        PixelShader = compile ps_4_0_level_9_1 PixelShaderFunction();
    }
}

```

And the monogame version of the game1.cs(Only the important stuff):

```
public class Game1 : Game
{
    GraphicsDeviceManager graphics;
    SpriteBatch spriteBatch;

    Texture2D lightMask;
    Texture2D SquareGuy;

    RenderTarget2D lightsTarget;
    RenderTarget2D mainTarget;

    Effect lightingEffect;

    public Game1()
    {
        graphics = new GraphicsDeviceManager(this);
        Content.RootDirectory = "Content";
        IsMouseVisible = true;
    }

     protected override void LoadContent()
     {
        spriteBatch = new SpriteBatch(GraphicsDevice);
        lightMask = Content.Load<Texture2D>("lightmask");
        SquareGuy = Content.Load<Texture2D>("SquareGuy");
        // lightingEffect = content.Load<Effect>("Lighting.mgfx");
        /*
        byte[] bytecode = File.ReadAllBytes("Content\\Lighting.mgfx");
        lightingEffect = new Effect(graphics.GraphicsDevice, bytecode);
        */
        BinaryReader Reader = new     BinaryReader(File.Open(@"Content\\Lighting.mgfx", FileMode.Open));
        lightingEffect = new Effect(GraphicsDevice,     Reader.ReadBytes((int)Reader.BaseStream.Length));

        var pp = GraphicsDevice.PresentationParameters;
     //   pp.BackBufferHeight = 1024;
     //   pp.BackBufferWidth = 1024;
        lightsTarget = new RenderTarget2D(
            GraphicsDevice, pp.BackBufferWidth, pp.BackBufferHeight);
        mainTarget = new RenderTarget2D(
            GraphicsDevice, pp.BackBufferWidth, pp.BackBufferHeight);
     }

     protected override void Draw(GameTime gameTime)
     {
        GraphicsDevice.Clear(Color.CornflowerBlue);

        // TODO: Add your drawing code here
        GraphicsDevice.SetRenderTarget(lightsTarget);
        GraphicsDevice.Clear(Color.Black);
        spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.Additive);
        spriteBatch.Draw(lightMask, new Vector2(0, 0), Color.White);
        spriteBatch.Draw(lightMask, new Vector2(100, 0), Color.White);
        spriteBatch.Draw(lightMask, new Vector2(200, 200), Color.White);
        spriteBatch.Draw(lightMask, new Vector2(300, 300), Color.White);
        spriteBatch.Draw(lightMask, new Vector2(500, 200), Color.White);
        spriteBatch.End();

        // Draw the main scene to the Render Target
        GraphicsDevice.SetRenderTarget(mainTarget);
        GraphicsDevice.Clear(Color.CornflowerBlue);
        spriteBatch.Begin();
        spriteBatch.Draw(SquareGuy, new Vector2(100, 0), Color.White);
        spriteBatch.Draw(SquareGuy, new Vector2(250, 250), Color.White);
        spriteBatch.Draw(SquareGuy, new Vector2(550, 225), Color.White);
        spriteBatch.End();

        // Draw the main scene with a pixel
        GraphicsDevice.SetRenderTarget(null);
        GraphicsDevice.Clear(Color.CornflowerBlue);
        spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend);
        lightingEffect.Parameters["lightMask"].SetValue(lightsTarget);
        lightingEffect.CurrentTechnique.Passes[0].Apply();
        spriteBatch.Draw(mainTarget, Vector2.Zero, Color.White);
        spriteBatch.End();

        base.Draw(gameTime);
    }
}

```

So the question is what do I need to change to make the effect work in monogame?

I tried it in XNA with this code and worked perfectly. I know almost nothing about HLSL, so I don't know if theres something wrong with the effect. I only changed the version thingy from `ps_2_0` to `ps_4_0_level_9_1`. If I change it to `ps_4_0_level_9_3` it still doesn't work. I read something about assigning textures from outside of the .fx here, but since I know so little about shaders I don't know if this is the problem.

# Answer
I had this same problem last week. You need to add all the parameters to your PixelShaderFunction, or monogame will map registers incorrectly. Change your PixelShaderFunction parameters to be like this:

```
PixelShaderFunction(float4 pos : SV_POSITION, float4 color1 : COLOR0, float2 coords: TEXCOORD0)

```

Here is a more detailed explanation, where I got the answer: http://www.software7.com/blog/pitfalls-when-developing-hlsl-shader/
> 1 votes

---
Tags: c#, xna, 2d, shaders, monogame
---


# Question
Title: Unity3D - leaving and then returning to a scene
Effectively, I need to know how to run a mini game and then return to a scene. I know about

```
DontDestroyOnLoad (this);

```

but that works for game objects only and doesn’t do what I need - also because it carries the objects over into the next scene. In my game you play as a computer. When you hack into a computer remotely, you have to go into a sort of mini game where you must traverse the computer for data, experience and end up ‘owning’ the computer, having destroyed its security systems. My problem is that this requires being in a different scene, where the hacking 'minigame' is played out, then return. So I could just make a new scene, fine. But when I have to return to the old scene, it has to kick off from the exact point where I left to hack the computer, as if no time had past and with nothing being different. I am stuck on how to do this, because as far as I know there is no way to write a scenes data to a binary file and the read from it when loading the scene again - and persistent data was the only solution I could think of. Any help is appreciated.

## Summary

How to play the scene, load a different scene, finish that minigame and then continue from where you were in the original scene

# Answer
Try to put whole minigame scene into prefab(s) and load it not like a scene, but like an object(s). If minigame is lightweight enough this will be the best choice.
> 3 votes

---
Tags: unity, game-design
---


# Question
Title: What is the difference between an alpha and a beta release?
What is the difference between an alpha and a beta release? I'm surprised this question hasn't been asked here before.

# Answer
In traditional software engineering, Alpha releases will still be introducing new features, while Beta releases will see no new features, but rather polishing up the existing stuff.

However the current development environment in game dev is that both of these are simply "not complete yet", and alpha is generally just "less complete" than beta.

Beta releases will still see new features, while sometimes I'll see alphas that simply try and flesh out existing stuff. And even a few things that stay in alpha or beta forever.
> 41 votes

# Answer
Alpha means the features haven't been locked down, it's an exploratory phase. Beta means the features have been locked down and are under development (no other features will be added).
> 11 votes

# Answer
More commonly:

**Alpha:** *Usually the first normally interact-able thing out (private or public use is irrelevant).*

If you are building something thats supposed to have a GUI - alpha is where you can rudimentary use the software to some degree of what the consumer is supposed to use. For games its where the core module/mechanic is somewhat usable. I've seen some coders call it alpha on a rudimentary basis that can be used only via command line or scripts - but most people refrain from doing so.

**Beta:** *Most of it is working - all intended features may not be deployed yet - but its still breaking or at least bugging out often.*

Over the years the beta "label" has been used as a prolonged excuse for broken games or lack of adequate support.

Not that the other way around is much more preferable. Many projects have been shipped off as complete when they were by all rights still beta. In the context of games - having easily detectable game breaking bugs has been the case quite a few times.

Generally while most of us can agree on definition the concepts are not uniform across every development space.
> 8 votes

# Answer
Pre-Alpha is the version before the Alpha version, Alpha is the version before the Beta version, Beta is the version before the Gamma version, Release Candidate is the version just before the release. It's basically just to denote "this version is not supposed to be completely satisfactory and may contain heavy bugs or may even be completely broken".

What the different notions mean exactly differs from developer to developer.
> 4 votes

# Answer
Alpha and beta testing are two of the stages that a software must undergo testing. Alpha testing occurs first and when the software passes that, beta testing can then be undertaken. If a software fails alpha testing, changes are done and it repeats the tests until the software passes.

So to answer your question, an Alpha and Beta release can be considered the 'testable deployed artifact' that you are currently developing.

Read more: Difference Between Alpha and Beta Testing | Difference Between | Alpha vs Beta Testing http://www.differencebetween.net/technology/difference-between-alpha-and-beta-testing/#ixzz338XZWLaj
> -1 votes

# Answer
Alpha version is the first working version and is for internal use (testing) only! After the programers are satisfied they release the Beta version to non employs who are hackers and stress testers who try to break it. The end result is a final release to the public that has stood the test of time! It's a win win for the manufacturer and the public!

That's the way it was intended to work but rarely does these days
> -2 votes

---
Tags: terminology
---


# Question
Title: How to deal with (bad?) player suggestions
Every game which builds a community while still being in active development will soon be confronted with players who post suggestions for new features on its forum. Most of these suggestions, however:

* Go into a completely different direction than where you want your game to go
* Would require far too much effort for the benefit they could have
* Are just plain awful

What's a good way to deal with such suggestions?

Should you tell the players honestly what you think about their suggestions so that they learn to make more constructive ones?

Should you always try to maintain a positive and encouraging attitude towards player ideas, even when you secretly think that there is not a chance in hell you are following them?

Should you just ignore any suggestions which you don't like?

# Answer
People who make suggestions are often fans or critics, who are invaluable as they help you know how well you are doing. Therefore you should treat these people with respect. Be gentle, firm, and most importantly, honest. This means you tell them exactly why you think their idea is bad, whilst being as understanding as possible.

* **If the idea is technically difficult**, tell them so, and explain how it is technically difficult. Stick to the facts, stick to established wisdom. Address the difficulty as a shortcoming of the current system, rather than the impracticality of the suggestion, and never suggest that the player lacks technical know-how (even though that is often true).

Good: *To support 100 billion players, we'll have to move to some server cluster solution, and we just don't have the resources to do that in a reasonable time.*

Bad: *That's not even physically possible; the algorithms involved have not even been discovered.*
* **If the idea has merit but goes in a different direction**, tell them so, and explain how the idea goes against your direction. Try to be diplomatic, and keep in mind that design is subjective, but at the same time be firm in stating that you have control over the artistic/design direction of the game.

Good: *I believe lasers will look out-of-place with the medieval theme of this game, and we want to be faithful in our rendition of a medieval society.*
* **If the idea has flaws or lacks merit**, tell them so, and explain its shortcomings. Keep in mind that for whatever reason (limitations of the medium, difficulty in expression, lack of forethought), the player may not be aware of the flaws, so kindly but clearly point them out. You'll find that players often come back with refinements, clarifications or just drop the idea, which are all much better outcomes. Remember that with a lot of ideas, players are dying to get a whiteboard and explain their idea face-to-face, but instead have to resort to a crappy text-only medium, so do not assume that just because the idea comes off as flawed that it is actually so. Also consider that a lot of great games started from ideas that don't seem brilliant at all, and it was execution that made them great.

Good: *Dishing out a 1-hit-KO spell may be fun, but I think it would be very annoying to be on the receiving side.*
* **If you just don't find the idea good**, tell them so, but be careful how you tell them, and always suggest alternatives. This type of response is the hardest to give, so see if you can treat it as one of the previous cases instead - eliminate the technical and obvious flaws first. In forming your response, assume that the idea is actually good, and ask why did the idea come off as bad? Does the player need to sell it a bit more? Would examples, sketches, or demos help? Would getting more community support help? Always give them a realistic out - what would convince you, and how could they go about it? Try to see the idea in the best possible light, don't be defensive, and look for that hidden kernel of wisdom that is often there.

Good: *I don't think a half-elf-dragon-devil-samurai-ninja would look good and be balanced, could you please show me what it might look like, what its stats and abilities might be?*

Another way of looking at the problem is: these people may not be game development experts, but they could very well be experts in other areas that you are not - they could be doctors or lawyers. I'm sure you've said things that your doctor/lawyer would consider hare-brained, so ask yourself how you would like them to respond in that situation.
> 77 votes

# Answer
Tell people things like, "Hey that's an interesting idea. Thanks for the feedback!" That is making no promises nor making any direct feedback on the quality (or lack of) for the suggestion. Of course if you really really think it's a good suggestion, do say so. The catch is, don't clearly gush over the good ones and say, "yea thanks for that (NOT!)" for the ones you don't like. People can subtly sense your mood there whether you think so or not.

Don't say "I'll look into it" (unless you really are going to), nor say things like "What a dumb idea!"

The key here is to acknowledge to the person posting that you saw their feedback, and that you appreciate their involvement in the community. That's what they really want to hear and see.

Think about how it is on this site. Suppose you post a question or an answer. It's very human to be curious how the community will respond to it. Get an upvote? That's great! Get NO votes? That's kind of a bummer because maybe nobody read it, maybe nobody cared. Get a down vote, and it's hard not to feel a bit rejected.

Also, be open minded. Good suggestions will come up in your forums. And with every suggestion, try to look beyond the specific idea and see if you can identify the root motivation to the suggestion. Maybe the aiming system in your shooter is actually not easy to use, and someone makes a suggestion about a change. It may be their idea really stinks, but their root issue with the aiming system is legitimate - and that's what you need to know. So you could turn that into a, "Hey thanks for your idea for a change to the aiming system" type response.

Lastly, this is why you need a person familiar with community management to handle such things. If you don't have such a person or aren't the person to do this, consider just not having an online forum. They can be more work than you think.
> 38 votes

# Answer
Telling your community that their ideas are bad is a sure way to make your community hate you. The most important point here is to **make your community feel like they are contributing something to the game** even if their ideas are not remotely feasible. Good responses would most certainly be *"Thanks for the feedback!"* or *"We'll take it on board!"*. However I feel that those response are just standard responses that make you think "blah, blah, blah".

The best kind of response to this is something that...

1. Encourages further input
2. Ensures player that their suggestion will be considered
3. Provides a positive human response

All of these points will go far in building your community. Best example I can think of would be *"That's a really interesting idea - jetpacks could add a whole new mechanic to the game! We'll present it to the rest of the team."*

That being said, you should jump on good suggestions, and **use them as examples**. That way, you can turn it to your advantage and report back to the community - saying *"PlayerX suggested this improvement - and we thought it was such a great idea that we'd add it in! Take a look at this screenshot/video etc!"* That kind of feedback will do wonders for your popularity.
> 12 votes

# Answer
Actual real world community management:

**1. Idea is economically useless - serious investment vs low return. Or a direct subversion of revenue:**

You can never tell the user that their obvious improvement is totally correct but your design demand inconvenience so relief can be monetized.

For any other tech heavy stuff - employing a two step approach is preferable. At step one you let them know you are going to pass it on (flag your milestone, and keep track to come back later). At point two you say you've checked with dev team and they say it takes too much time for too little benefit. If you are well embedded in the work-flow you can often make these decisions yourself without asking coders or designers. If your dev team actually wants solid feedback - you put these in to well comprised lists so devs can actually take a look at them in an organized fashion.

The only thing you have to do is make sure your assessment is solid. If you ever reject a SIMPLE fix with this statement for any reason, there is going to be a massive surge in credibility, as someone technical can say something like "Get serious, fixing a minor html bug on that page takes 5 minutes of a 10 year old - here - I'll give you the code for free".

**2. Post is in unintelligible:** "Can you please describe what is it that you suggest EXACTLY and more clearly, because I'm confused."

**3. The idea is outside the goal:** "We have have considered this option, but for now it is now what we are looking to do" often its enough, if the honest reason why is acceptable give it. Otherwise you may better lie and say its possible to happen in long term future, but its very low on the priorities list.

**4. Idea is a luxury:** Something kind of cool, but is really an EXTRA BONUS not a NEED.

I usually maintain a list of these, where devs can handpick them when they want to. Again i say to users this is added to a list of low priority possible improvements.

**General:**

What you can and cannot say is heavily based on your general disposition and behavior.

The user-base I work with trusts me because I have indeed officially credited people for suggestions that were implemented. I also have taken to account circumstances and I have given very detailed explanations where they weren't necessary.

If the general perception of a/the community manager is that he is paying attention. It is very bankable in the long run. You can close cases/threads/posts/tweets with a set of 10 template answers - and even if you get questioned - the regulars in the user-base are going to verify your credibility and that what you are saying holds weight.

I view it more or less like a currency, you earn some when possible (by going out of your way to give more than the average support hypocritical bland answer) - and then you spend some when brushing off people you don't want to deal with without having to explain yourself.

If you've always copy pasted templates people view you more or less as a drone trying to get rid of as many requests as possible - without ever trying to communicate with them on a person to person basis. You are never going to have a positive environment where people feel their expression is just wasted in a forum/whatever platform. And they don't need to know you. They can just list a few threads and see the proof that you indeed have taken another-random someone (just like them) and have bothered to engage with them thoroughly. Why didn't you enter extensive dialog with me? - Maybe you were busy or indeed my post has lees merit than I think. Its obvious though that you CAN engage and that you HAVE done so in the environment.

Following the all famous corporate official like behavior pattern is a slap in the face of anyone who is emotional or passionate about a thing. And its usually these people that bother diverting time from their lives to explain to you why and how you have to improve your product that you are profiting from.

And despite what many people think, being human even miss-spelled and with grammar errors HELPS. Better have a genuine communication with a few misspells, than a packet of honed in "perfect" cold-read copy-pastes. If your support environment is limited and you re-use templates, it comes a time people assume an AI is handling basic communication. And whats the point if having people to handle people if they are going to be perceived as machines.

Obviously none of this is possible if management never allows you to be a person on-line.

This mistake is made very often with games. Players come to have fun in games. When your rep handles them like a pro lawyer explains the 367 excerpt of a company merger contract to a committee. You instantly trigger the thought "Oh damn it, again its another suit that wants to drain my money and only has a forum/etc because - everybody else has or its traditional - they don't care"...

It is regular to run a company on that old tradition. But this is the lowest benefit factor you gain from a community.

There is no conclusive study on the greater benefit of community management. However a successfully positive community is easily felt anywhere it exists. And any fool in business can tell you a satisfied customer hold great referral value that is often immeasurable. Thats why some smarter companies out there handle support publicly. They want to world to know how their employees handle their other customers - because they've made an effort in there.

**P.S.** Here is a recent support that was done on me. The guy said "We are just not able to do as you ask." and finished. Maybe a little bit of polite cold read closure was inserted afterwords.

I vote this the top support person for 2015. For the year I've written many support tickets to many companies about many products. This was the first person for an entire year to resolve my case in 1 short answer, without stonewalling me, letting me expire or slapping me with 15 lines of cold read text that has almost zero relevance to what my request is about, and adds and absolute zero of value to the matter at hand.

For you see even being turned down becomes a joy in today's bland community management world. Because being told you are not going to have something right then and there is much better than waiting for it two months as some \_INSERT\_CURSE\_WORD\_ person said they are going to get back to you but they never intended to, much less did. So not only you didn't receive what you asked for - you were also hung out to dry, because some \_INSERT\_CURSE\_WORD\_ person in the company thinks community management has to be so polite at all times that they even have to change the topic instead of the apocalypse which would ensue if you they ever even slightly said anything that might disagree with the user.
> 5 votes

# Answer
You shouldn't be handling feedback by yourself. Eventually, you'll spend all your time responding to it, and nobody wants that.

Direct feedback to **forums**, a trustworthy **assistant-designer**, or a **ticketing system**. Aside from the assistant option, this allows you to ignore ideas outright and comes across as impersonal.

I'm still a fan of the forums system because it allows your fan base to discuss the idea. The first few times, tell them why it doesn't fit in with the system. Once your fans understand the direction of the game, they'll repeat your answer to future similar suggestions.

If it is a good idea, then simply acknowledge and respond to it.
> 4 votes

# Answer
I like the idea of having a list of suggestions from the users but first the other users of the forum had to approve it by voting. Then, since the list would be small because a fairly large (your choice) amount of users would have to like it, you could read the suggestions yourself or have someone you trust do it easily.

These suggestions would be good or at least not crazy so you wouldn't have to say to anybody that their ideas suck. From here, you can just tell them if it's hard to do, if it isn't fit for the game or ask for more details.
> 3 votes

# Answer
In forums where I participate developers rarely address fan suggestions. You are amazing to even consider addressing them. If they are completely flawed then it is probably best to let other fans engage with them (somebody is bound to have a different opinion). Unless you are in the unlikely situation where everybody agrees with an idea except you (in which case perhaps you should give it a second thought), it's probably safe to just ignore it.
> 3 votes

---
Tags: game-design, community-management
---


# Question
Title: Switching from Arcade to P2 physics in Phaser
I just started using phaser for testing purposes. I've followed the tutorial from the phaser website ("making-your-first-phaser-game") everything is clear, so far no problems.

But since I'm making a pool game I need rotation on collision so I've switched to P2 for physics. Suddenly everything moves and collides!

Here is the live code: http://199.26.84.223/

I have 2 groups:

1. sides (sides of table)
2. balls

**Point 1:** I want sides to be immovable so I've added:

```
side.body.immovable = true;

```

to each object just as with Arcade physics, but it doesn't work. How can I make objects immovable in P2?

```
game.physics.startSystem(Phaser.Physics.P2JS);

sides = game.add.physicsGroup(Phaser.Physics.P2JS);
side = sides.create(0,0 , 'sideA');
side.body.immovable = true;

```

**Point 2:** I don't want my player to collide with red balls only with the white ball.

So in arcade we had to define each collision otherwise they wouldn't collide:

```
game.physics.arcade.collide(player , wball);

```

But here there is no defining everything collides with everything.

How can I make exception for collisions, so my player wouldn't collide with anything other then the white ball (Wball)?

**Point 3:** What happend to overlap? Or collide callback functions? I need to add some holes to my table and make the balls disapearr on collide or overlap. In arcade I had it like this:

```
game.physics.arcade.overlap( balls , holes ,  killBall  , null, this);
function killBall  ( b , h  ){ b.kill() ; }

```

# Answer
Arcade physics, unlike P2 and most other physics engines, is a very simple and simplistic system. The former will use a lot of lay terms whereas P2 will use terms plucked straight from a physics text book. Switching between the two is not trivial; you'll need to relearn a lot of stuff. I highly recommend the P2 examples page to get a grasp of what P2's features are and how to use them.

To answer your questions:

1. **To make bodies immovable**

`sprite.body.immovable` is an arcade physics thing. For P2 it's `sprite.body.kinematic`. "Kinematic" in P2 means, generate collision events, but don't be affected by physics itself like gravity and collisions.
2. **To selectively collide**

P2 handles this problem using collision groups. Basically if you want one group to collide with another, but none of the bodies in the same group to collide with each other, you put them in separate groups and specify that the two groups collide with each other. Pay close attention to the example and documentation because it's not trivial to set up.
3. **To handle collision events**

Collision event callbacks are still there but they are set up differently; see the example given in the last part. Instead of explicitly requesting a collide/overlap, P2 will be doing all its stuff all the time, and if you gave it a callback during setup it will call it as collisions occur.

As for overlap, P2 doesn't support it directly, but there is an equivalent solution known as the "Postbroadphase Callback". Basically this is a callback where P2 collects all potential collisions and then asks you - via the callback - whether to allow those collisions to resolve or be ignored. You return false in the callback to tell P2 not to perform collision resolution, but the fact that the callback was called in the first place means that those two bodies have overlapped, so this is where you put your overlap handling code.

Good luck with P2, take it a step at a time because it (like most physics engines) have a bit of a learning curve.
> 5 votes

---
Tags: 2d, physics, html5, phaser
---


# Question
Title: Diverse loading-screen tips and who does that?
Smaller games and projects have been seen to add jokes and tips that are not directly game related and in any form advice to their loading screens. For some reason I can't think of a tripple A title? Anyone else?

Some people around the industry think its bad taste... I've seen arguments where companies have senseless aggression as core gameplay but get iffy about throwing harmless jokes into splash screens. It was really weird.

Can you name a big game that does it?

# Answer
Anything recent by Bethesda:

Fallout 3 Fallout New Vegas,

Skyrim, Dishonored.
> 0 votes

# Answer
Borderlands 2 does this.

> The Gunzerker skill "Sexual Tyrannosaurus" regenerates health upon taking damage. But hopefully you saw the skill name and were just like, "I want that."
>
> Shields are like friends: the best ones come with additional benefits.

The game is humorous in itself, which is probably a major factor.
> 0 votes

---
Tags: game-design
---


title: Unity Canvas blocking objects in Editor

text:
# Question
Title: Unity Canvas blocking objects in Editor
I think I am missing something really basic here..., I'm creating a 2D game in unity, and the UI Canvas (with the setting "Screen Space - Overlay") is blocking exactly a quarter of my workspace. I can not select any objects on the top right part of the screen.

Is there any fix to this?, or do I have to move the camera down half of the screen?

Thanks

# Answer
Click the canvas and move it back or forwards along the Z axis.
> 1 votes

# Answer
**`Layers`** *(top-right of editor)* \> **`UI`** \> **`Lock Layer for Picking`** *(the little padlock)*

This will allow any clicks to go through the canvas and reach whatever's behind!
> 5 votes

---
Tags: unity, gui
---


# Question
Title: Dynamic Events in an Entity Component System
My game makes extensive use of libGDX's Entity Component System Ashley, and my game world (including all levels and areas) is created with Tiled.

In Tiled, I have an object layer where all of my entities are added (as rectangles, although the shape does not matter). Each object properties links to a YAML file containing serialized components which are deserialized when the Entity is added. This system works well, and I want to use a similar method for handling all types of map events, although I don't know of a way to do this.

I want to create dynamic events that:

1. Have one or more causes
2. Have one or more effects for each cause

Where a cause is something such as a player interacting with a switch, and an effect is a door opening. One or more cause could be, for example, that the player must have a specific item and interact with a switch.

# Answer
What I would do is represent the event triggers as entities in my game. This way you can add event triggers on your maps with tiled as you would do for regular entities.

Let's take the example of a really simple event opening a door when the player walk on the trigger (collides with the trigger entity).

So at this point you should have a collision system notifying when two entities are colliding. Once you know a collision occurred between your player entity (or whatever) and the event trigger entity. You can fire the event linked to this trigger so it can be processed by the relevant systems.

So my event trigger would be composed of two components :

* Collision Component
* Event component : holds the event that will be fired

The event by itself would be defined by an enum defining what kind of event it is (OpenDoor, DestroyEntity or whatever) and something like an hash containing more informations about the event, like the id(s) of the entity(ies) affected by the event.

So, finally, to 'fire' the event you will need a messaging system allowing messages to be dispatched between systems in your game. For my own game I use a 'messaging system'. This system holds a list of fired messages. When a system is interested by a particular message, it queries the list for this particular message, if the message is present, it then processes and decides or not to consume it (removes it from the list). It works alright and this way you don't break the entity component systems pattern by keeping the logic in the systems and don't have your systems inherit from kind of listener interfaces.

I use messaging for various things, for example, my collision system uses it to notify the game when a collision occurred. A message is fired containing data about the collision, which entities are colliding. So i could have a damage system that query for collisions messages and act accordingly.

To fire an event I would just represent it as a message (an event message holding the event) and fire it as a normal message.

This system can be highly improved I think but it works and does not break the pattern you are trying to follow.
> 1 votes

---
Tags: libgdx, entity-system, events, entity-component
---


# Question
Title: Find two points in a point cloud with the maximum distance?
What is the least computationally complex way to find two points such that the distance between them is greater or equal to any other pair.

Remember hearing something about how you could find such a pair by randomly picking a point `r`, finding the point furthest away `fa` and then finding the most distant point from it, `md`. The diameter is then the distance between `fa` and `md` (i.e `norm(fa - md)`). Is this correct? Can you prove or disprove it? What is the correct way if this is incorrect?

# Answer
It wont be correct. If you take 4 points; 3 of which lie on a circle and the 4th is in the center. The diameter of this set is the distance of 2 points on the circle. Your algorithm may choose the other point which won't have a distance like that.

The proven correct way is to create the convex hull and use the Rotating Calipers method for finding the largest distance.

This ends up being `O(n log n + k)` time complexity. `O(n log n)` for creating the convex hull and `O(k)` for iterating over then entire hull to find the points the furthest apart.
> 5 votes

# Answer
There is already an answer for:

> What is the correct way if this is incorrect?

You should only ask one question at a time. I'll cover:

> Is this correct? Can you prove or disprove it?

Also, it was questioned in comments whether the OP algorithm might be "good enough" even if it isn't the diameter from a curve. Bottom line: you aren't guaranteed to get the two points that are furthest from each other.

Consider the point cloud with exactly four co-planar points, `{ A, B, C, D }`. `AB = AC = r`, `BAC = 70` degrees, `ABC = ACB = 55` degrees, and `D`is halfway along `BC`.

Like so:

```
          A

    r           r

B         D         C

```

Bottom line (TLDR;) using OP algorithm: if `D` is the random point, the next point is `A`, then either `B` (or `C`: same distance). OP algorithm yields `AB` or `AC`. However, the longest distance is `BC`. The algorithm fails in *at least* this case.

Math Proof:

* From random point `D` we compare `AD` and `BD`. `AD = r*sin(55)` and `BD = DC = r*cos(55)`. Since `cos(55) < sin(55)`, `AD > BD` and point 2 is `A`.
* From `A` we consider `AD` and `AC`. `AC = r` and `r > r*sin(55)`, so `AC > AD` and the final point is `C` (or `B`: same distance).
* Final OP diameter is `AC = r`.

However, `BC = 2*r*cos(55)` which means `BC > r`. The furthest two points from each other are `B` and `C`, **not** `A` and `C`.
> 5 votes

# Answer
Ok..

Let's look at the following shape:

```
   B
  / \
 A   C
  \ /
   D

```

Now, lets say, the distance `BD` is 5. The distance `AC` is 4. If you pick `A`, you will get `C` at a distance of 4. From `C` you will get `A` again. The distance `AD` = `CD` = `CB` = `AB` is from Pythagoras:

```
sqrt((4/2)^2 + (5/2)^2) = ~3.2

```

So yeah, you can miss the mark with a diamond shape.
> 0 votes

---
Tags: mathematics, algorithm, point-cloud
---


title: Convert MathAtan2 angle to degrees

text:
# Question
Title: Convert MathAtan2 angle to degrees
I use an angle to set the velocity (or direction if you prefer) of my sprite, however, I want the sprite to be heading in the same angle as I'm moving, rotating according to that angle.

How I set angle and velocity:

```
angle = (float)Math.atan2(0 - pos.y, 220 - pos.x); //using bottom mid of screen as destination for testing

//in update
pos.x += 200 * Math.cos(angle) * delta;
pos.y += 200 * Math.sin(angle) * delta;
sprite.setPosition(pos.x, pos.y);

//in render
sprite.draw(batch);

```

is there any way to use this value in LibGdx's "sprite.rotate()" function? I can't do "sprite.rotate(angle)". Can I do this some other way? Can I convert my angle-value somehow to degrees? I'm stuck.

I tried

```
sprite.rotate((float)Math.toDegrees(angle));

```

but that gave rly weird results, the following image is moving **down** and to the **right**

# Answer
`rotate` takes I believe a `relative` rotation while angle is an `absolute` rotation. In other words take the difference between the current angle and the wanted angle and pass that to rotate.

Or pass just the angle into `setRotation`.
> 1 votes

---
Tags: java, libgdx, mathematics
---


title: LibGDX drawing portion of tmx map

text:
# Question
Title: LibGDX drawing portion of tmx map
I am trying to make a tile based game in LibGDX and I have run into some problem. In earlier versions of LibGDX you were able to draw a certain section of a .tmx map instead of a whole and even a section of a layer. Even though , in the nightly builds I cannot find anything about this methods the only thing I have found was drawing of a whole map or one of its layers.

Ideally I would like to draw portion of a map something like draw nao from coords (5,5) to (25,25) . Meaning only the square 20x20 tiles starting from tile in the 5th row/column at position no. 5.

Is it even doable in the newer builds ?

# Answer
> 0 votes
Yes, using a `FrameBuffer`, a `TextureRegion` and a `OrthogonalCamera` You set the camera so that the bottom left of the "screen" (this is to the buffer, not the actual screen) is at the bottom left of the bottom left tile you want. Then you draw to a `FrameBuffer` and then extract the region you need.

This implementation will only work if the amount you're trying to pull off will fit on the screen you actually have.

Try making the `FrameBuffer` width and height bigger if you need a bigger region (I haven't tested this)

In init

```
//Set up the framebuffer (NOTE: RGBA8888 might not work on some divices)
fb = new FrameBuffer(Pixmap.Format.RGBA8888, Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), false);
//Attach a texture so you can draw a portion of the frame buffer
mapRegion = new TextureRegion(fb.getColorBufferTexture());

```

In the render thread:

```
cam.position.set(TILE_W * TILE_X, TILE_H * TILE_Y,0);
cam.update(); batch.setProjectionMatrix(cam.combined);
//to the buffer
fb.begin();
batch.begin();
renderTileLayer(tiledMapTileLayer);
batch.end();
fb.end();.

//Extract the portion from the buffer
mapRegion.setRegion(0, 0, TILE_W * NUM_TILES_ACROSS, TILE_H * NUM_TILES_VERTICALLY);

//to screen
cam.position.set(/*where the camera is supposed to be*/);
cam.update(); batch.setProjectionMatrix(cam.combined);
batch.begin();
//Draw the region you extracted from the tilemap to the screen
batch.draw(mapRegion, x, y + mapRegion.getRegionHeight(),
mapRegion.getRegionWidth(), -mapRegion.getRegionHeight());//Needs to be flipped rightside u
//Draw more stuff
batch.end();

```

To match your example you would have

```
TILE_X = 5;
Tile_Y = 5;
TILE_W = whatever your size is per tile (often 16 or 32 px);
TILE_H = same sort of thing as TILE_W;
NUM_TILES_ACROSS = 20;
NUM_TILES_VERTICALLY = 20;

```

---
Tags: rendering, libgdx, tiles
---


# Question
Title: Tangent space - Lengyel vs ShaderX5 - difference
I have been studiing tangent space calculations and came across two solutions

E. Lengyel - http://www.terathon.com/code/tangent.html

ShaderX5 solution - (solution is also desribed here http://www.thetenthplanet.de/archives/1180)

What is the difference between tangent computed one or another way? Lengyel solution seems "easier" but I am no quite sure of its orthogonality to the normal vector of the tangent plane.

# Answer
Lengyel's publication describes the standard method, where every vertex has a position and normal, as well as a tangent and bitangent vector. If the tangent and bitangent are not stored in the mesh, he describes how to calculate them using the normal and the uv texture coordinates.

The 2nd article describes how to calculate the tangent and bitangent in the shader. The advantage is that you do not need to send the tangents and bitangents to the vertex shader, reducing the required bandwidth. One of the disadvantages is that your fragment (pixel) shader now must work harder. It also requires the use of derivative functions (like ddx or dFdx), which are not exactly cheap.

There's even another approach, pioneered by Morten Mikkelsen, that does away with the normal map and simply uses a height map instead. This puts even more load on the fragment (pixel) shader, but you no longer need a normal map and it has advantages when doing procedural generation of textures and meshes. See here for more information.

I recently tried all 3 methods and found the 1st and 3rd option to be the best. Mikkelsen's solution is slightly slower on my machine, and requires a floating point texture for the height map, especially for close-ups. But it looked subjectively better than the 1st solution.
> 2 votes

---
Tags: mathematics, spaces
---


# Question
Title: Resource streaming with job threading system
I am currently researching resource streaming for my current game engine. To add a bit of context, I am doing a contiguous world for a Baulder's Gate style CRPG. So while the camera is usually looking downwards at an angle... it can be rotated and lifted up and down to compensate for mountains.

That means for vistas, it needs to be reasonably decent. At least with an added advantage that there will probably be very few unique assets that will be loaded in every terrain cell. (currently each cell is about 60m).

Most of the research I found turns up to have a separate thread for loading in assets. I can see how that works, as obviously holding such a thing on the main thread could introduce stalls.

But... currently my architecture is the main thread which has rendering and gamelogic. Then the rest are just worker threads for a job system.

I planned on moving the Rendering system off of the main thread, which means that on a common consumer PC (4 threads) I have two fixed threads... and two worker threads.

Moving a loader to it's own thread would basically reduce performance on some update cycles to a single threaded update.

My main thread is controlled by lua, and low level systems are in C++. Lua dispatches low level jobs only (Physics first, Animation updates, Transform updates, dispatch to renderer), and waits for them to finish before continuing to the next job dispatch, as certain data requires information from the previous component updates.

Annd... one recommendation I ran across, (because I am only targeting PC for now) was to keep data about each cell on the memory. Such as transforms, skeleton handles, material handles, etc.

So... I have a few questions. How well would a resource streamer work if each loading call was dispatch to a job as it is needed? From my research, I found multiple people stating that multiple async loading could slow the disk drive down.

What would be a few effective strategies for resource streaming? I know that it's better to have everything in one file, like a zip instead of scattered about folders. But I could never find any straight answers. One google search said to cut the file up into equally sized bits (which sounds logically stupid in my opinion.) another was priority loading, which sounds pretty reasonable. I understand this question is pretty vague, but finding answers in general in a world dominated by pre-built engines is already difficult enough.

# Answer
I can give you only general information, based on my own experience. I have worked on AAA game engine development, but as a graphics programmer I was never involved with loading assets efficiently. We already had a system for that.

Yes, streaming assets in from disk should happen on a separate thread (or a few) and never on the same thread as your game logic or rendering. Disk operations are very slow compared to crunching data and loading things from memory.

Having more than one thread for asset loading will speeds things up (especially if you're loading assets from an SSD), but having too many of them may cause the drive to jump from sector to sector, slowing things down. Test, test, test on a number of different setups to determine the right number of loader threads.

Writing your own threaded asset loader does not have to be hard. Create a pool of a few threads, each running infinitely (until application quits). Use a concurrent container for communication between the main thread and the worker threads: your main thread pushes a file path onto the container and notifies the workers using a condition variable. One of the workers pops the file path and loads the asset. If possible (shared contexts) it uploads the asset to the GPU as well, but be careful not to stall the GPU. It then notifies the main thread that the asset is available and sleeps until it needs to load the next asset.

See for example: https://juanchopanzacpp.wordpress.com/2013/02/26/concurrent-queue-c11/

To speed up loading, use binary file formats (so you don't have to parse text files like OBJ or JSON). Compress your data. Load a few big chunks of data instead of lots of small chunks.

EDIT: should you use ZIP files for your data? It depends: loading compressed data is usually faster, provided that decompression is fast. If you have a C++ library that can do the decompression, using ZIP files is a good start. Note that it will not protect your data from prying eyes, as everybody can decompress ZIPs. If possible, come up with your own data file format.

A good source of information is the Urho3D engine. See e.g. their PackageFile class.
> 5 votes

---
Tags: c++, architecture, multithreading, resource-management
---


# Question
Title: OnMouseOver() alternative for iPhone (Unity3D/Unity2D)
I am currently developing a game that uses the OnMouseOver() function of a MonoBehaviour object.

Is there a true alternative for iPhone? Would I be better of coding my own?

Thanks in advance

# Answer
You can use the new TouchInputModule on iOS and other mobile devices.

You just need a collider on the object you want to touch or hover, EventSystem AND TouchInputModule in the scene, and then it basically works this way:

```
public class TouchInputExample : MonoBehaviour, IPointerDownHandler, IPointerEnterHandler, IPointerExitHandler
{
    public void OnPointerDown(EventSystems.PointerEventData eventData)
    {
        Debug.log("Touched");
    }
    public void OnPointerEnter(EventSystems.PointerEventData eventData)
    {
        Debug.log("Hover start");
    }
    public void OnPointerExit(EventSystems.PointerEventData eventData)
    {
        Debug.log("Hover stop");
    }
}

```

As mentioned, you can not get a hover status on a touch screen. It always either touches or not.
> 1 votes

---
Tags: unity, iphone, touch
---


# Question
Title: Buttons implementation with regards to a basic Game Loop
As the title states I am creating a game with SFML being the only library used.

I am entirely unsure how to go about this.

I want the buttons to be activated by simple mouse clicks (when the mouse is within the defined area of the button).

My question however is how do I do this with regards to a standard Game Loop, with the following methods HandleInput(), Update() and Draw().

* Should I implement it so that HandleInput() calls a function (on left mouse click) which stores the mouse coordinates and in Update() every button checks if it has been clicked on?
* Or should I (attempt to) implement Observer pattern?
* Or is there a method I haven't even covered?

I hope this question is relevant to GameDev I believe it is.

# Answer
> 1 votes
Modern GUI libraries often use some sort of callbacks (classical Observer pattern, or function objects in languages that support them).

From the way you ask your question, I assume you want to keep `HandleInput()` and `Update()` strictly separate, where the latter executes the logic associated with the button. You can achieve this by determining and storing which buttons were clicked in `HandleInput()`, and invoke the corresponding callbacks later in `Update()`. A map allows you to associate buttons (more precisely, their unique identifiers, e.g. an `int` or the text written on them) with callbacks.

In C++, an easy way is to use `std::function`. Your class could look as follows:

```
std::vector<int>                     pressedButtons;
std::map<int, std::function<void()>> callbackMap;

void HandleInput()
{
   sf::Event event;
   while (window.pollEvent(event))
   {
      if (event.type == sf::Event::MouseButtonPressed)
      {
         for (Button& b : buttons)
         {
            if (IsOnButton(b, event.mouseButton))
                pressedButtons.push_back(button.GetId());
         }
      }
   }
}

void Update()
{
   for (int id : pressedButtons)
   {
      auto itr = callbackMap.find(id);
      if (itr != callbackMap.end())
         (*itr)();
   }
   pressedButtons.clear();
}

void RegisterCallback(const Button& b, std::function<void()> f)
{
   callbackMap[b.GetId()] = std::move(f);
}

```

You may ask why I store a container and not a single button, as users are very unlikely to click more than one button per frame. That is partially true, but not for special cases like overlapping buttons. Furthermore, this approach can easily be applied to other scenarios, where a container makes sense.

Since you're using SFML, there are existing solutions on the Wiki or in the Thor library that will help you with this design. For example, Thor allows you to define "actions" that map arbitrary combinations of SFML events to your callbacks.

---
Tags: design-patterns, sfml
---


title: Pointers in C# Unity

text:
# Question
Title: Pointers in C# Unity
Hey I've just learned about pointers recently and am wondering how I can use them in c# (I just learned about them in c++) in unity. I do have some questions though.

1. Pointers use low level programming to find positions of different values on the computer so does that mean that you can just access a the value of a variable from any script?
2. If so how do I just call upon a location of a variable with just its location code?
3. Are there any discernible differences between pointers in C# and C++ that I should know?
4. How can I use pointers with the variable types in Unity (Vector3s, Transforms, GameObjects, etc...)?

There are so many more questions I probably should and would like to ask so if you have any additional info or sources.

# Answer
In general for C# and specifically for Unity I would advise against it... but if you really wanted to, or had good reason, you could.

In C# you would need to familiarize yourself with what is called unsafe code. Scared yet?

In Unity you would need to enable unsafe compilation mode so you will not be able to use the web player if you planned on that. You can read more here or here.

So basically C# was designed with a Garbage Collector as many scripting languages are. The general idea is to try and abstract the notion of memory management to simplify development. You can still end up with resource leaks if you don't nullify your objects. I'm honestly not a huge supporter of GCs and would prefer RAII methods instead, but this is the world we live in.

Most C++ developers would also, however, agree that you shouldn't use pointers directly anyway and should prefer to use an RAII designed type aka smart pointers. If you are in C land then likely pointers are second nature to you, but even then it helps to abstract them to some degree.

If you do use them in C# just be aware that there is a very real potential you could add security vulnerabilities or really nasty and hard to track down bugs. You will also need to keep in mind that you must be careful not to reference objects that can be moved by the GC. Note the use of the fixed statement here.

You can also use Pointers in Unity by writing a native plugin. This again will rule out webplayer builds, but the new HTML5 feature works based on emscripten so if you planned on using that you likely could if you are careful. Native plugins allow you to extend Unity on a per platform basis. I wrote a native plugin to communicate with some microcontrollers via a serial connection for example.

So to summarize you should definitely ask yourself why do I want to use pointers in C# in Unity. If you just want to do it for fun... Knock yourself out.

***Edit:*** I'm sorry if I had offended anyone as I know my thoughts on GC are not of the popular opinion right now.

If you really read my answer you will note that I do not call C# a scripting language. I compare it to "many scripting languages", however, in the context of Unity it is very much so used as a scripting language. It is somewhat of a DSL to Unity if you will. Often times you will see it even referred to as Unity Script in this context (this is mostly in reference to Unity's Javascript alternative to C#). If you put LLVM in your pipeline you can just compile it to native code for the platform directly... then what would you call it? So really I didn't want to split hairs here.

Many great references to software engineering are filled with opinion:

Effective C++, More Effective C++, C++ FAQ, Effective C#, Modern C++ Design, Design Patterns ... And countless others. I don't feel this makes the arguments any less credible if they are followed by thoughtful explanation.

I was not really all out saying ***"Don't use pointers ever!!"***. In fact I still use them naked on occasion. I said "in general" as in "prefer using safe code to unsafe code in C#". There are situations where it can be beneficial, and that is one of the really powerful features of C# to pick and choose your tools. C# even allows you to have transparency in the GC process to some degree, languages like Dart do not and can lead to resource leaks very easily. Sure if you are the sole developer of a small project it isn't likely a problem. If you are on a team of say 10+ with hundreds of thousands of lines of code then it can get tricky.

I simply wanted the reader to exercise caution when using naked pointers. It is akin to saying be very careful when working with mains electricity. I'm not saying don't be an electrician, just that if you make the wrong move and don't treat it with respect you are dead.

I do like the example given by Lasse in which performance may have dictated the need.
> 6 votes

# Answer
C# uses references to pass around objects that are not value-types. This means that everything is usually passed by reference. If you want to pass a value-type by reference you can use the ref keyword. The difference of a reference type and value-type is that depending on how large the value-type is, it usually requires more memory copied when it gets passed on to a function. A reference is just 32 bits or 64 bits, or 4 bytes or 8 bytes. You can get more performance out from your code in very tight loops if you use references instead of just copying all the data the value-typed variables contain, assuming they are larger than 4 or 8 bytes.

For example on Unity any MonoBehaviour (class) object is a reference type, and any Vector3 (struct) object is a Value-type.

There is also unsafe code blocks that will allow you to type code that lets you create and modify data unsafely. To use unsafe code you will have to set the compiler to allow unsafe code. Pointers can be used this way. By using unsafe code certain checks are not used that are there with safe code, which makes unsafe code harder to write error-free. There are very few places that can benefit from unsafe code on C#. On Unity unsafe code is not supported on all platforms. Usually using references instead of unsafe pointers are enough when working with Unity.

Here is an example (source) of using unsafe code pointers in C# with Unity:

```
public static class Rope
{
    // C# function declaration to match C++
    [DllImport(SlingshotImport.c_libName)]
    static unsafe extern void UpdateRopeParticlesUnsafe(
        Vector3* oldNew,
        Vector3* curr,
        int numParticles);

    // C# wrapper function for Unity C# script
    static void UpdateRopeParticles(
        Vector3[] oldNew,
        Vector3[] curr,
        int numParticles)
    {
        unsafe
        {
            fixed (Vector3* oldNewPtr = oldNew)
            fixed (Vector3* currPtr = curr)
            {
                UpdateRopeParticlesUnsafe(oldNewPtr, currPtr, numParticles);
            }
        }
    }
}

```
> 7 votes

---
Tags: unity, c#, c++, software-engineering
---


title: If statement with both AND and OR Java

text:
# Question
Title: If statement with both AND and OR Java
I have a (maybe) really basic question about if statements. If I do something like this:

```
if (i == 0 && j == 2 || i == 2 && j ==0) {
    ...
}

```

Then what will happen? Something like `if (i == 0 and j == 1) OR (i == 1 and j== 0)`?

# Answer
> 2 votes
You can look up what operator precedence in java is.
So yes, it *should* be evaluated as `if (i == 0 and j == 1) OR (i == 1 and j== 0)`.
Question is - do you really want to *rely* on that? I would personally use explicit parenthesis for two reasons:

1. Human readability: anyone(and you when you review your code after few months) see what will will happen without looking up the precedence
2. Compilers can go crazy and you never know on which compiler you will compile it later. Even though compilers *should* do something, it does not mean they *will* do it.

# Answer
> 0 votes
Think of AND as a multiplication and OR as an addition (which they kind of are). Same precedence rules apply.

But if you have a complicated expression, it's better to add parenthesis anyway -- the more readable, the better. And for extra readability, assign the conditions to variables with reasonable names (in your case, it could be `isFirstColumn` and `isFirstRow`)

---
Tags: java
---


# Question
Title: Optimal way to find point D that lays at the perpendicular line between point A and line BC
I am trying to write a script in C# to find the position of point D in 2D space in a specific scenario.

I know the (X,Y) position of point A, which never happens to be on the line that contains the line-segment BC. I also know that point D lies on the perpendicular line that passes through A and crosses BC at a point that we can call P. Also, I know the distance that D is from P. Se the image below:

Can anyone shed some line on which is the most optimal way of achieving that?

# Answer
Finding point P is easy if you use the dot-product. In pseudo-code:

```
vec2  BC = C - B
vec2  BA = A - B
vec2  nBC = normalize( BC )
float dBP = dot( BA, nBC )
vec2  P = B + dBP * nBC

vec2  D = P + dist * normalize( A - P )

```
> 2 votes

# Answer
First, you need to find point P, it is the closest point on line BC. Knowing where P is, you can construct line AP. Going from that, finding point D on line AP is trivial (`P + dirAP * dist`).
> 1 votes

---
Tags: unity, c#, geometry, geolocation
---


# Question
Title: How do I detect if two sprites are being touched at the same time?
How do I detect if two sprites are being touched at the same time?

---

I was able to detect one sprite, but not if another sprite is being touched by the second pointer.

```
if(spr.getBoundingRectangles.contain(x,y))
{
    //do this
}

```

Then, I created two `Vector3` variables for the pointer coordinates, before iterating to each pointer.

```
for(int i = 0; i < Constants.MAX_POINTERS; i++)
{
    if(Gdx.input.isTouched(i))
    {
        xy.set(Gdx.input.getX(i), Gdx.input.getY(i), 0);
        xy1.set(Gdx.input.getX(i), Gdx.input.getY(i), 0);
        WorldRenderer.camera.unproject(xy);
        WorldRenderer.camera.unproject(xy1);

        if(Spr.getBoundingRectangle().contains(xy.x, xy.y) &&
            Spr1.getBoundingRectangle().contains(xy.x, xy.y))
        {
            score += 1;
        }
    }
}

```

What happens is that `xy` and `xy1` are always the same, so when I touch the screen with the second pointer, they will just both switch to the new coordinates instead of `xy` and `xy1` having different `x` and `y` values.

# Answer
> 1 votes
Assuming the bounds of your sprites are rectangular:

* if your sprites don't rotate, you can detect if they overlap by direct comparison of their respective top, bottom, left and right bounding box coordinates. This assumes the bounding box is in world coordinates.
* if the bounding box is not in world coordinates, or your sprites will rotate and scale, you should transform the bounding box using the sprite's transform (model) matrix and do direct comparison again. If your game framework does not provide functions to transform the bounds, you can find sample code here.
* to figure out if the mouse pointer is inside the bounding box, especially when a sprite is rotated or scaled, the easiest way is to convert the pointer coordinate from window to world coordinates using the unproject function (once every time the mouse moves), then multiply the world coordinate by the inverse of the sprite's transform (model) matrix to find the local coordinate. You can then use the bounding box's "contain" function to test if it's inside.

---
Tags: java, libgdx, touch, multitouch
---


title: How do I properly load maps?

text:
# Question
Title: How do I properly load maps?
I'm trying to load my map properly, but it takes some time (after the games has been started) to be how it should. Am I doing something wrong? Why is this happening?

AndroidStudio:

Tiled (map editor):

```
public class GameScreen extends Screen{
   private TmxMapLoader maploader;
   private TiledMap map;
   private OrthogonalTiledMapRenderer renderer;

   public GameScreen(Game game){
      maploader = new TmxMapLoader();
      map = maploader.load("level1.tmx");
      renderer = new OrthogonalTiledMapRenderer(map, 1);

```

# Answer
This is a common problem caused by using floating point numbers for your camera movement. Occasionally, you will see the spaces between tiles. There are two ways you can counteract this:

1. Round your camera position up to whole integers. This will make camera transitions look less smooth however.
2. Give each tile in your tileset a padding of 1px on each side, and in Tiled, when you add a new Tileset, set the Margin to 1px and Spacing to 2px.

Logically, you would expect each tile to line up correctly without the need to do this. I am unsure if this is a problem with the way libGDX handles TiledMap rendering or not.
> 2 votes

# Answer
I face this problem often. That annoying lines are there because when you import the tileset in Tiled you're selecting a wrong tile size. For example, you're saying Tiled that your tiles are 33x32 (when they are 32x32), or you've not adjusted correctly the margins... Check out your "import" tileset configuration to ensure it fits your image.

Also, make sure the tile size of your imported tileset is the same as the map tilesize.
> 1 votes

---
Tags: libgdx, tilemap, tiled
---


title: Interpolation using cubic Bezier curves

text:
# Question
Title: Interpolation using cubic Bezier curves
I am trying to create an interpolate function for an animation library to achieve a tweening effect between frames.

I want this to work with Bezier curves. I have created a jsFiddle (here) of my progress so far.

I am trying to create a linear tween using this bezier definition:

```
{
    p0: new Vector(0,0), //Start point
    p1: new Vector(0,0), //Control point 1
    p2: new Vector(1,1), //Control point 2
    p3: new Vector(1,1)  //End point
}

```

I have implemented the interpolation function from this tutorial.

```
var u = 1 - t;
var tt = t*t;
var uu = u*u;
var uuu = uu * u;
var ttt = tt * t;

var p = p0.multiply(uuu);
p = p.add(p1.multiply(3 * uu * t));
p = p.add(p2.multiply(3 * u * tt));
p = p.add(p3.multiply(ttt));

```

The problem I am having is that when I run the function, the animation does not appear to be linear, but rather like 'ease-in-out'.

Ideally I would like the linear animation to work the same as this CSS transition.

Can anybody see why it is not animating in a linear fashion?

# Answer
> 6 votes
After playing with this function more. I realise that the bezier control points are acting similar to magnets.

If I spread the control points so that they are positioned along a straight line with equal distance between, then the animation works as expected

```
{
    p0: new Vector(0,0), //Start point
    p1: new Vector(.333,.333), //Control point 1
    p2: new Vector(.666,.666), //Control point 2
    p3: new Vector(1,1)  //End point
}

```

# Answer
> 5 votes
I usually solve this using Catmull-Rom splines. Instead of using control points, you simply specify the two points between which you'd like to interpolate, as well as a "previous" point and a "next" point. If the 4 points all lie on the same line and are evenly spaced, the interpolation will be linear.

In the image above, there are four points p0, p1, p2 and p3. The following line of C++ code will interpolate between p1 and p2, where t is in the range \[0...1\]:

```
return p1 + 0.5*t*(p2-p0 + t*(2*p0-5*p1+4*p2-p3 + t*(3*(p1-p2)+p3-p0)));

```

You can interpolate any kind of value type, as long as the type supports addition and multiplication by a scalar.

If the values do not lie on a line, or are not spaced evenly, the catmull-rom interpolation will generate a smooth curve. Interpolation will be non-linear:

If there is no "previous" or "next" point (e.g. at the start or end of a series of curve segments), use the following equations:

```
p0 = 2 * p1 - p2;
p3 = 2 * p2 - p1;

```

# Answer
> 2 votes
Bezier curves are inherently for making smooth curves. Linear interpolation is simpler. To linearly interpolate two points, you can simply apply the following formula for time t in \[0,1\]:

`interpolatedPoint = startPoint * (1 - t) + endPoint * t`

When t=0, the interpolatedPoint is exactly equal to the startPoint. Similarly, when t=1, the interpolatedPoint is exactly equal to the endPoint. When t is in between 0 and 1, it is somewhere on the line between the two points.

I forked and modified your jsfiddle to clarify: http://jsfiddle.net/kevinAlbs/3em6br3b/1/

# Answer
> 2 votes
Why are you using bezier curves to do a linear interpolation? You could just use a linear interpolation to do linear interpolation and not use curves at all.

If the reason is that you want to have a more general purpose curve based interpolation system and you are trying to get it to do a linear interpolation for a specific usage case, there is a way.

Basically, the control points need to be points on a line. For instance the control points 0, 0.333, 0.666, 1.0 would give you a linear interpolation between 0 and 1, when using a cubic bezier curve to do it.

Again though, if you want linear interpolation, there is no reason to use a curve.

---
Tags: javascript, animation, interpolation, tweening, easing
---


# Question
Title: How to find if an object is facing another object given position and direction as separate vectors
I found a very helpful post about exactly what I need here. It uses dot products to which is what I'm specifically looking for.

It talks about players facing monsters basically. They give a helpful picture here,

My question though, is what if you have a function with 3 arguments: the position of object 1, the position of object 2, and the direction object 1 is facing given as a unit vector. So the picture would look as so:

How would you find whether A is facing B?

# Answer
> 3 votes
It depends on exactly what you mean by "A is facing B", but you can use the same approach mentioned in the link you give. The other vector to examine (in addition to the direction `A` is facing) is the one connecting and pointing from `A` to `B` (calculated by `B-A`).

Your code would be something like.

```
facing = dotProduct(normalize(B-A), normalize(directionFacingOfA))

```

Which will give you the cosine of the angle between where `A` is facing, and the vector where `A` faces `B`. Pretty easy. Three possibilities:

1. If `A` faces `B` almost perfectly (angle close to 0), `facing` will be close to 1 (`cos(0)`).
2. If `A` isn't facing *away* from `B`, `facing` will be between 0 and 1. It is up to you to decide if this is "close enough".
3. If `A` **is** facing away from `B`, `facing` will be negative.

This approach works for either 2D or 3D.

---
Tags: mathematics, software-engineering, vector
---