# Question
Title: How add fog with pixel shader (HLSL) XNA?
I started to make a small game in XNA . And recently i tried to add a "fog" on "pixel shader HLSL" with the class Effect from XNA . I search online about some tutorial and found many sample. But nothing want work on my game :-( . Before i already add a "fog" effect in my game and everything work, because i used the class "BasicEffect" but with the class "Effect" and HLSL, it's really more complicated. If somebody have an idea, it's will be wonderfull.

Thanks again.

Here is my code HLSL, i use.

```
// Both techniques share this same pixel shader.
float4 PixelShaderFunction(VertexShaderOutput input) : COLOR0
{
    //return tex2D(Sampler, input.TextureCoordinate) * input.Color;

    float d = length(input.TextureCoordinate - cameraPos);
    float l = saturate((d-fogNear)/(fogFar-fogNear));

    float fogFactory = clamp((d - fogNear) / (fogFar - fogNear), 0, 1) * l;

    return tex2D(Sampler, input.TextureCoordinate) * lerp(input.Color, fogColor, fogFactory);
}

```

Thanks to the big boss user =\> @ClassicThunder

**THE FINAL CODE HLSL ANSWER IS :**

```
//-----------------------------------------------------------------------------
// WorldEffect.fx
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
// ARCADIA Game
//-----------------------------------------------------------------------------

// Camera settings.
float4x4 World;
float4x4 View;
float4x4 Projection;

// This sample uses a simple Lambert lighting model.
float3 LightDirection = normalize(float3(-1, -1, -1));
float3 DiffuseLight = 1.25;
float3 AmbientLight = 0.25;
uniform const float3    DiffuseColor = 1;
uniform const float     Alpha = 1;
uniform const float3    EmissiveColor = 0;
uniform const float3    SpecularColor = 1;
uniform const float     SpecularPower = 16;
uniform const float3    EyePosition;
// FOG attribut
uniform const float     FogEnabled;
uniform const float     FogStart;
uniform const float     FogEnd;
uniform const float3    FogColor;
float3 cameraPos : CAMERAPOS;

texture Texture;

sampler Sampler = sampler_state
{
    Texture = (Texture);
};

struct CommonVSOutput
{
    float4  Pos_ws;
    float4  Pos_ps;
    float4  Diffuse;
    float3  Specular;
    float   FogFactor;
};
struct VertexLightingVSOutputTx
{
    float4  PositionPS  : POSITION;     // Position in projection space
    float4  Diffuse     : COLOR0;
    float4  Specular    : COLOR1;
    float2  TexCoord    : TEXCOORD0;
};
struct VertexLightingPSInputTx
{
    float4  Diffuse     : COLOR0;
    float4  Specular    : COLOR1;
    float2  TexCoord    : TEXCOORD0;
};
struct VSInputTx
{
    float4  Position    : POSITION;
    float2  TexCoord    : TEXCOORD0;
};
//Vertex Shader Bits
float ComputeFogFactor(float d)
{
    //d is the distance to the geometry sampling from the camera
    //this simply returns a value that interpolates from 0 to 1
    //with 0 starting at FogStart and 1 at FogEnd
    return clamp((d - FogStart) / (FogEnd - FogStart), 0, 1) * FogEnabled;
}

CommonVSOutput ComputeCommonVSOutput(float4 position)
{
    CommonVSOutput vout;

    float4 pos_ws = mul(position, World);
        float4 pos_vs = mul(pos_ws, View);
        float4 pos_ps = mul(pos_vs, Projection);

        vout.Pos_ws = pos_ws;
    vout.Pos_ps = pos_ps;

    vout.Diffuse = float4(DiffuseColor.rgb + EmissiveColor, Alpha);
    vout.Specular = 0;
    vout.FogFactor = ComputeFogFactor(length(EyePosition - pos_ws));

    return vout;
}

VertexLightingVSOutputTx VSBasicTx(VSInputTx vin)
{
    VertexLightingVSOutputTx vout;

    CommonVSOutput cout = ComputeCommonVSOutput(vin.Position);

    vout.PositionPS = cout.Pos_ps;
    vout.Diffuse = cout.Diffuse;
    vout.Specular = float4(cout.Specular, cout.FogFactor);
    vout.TexCoord = vin.TexCoord;

    return vout;
}

float4 PSBasicTx(VertexLightingPSInputTx pin) : COLOR
{
    float4 color = tex2D(Sampler, pin.TexCoord) * pin.Diffuse + float4(pin.Specular.rgb, 0);
    color.rgb = lerp(color.rgb, FogColor, pin.Specular.w);
    return color;
}

// For rendering without instancing.
technique NoInstancing
{
    pass Pass0
    {
        //VertexShader = compile vs_2_0 NoInstancingVertexShader();
        VertexShader = compile vs_2_0 VSBasicTx();
        PixelShader = compile ps_2_0 PSBasicTx();
    }
}

```

Here is the screenShot

With effect Without effect

# Answer
So as a warning I'm quite rusty with regards to shaders, but lets take a look at the BasicEffect's source code and see how Microsoft did it.

Overview of the shader pipeline. Most interesting bits below. For a fog shader BasicEffect utilizes the below 2 components.

* A vertex shader performs per-vertex processing such as transformations, skinning, vertex displacement, and calculating per-vertex material attributes. Tessellation of higher-order primitives should be done before the vertex shader executes. As a minimum, a vertex shader must output vertex position in homogeneous clip space. Optionally, the vertex shader can output texture coordinates, vertex color, vertex lighting, fog factors, and so on.
* A pixel shader performs per-pixel processing such as texture blending, lighting model computation, and per-pixel normal and/or environmental mapping. Pixel shaders work in concert with vertex shaders; the output of a vertex shader provides the inputs for a pixel shader.

Here is the code in BasicEffect's related to displaying the fog. You probably want to compare your `PixelShaderFunction` to the math in `PSBasicTx`. You have no depth in the PixelShader so this line doesn't make much sense `float d = length(input.TextureCoordinate - cameraPos);`. You should calculate the depth when you have access to the vertex information.

```
//Needed Variables
uniform const float     FogEnabled      : register(c0);
uniform const float     FogStart        : register(c1);
uniform const float     FogEnd          : register(c2);
uniform const float3    FogColor        : register(c3);

//Vertex Shader Bits
float ComputeFogFactor(float d)
{
    //d is the distance to the geometry sampling from the camera
    //this simply returns a value that interpolates from 0 to 1
    //with 0 starting at FogStart and 1 at FogEnd
    return clamp((d - FogStart) / (FogEnd - FogStart), 0, 1) * FogEnabled;
}

CommonVSOutput ComputeCommonVSOutput(float4 position)
{
    CommonVSOutput vout;

    float4 pos_ws = mul(position, World);
    float4 pos_vs = mul(pos_ws, View);
    float4 pos_ps = mul(pos_vs, Projection);

    vout.Pos_ws = pos_ws;
    vout.Pos_ps = pos_ps;

    vout.Diffuse    = float4(DiffuseColor.rgb + EmissiveColor, Alpha);
    vout.Specular   = 0;
    vout.FogFactor  = ComputeFogFactor(length(EyePosition - pos_ws ));

    return vout;
}

VertexLightingVSOutputTx VSBasicTx(VSInputTx vin)
{
    VertexLightingVSOutputTx vout;

    CommonVSOutput cout = ComputeCommonVSOutput(vin.Position);

    vout.PositionPS = cout.Pos_ps;
    vout.Diffuse    = cout.Diffuse;
    vout.Specular   = float4(cout.Specular, cout.FogFactor);
    vout.TexCoord   = vin.TexCoord;

    return vout;
}

float4 PSBasicTx(VertexLightingPSInputTx pin) : COLOR
{
    float4 color = tex2D(TextureSampler, pin.TexCoord) * pin.Diffuse + float4(pin.Specular.rgb, 0);
    color.rgb = lerp(color.rgb, FogColor, pin.Specular.w);
    return color;
}

```
> 3 votes

---
Tags: xna, hlsl
---


# Question
Title: Efficient way to calculate "vision cones" on 2D tile map?
I'm trying to calculate which tiles a particular unit can "see" if facing a certain direction on a tile map (within a certain range and angle of facing). The easiest way would be to draw a certain number of tiles outward and raycast to each tile. However, I'm hoping for something slightly more efficient. A picture says a thousand words:

The red dot is the unit (who's facing upwards). My goal is to calculate the yellow tiles. The green blocks are walls (walls are between tiles, and it's easy to check if you can pass between two tiles). The blue line represents something like the "raycasting" method I was talking about, but I'd rather not have to do this.

EDIT: Units can only be facing north/south/east/west (0, 90, 180, or 270 degrees) and FoV is always 90 degrees. Should simplify some calculations. I'm thinking there's some sort of recursive-ish/stack-based/queue-based algorithm, but I can't quite figure it out.

Thanks!

# Answer
> 15 votes
Yay I found a research paper!

In terms of computational cost Shadow Mapping seems pretty clear winner.

Algorithm used can be found here and a C# implementation can be found here, relevant bit below.

```
    #region FOV algorithm

    //  Octant data
    //
    //    \ 1 | 2 /
    //   8 \  |  / 3
    //   -----+-----
    //   7 /  |  \ 4
    //    / 6 | 5 \
    //
    //  1 = NNW, 2 =NNE, 3=ENE, 4=ESE, 5=SSE, 6=SSW, 7=WSW, 8 = WNW

    /// <summary>
    /// Start here: go through all the octants which surround the player to
    /// determine which open cells are visible
    /// </summary>
    public void GetVisibleCells()
    {
        VisiblePoints = new List<Point>();
        foreach (int o in VisibleOctants)
            ScanOctant(1, o, 1.0, 0.0);

    }

    /// <summary>
    /// Examine the provided octant and calculate the visible cells within it.
    /// </summary>
    /// <param name="pDepth">Depth of the scan</param>
    /// <param name="pOctant">Octant being examined</param>
    /// <param name="pStartSlope">Start slope of the octant</param>
    /// <param name="pEndSlope">End slope of the octance</param>
    protected void ScanOctant(int pDepth, int pOctant, double pStartSlope, double pEndSlope)
    {

        int visrange2 = VisualRange * VisualRange;
        int x = 0;
        int y = 0;

        switch (pOctant)
        {

            case 1: //nnw
                y = player.Y - pDepth;
                if (y < 0) return;

                x = player.X - Convert.ToInt32((pStartSlope * Convert.ToDouble(pDepth)));
                if (x < 0) x = 0;

                while (GetSlope(x, y, player.X, player.Y, false) >= pEndSlope)
                {
                    if (GetVisDistance(x, y, player.X, player.Y) <= visrange2)
                    {
                        if (map[x, y] == 1) //current cell blocked
                        {
                            if (x - 1 >= 0 && map[x - 1, y] == 0) //prior cell within range AND open...
                                //...incremenet the depth, adjust the endslope and recurse
                                ScanOctant(pDepth + 1, pOctant, pStartSlope, GetSlope(x - 0.5, y + 0.5, player.X, player.Y, false));
                        }
                        else
                        {

                            if (x - 1 >= 0 && map[x - 1, y] == 1) //prior cell within range AND open...
                                //..adjust the startslope
                                pStartSlope = GetSlope(x - 0.5, y - 0.5, player.X, player.Y, false);

                                VisiblePoints.Add(new Point(x, y));
                        }
                    }
                    x++;
                }
                x--;
                break;

            case 2: //nne

                y = player.Y - pDepth;
                if (y < 0) return;

                x = player.X + Convert.ToInt32((pStartSlope * Convert.ToDouble(pDepth)));
                if (x >= map.GetLength(0)) x = map.GetLength(0) - 1;

                while (GetSlope(x, y, player.X, player.Y, false) <= pEndSlope)
                {
                    if (GetVisDistance(x, y, player.X, player.Y) <= visrange2)
                    {
                        if (map[x, y] == 1)
                        {
                            if (x + 1 < map.GetLength(0) && map[x + 1, y] == 0)
                                ScanOctant(pDepth + 1, pOctant, pStartSlope, GetSlope(x + 0.5, y + 0.5, player.X, player.Y, false));
                        }
                        else
                        {
                            if (x + 1 < map.GetLength(0) && map[x + 1, y] == 1)
                                pStartSlope = -GetSlope(x + 0.5, y - 0.5, player.X, player.Y, false);

                            VisiblePoints.Add(new Point(x, y));
                        }
                    }
                    x--;
                }
                x++;
                break;

            case 3:

                x = player.X + pDepth;
                if (x >= map.GetLength(0)) return;

                y = player.Y - Convert.ToInt32((pStartSlope * Convert.ToDouble(pDepth)));
                if (y < 0) y = 0;

                while (GetSlope(x, y, player.X, player.Y, true) <= pEndSlope)
                {

                    if (GetVisDistance(x, y, player.X, player.Y) <= visrange2)
                    {

                        if (map[x, y] == 1)
                        {
                            if (y - 1 >= 0 && map[x, y - 1] == 0)
                                ScanOctant(pDepth + 1, pOctant, pStartSlope, GetSlope(x - 0.5, y - 0.5, player.X, player.Y, true));
                        }
                        else
                        {
                            if (y - 1 >= 0 && map[x, y - 1] == 1)
                                pStartSlope = -GetSlope(x + 0.5, y - 0.5, player.X, player.Y, true);

                            VisiblePoints.Add(new Point(x, y));
                        }
                    }
                    y++;
                }
                y--;
                break;

            case 4:

                x = player.X + pDepth;
                if (x >= map.GetLength(0)) return;

                y = player.Y + Convert.ToInt32((pStartSlope * Convert.ToDouble(pDepth)));
                if (y >= map.GetLength(1)) y = map.GetLength(1) - 1;

                while (GetSlope(x, y, player.X, player.Y, true) >= pEndSlope)
                {

                    if (GetVisDistance(x, y, player.X, player.Y) <= visrange2)
                    {

                        if (map[x, y] == 1)
                        {
                            if (y + 1 < map.GetLength(1)&& map[x, y + 1] == 0)
                                ScanOctant(pDepth + 1, pOctant, pStartSlope, GetSlope(x - 0.5, y + 0.5, player.X, player.Y, true));
                        }
                        else
                        {
                            if (y + 1 < map.GetLength(1) && map[x, y + 1] == 1)
                                pStartSlope = GetSlope(x + 0.5, y + 0.5, player.X, player.Y, true);

                             VisiblePoints.Add(new Point(x, y));
                        }
                    }
                    y--;
                }
                y++;
                break;

            case 5:

                y = player.Y + pDepth;
                if (y >= map.GetLength(1)) return;

                x = player.X + Convert.ToInt32((pStartSlope * Convert.ToDouble(pDepth)));
                if (x >= map.GetLength(0)) x = map.GetLength(0) - 1;

                while (GetSlope(x, y, player.X, player.Y, false) >= pEndSlope)
                {
                    if (GetVisDistance(x, y, player.X, player.Y) <= visrange2)
                    {

                        if (map[x, y] == 1)
                        {
                            if (x + 1 < map.GetLength(1) && map[x+1, y] == 0)
                                ScanOctant(pDepth + 1, pOctant, pStartSlope, GetSlope(x + 0.5, y - 0.5, player.X, player.Y, false));
                        }
                        else
                        {
                            if (x + 1 < map.GetLength(1)
                                    && map[x + 1, y] == 1)
                                pStartSlope = GetSlope(x + 0.5, y + 0.5, player.X, player.Y, false);

                            VisiblePoints.Add(new Point(x, y));
                        }
                    }
                    x--;
                }
                x++;
                break;

            case 6:

                y = player.Y + pDepth;
                if (y >= map.GetLength(1)) return;

                x = player.X - Convert.ToInt32((pStartSlope * Convert.ToDouble(pDepth)));
                if (x < 0) x = 0;

                while (GetSlope(x, y, player.X, player.Y, false) <= pEndSlope)
                {
                    if (GetVisDistance(x, y, player.X, player.Y) <= visrange2)
                    {

                        if (map[x, y] == 1)
                        {
                            if (x - 1 >= 0 && map[x - 1, y] == 0)
                                ScanOctant(pDepth + 1, pOctant, pStartSlope, GetSlope(x - 0.5, y - 0.5, player.X, player.Y, false));
                        }
                        else
                        {
                            if (x - 1 >= 0
                                    && map[x - 1, y] == 1)
                                pStartSlope = -GetSlope(x - 0.5, y + 0.5, player.X, player.Y, false);

                            VisiblePoints.Add(new Point(x, y));
                        }
                    }
                    x++;
                }
                x--;
                break;

            case 7:

                x = player.X - pDepth;
                if (x < 0) return;

                y = player.Y + Convert.ToInt32((pStartSlope * Convert.ToDouble(pDepth)));
                if (y >= map.GetLength(1)) y = map.GetLength(1) - 1;

                while (GetSlope(x, y, player.X, player.Y, true) <= pEndSlope)
                {

                    if (GetVisDistance(x, y, player.X, player.Y) <= visrange2)
                    {

                        if (map[x, y] == 1)
                        {
                            if (y + 1 < map.GetLength(1) && map[x, y+1] == 0)
                                ScanOctant(pDepth + 1, pOctant, pStartSlope, GetSlope(x + 0.5, y + 0.5, player.X, player.Y, true));
                        }
                        else
                        {
                            if (y + 1 < map.GetLength(1) && map[x, y + 1] == 1)
                                pStartSlope = -GetSlope(x - 0.5, y + 0.5, player.X, player.Y, true);

                            VisiblePoints.Add(new Point(x, y));
                        }
                    }
                    y--;
                }
                y++;
                break;

            case 8: //wnw

                x = player.X - pDepth;
                if (x < 0) return;

                y = player.Y - Convert.ToInt32((pStartSlope * Convert.ToDouble(pDepth)));
                if (y < 0) y = 0;

                while (GetSlope(x, y, player.X, player.Y, true) >= pEndSlope)
                {

                    if (GetVisDistance(x, y, player.X, player.Y) <= visrange2)
                    {

                        if (map[x, y] == 1)
                        {
                            if (y - 1 >=0 && map[x, y - 1] == 0)
                                ScanOctant(pDepth + 1, pOctant, pStartSlope, GetSlope(x + 0.5, y - 0.5, player.X, player.Y, true));

                        }
                        else
                        {
                            if (y - 1 >= 0 && map[x, y - 1] == 1)
                                pStartSlope = GetSlope(x - 0.5, y - 0.5, player.X, player.Y, true);

                            VisiblePoints.Add(new Point(x, y));
                        }
                    }
                    y++;
                }
                y--;
                break;
        }

        if (x < 0)
            x = 0;
        else if (x >= map.GetLength(0))
            x = map.GetLength(0) - 1;

        if (y < 0)
            y = 0;
        else if (y >= map.GetLength(1))
            y = map.GetLength(1) - 1;

        if (pDepth < VisualRange & map[x, y] == 0)
            ScanOctant(pDepth + 1, pOctant, pStartSlope, pEndSlope);

    }

    /// <summary>
    /// Get the gradient of the slope formed by the two points
    /// </summary>
    /// <param name="pX1"></param>
    /// <param name="pY1"></param>
    /// <param name="pX2"></param>
    /// <param name="pY2"></param>
    /// <param name="pInvert">Invert slope</param>
    /// <returns></returns>
    private double GetSlope(double pX1, double pY1, double pX2, double pY2, bool pInvert)
    {
        if (pInvert)
            return (pY1 - pY2) / (pX1 - pX2);
        else
            return (pX1 - pX2) / (pY1 - pY2);
    }

    /// <summary>
    /// Calculate the distance between the two points
    /// </summary>
    /// <param name="pX1"></param>
    /// <param name="pY1"></param>
    /// <param name="pX2"></param>
    /// <param name="pY2"></param>
    /// <returns>Distance</returns>
    private int GetVisDistance(int pX1, int pY1, int pX2, int pY2)
    {
        return ((pX1 - pX2) * (pX1 - pX2)) + ((pY1 - pY2) * (pY1 - pY2));
    }

    #endregion

```

---
Tags: 2d, algorithm, tilemap
---


title: Wake locks in Android multiplayer games

text:
# Question
Title: Wake locks in Android multiplayer games
I'm porting an FPS game to Android, and I have a question about the use of wake locks.

Should the client acquire a wake lock when it connects to a server to keep frames running at a proper rate when the player is AFK and the device is in sleep mode?

And should a wake lock be used if the game is running a listen or a dedicated server?

# Answer
If the player is afk and the phone goes to sleep, there is no reason to keep him connected at all. Maintaining a connection will drain the player's battery and place additional stress on your servers, both for no benefit, since the player isn't using the game anyway. This means higher costs for you and (potentially) negative reviews for your game.

Instead, you should just drop the connection when the phone goes to sleep and attempt to reconnect when the phone wakes up.

If you don't want to disconnect a user without him willing it to happen, you can set FLAG\_KEEP\_SCREEN\_ON. This will keep the phone awake as long as the app is in focus while also shouting to the user, "Hey, I'm eating your battery! You should turn me off if you're really not playing anymore!"
> 1 votes

---
Tags: android, multiplayer
---


# Question
Title: Unity - Mecanim & Rigidbody on Third Person Controller - Gravity bug?
I'm working on a third person controller which uses physX to interact with the other objects (using the Rigidbody component) and Mecanim to animate the character.

All the animations used are baked to Y, and the movement on this axis is controlled by the gravity applied by the rigidbody component.

The configuration of the falling animation:

And the character components configuration:

Since the falling animation doesn't have root motion on XZ, I move the character on XZ by code. Like this:

```
    // On the Ground
    if (IsGrounded())
    {
        GroundedMovementMgm();

        // Stores the velocity
        velocityPreFalling = rigidbody.velocity;
    }
    // Mid-Air
    else
    {
        // Continue the pre falling velocity
        rigidbody.velocity = new Vector3(velocityPreFalling.x, rigidbody.velocity.y, velocityPreFalling.z);
    }

```

The problem is that when the chracter starts falling and hit against a wall in mid air, it gets stuck to the wall. Here are some pics which explains the problems:

Hope someone can help me. Thanks and sory for my bad english!

PD.: I was asked for the IsGrounded() function, so I'm adding it:

```
    void OnCollisionEnter(Collision collision)
    {
        if (!grounded)
            TrackGrounded(collision);
    }

    void OnCollisionStay(Collision collision)
    {
        TrackGrounded(collision);
    }

    void OnCollisionExit()
    {
        grounded = false;
    }

    public bool IsGrounded()
    {
        return grounded;
    }

    private void TrackGrounded(Collision collision)
    {
        var maxHeight = capCollider.bounds.min.y + capCollider.radius * .9f;
        foreach (var contact in collision.contacts)
        {
            if (contact.point.y < maxHeight && Vector3.Angle(contact.normal, Vector3.up) < maxSlopeAngle)
            {
                grounded = true;
                break;
            }
        }
    }

```

I'll also add a LINK to download the project if someone wants it.

# Answer
> 2 votes
The problem was caused by the friction configuration on the character's physic material. Changing it as the image shows fixed the problem:

It seems that over .001 of dynamic friction and .01 of static are enough to start slowing the fall of the character when hitting a wall.

# Answer
> 0 votes
Most of the mecanim setup stuff is irrelevant; this question mostly rests on what IsGrounded() is doing. Whatever is happening in there to detect the ground is not working correctly, and it considers hitting the wall to be "on the ground".

---
Tags: unity, physics, third-person-view
---


title: Algorithm for waypoint path following?

text:
# Question
Title: Algorithm for waypoint path following?
I have a worldmap, with different cities on it. The player can choose a city from a menu, or click on an available cities on the world map, and the toon should walk over there.

I want him to follow a predefined path.

Lets say our hero is on the city 1. He clicks on city 4. I want him to follow the path to city 2 and from there to city 4.

I was handling this easily with arrow movement (left right top bottom) since its a single check.

Now I'm not sure how I should do this. Should I loop threw each possible path and check which one leads me to D the fastest ... and if I do how do I avoid running in circle forever with cities 1-5-2 ?

# Answer
> 3 votes
Unless you're dealing with a very large grid, A\* is overkill. You're probably better off with Dijkstra's Shortest Path, which has the advantage of being far easier to implement, to boot.

A\* matters when you have an enormous number of possible paths, like when searching a large game grid. However it also relies on datastructures, particularly the priority queue, which aren't commonly available (and when are are often inefficient.)

http://rosettacode.org/wiki/Dijkstra%27s\_algorithm

# Answer
> 1 votes
Any A\* implementation will do the trick. Look on Wikipedia for example.

A\* even allows you to add weight to your connections, resulting in not the route with the fewest hops, but the route with the shortest travel time beeing selected.

Example: `Frankfurt→NYC`
There is a connection `Frankfurt→Moskau→NYC`. This one has 2 hops, but the cost is high.
Then there os a way `Frankfurt→Rotterdam→London→NYC`. This one has three hops, but the cost is low.

Adding costs is worthwile if distance, the mean of transport or something else is important.

---
Tags: path-finding
---


title: Character creation using spritesheets

text:
# Question
Title: Character creation using spritesheets
I am currently creating a 2D fighting game and have implemented a system where upon starting a new game, the player is presented with the option to create a custom character. I have a set of string arrays set with values that correspond to hair, headgear, chest, lower body and shoes.

When done selecting a variety of items from the lists, a code is generated based off the index of each item (i.e 01123), which is then used to assign the correct Spritesheet to the player character.

This has already presented a lot of work as I have had to create quite a few spreadsheets based of possible combinations, but I am now looking at a massive amount of work to implement each variation.

I have started to look into setting layers for each item to reduce workload, but I am also looking at having different stances for the character - Depending on the currently equipped weapon - so this may present a lot of work either way.

My question is, do I have any alternatives or am I stuck creating masses of Spritesheets to cover all combinations?

As a side note, how much impact will assigning layered items have on overall performance?

# Answer
> 4 votes
You should be using layers.

That is you have a naked character sprite. On top of that you add layers for hair, armor, gear, weapons.

Depending on your actual game, you might do that in generic form, or split in parts or even add skeletal system.

For example in Diablo 2 character was split into parts that were combined:

Here's another example of similar approach:

---
Tags: c#, 2d, xna, spritesheet
---


title: Collisions and Lists

text:
# Question
Title: Collisions and Lists
I've run into an issue that breaks my collisions. Here's my method:

* Gather Input
* Project Rectangle
* Check for intersection and ispassable
* Update

The update method is built on `object_position * seconds_passed * velocity * speed`. Input changes velocity and is normalized if \> 1.

This method works well with just one object comparison, however I pass a list or a for loop to the collision detector and velocity gets changed back to a non zero when the list hits an object that passes the test and the object can pass through.

Any solutions would be much appreciated. Side note is there a more proper way to simulate movement?

# Answer
> 1 votes
Lets see what you're trying to do : you're trying to check if 1 entity collides with N other entities, but I suppose those collide as well. Basically (if I understood you right) you\`re trying to do N\*N comparisons every frame, or even N. You should, first and foremost, switch your data structure. Use a quadtree, with that, you will have a complexity of O(n\*n(logn)), which is close to linear speed.

Also, the velocity negating itself - this is just a response to the collision, for instance in pong-like games its a common practice to negate one part of the velocity vector.

This is just general advice based on what you said, please provide code and I\`ll be more specific.

---
Tags: xna, c#, collision-resolution
---


# Question
Title: How to avoid movement speed stacking when multiple keys are pressed?
I've started a new game which requires no mouse, thus leaving the movement up to the keyboard. I have tried to incorporate 8 directions; up, left, right, up-right and so on. However when I press more than one arrow key, the movement speed stacks (http://gfycat.com/CircularBewitchedBarebirdbat). How could I counteract this?

Here is relevant part of my code:

```
var speed : int = 5;

function Update () {
    if (Input.GetKey(KeyCode.UpArrow)) {
        transform.Translate(Vector3.forward * speed * Time.deltaTime);
    } else if (Input.GetKey(KeyCode.UpArrow) && Input.GetKey(KeyCode.RightArrow)) {
        transform.Translate(Vector3.forward * speed * Time.deltaTime);
    } else if (Input.GetKey(KeyCode.UpArrow) && Input.GetKey(KeyCode.LeftArrow)) {
        transform.rotation = Quaternion.AngleAxis(315, Vector3.up);
    }
    if (Input.GetKey(KeyCode.DownArrow)) {
        transform.Translate(Vector3.forward * speed * Time.deltaTime);
    }
}

```

# Answer
Separate your direction selection code from actual movement code.

1. Choose `Direction` by checking which keys are pressed. Store it as a unit (normalized) vector.
2. Multiply your `Direction` with `Speed` and with `DeltaTime`.
3. Apply resulting transform to your object/camera.
> 13 votes

# Answer
You need to take the sum of the directions, normalize that, then multiply by the speed.

I tangentially answered this as part of my response to Preventing diagonal movement

Specifically:

```
velX = 0;
velY = 0;

if(keyLeft) velX += -1;
if(keyRight) velX += 1;
if(keyUp) velY += -1;
if(keyDown) velY += 1;

// Normalize to prevent high speed diagonals
length = sqrt((velX * velX ) + (velY * velY ));
if (length != 0)
{
    velX /= length;
    velY /= length;
}

velX *= speed;
velY *= speed;

```
> 28 votes

# Answer
The "normalized direction vector" is how this task is usually approached, and how I often do it, but lately I've simply been clamping the resulting movement vector. It usually achieves the same end result and the code is a lot simpler:

```
var moveSpeed = 6.0f;
function Update() {
  var movement = Vector3.zero;
  movement.x = Input.GetAxis("Horizontal") * moveSpeed;
  movement.z = Input.GetAxis("Vertical") * moveSpeed;
  movement = Vector3.ClampMagnitude(movement, moveSpeed);
  movement *= Time.deltaTime;
  transform.Translate(movement);
}

```

Simpler code is almost always better :E
> 11 votes

---
Tags: unity, javascript, movement
---


# Question
Title: How can I create straight, glowing lines?
What techniques are used in this style? What steps would be required to recreate it?

(Screenshot of this app: https://play.google.com/store/apps/details?id=com.dkeesto.holographlw)

# Answer
> 2 votes
This is generic solution that will work even with **FFP**:

1. Sort models from far to near (in the example this is just a matter of 2 planes)
2. Set blending to additive.
3. Render opaque outline;
4. Render half-transparent insides;
5. Render outlines with half-transparent fading gradient;
6. Render glowing dots sprites on the corners.

# Answer
> 1 votes
To render just the edges of an arbitrary polygon you could use a Solid Wireframe technique. It uses barycentric coordinates to determine which edges to draw. For example you might have a triangle whose barycentric coordinates are (for each vertex) `B0: (1, 0, 0) B1: (0, 1, 0) B2: (0, 0, 1)`. Put it simply, when these values are interpolated the further any of the values are close to zero, then the further you are to an edge. You can use this to shade the edges differently than the inside of a the polygon.

I have used this technique to draw the sphere and hexagon tiles you see in this video. As the others have suggested, you can add a glow/bloom effect to improve the overall effect.

# Answer
> 0 votes
In very crude pseudo-code :

* Draw the "laser lines" to an off screen buffer.

*in case of openGL, this could be a FrameBuffer*

* Then draw the off screen buffer to the screen.
* Blur the off screen buffer

*you could use GLSL shaders, or even a hand coded kernel for this*

* Blend the (now blurred off screen buffer) to the screen (using additive blending)

*note that additive blending in OPENGL is done by subtraction!*

---
Tags: 3d, glow, bloom
---


# Question
Title: Problems with texture orientation in space
I am currently drawing texture in 3D space and have some problems with it's orientation.

I'd like me textures always to be oriented with front face to user.

My **desirable result** looks like

Note, that text size stay without changes when we rotating world and stay oriented with front face to user.

**Now** I can draw text in 3D space, but it is not oriented with front but rotating with world.

Such results I got with following shaders:

*Vertex Shader*

uniform vec3 Position;

```
void main()
{
    gl_Position = vec4(Position, 1.0);
}

```

*Geometry Shader*

```
layout(points) in;
layout(triangle_strip, max_vertices = 4) out;

out vec2 fsTextureCoordinates;

uniform mat4 projectionMatrix;
uniform mat4 modelViewMatrix;
uniform sampler2D og_texture0;
uniform float og_highResolutionSnapScale;
uniform vec2 u_originScale;

void main()
{
    vec2 halfSize = vec2(textureSize(og_texture0, 0)) * 0.5 * og_highResolutionSnapScale;
    vec4 center = gl_in[0].gl_Position;
    center.xy += (u_originScale * halfSize);

    vec4 v0 = vec4(center.xy - halfSize, center.z, 1.0);
    vec4 v1 = vec4(center.xy + vec2(halfSize.x, -halfSize.y), center.z, 1.0);
    vec4 v2 = vec4(center.xy + vec2(-halfSize.x, halfSize.y), center.z, 1.0);
    vec4 v3 = vec4(center.xy + halfSize, center.z, 1.0);

    gl_Position =  projectionMatrix * modelViewMatrix   * v0;
    fsTextureCoordinates = vec2(0.0, 0.0);
    EmitVertex();

    gl_Position =  projectionMatrix * modelViewMatrix   * v1;
    fsTextureCoordinates = vec2(1.0, 0.0);
    EmitVertex();

    gl_Position =  projectionMatrix * modelViewMatrix   * v2;
    fsTextureCoordinates = vec2(0.0, 1.0);
    EmitVertex();

    gl_Position =  projectionMatrix * modelViewMatrix  * v3;
    fsTextureCoordinates = vec2(1.0, 1.0);
    EmitVertex();
}

```

*Fragment Shader*

```
in vec2 fsTextureCoordinates;

out vec4 fragmentColor;

uniform sampler2D og_texture0;
uniform vec3 u_color;

void main()
{
    vec4 color = texture(og_texture0, fsTextureCoordinates);

    if (color.a == 0.0)
    {
        discard;
    }
    fragmentColor = vec4(color.rgb * u_color.rgb, color.a);
}

```

Any ideas how to get my desirable result?

## **EDIT 1:**

I make edit in my geometry shader and got part of lable drawn on screen at corner. But it is not rotating.

```
..........

    vec4 centerProjected = projectionMatrix * modelViewMatrix * center;
    centerProjected /= centerProjected.w;

    vec4 v0 = vec4(centerProjected.xy - halfSize, 0.0, 1.0);
    vec4 v1 = vec4(centerProjected.xy + vec2(halfSize.x, -halfSize.y), 0.0, 1.0);
    vec4 v2 = vec4(centerProjected.xy + vec2(-halfSize.x, halfSize.y), 0.0, 1.0);
    vec4 v3 = vec4(centerProjected.xy + halfSize, 0.0, 1.0);

    gl_Position =  og_viewportOrthographicMatrix * v0;

..........

```

# Answer
> 1 votes
I mostly work on GLES where we don't have geometry shaders, so don't expect my code to work as-is.

The problem is that you're creating the vertices in world space (3D), and then projecting them independently.

If you want your text to be facing the camera regardless of the camera settings, then you want to create your vertices in screen space (2D), not world space.

You already know how to project a point, so instead of projecting each of the 4 vertices, you just project the center, divide by w (important), and then you just keep x and y:

```
vec4 center = gl_in[0].gl_Position;
vec4 centerProjected = projectionMatrix * modelViewMatrix * center;
centerProjected /= centerProjected.w;

```

Once you're in screen space, you create your other vertices in screen space:

```
vec4 v0 = vec4(centerProjected.xy - halfSize, 0.0, 1.0);
vec4 v1 = vec4(centerProjected.xy + vec2(halfSize.x, -halfSize.y), 0.0, 1.0);
vec4 v2 = vec4(centerProjected.xy + vec2(-halfSize.x, halfSize.y), 0.0, 1.0);
vec4 v3 = vec4(centerProjected.xy + halfSize, 0.0, 1.0);

```

Notice that now that we're on screen space, z becomes mostly meaningless, so I set it at 0.

All that is left is to emit the vertices:

```
gl_Position = v0;
fsTextureCoordinates = vec2(0.0, 0.0);
EmitVertex();

gl_Position = v1;
fsTextureCoordinates = vec2(1.0, 0.0);
EmitVertex();

gl_Position = v2;
fsTextureCoordinates = vec2(0.0, 1.0);
EmitVertex();

gl_Position = v3;
fsTextureCoordinates = vec2(1.0, 1.0);
EmitVertex();

```

I'm not sure if the size of the sprite will be correct, because now you're working on screen space, which goes from -0.5 to 0.5, but you should get the idea.

Also notice that for this technique you don't need to have separate projection and world-view matrices, so if you want to, you can mix them into one world-view-projection matrix before you pass it to the shaders.

---
Tags: opengl, 3d, shaders
---


title: AABB implementation

text:
# Question
Title: AABB implementation
I have seen in some texts and tutorials on the web where an AABB is implemented as a position vector and then half-width and half-height vectors. What is the advantage in using the half-width and half-height vectors? Why not use the full width and height vectors?

# Answer
> 2 votes
You then have the centers of the BB without having to know the size of it, if your game needs to know the centers more often than the top left then that is preferable.

Storing the half vectors is to simplify retrieving the left/right and bottom/top vectors center-halfHeight provides the bottom and center+halfHeight provides the top. Granted all it does is avoid dividing by 2 but when it's done often enough the difference can be felt.

---
Tags: collision-detection, mathematics, physics
---


title: Retrieving snapshots of game statistics

text:
# Question
Title: Retrieving snapshots of game statistics
What is a good architecture for storing game statistics, so that I can retrieve snapshots of it at various moments?

Say I have a game, and the user's statistics initially are:

```
 {
 hours_played = 0,
 games_played = 0,
 no_of_times_killed = 0,
 }

```

When the user purchases something for the first time from within the game, the stats are

```
 {
 hours_played = 10,
 games_played = 2,
 no_of_times_killed = 5,
 }

```

And when he purchases something for the second time, the stats are

```
 {
 hours_played = 20,
 games_played = 4,
 no_of_times_killed = 10,
 }

```

Let me name the events as "purchase1" and "purchase2"

How do I model my statistics, so that at any point in the future, I will be able to retrieve the snapshot of the statistics at the time when "purchase1" was fired. Similarly for "purchase2" and any other event I will add.

Hope that made sense..

# Answer
> 1 votes
Every time a memorable Event (purchase1,...) happens, save it to a list. Then, serialize it to a File.

If order doesn't matter, a Set would probably more performant.

If order doesn't matter, but you want to reference by name, look into maps/dictionaries. Your language may not nativly supply them, but implementation is fairly easy.

---

More indepth:

Create a datatype containing all relevant information.
I will call it `DataPoint` from here on.

Create a list containing `DataPoint`s.
I will call it `Events`.
*In Java you would write `List<DataPoints> Events = ...`*

Now, every time something happens, you add a new Element to the list. //something happens Events.add(new DataPoint(...));

To retrieve an element, you just get it from the list. Events.get(indexOfEvent)

To go over all (or at least more than one) elements of the list, use *Iterators*. As Iterators differ too much between languages, I will not show hoe to use them here.
*A lot of languages support `foreach`-loops.*

---
Tags: architecture, statistics, metrics
---


# Question
Title: Why do I seem to lose control of my computer when full screen Unity game loses focus?
When I press Ctrl+Alt+Esc or Ctrl+Shift+Esc the game loses focus, but then the whole PC is unusable and I need to restart the PC to regain control

How do I prevent the computer from locking up (let the player control their PC) when a full screen Unity game loses focus?

# Answer
I just tested this myself and confirmed this is a bug with Unity. When a full-screen Unity game loses focus, it still intercepts all input, so any clicks just give focus back to the game. (Without making it reappear, strangely enough.)

This issue was also noted by GG67 in a comment on this bug report, followed by CLEROTH saying he doesn't notice the issue in 4.5.3p1, so you should try updating and see if that fixes anything.

And if updating to 4.5.3p1 or beyond does not fix your problem, you should then report the bug by following this process.
> 26 votes

---
Tags: unity
---


# Question
Title: Best way to detect if vec3 is between vec3(x) and vec3(y) in glsl
As titled

I am sampling from a texture and if the color is somehow gray \[vec3(.8), vec3(.9)\] and an uniform is 1 I need to substitute that color with another one

I am not a glsl veteran but I am pretty sure there is a more elegant and compact (without mentioning faster) way than this:

```
vec3 textureColor = texture(texture0, oUV);

if(settings.w == 1 && textureColor.r > .8 && textureColor.r < .9
                    && textureColor.g > .8 && textureColor.g < .9
                    && textureColor.b > .8 && textureColor.b < .9)

```

# Answer
How about:

```
vec3 delta = abs(textureColor - vec3(0.85, 0.85, 0.85)); // Get delta from middle vec3

if (delta.r <= 0.05) && (delta.g <= 0.05) && (delta.b <= 0.05)

```

Performance needs to be profiled, but it's sure shorter to write
> 1 votes

# Answer
You can use the inbuilt GLSL lessThan() and greaterThan() functions (supported in all GLSL versions). These give two boolean vectors as a result.

https://www.opengl.org/sdk/docs/man/html/greaterThan.xhtml http://www.opengl.org/sdk/docs/man4/html/lessThan.xhtml

Then, you can use 'equal' (https://www.opengl.org/sdk/docs/man/html/equal.xhtml) on those results.

I would still do the first version though, even if its a bit more code, its perfectly understandable. :)
> 1 votes

---
Tags: opengl, textures, glsl, fragment-shader
---


# Question
Title: openGL Camera setup for Zoom in/out centered at point under cursor
I am trying to implement a zoom in/out navigation mode in a openGL 3dViewer. I was able to implement zoom functionality centered at screen center just by moving eye towards the center in perspective mode.

Now i am trying to do the zoom centered at arbitrary position under the cursor. I am unable to figure out how should i move my camera forward and backward such that point under cursor remains at the same screen coordinates after zoom in/out. Any help would be appreciated.

Below are the images which show the desired effect. Just to mention, I am working in a perspective mode with eye target and up vectors to control camera.

Same effect i found in google sketchup and 'zoom to mouse position' setting in blender.

# Answer
> 1 votes
In order for an object to remain stationary in your field of view, it has to move directly towards you, or directly away from you. Incidentally, this is why mid-air collisions with airplanes are so nasty, our eyes are trained to see movement in our field of view, and an airplane on a collision course would remain stationary. Bit I digress.

What you need to do is figure out the world space coordinates of the point 'under the cursor'. If you're just displaying a rectangle this should be fairly easy. If you're displaying a full 3D-scene, things get more complicated, and you need to figure out what you're actually pointing at. There are a number of ways to do this, but it would be more suitable for a separate question. Once you have the world space coordinates of the 'point under the cursor' you need to translate the camera along the vector from the camera to that point, note that this will be moving the camera sideways.

Strictly speaking, when using a perspective transformation, a point on screen corresponds to an angle in world space, if you move along the track to the point, but do not turn the camera, the angle from the camera's forward-looking vector (center of the screen) and your target point will remain the same.

# Answer
> 0 votes
I have achieved this by following this algorithm,

1. Calculate the screen point of the 3D point under the mouse cursor (the point that needs to be on fixed location) before move the camera. (Say screen point as Pt2DScr and 3D point under mouse Pt3D1)
2. Move camera along camera Z axis. That's mean zoom to center of the viewport.
3. Calculate current 3D point which is under Pt2DScr, say Pt3D2.
4. Calculate the difference between Pt3D1 and Pt3D2 by (Pt3D1 - Pt3D2), say Pt3DOffset
5. Move the camera by the amount of Pt3DOffset.

Note that you will need a fixed plane to calculate Pt3D1 and Pt3D2 which normal vector of the plane parallel to the camera z axis (plane always face to the camera)

Hope this will help to somebody!

---
Tags: opengl, camera
---


# Question
Title: How to increase the acceleration of an object on the Y axis?
So far I am able to make the character fall at a constant rate but I am unsure how to make the character accelerate while falling.

When the character is falling I have a line of code as such:

```
position.y -= 7f;

```

How can I change my implementation such that the character falls faster over time?

# Answer
> 1 votes
```
position.y -= 7f;

```

change 7f to a variable

```
var fallspeed = 7.0f;
position.y -= fallspeed;

```

increase the fallspeed every update

```
var fallspeed = 7.0f;
var gravity = 5.0f;
position.y -= fallspeed;
fallspeed += gravity;

```

This creates a linear acceleration. Gravity on the other hand isnt linear, so you might wanna try something like this

```
var fallspeed = 7.0f;
var gravity = 2.0f;
position.y -= fallspeed;
fallspeed *= gravity; // *= instead of +=

```

values are totally of, you will have to try around a bit.

# Answer
> 2 votes
Change your thought process from "Moving 7 units" to "Applying a velocity of 7 units" and you can come up with something like:

```
velocity.Y = -7;
position.Y += velocity.Y;

```

Now if we take this and we want to apply acceleration every frame we can simply update the velocity every frame.

```
accelerationRate = 2; //arbitrarily picked - no significance
velocity.Y = velocity.Y + accelerationRate;
position.Y += velocity.Y;

```

A more appropriate and less naive approach would take elapsed time into account. This results in consistent distance traversed over time. To implement this we are required to somehow track the amount of time elapsed since the last update. Some libraries will include this functionality but otherwise using time keeping measures built into your language of choice are likely sufficient. This value will be stored in deltaTime in the sample below and will expressed in seconds.

```
accelerationRate = 2;
velocity.Y = velocity.Y + (accelerationRate * deltaTime); //We should only increase our accelration based on the elapsed time
position.Y += velocity.Y * deltaTime; //Only apply velocity as much as we should given the amount of elapsed time

```

You could take this and easily apply it to moving in either direction on the Y axis, up or down. Your velocity should just be positive or negative to behave appropriately as needed.

---
Tags: android, libgdx, game-mechanics
---


# Question
Title: How can I resolve component types in a way that supports adding new types relatively easily?
I am trying to build an Entity Component System for an interactive application developed using C++ and OpenGL. My question is quite simple. In my GameObject class I have a collection of Components. I can add and retrieve components.

```
class GameObject: public Object
{
public:
    GameObject(std::string objectName);
    ~GameObject(void);
    Component * AddComponent(std::string name);
    Component * AddComponent(Component componentType);
    Component * GetComponent (std::string TypeName);
    Component * GetComponent (<Component Type Here>);
private:
    std::map<std::string,Component*> m_components;

};

```

I will have a collection of components that inherit from the base Components class. So if I have a meshRenderer component and would like to do the following

```
GameObject * warship  = new GameObject("myLovelyWarship");
MeshRenderer * meshRenderer =  warship->AddComponent(MeshRenderer);

```

or possibly

```
MeshRenderer * meshRenderer =  warship->AddComponent("MeshRenderer");

```

I could be make a Component Factory like this:

```
 class ComponentFactory
 {
 public:
     static Component * CreateComponent(const std::string &compTyp)
     {
         if(compTyp == "MeshRenderer")
             return new MeshRenderer;
         if(compTyp == "Collider")
             return new Collider;
         return NULL;
     }
 };

```

However, I feel like I should not have to keep updating the Component Factory every time I want to create a new custom Component but it is an option. Is there a more proper way to add and retrieve these components? Is standard templates another solution?

# Answer
> 2 votes
Templates could work:

```
template <typename ComponentType>
static Component * CreateComponent () {
  return new ComponentType();
}

```

However, that means all components must be created based on *compile time* data. Honestly, at that point you may as well just do

```
myGameObject->AddComponent(new MeshComponent());

```

instead of bothering with a factory, which would look almost the same:

```
myGameObject->AddComponent(ComponentFactory::CreateComponent<MeshComponent>());

```

If you need to be able to create component types based on *runtime* data, you'll have to use some kind of runtime key -- a string will suffice, as in your example (although other options may result in faster lookup time).

To avoid the problem of having to modify the factory every time in this case, provide a way to delegate the actual creation to something outside the factory. A function pointer is an extremely basic way to do this. For example:

```
typedef Component * (* CreateComponentFunction)();

std::map<std::string, CreateComponentFunction> m_delegates;

// ...

static Component * CreateComponent (const std::string & type) {
  return m_delegates[type]();
}

```

You could use `std::function` instead if you wanted, or an abstract interface... et cetera. The point is to move the actual instantiation into some delegate you can implement *with* the new kind of component you are authoring.

Then, you implement some kind of "registration" method in the factory:

```
void Register (const std::string & type, CreateComponentFunction delegate) {
  m_delegates[type] = delegate;
}

```

Then you can register the binding between strings keys and delegate functions at game startup, or somewhere -- somewhere higher-level than the component factory, so you no longer need to modify it when you add new components. For example, if a running instance of your game was represented by the `MyGame` class, you might register all your components during startup:

```
void MyGame::Start () {
  m_componentFactory = new ComponentFactory();
  m_componentFactory->Register("RigidBody", &RigidBodyComponent::Create);
  ...

  // ...here you could also call into your script-based hook for registering
  // component types as well, if you choose to build such a thing...
}

```

You can continue to expand upon this delegate technique in the same way and even move the registration out of code, into script files (as alluded to above), if you have a suitably robust scripting system integrated.

Unfortunately you'll never really get away from the task of having to make *some* kind of association between your runtime key data and the (compile-time) code that creates the appropriate, desired instances. It's simply a matter of choosing the ideal level of abstraction to do so. Moving it out of the "factory" is important, since it means that association is at *least* at the level of the component type you're implementing anyway, and also means the factory itself could be part of common library code you use across your projects.

---
Tags: component-based, entity-component, game-component, entity
---


# Question
Title: Vehicle: Boat accelerating and turning in Unity
I'm trying to make a player-controllable boat in Unity and I'm running into problems with my code.

1) I want to make the boat to accelerate and decelerate steadily instead of simply moving the speed I'm telling it to right away.

2) I want to make the player unable to steer the boat unless it is moving.

3) If possible, I want to simulate the vertical floating of a boat during its movement (it going up and down)

My current code (C#) is this:

```
using UnityEngine;
using System.Collections;

public class VehicleScript : MonoBehaviour {
public float speed=10;
public float rotationspeed=50;

// Use this for initialization
// Update is called once per frame
void Update () {

    // Forward movement
    if(Input.GetKey(KeyCode.I))
    speed =
    transform.Translate (Vector3.left*speed*Time.deltaTime);

    // Backward movement
    if(Input.GetKey(KeyCode.K))
        transform.Translate (Vector3.right*speed*Time.deltaTime);

    // Left movement
    if(Input.GetKey(KeyCode.J))
        transform.Rotate (Vector3.down*rotationspeed*Time.deltaTime);

    // Right movement
    if(Input.GetKey(KeyCode.L))
        transform.Rotate (Vector3.up*rotationspeed*Time.deltaTime);

}
}

```

In the current state of my code, when I press the specified keys, the boat simply moves 10 units/sec instantly, and also stops instantly. I'm not really sure how to make the things stated above, so any help would be appreciated. Just to clarify, I don't necessarily need the full code to implement those features, I just want to know what functions to use in order to achieve the desired effects.

Thank you very much.

# Answer
> 1 votes
Don't directly translate the object in response to key presses. Instead, increase the speed in response to key presses, and then translate the object's position using that speed. That way the speed changes every frame. pseudocode:

```
float speed = 0f;
float maxSpeed = 20f;
float accel = .2f;

void Update() {
  if (Input.GetKey(KeyCode.I)) {
    speed += accel;
  }
  if (speed > maxSpeed) {
    speed = maxSpeed;
  }
  transform.Translate(speed);
}

```

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


# Question
Title: Checking whether a specific key was pressed in enchantJS
I am using enchantJS and would like to use the letters and numbers as well as numpad on a keyboard to do different things (eg: hotkeys).

From this page http://users.csc.calpoly.edu/~foaad/enchant/guide/playerInput.html

> By default, enchant.js provides input listeners for six buttons: UP, DOWN, LEFT, RIGHT, A, and B. By default, the directions are bound to the arrow keys. Any of the six buttons may also be bound to any key with an ASCII value. We’ll address that later.

So enchant provides the ability to bind keys to different input such as up, down, left, right...but how can I simply check whether the `D` or `X` key was pressed, and if so, perform certain actions based on that event?

# Answer
> 2 votes
EnchantJS can bind **actions** to **keys**. Let's define both so we can get a deeper understand before we begin.

**Actions.** These are things you call "left" and "right". There is no actual "left" and "right" key. There are arrow keys, but these concepts of left and right are misleading. Let's think of this in a different context.

Think of the action "Jump" in a platformer game. When you want the player to jump, they need to press "JUMP".

**Keys** This is where keys come into play. What is a key? It's the thing on your keyboard you press -- a keycode. You assign these to actions.

**Putting it all together.** So, assign a keycode to an action.

```
game.keybind(32, 'jump');

```

By using this as a keybinding, I have declared 32 is jump. Now in my code, I can use:

```
if (game.input.jump)

```

To determine if I need to jump.

If you need to know what a specific keycode is, try this web page: http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes

---
Tags: input, keyboard, enchant.js
---


# Question
Title: How can I test if an oriented rectangle contains another oriented rectangle?
I have the following situation:

To detect whether is the red rectangle is inside orange area I use this function:

```
- (BOOL)isTile:(CGPoint)tile insideCustomAreaMin:(CGPoint)min max:(CGPoint)max {
    if ((tile.x < min.x) ||
        (tile.x > max.x) ||
        (tile.y < min.y) ||
        (tile.y > max.y)) {
        NSLog(@" Object is out of custom area! ");
        return NO;
    }
    return YES;
}

```

But what if I need to detect whether the red tile is inside of the blue rectangle? I wrote this function which uses the world position:

```
- (BOOL)isTileInsidePlayableArea:(CGPoint)tile {

    // get world positions from tiles
    CGPoint rt = [[CoordinateFunctions shared] worldFromTile:ccp(24, 0)];
    CGPoint lb = [[CoordinateFunctions shared] worldFromTile:ccp(24, 48)];
    CGPoint worldTile = [[CoordinateFunctions shared] worldFromTile:tile];

    return [self isTile:worldTile insideCustomAreaMin:ccp(lb.x, lb.y) max:ccp(rt.x, rt.y)];
}

```

How could I do this without converting to the global position of the tiles?

# Answer
Rectangles are convex polygons which makes this very easy.

To test whether a point lies within a convex polygon, check that it lies on the same "side" of all the edges of the polygon. Sketch this out to see how this is only possible if the point is inside. Here's the SO question for this: https://stackoverflow.com/questions/1119627/how-to-test-if-a-point-is-inside-of-a-convex-polygon-in-2d-integer-coordinates

To test whether a convex polygon lies within another convex polygon, simply perform the same point-inside-polygon test but repeat it for all the points of the first polygon.
> 0 votes

---
Tags: mathematics, objective-c
---


# Question
Title: How to implement a game launch counter in LibGDX
I'm writing a game using LibGDX in which I want to save the number of launches of a game in a text file. So, In the create() of my starter class, I have the following code ..but it's not working

```
public class MainStarter extends Game {

    private int count;

    @Override
    public void create() {
        // Set up the application
        AppSettings.setUp();
        if(SettingsManager.isFirstLaunch()){
            SettingsManager.createTextFileInLocalStorage("gamedata");
            SettingsManager.writeLine("gamedata", "Launched:"+count ,FileType.LOCAL_FILE );
        }
        else{
            SettingsManager.writeLine("gamedata", "Not First launch :"+count++ ,FileType.LOCAL_FILE );
        }

        //
        // Load assets before setting the screen
        // #####################################
        Assets.loadAll();

        // Set the tests screen
        setScreen(new MainMenuScreen(this, "Main Menu"));
    }
}

```

What is the proper way to do this?

# Answer
> 1 votes
I'm not sure what exactly the "SettingsManager" is, as you haven't provided any information on what it does internally. Normally for this kind of persistent data you would use Preferences to store it in a cross-platform manner. Something like the following code in your create() method:

```
Preferences prefs = Gdx.app.getPreferences("My Preferences");
int count = prefs.getInteger("RunCount", 0);
count++;
prefs.putInteger("RunCount", count);
prefs.flush();

```

# Answer
> 0 votes
To get the count of your game launch first make a LocalPreferences class and write following

```
public class LocalPreferencees{
    Preferences prefs;

    public LocalPreferencees() {
        prefs = Gdx.app.getPreferences("GAMECOUNT");
        }

     public void setCount (int count) {
        prefs.putInteger("COUNT",count);
        prefs.flush();
    }

    public int getCount() {
        return prefs.getInteger("COUNT",0);
    }
}

```

then in your create() method write following

```
@Override
public void create(){

    LocalPreferences preferences=new LocalPreferences();

   //this will get your game launch count
    int count=preferences.getCount();

    //now set the count
    prferences.setCount(count+1);

}

```

So each time when your game launches you will get the launchCount .

---
Tags: android, libgdx
---


# Question
Title: How can I obtain in-game data from Warcraft 3 from an external process?
I am implementing a behavior algorithm and would like to test it with my lovely Warcraft III game to watch how it will fight against real players.

The problem I'm having is that I don't know how to obtain information about in-game state (units, structures, environment, etc.) from the running WC3 game. My algorithm needs access to the hard drive and possibly distributed computing, that's why JASS (WC3's editor language) isn't appropriate; I need to run my algorithm from a separate process.

Direct3D hooking is an approach, but it wasn't done for WC3 yet and a significant drawback of that approach would be the inability to watch how the AI performs online, since it uses the viewport to issue commands.

How I read in-game data from WC3 in a different process in a fastest and easiest way?

Precisely what I need for Warcraft 3 exists for Starcraft: BWAPI.

# Answer
I see basically two ways you could solve this, but in both cases you'll need to utilize my SharpCraft project, which is a C# powerered way of injecting functionality into Warcraft III made by me, with research from a bunch of other people. Do note that the readme is outdated, but I'll do my best to help you out with the current release.

## Use JASS

This way you have easy access to the full JASS API, which allows you to fetch everything easily. What you do here is add some custom natives to the JASS API that help bridge the gap between JASS and your application. This could be natives that write to the hard disk or natives that send messages to your application.

## Use C#

This approach has the advantage that you can keep it in all C#, which is much more versatile than JASS, but you can't use natives that use strings. You have full access to the JASS API from C#, so you'll not lose out on any features.

There's a plugin included in the pack that shows the XML structure for plugins. To use the library, you add a reference to SharpCraft.dll, and then create a class that implements the FullPluginBase class. From there you have access to the different parts of the API.

```
public class MyPlugin : FullPluginBase
{
    public override void Initialize()
    {
        // This is a pretty cheap way to get into any map without the map needing to be coded for it.
        Script.PostMain = this.Script_PostMain;
    }

    private void Script_PostMain()
    {
        // Create a JASS trigger.
        var trigger = JassTrigger.Create();
        // Make the trigger run every .01 seconds, repeatedly.
        trigger.RegisterTimerEvent(0.01f, true);
        // Make the trigger call our Tick function when triggered.
        trigger.AddAction(new DelegateAction(this.Tick));
    }

    private void Tick(JassTrigger trigger)
    {
        // Do the stuff you want to do, using the JASS API or .NET API.
    }
}

```

I hope this gives you an idea of how to use it.
> 4 votes

---
Tags: ai, bot
---


# Question
Title: How to use lemodev highscore plugin for unity?
I am trying to add a server-sided highscore system to my game in unity. I have downloaded the free lemodev highscore plugin from the asset store but I cant figure out how to use it. I know where to put my server info and so on but other what are you supposed to do ? I added the main camera prefab that came with the package to my scene but other than adding an additional camera it did precisely nothing ( at least it seems that way ). Could anyone look into it and tell me how to use it ? The developer's website seems to have no information on the subject.

# Answer
> 0 votes
Just like with almost ANY unity3d package there is a file called read me.txt. This is where the general use and how to is explained. This file can be found after importing the package in the folder Assets/Highscore/readme. Pictures also seem to be included with this particular one

> 1. Import the package
> 2. Create database
> 3. Create table in database (use the file "create database table" - see picture 1)
> 4. Edit common.php (find them under PHP), use notepad or notepad++ to edit Change Host to your database location (e.g. MySql.Example.com), Change User to your database login name Change Pass to your database login password Change Databasename to your database name Change SecretKey to your secretKey in unity (see picture 2)
> 5. Upload the PHP folder to your server (crossdomain.xml must be placed in the root folder)
> 6. Go to Highscore, choose Scene, open Highscore
> 7. Under Main Camera - Highscore Script, change variables
>
> Secretkey must be the same as in the php script Locate files on server. (Important: add a questionmark at the end) Skin: you can keep the default or customize Get limit score: the number of scores you get back

Source: read me file included in the package

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


title: LibGDX . draw multiline text

text:
# Question
Title: LibGDX . draw multiline text
I am trying to write a big text using BitmapFont in libGDX . But it shows on one line and the user can see only the first part of the text . How can I make that bitmapFont made new line automatically and show whole text on the screen ?

# Answer
You should use BitmapFont.drawWrapped.

```
public BitmapFont.TextBounds drawWrapped(Batch batch,
                                     java.lang.CharSequence str,
                                     float x,
                                     float y,
                                     float wrapWidth)

```

All you need to do is set the `wrapWidth` variable as the maximum length of the line. In your case, this works better than `BitmapFont.drawMultiLine` because it automatically wraps rather than solely responding to `\n`.
> 3 votes

# Answer
**Write multiline text in LibGdx**

To write a multiline text with bitmapFont just use this following code-

```
String completeText= "In this text there are multi lines\n.To write this race in your game
                     \n you have to write in proper manner.
                     \nYou have to make the text look better .";

 font.drawMultiLine(
            batch,
            completeText,
             x,y,width,heigth, HAlignment.LEFT);

```

**Isn't is simple to write a multiline text.**
> 0 votes

---
Tags: java, android, libgdx
---


# Question
Title: Problem to match font size to the screen resolution in libgdx
I'm having problems to show text on my game at same size on different screens, and I did a simple test.

This test consists to show a text fitting at the screen, I want the text has the same size independently from the screen and from DPI.

I've found this and this answer that I think should solve my problem but don't. In desktop the size is ok, but in my phone is too big.

This is the result on my Nexus 4: (768x1280, 2.0 density)

And this is the result on my MacBook: (480x800, 0.6875 density)

I'm using the Open Sans Condensed (link to google fonts)

As you can see on desktop looks good, but on the phone is so big.

Here the code of my test:

```
public class TextTest extends ApplicationAdapter
{
    private static final String TAG = TextTest.class.getName();
    private static final String TEXT = "Tap the screen to start";

    private OrthographicCamera camera;
    private Viewport viewport;

    private SpriteBatch batch;
    private BitmapFont font;

    @Override
    public void create ()
    {
        Gdx.app.log(TAG, "Screen size: "+Gdx.graphics.getWidth()+"x"+Gdx.graphics.getHeight());
        Gdx.app.log(TAG, "Density: "+Gdx.graphics.getDensity());

        camera = new OrthographicCamera();
        viewport = new ExtendViewport(Gdx.graphics.getWidth(), Gdx.graphics.getWidth(), camera);
        batch = new SpriteBatch();

        FreeTypeFontGenerator generator = new FreeTypeFontGenerator(Gdx.files.internal("fonts/OpenSans-CondLight.ttf"));
        font = createFont(generator, 64);
        generator.dispose();
    }

    private BitmapFont createFont(FreeTypeFontGenerator generator, float dp)
    {
        FreeTypeFontGenerator.FreeTypeFontParameter parameter = new FreeTypeFontGenerator.FreeTypeFontParameter();

        int fontSize = (int)(dp * Gdx.graphics.getDensity());
        parameter.size = fontSize;

        Gdx.app.log(TAG, "Font size: "+fontSize+"px");

        return generator.generateFont(parameter);
    }

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

        int w = -(int)(font.getBounds(TEXT).width / 2);

        batch.setProjectionMatrix(camera.combined);
        batch.begin();
        font.setColor(Color.BLACK);
        font.draw(batch, TEXT, w, 0);
        batch.end();
    }

    @Override
    public void resize(int width, int height)
    {
        viewport.update(width, height);
    }

    @Override
    public void dispose()
    {
        font.dispose();
        batch.dispose();
    }
}

```

I'm trying to find a neat way to fix this. What I'm doing wrong? is the camera? the viewport?

UPDATE:

What I want is to keep the same margins in proportion, independently of the screen size or resolution. This image illustrates what I mean.

# Answer
> 16 votes
You seem to want to keep the same textsize/screensize ratio. Basically what you do is develop at one resolution and let that be scale 1.0. Then you divide the new screen width by the old width and that is your scale factor.

For example. Developing on 2560x1440 with font size 16 and running on 1920x1080.

Font size will be: 1920 * 16 / 2560 = 12

I do the same in my interface library and it works perfectly.

# Answer
> 3 votes
Don,t do any thing just set the scale of the font and it will work for all type of device

```
 font.setScale( .9f,.9f);

```

---
Tags: java, android, libgdx, fonts, aspect-ratio
---


# Question
Title: Transparent JPanel, Canvas background in JFrame
I wanna make canvas background and add some elements on top of it. For this goal I made JPanel as transparent container with setOpaque(false) and added it as first of JFrame container, then I added canvas with black background (in future I wanna set animation) to JFrame as second element.

But I can't undestand why i see grey background, not a black. Any suggestions?

```
public class Game extends JFrame {
    public Container container; //Game container with components
    public Canvas backgroundLayer; //Background layer of a game
    public JPanel elementsLayer; //elements panel (top of backgroundLayer), holds different elements

    private Dimension startGameDimension = new Dimension(800,600); //start game dimension

    public Game() {
        //init main window
        super("Astra LaserForces");
        setSize(startGameDimension);
        setBackground(Color.CYAN);
        container=getContentPane();
        container.setLayout(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //init jpanel elements layer
        elementsLayer=new JPanel();
        elementsLayer.setSize(startGameDimension);
        elementsLayer.setBackground(Color.BLUE);
        elementsLayer.setOpaque(false);
        container.add(elementsLayer);

        //init canvas background layer
        backgroundLayer = new Canvas();
        backgroundLayer.setSize(startGameDimension);
        backgroundLayer.setBackground(Color.BLACK); //set default black color
        container.add(backgroundLayer);

    }

    //start game
    public void start() {
        setVisible(true);

    }

    //create new instance of game and start it
    public static void main(String[] args) {
        new Game().start();
    }
}

```

# Answer
> 0 votes
`Container.add` doesn't stack components on top of each other -- it `appends` them according to the installed `LayoutManager`. Have a look at `JLayeredPane` instead to achieve the effect you're looking for.

But also consider just drawing everything in the `Canvas` directly (first the background, then the foreground) to avoid the whole Swing kitchen sink.

---
Tags: java
---


# Question
Title: How to solve the overlap between a rectangle and a circle that collide
I have two figures - a circle and a rectangle and i have a method that checks whether the two figures collide. How to prevent them from overlapping during collision?

# Answer
> 1 votes
One solution would be to use raycasting collision for the circles, and traditional box-collisions for rect-rect collisions.

# Answer
> 1 votes
if the speed of the objects is constant (or you can predict it accurately) you can check if they are going to collide, if yes don't move object (or move them so they touch side to side)

one other thing you can do is save previous location, calculate object's new location, if objects collide, move to previous location

---
Tags: collision-detection
---


title: libgdx get rotated sprite coords points

text:
# Question
Title: libgdx get rotated sprite coords points
I would like to get the position of each edge of a sprite when he has been rotated.

I have no idea how to do it, I made a image to explain it.

I would like to get **the X and Y position of each Red circles** please thanks you .

```
Sprite sprite = new Sprite(texture);
sprite.setRotation(-20);

```

# Answer
> 4 votes
To get the rotated sprites coordinate simply call the `getVertices()` method.

For example: `sprite.getVertices()[SpriteBatch.X2]`

Gets you the X coordinates of the top left corner.

The same call but replacing `X<number>` with `Y<number>` gets you the Y coordinate.

The corner numbers go like this:

```
2-3
| |
1-4

```

---
Tags: java, mathematics, libgdx, sprites, rotation
---


# Question
Title: how to define a field of view for the entire map for shadow?
I recently added "Shadow Mapping" in my XNA games to include shadows. I followed the nice and famous tutorial from "Riemers" : http://www.riemers.net/eng/Tutorials/XNA/Csharp/Series3/Shadow\_map.php .

This code work nice and I can see my source of light and shadow. But the problem is that my light source does not match the field of view that I created. I want **the light covers the entire map of my game.** I don't know why , but the light only affect 2-3 cubes of my map.

**ScreenShot**: (the emission of light illuminates only 2-3 blocks and not the full map)

**Here is my code i create the fieldOfView for LightviewProjection Matrix:**

```
Vector3 lightDir = new Vector3(10, 52, 10);
Vector3 lightPos = new Vector3(2, 52, 2);
Matrix lightsView = Matrix.CreateLookAt(lightPos, lightDir ,new Vector3(0, 1, 0));
Matrix lightsProjection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver2, 1f, 20f, 1000f);
lightsViewProjectionMatrix = lightsView * lightsProjection;

```

As you can see , my nearPlane and FarPlane are set to 20f and 100f . So i don't know why the light stop after 2 cubes. it's should be bigger

**Here is set the value to my custom effect HLSL in the shader file**

```
    /* SHADOW VALUE */

    effectWorld.Parameters["LightDirection"].SetValue(lightDir);
    effectWorld.Parameters["xLightsWorldViewProjection"].SetValue(Matrix.Identity * .lightsViewProjectionMatrix);
    effectWorld.Parameters["xWorldViewProjection"].SetValue(Matrix.Identity * arcadia.camera.View * arcadia.camera.Projection);
    effectWorld.Parameters["xLightPower"].SetValue(1f);
    effectWorld.Parameters["xAmbient"].SetValue(0.3f);

```

**Here is my custom HLSL shader effect file "\*.fx"**

```
    // This sample uses a simple Lambert lighting model.
float3 LightDirection = normalize(float3(-1, -1, -1));
float3 DiffuseLight = 1.25;
float3 AmbientLight = 0.25;
uniform const float3    DiffuseColor = 1;
uniform const float     Alpha = 1;
uniform const float3    EmissiveColor  = 0;
uniform const float3    SpecularColor = 1;
uniform const float     SpecularPower = 16;
uniform const float3    EyePosition;
// FOG attribut
uniform const float     FogEnabled  ;
uniform const float     FogStart ;
uniform const float     FogEnd ;
uniform const float3    FogColor ;
float3 cameraPos : CAMERAPOS;

texture Texture;

sampler Sampler = sampler_state
{
    Texture = (Texture);
    magfilter = LINEAR;
    minfilter = LINEAR;
    mipfilter = LINEAR;
    AddressU = mirror;
    AddressV = mirror;

};
texture xShadowMap;
sampler ShadowMapSampler = sampler_state
{
    Texture = <xShadowMap>;
    magfilter = LINEAR;
    minfilter = LINEAR;
    mipfilter = LINEAR;
    AddressU = clamp;
    AddressV = clamp;
};

/* *************** */
/* SHADOW MAP CODE */
/* *************** */
struct SMapVertexToPixel
{
    float4 Position     : POSITION;
    float4 Position2D    : TEXCOORD0;
};

struct SMapPixelToFrame
{
    float4 Color : COLOR0;
};
struct SSceneVertexToPixel
{
    float4 Position             : POSITION;
    float4 Pos2DAsSeenByLight    : TEXCOORD0;

    float2 TexCoords            : TEXCOORD1;
    float3 Normal                : TEXCOORD2;
    float4 Position3D            : TEXCOORD3;

};

struct SScenePixelToFrame
{
    float4 Color : COLOR0;
};
float DotProduct(float3 lightPos, float3 pos3D, float3 normal)
{
    float3 lightDir = normalize(pos3D - lightPos);
        return dot(-lightDir, normal);
}

SSceneVertexToPixel ShadowedSceneVertexShader(float4 inPos : POSITION, float2 inTexCoords : TEXCOORD0, float3 inNormal : NORMAL)
{
    SSceneVertexToPixel Output = (SSceneVertexToPixel)0;

    Output.Position = mul(inPos, xWorldViewProjection);
    Output.Pos2DAsSeenByLight = mul(inPos, xLightsWorldViewProjection);
    Output.Normal = normalize(mul(inNormal, (float3x3)World));
    Output.Position3D = mul(inPos, World);
    Output.TexCoords = inTexCoords;

    return Output;
}

SScenePixelToFrame ShadowedScenePixelShader(SSceneVertexToPixel PSIn)
{
    SScenePixelToFrame Output = (SScenePixelToFrame)0;

    float2 ProjectedTexCoords;
    ProjectedTexCoords[0] = PSIn.Pos2DAsSeenByLight.x / PSIn.Pos2DAsSeenByLight.w / 2.0f + 0.5f;
    ProjectedTexCoords[1] = -PSIn.Pos2DAsSeenByLight.y / PSIn.Pos2DAsSeenByLight.w / 2.0f + 0.5f;

    float diffuseLightingFactor = 0;
    if ((saturate(ProjectedTexCoords).x == ProjectedTexCoords.x) && (saturate(ProjectedTexCoords).y == ProjectedTexCoords.y))
    {
        float depthStoredInShadowMap = tex2D(ShadowMapSampler, ProjectedTexCoords).r;
        float realDistance = PSIn.Pos2DAsSeenByLight.z / PSIn.Pos2DAsSeenByLight.w;
        if ((realDistance - 1.0f / 100.0f) <= depthStoredInShadowMap)
        {
            diffuseLightingFactor = DotProduct(xLightPos, PSIn.Position3D, PSIn.Normal);
            diffuseLightingFactor = saturate(diffuseLightingFactor);
            diffuseLightingFactor *= xLightPower;
        }
    }

    float4 baseColor = tex2D(Sampler, PSIn.TexCoords);
        Output.Color = baseColor*(diffuseLightingFactor + xAmbient);

    return Output;
}

SMapVertexToPixel ShadowMapVertexShader(float4 inPos : POSITION)
{
    SMapVertexToPixel Output = (SMapVertexToPixel)0;

    Output.Position = mul(inPos, xLightsWorldViewProjection);
    Output.Position2D = Output.Position;

    return Output;
}

SMapPixelToFrame ShadowMapPixelShader(SMapVertexToPixel PSIn)
{
    SMapPixelToFrame Output = (SMapPixelToFrame)0;

    Output.Color = PSIn.Position2D.z / PSIn.Position2D.w;

    return Output;
}

/* ******************* */
/* END SHADOW MAP CODE */
/* ******************* */

/ For rendering without instancing.
technique ShadowMap
{

    pass Pass0
    {
        VertexShader = compile vs_2_0 ShadowMapVertexShader();
        PixelShader = compile ps_2_0 ShadowMapPixelShader();

    }
}

technique ShadowedScene
{
    /*
    pass Pass0
    {
        VertexShader = compile vs_2_0 VSBasicTx();
        PixelShader = compile ps_2_0 PSBasicTx();
    }
    */
    pass Pass1
    {
        VertexShader = compile vs_2_0 ShadowedSceneVertexShader();
        PixelShader = compile ps_2_0 ShadowedScenePixelShader();
    }

}
technique SimpleFog
{
    pass Pass0
    {
        VertexShader = compile vs_2_0 VSBasicTx();
        PixelShader = compile ps_2_0 PSBasicTx();
    }
}

```

**Draw Function:**

```
public void Draw(GameTime gameTime)
    {

        GraphicsDevice.SetRenderTarget(shadowMapRender);
        GraphicsDevice.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Microsoft.Xna.Framework.Color.Black, 1.0f, 0);

        // "ShadowMap" as technique param
        DrawWorld("ShadowMap");

        GraphicsDevice.SetRenderTarget(null);
        shadowMap = (Texture2D)shadowMapRender;
        GraphicsDevice.SetRenderTarget(null);

        GraphicsDevice.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Microsoft.Xna.Framework.Color.Black, 1.0f, 0);

        // "ShadowedScene" as technique param
        DrawWorld("ShadowedScene");

        shadowMap = null;
    }

```

I edited my fx file , for show you only information and functions about the shadow ;-)

**UPDATE : i tried with an orthagraphic matrix as we advice me, but still not work. i can no see the light and shadow**

```
Vector3 lightDir = new Vector3(10, 52, 10);
Vector3 lightPos = new Vector3(2, 52, 2);

Matrix lightViewMatrix = Matrix.CreateLookAt(lightPos, lightDir, Vector3.Up);

float minX = 0, maxX = 1000;
float minY = 50, maxY = 100;
float minZ = 0, maxZ = 1000;

Matrix lightProjectionMatrix = Matrix.CreateOrthographicOffCenter(minX, maxX, minY, maxY, minZ, maxZ);

lightsViewProjectionMatrix = lightViewMatrix * lightProjectionMatrix;

```

# Answer
> 1 votes
Perspective shadow maps like that are usually not used to shadow the whole scene, but for a single lamp or flashlight.
If you want to shadow the whole scene, You probably don't want to use perspestive shadow maps, but rather orthographic ones (I guess you want shadows from the sun?). When you are creating an othographic matrix (MSDN) you specify its dimensions, like a cube (because it will project everything in that cube). I guess it is easy from there to calculate its required size. It's even better for sunlight for an other reason, too, because shadows generated from that will look like they have been generated from a light source which is infinitely far away (or as far away as the sun).
If you shadow a whole scene like that, probably one shadow map will not be sufficient (or efficient), so when you got it working with one, you should look into cascaded shadow maps then.

---
Tags: xna, shadows, shadow-mapping, lighting
---


# Question
Title: How can I quickly determine whether objects are onscreen in 2D?
Currently, I have this in each object's renderer's update method:

```
        float a = transform.position.x * Main.scale;
        float b = transform.position.y * Main.scale;
        float c = Camera.main.transform.position.x * Main.scale;
        float d = Camera.main.transform.position.y * Main.scale;
        onscreen = a + width - c > 0 &&
                a - c < GameView.width &&
                b + height - d > 0 &&
                b - d < GameView.height;

```

`transform.position` is a 2D vector containing the game engine's definition of where the object is. This is then multiplied by `Main.scale` to translate that coordinate into actual screen space.

Similarly, `Camera.main.transform.position` is the in-engine representation of where the main camera is, and this is also multiplied by `Main.scale`.

The problem is, as my game is tile-based, thousands of these updates get called every frame, just to determine whether or not each object should be drawn. How can I do this more efficiently, please?

# Answer
With just a couple of slight rearrangements, you could have:

```
float a = (transform.position.x - Camera.main.transform.position.x) * Main.scale;
float b = (transform.position.y - Camera.main.transform.position.y) * Main.scale;

onscreen = a > -width && a < GameView.width
    && b > -height && b < GameView.height;

```

It will save you a few calculations, but wont really make a big performance difference I think. Another way would be to do the reverse of the scaling. Instead of calculating the scaling for each tile each time, you can calculate the reverse for the camera and GameView positions, whenever they chance. This happens one time per frame at most, while the tiles take N\_TILES per frame calculations. So reformulating the code, it could be something like this:

```
float a = transform.position.x - ScaleCamera.x;
float b = transform.position.y - ScaleCamera.y;

onscreen = a > -width && a < ScaledGameView.width
    && b > -height && b < ScaledGameView.height;

```

A perhaps more efficient way to do it is by blocks. Make a set of say 10x10 tiles be in a block. Now calculate for the block as a whole if it should appear on the screen, considering it's greater dimension. If it does, you can either draw all the tiles, or refine what you show or not from there. You can later change the size of each block to make your needs, making them larger if it's needed, so you can quickly jump big blocks of tiles.

So, given that I don't know how your code is, you could have something like this:

```
class TileBlock {
    int x, y, w, h; // defines the area of the block
    Vector<Tile> tiles;

    public boolean isInsideBlock(Tile tile) {
        if inside area
            return true

        return false
    }

    public boolean add(Tile tile) {
        if isInsideBlock(tile)
            add tile to tiles
            return true

        return false
    }

    public Vector<Tile> getTiles() {
        return tiles;
    }

    ... etc ...
}

```

Then on tile creation, you can have either try to directly add to the blocks until it returns true, or you could make it more elegantly, and have a TileManager or TileBlocksManager, to handle that for you. So then:

```
for(Tile tile : tiles)
    blocksManager.add(tile)

```

And on rendering:

```
blocks = blocksManager.getVisibleBlocks(Camera camera, GameView gameView)
for(TileBlock block : blocks) {
    Vector<Tile> tiles = block.getTiles()
    for(Tile tile : tiles) {
        do what you need to do
    }
}

```

On a side note, too big blocks will mean that if a block is accepted for refining/showing, then you will have to process all the small tiles inside. So be wise when picking a number, don't make it too small or it's pointless the work and time you spend, but don't be greedy and make huge blocks as well.

I hope this gives some ideas.
> 1 votes

# Answer
Keep an "on-screen tiles" collection that you update each time the camera moves and each tile has a reference to the objects in it. This was you only need to update the objects referenced by the tiles that are on screen (or just outside).
> 2 votes

---
Tags: 2d, optimization, visibility-determination
---


title: Structure gameobjects and call events

text:
# Question
Title: Structure gameobjects and call events
I'm working on a 2D tile based game in which the player interacts with other game objects (chests, AI, Doors, Houses etc...). The entire map will be stored in a file which I can read. When loading the tilemap, it will find any tile with the ID that represents a gameobject and store it in a hashmap (right data structure I think?).

```
    private static HashMap<Integer, Class<GameObject>> gameObjects = new HashMap<Integer, Class<GameObject>>();

```

How exactly would I go about calling, and checking for events? I figure that I would just call the update, render and input methods of each gameobject using the hashmap.

Should I got towards a Minecraft/Bukkit approach (sorry only example I can think of), where the user registers an event, and it gets called whenever that event happens.

Or should I just loop through the entire hashmap looking for an event that fits?

I'm using Java and LWJGL.

Thanks waco

# Answer
> 1 votes
I think that a entity would register a listener with whatever was firing the events that entity wanted (much the way you register event listeners to swing components). The entity that was firing events would just make a ArrayList or similar of all the listeners registered to it and whenever it wanted to fire events, it would just iterate through the list calling the actionPerformed (or similar) functions on each one. This has the benefit that it is fairly straightforward to make run asynchronously if you wanted to, say, run a pathing algorithm as soon as a sort of event is received.

---
Tags: java, tilemap, lwjgl, events
---


# Question
Title: How to synchronize the ball in a network pong game?
I’m developing a multiplayer network pong game, my first game ever. The current state is, I’ve running the physic engine with the same configurations on the server and the clients. The own paddle movement is predicted and get just confirmed by the authoritative server. Is a difference detected between them, I correct the position at the client by interpolation. The opponent paddle is also interpolated 200ms to 100ms in the past, because the server is broadcasting snapshots every 100ms to each client.

So far it works very well, but now I have to simulate the ball and have a problem to understanding the procedure.

I’ve read Valve’s (and many other) articles about fast-paced multiplayer several times and understood their approach. Maybe I can compare my ball with their bullets, but their advantage is, the bullets are not visible. When I have to display the ball, and see my paddle in the present, the opponent in the past and the server is somewhere between it, how can I synchronize the ball over all instances and ensure, that it got ever hit by the paddle even if the paddle is fast moving? Currently my ball’s position is simply set by a server update, so it can happen, that the ball bounces back, even if the paddle is some pixel away (because of a delayed server position).

Until now I’ve got no synced clock over all instances. I’m sending a client step index with each update to the server. If the server did his job, he sends the snapshot with the last step index of each client back to the clients. Now I’m looking for the stored position at the returned step index and compare them. Do I need a common clock to sync the ball?

**EDIT:**
I've tried to sync a common clock for the server and all clients with a timestamp. But I think it's better to use an own stepping instead of a timestamp (so I don't need to calculate with the ping and so on - and the timestamp will never be exact). The physics are running 60 times per second and now I use this for keeping them synchronized. Is that a good way?

When the ball gets calculated by each client, the angle after bouncing can differ because of the different position of the paddles (the opponent is 200ms in the past). When the server is sending his ball position, velocity and angle (because he knows the position of each paddle and is authoritative), the ball could be in a very different position because of the different angles after bouncing (because the clients receive the server data after 100ms). How is it possible to interpolate such a huge difference?

I posted this question some days ago at stackoverflow, but got no answer yet. Maybe this is the better place for this question.

# Answer
The ball, by pretty much the law of Pong and physics must either be going towards player one, or player two, not both.

You could use this to switch interpolation priority between the two players. When the ball is heading towards player **one** then use player one to synchronise your information, as he is the only one that can affect the outcome of if the ball manages to either bounce in the opposite direction or score for player two.

Once the ball starts bouncing in the opposite direction (either because player one succeeded to hit it or player two scored and the next round began) you can then use player **two** to synchronise your information with. Which ever player has to interact with the ball next, is the player that should report where they and the ball are. This way the lag is only significant against the player who doesn't need the accuracy at that time.
> 3 votes

# Answer
If your physics are deterministic, could you not broadcast a ball-bounce event, giving a position of the ball and similar statistics, and a step count?

Whilst the ball is in the air the server shouldn't need to keep sending its position, again, if you are using a deterministic model.
> 0 votes

---
Tags: networking, multiplayer, interpolation, synchronization
---


title: Collision detection problem in XNA

text:
# Question
Title: Collision detection problem in XNA
I'm having two problems with my collision detection in XNA. There are two boxes, the red box represents a player and the blue box represents a wall.

The first problem is when the player moves to the upper side or bottom side of the wall and collides with it, and then try to go to the left or right, the player will just jump in the opposite direction as seen in the video.

However if I go to the right side or the left side of the wall and try to go up or down the player will smoothly go up or down without jumping.

The second problem is that when I collide with the box and my key is still pressed down the blue box goes half way through red box and and goes back out and it keeps doing that until I stop pressing the keyboard. its not very clear on the video but the keeps going in and out really fast until I stop pressing the key.

Here is a video example:- http://www.youtube.com/watch?v=mKLJsrPviYo

and Here is my code

```
Vector2 Position;
Rectangle PlayerRectangle, BoxRectangle;
float Speed = 0.25f;

enum Direction { Up, Right, Down, Left };
Direction direction;

protected override void Update(GameTime gameTime)
{
    // Allows the game to exit
    if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
        this.Exit();

    KeyboardState keyboardState = Keyboard.GetState();

   if (keyboardState.IsKeyDown(Keys.Up))
   {
       Position.Y -= (float)(Speed * gameTime.ElapsedGameTime.TotalMilliseconds);
       direction = Direction.Up;
   }

   if (keyboardState.IsKeyDown(Keys.Down))
   {
       Position.Y += (float)(Speed * gameTime.ElapsedGameTime.TotalMilliseconds);
       direction = Direction.Down;
   }

   if (keyboardState.IsKeyDown(Keys.Right))
   {
       Position.X += (float)(Speed * gameTime.ElapsedGameTime.TotalMilliseconds);
       direction = Direction.Right;
   }

   if (keyboardState.IsKeyDown(Keys.Left))
   {
        Position.X -= (float)(Speed * gameTime.ElapsedGameTime.TotalMilliseconds);
        direction = Direction.Left;
    }

    if (PlayerRectangle.Intersects(BoxRectangle))
    {
         if (direction == Direction.Right)
             Position.X = BoxRectangle.Left - PlayerRectangle.Width;
         else if (direction == Direction.Left)
             Position.X = BoxRectangle.Right;

         if (direction == Direction.Down)
             Position.Y = BoxRectangle.Top - PlayerRectangle.Height;
         else if (direction == Direction.Up)
             Position.Y = BoxRectangle.Bottom;
     }

     PlayerRectangle = new Rectangle((int)Position.X, (int)Position.Y, (int)32, (int)32);

     base.Update(gameTime);
}

```

# Answer
Look again at your else/ifs:

* regardless of key combination pressed, only **ONE** direction is saved, because you override them. (the last of them in code)
* if left/right direction is pressed collision from the other side(right/left) is always assumed. (if (direction == Direction.Right) =\> move player to left side regardless where he is)

quick fix: add another direction, so you have one for left/right other for top/down and check from collisions from both directions separately(own intersect code).
> 1 votes

# Answer
What you want to do is test *how far* the rectangle can move in a direction, then change it. For example:

```
desiredX += speedX * timeSinceLastUpdate;
desiredY += speedY * timeSinceLastUpdate;

desiredRect = new Rectangle(desiredX, desiredY, width, weight);
intersect = Rectangle.Intersect(desiredRect, collider);
collisionWidth = intersect.Width;
collisionHeight = intersect.Height;
correctedX = 0;
correctedY = 0;
// using speed's sign as the direction of travel
//     and correcting in the opposite direction...
if (collisionWidth > 0)
    correctedX = Math.Sign(speedX) * collisionWidth;
if (collisionHeight > 0)
    correctedY = Math.Sign(speedY) * collisionHeight;
PlayerRectangle = new Rectangle(desiredX - correctedX, desiredY - correctedY, width, weight);

```
> 1 votes

---
Tags: xna
---