title: Calculate laser bounce inside polygon

text:
# Question
Title: Calculate laser bounce inside polygon
I am trying to calculate the reflection of a laser within a polygon. My current calculations are probably quite long-winded because I'm building on line intersection and other functions. The problem is that I'm using a point (x,y) with velocity(x,y) and trying to calculate where the point is after each reflection off a line - this is a problem because when the point reflects within very small corners I can't seem to calculate the final location and velocity of the laser point.

Is there a well known algorithm for calculating laser reflection in 2D within polygons?

Note: I would post my code but as stated above it's extremely long ATM.

My general logic is:

```
Call method with particle {x,y,velocity={x,y}}
Begin loop
  Check for intersections
  If no intersections then exit
  Get closest intersection to particle
  Update particle location, direction and velocity
End loop
Refresh particle velocity (to maintain speed)
Return particle

```

I was hoping there something a bit more concise for this (basic?) math problem.

# Answer
One approach to simplifying this is to spawn new lasers instead of trying to work out reflection points on single beams.

E.g.

Here the red laser shot is moving out of the rectangle, and we detect this by testing intersection on each boundary of our rectangle. Since we have detected that it's moving out (And therefore hit a reflective surface) we place a new laser beam at a point that intersects with the reflective surface and the red laser. We place it such that the correct amount of laser is discarded outside the boundary.

For clarity in the diagram, our new reflection is green.

Immediately, we test the new laser for intersection on the other boundaries and if it too intersects we spawn a third (Blue in our example) and so on until we have no intersections with new boundaries.

In this way we can support multiple reflections on single updates.

To render, clip all lasers to the boundary object and discard forever any which have moved completely outside.

I'd imagine that a variant of this approach could be figured out for solid beams and not the 'shot' type blaster lasers described here.
> 2 votes

# Answer
I had a similar problem in some other code I wrote. Didn't find a pre-written algorithm with my (admittedly quick) search. This was in python, so this might not be too helpful for you.

Firstly, I stored my line to test as a point and an angle. This made a lot of the calculations easier, and let me put the math library to good use.

My intersection test function returned a point, though in your case it would also need to return another angle. In the case of multiple reflections the following pattern may be useful:

```
getNextLine(line, polygon, n = maxReflections)
   if n = 0: return line #Max number of tests reached
   next = intersection(line, polygon)
   if next = None:
       return line
   else:
       return getNextLine(next, n-1)

```

In this case intersection would be your ready-made intersection finder. (I assumed it returns None if there is no intersection)

One thing to watch out, that got me, is that you can end up with multiple intersections and need to make sure you pick the closest.

Without knowing more about your application I can't really say much more, hope this helps.
> 0 votes

---
Tags: 2d, physics, geometry
---


title: C#Script select GameObject

text:
# Question
Title: C#Script select GameObject
I want to load the prefab instead of the gameobject that is in the screen, my code is this one:

```
using UnityEngine;
using System.Collections;

public class Arma : MonoBehaviour {

public static int municao;
GameObject bullet;
GUIText texto;
// Use this for initialization
void Start () {
    bullet = GameObject.Find("Bullet");
    municao = 10;
    texto = GameObject.Find ("qtdMunicao").GetComponent<GUIText>() as GUIText;
}

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

    texto.text = municao.ToString ();

    if(Input.GetKeyDown("i"))
    {
        if(municao > 0)
        {
            Instantiate(bullet, transform.position, transform.rotation);
            municao--;
        }
    }
}

```

} \`

# Answer
> 2 votes
The equivalent code in C# is

```
public GameObject object;

```

---

referring to your additional edits:

Your code will instantiate whatever object is referenced in the "bullet" variable, so just make sure to stick the object you want in there. In your case, it sounds like what you want is delete the GameObject.Find() line for "bullet" and instead drag-and-drop the prefab asset; in the editor, drag the prefab from the Project view over to the Inspector.

# Answer
> 0 votes
The "roll it yourself" way ...

```
public class Gun : MonoBehaviour
{
   public List<GameObject> bullets;

   void Start()
   {
      var bullet = new GameObject();
      bullets.add(bullet);
      something.AddComponent<BulletBehaviour>();
   }
}

```

The "load something I already configured" way ...

```
public class MyThing : MonoBehaviour
{
   public Transform bulletPrefab;
   public List<GameObject> bullets;

   void Start()
   {
      bullets.Add(Instantiate(bulletPrefab) as Bullet);
   }
}

```

EDIT: Based on your change of question (not recommended by the way) I would say that what you should do is declare a new variable of type Transform and in unity (before running) drop your bullet prefab on to that in the inspector.

That gives unity a reference to the asset not some instance of an object. You can then call instantiate on the ref ...

```
using UnityEngine;
using System.Collections;

public class Arma : MonoBehaviour {

  public static int municao;
  //GameObject bullet;
  Transform bulletPrefab; // set this in the unity editor before runtime
  GUIText texto;
  // Use this for initialization
  void Start () {
    //bullet = GameObject.Find("Bullet");
    municao = 10;
    texto = GameObject.Find ("qtdMunicao").GetComponent<GUIText>() as GUIText;
  }

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

    texto.text = municao.ToString ();

    if(Input.GetKeyDown("i"))
    {
        if(municao > 0)
        {
            Instantiate(bulletPrefab, transform.position, transform.rotation);
            municao--;
        }
    }
  }
}

```

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


# Question
Title: How to Calculate Velocity in a 2D space game
I am currently using

```
screenpos.X = (float)(screenpos.X + velocity * Math.Sin(r));
screenpos.Y = (float)(screenpos.Y - velocity * Math.Cos(r));

```

For my Movement with r being the Rotation in Radians. However, I want to know how I can calculate my velocity realistically based on values of Thrust and Mass.

Any Idea's?

# Answer
> 3 votes
First off, you'll likely have an easier time using vectors for this instead of a float value with rotation separately. (The name `velocity` implies speed and direction, you appear to only be storing a speed and keeping your direction in your `r` value).

Next thing you'll want to acceleration. This will be the change in velocity over time. This is where you'll want to apply your changes to move your object.

So what acts on acceleration? Forces. Forces like gravity and thrust. Force is calculated with F=MA. In this equation you have all the things you want. Mass is the mass of your ship and force is the output of the thruster. Since you want to calculate an acceleration, you can rearrange things to A=F/M. This means each thruster will have a force (a scaled directional vector) and each ship will have a mass. To calculate the acceleration change of that thruster, simply take its force and divide it by the mass of the ship.

There's actually a lot more too this if you want "realistic" values. That's a bit too much to explain here. This should get you started and then you can ask more specific questions as you implement things.

# Answer
> 2 votes
As Fault pointed out, use Newton's second law. Every time-step set your acceleration based on your thrust force (F):

```
a.X = F * Math.Sin(r);
a.Y = F * Math.Cos(r);

```

Then update your velocity:

```
v.X = v.X + a.X * dt;
v.Y = v.Y + a.Y * dt;

```

Finally, update your new position:

```
screenpos.X = screenpos.X + v.X * dt;
screenpos.Y = screenpos.Y + v.Y * dt;

```

dt is the time between two updates. This will give you a realistic behavior including inertia.

---
Tags: c#, xna-4.0, physics
---


title: MSAA deferred implementation issue

text:
# Question
Title: MSAA deferred implementation issue
I recently implemented MSAA in my deferred renderer, it looks good but I just got a feeling I might have done it wrong.

Here is what for example the directional light fragment shader looks like:

```
const float DEPTH_BIAS = 0.00005;                                                                                \n \
                                                                                \n \
layout(std140) uniform UnifDirLight                                                                                \n \
{                                                                                \n \
    mat4 mVPMatrix[4];                                                                                \n \
    mat4 mCamViewMatrix;                                                                                \n \
    vec4 mSplitDistance;                                                                                \n \
    vec4 mLightColor;                                                                                \n \
    vec4 mLightDir;                                                                                \n \
    vec4 mGamma;                                                                                \n \
    vec2 mScreenSize;                                                                                \n \
    int mNumSamples;                                                                                \n \
} UnifDirLightPass;                                                                                \n \
                                                                                \n \
layout (binding = 2) uniform sampler2DMS unifPositionTexture;                                                                   \n \
layout (binding = 3) uniform sampler2DMS unifNormalTexture;                                                                     \n \
layout (binding = 4) uniform sampler2DMS unifDiffuseTexture;                                                                    \n \
layout (binding = 6) uniform sampler2DArrayShadow unifShadowmap;                                                                \n \
                                                                                \n \
out vec4 fragColor;                                                                                \n \
                                                                                \n \
void main()                                                                                \n \
{                                                                                \n \
    ivec2 texcoord = ivec2(textureSize(unifDiffuseTexture) * (gl_FragCoord.xy / UnifDirLightPass.mScreenSize));                 \n \
                                                                                \n \
    vec3 worldPos = vec3(0.0), normal = vec3(0.0), diffuse = vec3(0.0);                                                         \n \
    for (int i = 0; i < UnifDirLightPass.mNumSamples; i++)                                                                      \n \
    {                                                                                \n \
        worldPos += texelFetch(unifPositionTexture, texcoord, i).rgb;                                                           \n \
        normal   += texelFetch(unifNormalTexture, texcoord, i).rgb;                                                             \n \
        diffuse  += texelFetch(unifDiffuseTexture, texcoord, i).rgb;                                                            \n \
    }                                                                                \n \
    worldPos /= UnifDirLightPass.mNumSamples;                                                                                \n \
    normal   /= UnifDirLightPass.mNumSamples;                                                                                \n \
    diffuse  /= UnifDirLightPass.mNumSamples;                                                                                \n \
    normal = normalize(normal);                                                                                \n \
                                                                                \n \
    vec4 camPos = UnifDirLightPass.mCamViewMatrix * vec4(worldPos, 1.0);                                                        \n \
                                                                                \n \
    int index = 3;                                                                                \n \
    if (camPos.z > UnifDirLightPass.mSplitDistance.x)                                                                           \n \
        index = 0;                                                                                \n \
    else if (camPos.z > UnifDirLightPass.mSplitDistance.y)                                                                      \n \
        index = 1;                                                                                \n \
    else if (camPos.z > UnifDirLightPass.mSplitDistance.z)                                                                      \n \
        index = 2;                                                                                \n \
                                                                                \n \
    vec4 projCoords = UnifDirLightPass.mVPMatrix[index] * vec4(worldPos, 1.0);                                                  \n \
    projCoords.w    = projCoords.z - DEPTH_BIAS;                                                                                \n \
    projCoords.z    = float(index);                                                                                \n \
    float visibilty = texture(unifShadowmap, projCoords);                                                                       \n \
                                                                                \n \
    float angleNormal = clamp(dot(normal, UnifDirLightPass.mLightDir.xyz), 0, 1);                                               \n \
                                                                                \n \
    fragColor = vec4(diffuse, 1.0) * visibilty * angleNormal * UnifDirLightPass.mLightColor;                                    \n \
}                                                                                \n";

```
1. I average the position/normals/diffuse before light and shadow calculations, but I just realised perhaps I should average the computed results instead. Which one is correct?
2. Right now I'm using hardware PCF for my shadows. Since I'm fetching several samples anyway for MSAA, couldn't I use that for shadow filtering aswell? Any downsides?

# Answer
To be correct, lighting calculations should be carried out separately for each surface contained in a pixel, then the results should be averaged. For instance, think about the silhouette edge of an object, which contains some samples from the object and some other samples from whatever's behind it. If you simply averaged the positions, normals, etc. of all samples, you'd be lighting a surface that didn't exist, halfway between the object and the background.

One easy but slow way to do correct deferred lighting with MSAA is to run the lighting shaders at per-sample rate, which can be done with the ARB\_sample\_shading GL extension.

However, the majority of pixels on screen have only one visible surface in them and therefore don't need separate shading results for each subpixel sample. Some approaches to deferred MSAA try to detect which pixels contain multiple surfaces (by using heuristics based on depth, for instance) and perform per-sample shading only for those pixels - e.g. by marking them in the stencil buffer, and using stencil test to limit the per-sample shading. A simpler shader that only shades once per pixel can then be used for all other pixels on screen. Doing deferred MSAA efficiently is still an open problem that is being researched.
> 3 votes

---
Tags: opengl, c++, deferred-rendering, antialiasing
---


title: Tons of stuttering in XNA?

text:
# Question
Title: Tons of stuttering in XNA?
As stated in the title, my program stutters like crazy, even though my program for the most part runs for 60 fps. During the moments it stutters, FPS momentarily drops down to 59(stats from FRAPS).

Here is an video capture of the stuttering in action. If you look closely, you can see the game stutter around 3-4 times. It is much more noticeable in real life.

http://gfycat.com/SevereCanineBabirusa

CLR Profiler shows that garbage collection doesn't run at all during that time, never mind 4 times, so it's not that.

Here's the code for movement:

```
            //Movement logic
            //Increase the speed
            speed = Math.Min(speed + (speedIncrement * (gameTime.ElapsedGameTime.Milliseconds / 200.0f)), maxSpeed);

            for (int i = fruits.Count - 1; i >= 0; i--)
            {
                //Move the fruits
                fruits[i].pos.Y += speed * gameTime.ElapsedGameTime.Milliseconds;
                fruits[i].rect.Y = (int)fruits[i].pos.Y;
                //Check if the fruit is past the screen. If it is, remove it from fruits
                if (fruits[i].rect.Y > screenHeight)
                {
                    fruits.Remove(fruits[i]);
                }
            }

```

IsFixedTimeStep is set to false, but SyncronizeWithVerticalTrace is on. Any idea what could be the cause of the stuttering?

EDIT: Apparently it was a combination of this: http://answers.microsoft.com/en-us/windows/forum/windows\_7-performance/presentationfontcacheexe-uses-50-of-my-cpu/4200fe85-458f-4f19-b791-1fe5395304da and f.lux eating up my CPU/GPU cycles.

# Answer
> 1 votes
Try using Stopwatch to capture a start and end time at the beginning and end of your Update method to find an average time spent in Update. Then, add a branch to a breakpoint when the time exceeds the average by some threshold and take a look at the program state at that time.

You might consider recycling your objects by moving them to a pool, instead of simply forgetting about them altogether. While it probably isn't the GC interrupting the flow, it worth checking out.

Also, try building the game in Release mode instead of Debug, if you haven't done so already.

# Answer
> 0 votes
Set `IsFixedTimestep = false`. But in doing so, you'll need to consider Shawn Hargreaves' explanation first: http://xboxforums.create.msdn.com/forums/p/9934/53561.aspx#53561.

---
Tags: xna, monogame
---


# Question
Title: Checking if a vector is contained inside a viewing frustum
I have a three dimensional pyramid given by four vectors **a**, **b**, **c**, **d** and want to test if a given vector **x** is inside that region or not. Here is an image:

A related question can be found here: 2D problem.

How can I test to see if the vector is contained by the others?

# Answer
Think of your frustum as a set of planes defined by three vectors each. In your case, 5 planes (left, right, top, bottom, far). A typical frustum has 6 (near, far, left, right, top, bottom)

Take the dot product of each plane's normal with the point's location to get the distance of that point from that plane. If the distance is greater than zero, it's in *front* of the plane. If it's less, it's in back.

If all the plane's normals are oriented toward the centre of the frustum, then the point should be *in front* of all of them. That would indicate the point is inside. Otherwise it's outside the frustum.

If the normals are pointed out, then it would be *in back*. So if it isn't in back of all the planes, then it would be outside the frustum.

The normals of the planes will be determined by the winding order of your frustum's vertices. ABC -\> normal "out," CBA -\> normal "in." Just be sure that you always use the same winding order for plane vertices and everything will be okay.
> 6 votes

# Answer
First bit is to get a model of the pyramid's bottom rectangle R. Define

**u** = **b** \- **a** = (b1 - a1, b2 - a2, b3 - a3)

**v** = **c** \- **a** = (c1 - a1, c2 - a2, c3 - a3)

If the bottom is really flat then the equation

**d** = **u** \+ **v**

should hold (otherwise vector **d** is ignored).

The rectangle R is defined by

R = { **y** | **y** = **a** \+ α **u** \+ β **v** ∧ 0 ≤ α ≤ 1 ∧ 0 ≤ β ≤ 1 }

To test for the whole pyramid, one can scale R along **a**, meaning moving the rectangle along the vector **a**, giving a scaled rectangle R'.

**u'** = f (**b** \- **a**)

**v'** = f (**c** \- **a**)

**x'** = **x** \- f **a**

with 0 ≤ f ≤ 1. This leads to the equation

(**x** \- f **a**) = f α **u** \+ f β **v**

-**a** = α **u** \+ β **v** \+ t (-**x**)

**y** = **A**^-1 **b**

with **A** = (**u**; **v**; -**x**), **b** = -**a** and **y** = (α, β, 1/f).
> 3 votes

---
Tags: 3d, intersection
---


title: Load Prefab to variable

text:
# Question
Title: Load Prefab to variable
I have my code, for my weapon:

```
using UnityEngine;
using System.Collections;

public class Arma : MonoBehaviour {

    public static int municao;
    GameObject bullet;
    GUIText texto;
    // Use this for initialization
    void Start ()
    {

        //bullet = GameObject.Find("Bullet");
        municao = 10;
        texto = GameObject.Find ("qtdMunicao").GetComponent<GUIText>() as GUIText;
    }

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

        texto.text = municao.ToString ();

        if(Input.GetKeyDown("i"))
        {
            if(municao > 0)
            {
                Instantiate(bullet, transform.position, transform.rotation);
                municao--;
            }
        }
    }
}

```

\`

How can i load the prefab to my variable to use in my instantiate?

# Answer
> 2 votes
You can use the `Load` method from the Resources API:

```
// Instantiates a prefab named "enemy" located in any Resources
// folder in your project's Assets folder.
void Start()
{
    GameObject instance = Instantiate(Resources.Load("enemy", typeof(GameObject)));
}

```

# Answer
> 0 votes
You can drag-and-drop objects from the Project view just as you would in the main scene, linking them to variables in the Inspector.

That is, click-and-drag the prefab asset in the Project view, and then drop it onto the variable in the Inspector.

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


title: AI and shapes in 2D Grid

text:
# Question
Title: AI and shapes in 2D Grid
I'm working on a grid- and turn-based strategy rpg. My problem is concerning finding best position for my AI to use a skill. But lets start at the beginning.

My plan is to make each skill an action for my AI. It checks for each action how effective it would be, chooses the best and does it.

Each skill has a usage and a affect area that can be circular or shapes like

```
[
 [1,1,1,1,1],
 [0,1,1,1,0],
 [0,0,1,0,0]
]

```

which can be used in 4 directions.

The most simple solution would be to just check the affect area for each position and direction of the movable and usage area. But as these checks can get quite intensive I want to minimize them as far as possible.

One approach would be to combine the circular movement area with the skills usage and affect areas and find all target entities in it. So I have a list of all entities that could be targeted by the skill. The next step would be to group these entities by the skills affect area to rate it higher when the skill hits multiple targets. And as the new position and direction should get into that rating as well I have to check all possible positions for each group. And I've no idea on how to effectively do that.

1) Does this AI approach makes sense?

2) Is there a better way to define such grid-shapes and apply them to the checks later on?

3) Any ideas on how to group the targets by the skills usage area or minimize the positions and directions to check by the knowledge of where the target entities are?

Thanks for reading!

EDIT: After this is not going to get answered I have to ask another question: Am I bad in asking for help? In the 10 year's I'm developing now there were like five times were I really couldn't get further without a tip. But unless which way I try to ask for help (in the internet, asking the few developers I know or someone outside of the industry for understanding problems) I've never got any. To be fair I'm only coming with real problems after being stuck for days. But as I see the internet full of perfectly answered questions I begin to think: Is that my fault? What makes this question not worthy for an answer?

# Answer
> 1 votes
Is it really fun to play against an AI that is "perfect"? Perhaps better is to randomly sample N configurations, and choose the best one out of those N. Here, choose N such that the computation is not too intensive.

You can of course make a hybrid solution: For every skill, try N random choices, or something like that. You can make the choices "better" by perhaps making it more likely that you are close to something you want to hit (but this depends of course on what information you have available).

# Answer
> 0 votes
This is a quite complex problem, are you sure you need to optimize this (how big are the areas?), One options is to generate a 2d array for each power (note different orientations = different powers)and use it to store how many chars you can hit if you target that position. You can calculate this by picking each character and then increasing each position that could hit that character by one. You then keep track of the best square and target that when you have checked each position.

So

```
int[][] hit
    for each char
          for each power
                for each tile hit by power
                      hit[tilex][tiley]++
                           if(biggest(hit[tilex][tiley]))
                                 temphighest=tile
target temphighest

```

---
Tags: 2d, ai, grid
---


# Question
Title: How to get the normal that points *out* of a polygon
In 2D, each vector (x, y) has two normals: (-y, x) and (y, -x), pointing in opposite directions.

Say I have a polygon and for each of it's edges I need to get the normal *pointing outwards*. In the picture below, the red normals:

For each edge of the shape, how can I decide if I need (-y, x) or (y, -x)?

# Answer
If you have your edges so that they run in a certain direction, either clockwise or anticlockwise, then your normal-generating routine should always be able to work out which points in and which points out. In the about picture, going clockwise from the top point, then the normal pointing outwards will always be 90degrees anticlockwise.

Hope that helps.

Edit: By running in a direction I mean something like a-\>b-\>c-\>d-\>a.
> 2 votes

# Answer
1st find the center of the polygon. Then find both normals of all the sides. Now consider a side and transform both of its normals to the center of the considered side. Now the normal which is nearer to the center will be directing inside and which is not near will be directing outwards. I hope it helps.
> 0 votes

---
Tags: mathematics, vector
---


# Question
Title: How can I prevent resizing of an Ogre3D object once imported into jMonkeyEngine?
I created an object in Blender:

Then I exported it as a *mesh.xml file* and attached it to the game scene: \[Note: The gray color is the ground.\]

In the game I end up with have a smaller, horizontal tower. Any suggestions?

Note: I exported the file with "Force Camera", "Force Lamps" and "Export Scene" unchecked and "Swap Axis: x,y,z".

# Answer
You probably need to apply your scale in blender first before exporting. Select the object (in your case the tower), press `Cntrl`+`A` and then select "Apply Rotation and Scale".

More info in the Blender Wiki.
> 1 votes

# Answer
I don't export a lot of meshes, but this hasn't received much attention, and I figure I'd offer a fix at the very least.

You can change the size of Geometry objects with the scale() function and you can rotate them with setLocalRotation()

You can also change what the model considers up with rotateUpTo()

hopefully that helps.
> 0 votes

---
Tags: blender, jmonkeyengine
---


title: More Precise PathSmoothing

text:
# Question
Title: More Precise PathSmoothing
I'm reading a book about AI - Path planning and path smoothing. Yet this book is using c++ code. And i'm coding in c# with the XNA framework.

I have a path smoothing working, yet the book says it can be more precise (but being a bit slower).

This is the code i have until now:

```
    public static LinkedList<Vector2> SmoothPathEdgesQuick(LinkedList<Vector2> path, Player player)
    {
        LinkedList<Vector2> newLinkedList = new LinkedList<Vector2>();
        List<Vector2> toBeDeleted = new List<Vector2>();

        var edge1 = path.First;
        var edge2 = path.First.Next;
        while (edge2 != null && edge2.Next != null)
        {
            if (player.CanWalkBetween(edge1.Value, edge2.Next.Value))
            {
                toBeDeleted.Add(edge2.Value);
                edge2 = edge2.Next;
            }
            else
            {
                edge1 = edge2;
                edge2 = edge2.Next;
            }
        }
        foreach (var vector2 in path)
        {
            if (toBeDeleted.Contains(vector2))
                continue;
            newLinkedList.AddLast(vector2);
        }
        return newLinkedList;
    }

```

And this is working as it should work. But the book says it can be more precise by using this code:

```
void Raven_PathPlanner::SmoothPathEdgesPrecise(Path& path)
{
  Path::iterator e1, e2;

  e1 = path.begin();

  while (e1 != path.end())
  {
    e2 = e1;
    ++e2;

    while (e2 != path.end())
    {
      if ( (e2->Behavior() == EdgeType::normal) &&
            m_pOwner->canWalkBetween(e1->Source(), e2->Destination()) )
      {
        e1->SetDestination(e2->Destination());
        e2 = path.erase(++e1, ++e2);
        e1 = e2;
        --e1;
      }

      else
      {
        ++e2;
      }
    }

    ++e1;
  }
}

```

Somehow i don't know how to update my original code to the one below to make my pathsmoothing more precise.

# Answer
> 1 votes
This took some figuring out for myself, but I've got one for you.

Note that in the if statement we have no changes to `path` (since nothing is removed from it). Now `edge2` is changed it it's next every iteration, removing the need of the `else` statement.

I added `nextEdge1Spot` to avoid checking whether an edge has been deleted or not.

```
public static LinkedList<Vector2> SmoothPathEdgesPrecise(LinkedList<Vector2> path, Player player)
{
    LinkedList<vector2> newLinkedList = new LinkedList<Vector2>();
    List<Vector2> toBeDeleted = new List<Vector2>();

    var edge1 = path.First;

    while (edge1.Next != null)
    {
        var edge2 = edge1.Next;
        var nextEdge1Spot = edge1.Next;

        while (edge2 != null && edge2.Next != null)
        {
            if (player.CanWalkBetween(edge1.Value, edge2.Next.Value))

                //'Delete' all the skipped edges.
                var tempValue = edge1.Next;
                while (!tempValue.Equals(edge2))
                {
                    toBeDelete.Add(tempValue);
                    tempValue = tempValue.Next;
                }

                //Also delete edge2.
                toBeDeleted.Add(edge2);

                //Next time edge1 has to start here.
                nextEdge1Spot = edge2.Next;
            }

            edge2 = edge2.Next;
        }

        edge1 = nextEdge1Spot;
    }

    foreach (var vector2 in path)
    {
        if (toBeDeleted.Contains(vector2))
            continue;
        newLinkedLast.AddLast(vector2);
    }

    return newLinkedList;
}

```

Personally I would do the same as what the book does, removing nodes from the list you receive. But this should align well with your current code.

Hope it helps! :)

---
Tags: xna, c#, c++, path-finding, graph
---


title: background move to the right

text:
# Question
Title: background move to the right
I'm developing an android app and want to make move the background to the right. The problem that I have is if it moves it does not repeat the background. I appreciate every suggestion. Thanks.

The code:

```
public class Background
{
    private Bitmap bmp = null;
    private int newWidth = 0;
    private int newHeight = 0;
    private Bitmap bmpScaled = null;
    private int move = 0;
    private float scale = 0;
    private GameView gameView = null;

    public Background(GameView gameView, Bitmap bmp, int x, int y)
    {
        this.gameView = gameView;
        this.bmp = bmp;
        scale = (float) bmp.getHeight() / (float) gameView.getHeight();
        newWidth = Math.round(bmp.getWidth() / scale);
        newHeight = Math.round(bmp.getHeight() / scale);
        bmpScaled = Bitmap.createScaledBitmap(bmp, newWidth, newHeight, true);
    }

    private void start()
    {
        move++;
    }

    private void update()
    {
        start();
    }

    public void onDraw(Canvas canvas)
    {
        update();
        canvas.drawBitmap(bmpScaled, move, 0, null);
    }
}

```

# Answer
If you want to repeat the background you will actually need to call drawBitmap twice.

Consider what would happen if you wanted to repeat a very small background. You would need to tile it several times to cover the area. In this case, you need to tile it twice - once for each screen width.

So it should be something like

```
canvas.drawBitmap(bmpScaled, move % newWidth, 0, null);
canvas.drawBitmap(bmpScaled, (move % newWidth) - newWidth, 0, null);

```
> 1 votes

---
Tags: java, android
---


title: Removing something on Collision?

text:
# Question
Title: Removing something on Collision?
I have my collision detection code working so how would I tell my HealthPickup to disappear when my Player collides with it? I haven't played around with it yet but I think I may have to somehow remove the hitbox and stop calling the `Draw()` function (at least for my HealthPickup anyway)

Please note I am a novice and have not really dealt with XNA before.

# Answer
> 2 votes
If you have a list of entities or a list of potions which you loop through, you can simply remove the entity from the list. This should be standard practice anyway, as this makes it extremely easy to add more items without assigning loads of variables.

# Answer
> 0 votes
If your Health pickup is an object, you could set it to null if you detect a collision. The garbage collector will do the rest for you. But don't try to reference that object after it is null because it will give your a runtime error.

```
if(player.collides(healthpotion))
{
 player.health += 100;
 healthpotion = null;
}

```

# Answer
> 0 votes
To add a bit to Rokk's answer.

Chances are, since you say you are new to XNA, that you use the `GameComponentList`, in the `Game` class, known as `Components`.

If so, then the solution is simple. Just make sure you can reach that `Components` list from your collision code and use `Components.Remove(healthPickup);`. Your game will now stop drawing it and the garbage collector will (if you aren't referencing it from some other spot) clean it up for you.

If you are not using that Component list I was talking about, then it depends on your code. This is also where I refer you back to Rokk's answer.

---

EDIT: Some examples and explenation supporting my comment.

In my comment I mentioned a `DrawableGameComponent`. You mentioned that nothing happened. A guess I could make for why nothing is happening is that you might miss the calls to the base class in your game class. Example below.

```
public class Game1 : Game
{
    protected override void Initialize()
    {
        Components.Add(new HealthPickup(/* constructor arguments here */));
    }

    protected override void Update(GameTime gameTime)
    {
        //Next line will call Update(GameTime) on all Components in Components.
        base.Update(gameTime);
    }

    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(/* Your color here */);

        //Next line will call Draw(GameTime) on all DrawableComponents in Components.
        base.Draw(gameTime);;
    }
}

```

The `base.something` calls I made in both `Draw()` and `Update()` make sure that XNA will call the `Draw()` of each `DrawableGameComponent` and the `Update()` of each `GameComponent` (including `DrawableGameComponent`).

Then your HealthPickup should have the following:

```
public class HealthPickup : DrawableGameComponent
{
    //Ignoring constructor and other component stuff for the sake of an example.

    //Adding this component to the GameComponentList causes this function
    //to be called during every update cycle.
    public override void Update(GameTime gameTime)
    {
        base.Update(gameTime);

        //TODO update logic here...
    }

    public override void Draw(GameTime gameTime)
    {
        base.Draw(gameTime);

        //TODO draw logic here...
    }
}

```

If you have this then HealthPickup should be called every update cycle.

Maybe something nice to read is this guide. It does not cover classes, but it does cover the XNA basics. It does ignore the Component list so you have to trust the examples above for that.

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


# Question
Title: Is there a way to view all colliders in a unity project at runtime (after the game have been deployed)?
I'm have created a small `Unity` project but physics has weird behavior (bug). Unfortunately it only happens on some specific hardware (after build), not on development machine.

I don't know what is the reason it's probably due to different framerate. Viewing all object and their colliders would probably help me a lot.

Is there a possibility in `Unity` to view all colliders in the game at run time (some kind of debug mode). Something similar as `Game` tab view in Unity with `Gizmos` option enabled, but for all objects ?

# Answer
There's nothing built in that'll allow you to view gizmos in a released game. However, you can create your own debugging viewer by using the LineRenderer.

Personally I would create something like a `DrawBounds` method that accepts the `Bounds` property of the collider.
> 1 votes

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


# Question
Title: Accessing uniform variables from a Cg shader in OpenGL
I am trying to implement a simple PC program with OpenGL, using mandatorily Cg shaders (no Unity whatsoever).

I have found some tips on this page http://bobobobo.wordpress.com/2008/10/05/cg-1/ and kept the **Cgprogram**, **Cgcontext** and **Cgprofile** types in my own project.

Problem is: How can you access uniform variables in the C++ code? I have tried the **glGetUniformLocation** way, but that won't work because the first parameter must be the program's ID of **GLuint** type and I have **CGprogram** type.

I have already searched by myself (including the Nvidia Cg 'tutorial') but I can't seem to find both Cg and OpenGL discussed on a page without having to deal with Unity.

***edit:*** I can now access the variables, but in my case I'm trying to change a texture, and it doesn't bind.

# Answer
> 0 votes
I have finally managed to find a way to access uniform texture variables.

First (after preparing the GL window) you have to initialize the Cg stuff:

```
myCgContext = cgCreateContext();
myCgVertexProfile = cgGLGetLatestProfile(CG_GL_VERTEX);
cgGLSetOptimalOptions(myCgVertexProfile);
myCgFragmentProfile = cgGLGetLatestProfile(CG_GL_FRAGMENT);
cgGLSetOptimalOptions(myCgFragmentProfile);

myCgVertexProgram =
    cgCreateProgramFromFile(myCgContext, CG_SOURCE,"../vertexshader.cg", myCgVertexProfile,"VS_Main",NULL);

myCgFragmentProgram =
    cgCreateProgramFromFile(myCgContext, CG_SOURCE,"../fragmentshader.cg", myCgFragmentProfile,"FS_Main",NULL);

cgGLLoadProgram(myCgVertexProgram);
cgGLLoadProgram(myCgFragmentProgram);

```

Then, in your *display* function, you have to do what you usually do, but put the following lines **exactly BEFORE** the actual draw (glDrawArrays in my case):

```
CGparameter loctex = cgGetNamedParameter(myCgFragmentProgram, "tex"); // in my fragment shader I have declared: "uniform sampler2D tex;"
cgGLSetTextureParameter(loctex, IDtex[1]); // IDtex is my array of texture IDs
cgGLEnableTextureParameter(loctex);

```

You can find more examples of accessing Cg variables in the NVIDIA OpenGL SDK projects (but that's difficult...); otherwise I have found great simple examples of using Cg with OpenGL here (scroll down & check right column): http://perso.limsi.fr/jacquemi/RGA-TD/index.html

# Answer
> 1 votes
`cgGetNamedParameter`

Example code:

```
CGprogram cgprog;
cgprog = cgCreateProgram(...);
cgGLLoadProgram(cgprog);
CGparameter modelviewproj, lightpos;
modelviewproj = cgGetNamedParameter(cgprog, "modelviewproj");
lightpos = cgGetNamedParameter(cgprog, "lightpos");

```

Sample code paraphrased from the book Advanced Game Development with Programmable Graphics Hardware by Watt Policarpo.

---
Tags: opengl, shaders, cg
---


# Question
Title: Lock mouse in center of screen, and still use to move camera Unity
I am making a program from 1st person point of view. I would like the camera to be moved using the mouse, preferably using simple code, like from XNA

```
var center = this.Window.ClientBounds;
 MouseState newState = Mouse.GetState();

  if (Keyboard.GetState().IsKeyUp(Keys.Escape))
  {
      Mouse.SetPosition((int)center.X, (int)center.Y);
      camera.Rotation -= (newState.X - center.X) * 0.005f;
      camera.UpDown += (newState.Y - center.Y) * 0.005f;
  }

```

Is there any code that lets me do this in Unity, since Unity does not support XNA, I need a new library to use, and a new way to collect this input.

this is also a little tougher, since I want one object to go up and down based on if you move it the mouse up and down, and another object to be the one turning left and right.

I am also very concerned about clamping the mouse to the center of the screen, since you will be selecting items, and it is easiest to have a simple cross-hairs in the center of the screen for this purpose.

---

Here is the code I am using to move right now:

```
using UnityEngine;
using System.Collections;

[AddComponentMenu("Camera-Control/Mouse Look")]

```

public class MouseLook : MonoBehaviour {

```
public enum RotationAxes { MouseXAndY = 0, MouseX = 1, MouseY = 2 }
public RotationAxes axes = RotationAxes.MouseXAndY;
public float sensitivityX = 15F;
public float sensitivityY = 15F;

public float minimumX = -360F;
public float maximumX = 360F;

public float minimumY = -60F;
public float maximumY = 60F;

float rotationY = 0F;

void Update ()
{
    if (axes == RotationAxes.MouseXAndY)
    {
        float rotationX = transform.localEulerAngles.y + Input.GetAxis("Mouse X") * sensitivityX;

        rotationY += Input.GetAxis("Mouse Y") * sensitivityY;
        rotationY = Mathf.Clamp (rotationY, minimumY, maximumY);

        transform.localEulerAngles = new Vector3(-rotationY, rotationX, 0);
    }
    else if (axes == RotationAxes.MouseX)
    {
        transform.Rotate(0, Input.GetAxis("Mouse X") * sensitivityX, 0);
    }
    else
    {
        rotationY += Input.GetAxis("Mouse Y") * sensitivityY;
        rotationY = Mathf.Clamp (rotationY, minimumY, maximumY);

        transform.localEulerAngles = new Vector3(-rotationY, transform.localEulerAngles.y, 0);
    }
    while (Input.GetKeyDown(KeyCode.Space) == true)
    {
        Screen.lockCursor = true;
    }
}

void Start ()
{
    // Make the rigid body not change rotation
    if (GetComponent<Rigidbody>())
        GetComponent<Rigidbody>().freezeRotation = true;
}
}

```

This code does everything except lock the mouse to the center of the screen. Screen.lockCursor = true; does not work though, since then the camera no longer moves, and the cursor does not allow you to click anything else either.

# Answer
> 1 votes
use Screen.lockCursor in your Start() method

http://docs.unity3d.com/ScriptReference/Screen-lockCursor.html

---
Tags: unity, camera, mouse
---


title: facebook like for unity android

text:
# Question
Title: facebook like for unity android
Is there a way to add a like button which links to my page for my android game which I made in unity. Any help would be appreciated.

# Answer
> 0 votes
Add a Like button yourself and Open a page on it's click. To open external links in browser, you can use Application.OpenURL().

In this method the user have to like the page from the browser itself. I don't think there's any way by which you can make him like it from the game itself.

---
Tags: unity, android, facebook
---


# Question
Title: Practical balance of "chance" video game mechanics
I've been a small games developer and designer for years, and I've recently begun working on more serious design documents for bigger projects.

A common theme I'm running in to is imbalance when it comes to "chance" RPG mechanics. Critical Strike Chance. Chance to Hit/Dodge/Miss/Parry/Block so on. The biggest problem in modern RPG games is factoring in Haste (Attack Speed), since it compounds so aggresivly with the other base mechanics. Obviously, the more times a player attacks, indirectly increases their "rate" of critical strikes, or hits. This creates an immense imbalance, and most of the solutions come in the form of capping haste or utilizing diminishing returns or to killing the big stat increases.

As a designer and player, I don't feel this is a healthy way to deal with the issue. It's not a "fun" solution. Recently, gamers seen Blizzard's answer to this Haste issue in Diablo3, by halfing the stat increases on most all items.

Here is a practical example:

* 50% chance to critically strike, with 1 attack per second = on average 0.5 critical strike per second.
* 50% chance to critically strike, with 2 attacks per second = on average 1 critical strike per second.

The second situation is by far favorable, rather than increasing your Critical Strike Chance alone, since not only will you see more larger numbers (or hits in terms of a miss chance mechanic) per unit of DPS, you'll also be hitting more and games with Proc Chance mechanics also benefits. More Complex games balance such things with Internal Cooldowns and Weighing the stats against each other, but often times Haste still comes out on top as being the supremely powerful stat.

Is it practical to instead use a Rate to decide weather or not something happens vs stat weights, capping and cooldowns?
My simplified example is:
Critical Strike RATE = Crit Chance / Attacks Per Second

The result is basically a simple stat weight system. Mechanics such a proc chances still benefit from Haste, however it may be easier to change the damage output of attacks and abilities to reflect the balance. This keeps enjoyable haste mechanics in the game, which are fun to play. It also creates more depth for slower attack builds, rather than just an ability or proc benefiting from slow weapons.

Is this a near-sighted solution? Are there working examples of games currently on the market that don't cap or punish "haste" character builds?

# Answer
The problem you are describing is not necessarily about haste. It is about the multiplicative effects of increasing different stats. Haste increases hits per second, which increases damage and anything with a chance to happen per hit. Another example would be increasing +crit dmg which then increases the value of any +crit % chance.

You could benefit from extracting bonus hit procs from the critical hit event.

Instead of a talent that inflicts poison on the target when a critical hit occurs, give the proc its own independent chance of occurring. This will still scale with haste, but increasing critical strike chance will not increase the value of the poison talent.

Any on-hit chance is going to be affected this way by haste. World of Warcraft uses a proc-per-minute (ppm) implementation for things like trinkets that activate on hit or spellcast. This is primarily intended to reduce the randomness and clustering of procs.

If that is still distasteful to you, perhaps what you are looking for is not a haste mechanic, but something more akin to windfury in WoW. Pure haste percentage is always going to need high numbers before it becomes noticeable and those high numbers are what cause problems with other systems.

If you are just looking to see extra normal attacks, add a stat that gives a chance on hit to give a free extra normal swing that cannot proc a crit or any other special attack. In WoW this ability is called windfury and it is always more exciting to see than a flat haste percentage. Numerically is not that different from a critical hit, but it can still be dodged, trigger thorns, etc. like a hasted attack. If you want these extra hits at a regular interval, implement a ppm system.
> 3 votes

# Answer
The multiplicative nature of these stats are not the cause the imbalance you refer to. In fact, they tend to prevent one single stat from being dominant. For example, higher attack speeds increase the usefulness of boosting attack damage. Doubling either value will have the same effect on the DPS, but most systems automatically enforce doubling numbers that are already high is quite difficult.

As the player progresses, their increase in attack damage is often opposed by an increase in the enemy's defensive capabilities, which can scale almost indefinitely, unlike attack speed, which has a narrow 'logical' range. I suspect this is the main reason developers turn to caps or diminishing returns.

There are other options, however. By defining the on-hit critical strike chance as the ratio of crit statistic and attack speed, you effectively end up with a fixed estimate for the number of critical hits per unit time, removing a multiplicative relation from attack speed. A very common alternative is to use a stamina pool that haste quickly depletes. In other games, attack speed may have limited merit due to it being uncommon for an enemy to stay in attack range long enough for you to land more than one hit anyway. As for critical strikes, a lot of games don't bother with probabilities, but use different criteria, such as attacking from behind.

Most importantly, if you can't find a way to make it fun, eliminate the system altogether. Numerous RPGs don't even have variable attack speeds or critical strikes. Arbitrarily making equations more complicated doesn't add any interesting depth.
> 1 votes

# Answer
There's no intrinsic problem regarding critical hits etc. The small chance of doing critical damage can be disregarded and considered a small boost to the average damage if you prefer.

Obviously with any random event that occurs periodically, as you shrink the period the frequency of the event increases exponentially (because if the period is infinitely small, the frequency is infinitely high). The answer is to ensure that the period cannot approach zero, which means a lower bound on the period.

If you don't want to put a lower bound on it, you would have to decrease other capabilities at at least the same rate or higher. If you decreased them at a slower rate, then it would still end up tending towards infinity as the period shortens. But if you decrease at a higher rate, there's no point shortening the period as the player gets no benefit. So a clamp seems the most reasonable solution.

> Here is a practical example. Think of damage in terms of units of DPS, or active combat time. 50% Chance to Crit, with 1 attack per second = (roughly)50% Critical Strike RATE per DPS unit. 50% Chance to Crit, with 2 attacks per second = (roughly)100% Critical Strike RATE per DPS unit.

No, the second example gives you 75% chance of at least 1 critical strike per second. However it gives you an average of 1 critical strike per second. These are different things!
> 0 votes

# Answer
Instead of giving just flat +crit chance bonus, you could adopt a stat which determines your crit chance. This is usually included in precision/dexterity/agility, depending on the game. Precision requires more and more stat points in order to get an increase in crit chance as you go higher, so at a certain point, the return on invest is so low, it would be better to invest in another stat (usually strength) to increase your damage.

This would still allow a player to create a character that crits (nearly) 100% of the time, but it's other stats (including strength) would be very low and it would have to rely on special effects caused by crit damage (like bleeding, life steal,...)

IAS can be countered with enemy curses that cause you damage every time you attack, or by simple making it a temporary activated ability with a downside: take 50% more damage while active, or cause less damage.

try to keep the damage boosting abilities in different attribute lines: crit chance, attack damage, crit damage and IAS should never be in the same line. (IMHO, I wouldn't put IAS in a stat line, since it has the potential to make other things overpowered, as you pointed out).
> 0 votes

# Answer
A higher haste value doesn't necessarily have to reflect a higher amount of critical hits. Many games use two different stats for calculations - base stats, and modifiers. (D&D is a great example). Why not calculate critical hits based on the base of the haste stat, but still reflect the critical chance? For example, a level 1 character has an unmodified base haste of 1. He hits one time per second. Once per second he has a calculation that gives him a chance to critically hit. The character then levels up to 2. He now has a haste level of 2 that allows him to attack twice per second. Critical chance is still calculated on base haste which is 1 allowing him to still only get a maximum of 1 critical hit per second. This is the route that some games go down, and often it's not quite as simple as I've described, but it's something to think about. It depends on the game, the situations and the core mechanics.
> 0 votes

---
Tags: game-design, rpg, balance
---


title: How do you change movement to strafe

text:
# Question
Title: How do you change movement to strafe
Right now my player can move forward and backward using

```
case 'a':case 'A':
    speed.x = lx * 0.1;
    speed.z = lz * 0.1;
    break;
case 'b':case 'B':
    speed.x = -(lx * 0.1);
    speed.z = -(lz * 0.1);
    break;

```

Ly is equal `sin(vertAngle);`

Lz is equal `-cos(horAngle);`

What should i do for sideways movement?

# Answer
> 1 votes
Since no one answered, I'll write a more complete answer here:

Hint: If the vector (lx,lz) points in the direction of the character, the vector (-lz,lx) points to the character's left.

So something like:

```
case 'c':case 'C':
    speed.x =-lz * 0.1;
    speed.z = lx * 0.1;
    break;
case 'd':case 'D':
    speed.x = lz * 0.1;
    speed.z =-lx * 0.1;
    break;

```

should work, where "c" moves left. If you want to move forward AND strafe, you can just say "speed.x=0; speed.z=0" and the beginning, and replace each "=" with a "+=". If speed-weirdness bothers you (if speed.x=1 and speed.z=1, the total speed is actually 1.41), you can normalize the speed after this procedure. "normalization" means reducing the length to one, so the full code would be something like:

```
speed.x=0;
speed.z=0;
case 'a':case 'A':
    speed.x += lx;
    speed.z += lz;
    break;
case 'b':case 'B':
    speed.x += -lx;
    speed.z += -lz;
    break;
case 'c':case 'C':
    speed.x +=-lz; //left movement
    speed.z += lx;
    break;
case 'd':case 'D': //right movement
    speed.x += lz;
    speed.z +=-lx;
    break;
dist=sqrt(speed.x*speed.x+speed.z*speed.z); //total speed
if(dist>0){ //prevent against division by zero
    speed.x=(speed.x/dist)*.1; //ensure the total speed is precisely 0.1
    speed.z=(speed.z/dist)*.1;
}

```

---
Tags: mathematics, movement
---


# Question
Title: Cocos2d/Cocos2d-x Attaching an arrow (sprite) to another body sprite (person)
I am trying to set up a simple bow and arrow game. When the arrow hits the enemy body, the arrow's body is deleted and the arrow sprite continues to update, keeping the position correct in relation to the enemy it hit. Picture an arrow sticking into a body and that body still rotating and moving. My problem is that the rotation is completely wrong when the enemy rotates. I know how to do this in 3d with matrix transformation but I can't seem to figure it out in 2d with Cocos.

Here is my method.

1. I save offset at which the arrow hit the enemy.
2. Every frame, I make the rotation of the sprite match the rotation of the enemy.
3. Then, I apply the offset I took initially which is where the arrow hit the enemy.

When they rotate, they rotate about their respective anchors and I am wondering if I need to set the anchor of the arrow to the center of the sprite. Does anyone know of an easy way to do this. If not, I will try to create an algorithm where the anchor is set to the offset divided by the width and height of the sprite image hopefully giving me the correct anchor values.

Then I assume I need to reposition the sprite.

Does anyone have a simpler way to do this?

# Answer
> 0 votes
I think you could accomplish this by applying the following algorithm (shown in pseudocode):

```
rotateEnemyAndArrow() {
 start = arrowPointOfContact - enemyCenter
 destination = start.rotate()   // Rotate the start vector by the enemy's rotation
 enemy.rotateAroundPoint(enemyCenter)
 arrow.rotateAroundPoint(arrowPointOfContact)
 arrow.translate(destination - start)
}

```

`arrowPointOfContact` and `enemyCenter` represent the point of contact of the arrow on the enemy and the enemy's center of rotation, respectively.

To illustrate:

Before any rotation is done, we have:

where the blue arrow represents the `start` vector.

After performing all rotations as listed in the algorithm (in this case it is a 90 degree rotation, but it will work for any) we have:

where the yellow arrow represents the `destination` vector, and the magenta arrow is our `destination - start` vector, which the green arrow sprite must be translated by to get to its final position.

---
Tags: sprites, cocos2d, cocos2d-x
---


title: Three Screens = Three Cameras?

text:
# Question
Title: Three Screens = Three Cameras?
I have three screens which are at an angle to each other. Basically, the left and right cameras need to move relative to the main camera in such a way that it would look like each screen is a window the player is looking out of (like the cockpit of an airplane).

How can I achieve this effect?

# Answer
Yes, you can implement this with three cameras. There's a few ways to approach this, and none of them are built in easy to use solutions from Unity.

* Create one large borderless window that spans multiple screens (for example you can use the command line argument -popupwindow). You'd then set up each camera to take up the portion of the window that is visible on each screen. Sort of like chopping up the window based on the monitors.
* Spawn child processes that connect to the "main" game process and are just there to display an additional view. These could talk to the main program through a named pipe or some other inter-process communication.

The details of implementing these can get complicated, so it's too much to go into here. However, know that this is entirely possible and you have options.
> 2 votes

# Answer
Unless you have the screens at angles greater than roughly 45 degrees, you should be able to create a viewport that covers the three screens, and have it look realistic. Instead of having a 1600x900 viewport, you would have a 4800x900 viewport. I would not recommend having three separate cameras. If the displays render slightly out of sync, it can disorient the player.

Technology wise, have a look at the Matrox TripleHead2Go solution (http://www.matrox.com/graphics/en/products/gxm/th2go/digital/)

As far as as simulating the window effect, display an overlay on each screen.
> 2 votes

---
Tags: unity, camera
---


# Question
Title: Using DirectX9 within Visual Studio 2012 in Windows 8?
Asking the question here simply because my PC is down for the count for a while and wasn't able to stave a curiosity before that happened.

I picked up a few books about programming Games in DirectX, specifically 9.0c.

I have a Windows 8 machine, and have Visual Studio 2012, and remember a massive headache about following some of the more simple DirectX tutorials on the web as everything I could find was prior to Windows 8 when all headers and such we're available, and DirectX wasn't merged into the WindowsSDK. (I think specifically it was the absence of a commonly used DX UTILITY that was causing issues).

Before my PC went down, I wasn't able to try simply installing previous SDK's.

.. Does this work? Can one, under a Windows 8 environment with Visual 2012, install the previous DX9 SDK's and it'd work out alright? Are there going to be conflicts? How can I set this up correctly? I'm just interested in getting going with the basics of what can be followed by the majority of the resources available today, and not so much "bleeding edge" at the moment...

Thank you in advance!

# Answer
> 1 votes
Yes. You may have to change some include path orders in your V++S directories properties tab to get the right headers. I don't use DX9 for new projects in VS2012 (and our DX9 projects at work are all developed in VS2008 on Win7), so I'm unsure of any details. For DX11 that was all that was necessary to use the June 2010 SDK specific interfaces (most of the important APIs are the same).

Most of the DX9 headers should just work, though. The libraries will link and run just fine.

Be sure you're using a more fully-featured of VS2012. If you're using Express, be sure you're using the Desktop edition. If you're using 2012 Express for Windows 8 you will have problems; it only produces newer Windows 8 style apps, which DX9 games most certainly aren't.

Visual Studio 2012 for Desktop

# Answer
> 0 votes
I have had some major headaches trying to get DX9 to work with VS2012. Most of our dev code is in DX9. I'd recommend against touching DX9 at all these days, unless you are working with an existing project that uses DX9. DX10 and up bring some new nice features, and a couple of critical ones (depending on your project needs). DX9 has pre-compiled libs that use an older runtime than VS2012 - you will get linker errors, and a couple of header compiler mismatches.

# Answer
> 0 votes
If you want to develop DirectX applications using Visual Studio 2012 and the June 2010 DirectX SDK (the last one to be released as a stand alone SDK) then you will need to follow some steps first:

Installing the SDK might crash with an error S1023 – if it does check this link out:

https://stackoverflow.com/questions/4102259/directx-sdk-june-2010-installation-problems-error-code-s1023

All I did was run the MSIEXEC commands (create a batch file if you want, makes it easier to execute) and then re-installed the SDK.

Fixing D3DX9

There are extension libraries and headers that VS2012 can’t see by default. There are no explicit instructions on the tutorial site on how to setup VC++ directories and to be honest, most people will probably do this par for the course but I forgot this time so here’s what I did:

"#include" wasn’t working and therefore any references to the “X” components wouldn’t compile. Simple enough to fix. Right click on the project in the solution explorer and choose properties. Once there find the VC++ Directories option on the right (it’s under “Configuration Properties”). Make sure that the “Configuration” drop down at the top is set to “All Configurations” then click on Include Directories and add the following entry:

$(DXSDK\_DIR)\Include

Do the same with the Libraries entry but change it to:

$(DXSDK\_DIR)\Lib\x86

---
Tags: directx, windows, directx9, windows-8
---


title: Trigger for Melee-attack not working

text:
# Question
Title: Trigger for Melee-attack not working
I'm currently trying to add a melee-slash attack to my Sidescroller.

For that I decided to to have an invisible box-colliders infront of my character. My idea is to activate it when the attack-key is pressed and leave it active for the duration of the attack before turning it inactive again.

I know from a previous attempt with a dash instead (didn't work out on the movement for it) that my code for the attack-triggering in the player-script works just fine, so now in my box-collider infront of the player I have:

```
    public GameObject Player;
//public GameObject Box;
bool attack = false;
//Collider c;

void Awake ()
{
    Player = GameObject.FindGameObjectWithTag ("Player");
    //Box = GameObject.FindGameObjectWithTag ("AttackBox");
    gameObject.collider.enabled = false;
}

void Update ()
{
    Player pstats = Player.GetComponent<Player>();
    attack = pstats.attacking;

    if (!attack)
    {
        gameObject.collider.enabled = false;
    }

    if (attack)
    {
        gameObject.collider.enabled = true;
    }

}

```

And in my Enemy script I have

```
    void OnTriggerEnter(Collider collision)
{
    Player pstats = Player.GetComponent<Player>();
    if (collision.gameObject.tag == "Player") {
        collision.gameObject.GetComponent<Player>().PlayerHit();
    }

    if (collision.gameObject.tag == "AttackBox")
    {
        pstats.CurrentEXP += 25;
        EnemyDeath ();
    }

}

```

Though the hit isn't recognized.

The issue I see is that probably the OnTriggerEnter is the issue since the Enemy tends to be allready inside the attack-box collider when the attack is triggered. I tested a bit with the Debug-Log and the box is activated at least, so it should really be just the issue of calling the Trigger at the right time.

Are there any alternatives to OnTriggerEnter that would be working better?

edit: I tried adding this right below my collision-part in the enemy-script:

```
    void OnTriggerStay(Collider collision)
{

    Player pstats = Player.GetComponent<Player> ();
    if (collision.gameObject.tag == "AttackBox")
    {
        pstats.CurrentEXP += 25;
        EnemyDeath ();
    }

}

void OnTriggerExit(Collider collision)
{
    Player pstats = Player.GetComponent<Player> ();
    if (collision.gameObject.tag == "AttackBox")
    {
        pstats.CurrentEXP += 25;
        EnemyDeath ();
    }
}

```

Though the hit is still not recognized.

# Answer
> 1 votes
For a situation like this you'd be better off using something like a `OverlapSphere`. Or if you're using 2D, you have a few more options with the `OverlapAreaAll` or the `OverlapCircleAll` methods.

All of these methods are going to return a list of colliders that intersect with the shape you choose (sphere, circle, rectangle). These have the additional benefit of being able to specify a layer mask to ensure you're only colliding the the objects in your scene you want to collided with, in this case, enemy hit boxes.

Once you have a list of colliders that intersect with your shape, you can iterate through them and do more complex collision checking, or just go straight to applying damage.

For example, your attack might look like this:

```
void Attack() {
    Player pstats = Player.GetComponent<Player> ();
    Collider[] hitColliders = Physics.OverlapSphere(Player.transform.position, pstats.attackRadius, Enemy.LayerMask);
    int i = 0;
    while (i < hitColliders.Length) {
        pstats.CurrentEXP += 25;
        EnemyDeath ();
    }
}

```

Where you'll need to define an `attackRadius` and the `Enemy.LayerMask`. If you're not sure how to use layer masks you can learn more about them in this video I made.

---
Tags: c#, unity, collision-detection
---


# Question
Title: Box2d - Attaching a fired arrow to a moving enemy
I am firing an arrow from the player to moving enemies. When the arrow hits the enemy, I want it to attach exactly where it hit and cause the enemy (a square) to tumble to the ground. Excluding the logistics of the movement and the spin (it already works), I am stuck on the attaching of the two bodies. I tried to weld them together initially but when they fell, they rotated in opposite directions.

I have figured that a revolute joint is probably what I am after. The problem is that I can't figure out a way to attach them right where they collide.

Using code from iforce2d:

```
b2RevoluteJointDef revoluteJointDef;
revoluteJointDef.bodyA = m_body;
revoluteJointDef.bodyB = m_e->m_body;
revoluteJointDef.collideConnected = true;
revoluteJointDef.localAnchorA.Set(0,0);//the top right corner of the box
revoluteJointDef.localAnchorB.Set(0,0);//center of the circle
b2RevoluteJoint m_joint = *(b2RevoluteJoint*)m_game->m_world->CreateJoint( &revoluteJointDef );
m_body->SetLinearVelocity(m_e->m_body->GetLinearVelocity());

```

This attaches them but in the center of both of their points.

Does anyone know how I would go about getting the exact point of collision so I can link these? Is this even the right method of doing this?

Update:

I have the exact point of collision. But I still am not sure this is even the method I want to go about this. Really, I just want to attach body A to B and have body B unaffected in any way.

# Answer
> 1 votes
I would recommend destroying the physics body of the arrow when it comes to rest, but continue to draw the sprite at the location where it contacted the enemy.

The cleanest way to do this is with object aggregation: i.e. make the arrow a 'child' of entity B. It appears this feature is built-in to cocos2d-x.

I assume you already have a technique for stopping the arrow after it penetrates body B by some distance, so I will just talk about what should happen when the arrow comes to rest relative to body B.

You really just need to call something like `enemySprite->addChild(arrowSprite)`, and destroy body A (or queue it for destruction). I haven't tested it out, but the documentation is pretty clear that child sprites are drawn relative to the parent sprite's transform.

Like in one of my previous answers, I will point out that if you can encapsulate this collision-attachment code with the arrow objects, you won't need to worry about what the arrow is embedding itself into (could be enemies, wagons, bridges, molasses, etc...), it will happily attach itself to the other sprite.

---
Tags: box2d, cocos2d-x
---


# Question
Title: How can I create a 3D point cloud in WPF?
I need to render some 3D points with WPF. How can I do this?

I need an easy and fast solution to just render this point cloud. No lights, no texture, no sound, no physics, just colored 3D points in a space with rotating camera.

How can I do this without having to learn Direct3D/OpenGL/any complex 3D engine?

# Answer
This isn't something WPF is particularly well-suited for; it's 3D capabilities, while backed by hardware acceleration *eventually*, are very abstract and high-level.

Using only technology built-in to WPF itself, your best bet is probably to leverage the `MeshGeometry3D` class. This object has a list of 3D positions and a list of indices into that 3D position list. Every three indices into the position list define a triangle with the three referenced position points. Thus, you'd need to:

* Generate your 3D point cloud.
* Turn each point into some simple 3D primitive (such as a quad defined by two triangles within a plane perpendicular to the view direction).
* Insert those points, and corresponding indices, into the relevant lists.
* Bind those lists to a `MeshGeometry3D` object (or just instantiate one at runtime).

While you might be able to come up with a method that is simpler *in code* (in particular by avoiding the second step by simply placing a bunch of pre-defined geometry objects, like cubes or 2D rectangles adjusted by depth to fake perspective), you are likely to run into scale problems much sooner given the overhead of each point in such an approach. Stuffing everything into a single object eliminates much of that overhead for improved scaling and performance. Plus, it doesn't require you to recompute every point when the camera rotates as you would in the projected 2D case (instead, you adjust the object's 3D transform property).

If you are okay with a solution that uses external dependencies, the Helix toolkit provides a bunch of simple 3D primitives and utilities that will likely take a large chunk of the grunt work out of the above implementation.
> 1 votes

---
Tags: wpf
---


# Question
Title: How can I spawn a sprite based on a condition after the game starts?
How do I spawn a sprite anytime later in the game when the game starts?

I'm using FlashDevelop with Flixel. I did try it in `override public function create(): void`. It works only in the beginning. I try it using `if (FlxG.score == 1)` but it doesn't work. I also tried it in `override public function update(): void`. It works and it is moving but it leaves a sprite making it a multi-sprite. I also did try FlxGroup but to no avail.

# Answer
Spawn the sprite when the appropriate event or conditions for spawning are met.

Flixel gives you an `update` method that runs periodically. For example, in the Flixel platformer tutorial, the `update` method is overridden thusly:

```
override public function update():void
{
    player.acceleration.x = 0;
    if(FlxG.keys.LEFT)
        player.acceleration.x = -player.maxVelocity.x*4;
    if(FlxG.keys.RIGHT)
        player.acceleration.x = player.maxVelocity.x*4;
    if(FlxG.keys.SPACE && player.isTouching(FlxObject.FLOOR))
        player.velocity.y = -player.maxVelocity.y/2;

    super.update();

    FlxG.collide(level,player);
}

```

One (of many potential) ways to handle spawning on some condition is to check for that condition during the periodic update and spawn creatures as needed. Of course, you can't just check for the condition *directly* (for example, doing `if (score == 1) spawn()` in the update loop would spawn a new enemy every frame that the score is still 1, which probably isn't what you want).

Instead, consider storing information about what you need to do during the update. If your game object had an integer field for `enemySpawnsThisFrame`, you could do something like:

```
while (enemySpawnsThisFrame > 0) {
  spawn();
  --enemySpawnsThisFrame;
}

```

Then, when an event occurs that should trigger a spawn on the next frame update, you simply increment this counter. For example, in the code where you *increment* the score:

```
++score;
if (score == 1) {
  // Spawn a bad guy next frame.
  ++enemySpawnsThisFrame;
}

```

This should get you off the ground. As your project grows, this kind of tight coupling between systems becomes very undesirable, because it increases the difficulty of maintenance. To avoid this, you can implement some kind of observer pattern to isolate dependencies. In such a world, incrementing the score would raise a "score incremented" event. External systems (like the game itself) interested could subscribe to that event and set up the enemy spawn.
> 1 votes

---
Tags: sprites, actionscript-3, flixel
---


# Question
Title: How can I simulate objects floating on water without a physics engine?
In my game the water movement is done in a shader using Gerstner equations. The water movement looks realistic enough for a school project but I encounter serious problem when I wanted to do sailing on waves (similar to this). I managed to do collision with land by calculating quad's vertices and normals beneath ship, however same method can not be applied to water because XZ are displaced and Y is calculated in a shader :(

1. How to approach this problem ?
2. Is it possible to retrieve transformed grid from shader?
3. Unfortunately no external physics libraries can be used.

# Answer
> 1. How to approach this problem?

Move the simulation of the wave height to the CPU. Depending on which works better for you and your logic/performance needs, you can move the *entire* simulation to the CPU and simply send the computed coordinates to the GPU (avoiding duplicate work) or you can do a simpler approximation of the computation on the CPU.

> 2.Is it possible to retrieve transformed grid from shader?

Not easily. Shaders aren't really designed for that. You can do various things to make the GPU do general purpose computation and read the results back on the CPU, and various GPGPU ("general purpose GPU") libraries and tools exist to wrap and abstract all that complexity, such as OpenCL. However, in this particular case it's unlikely to be that useful for you.

> 3.Unfortunately no external physics libraries can be used

That's fine, you should not need them, you've already done the majority of work you need.
> 1 votes

---
Tags: xna, hlsl, water
---


# Question
Title: Is there a standard way to track 2D tile positions both locally and on screen?
I'm building a 2D engine based on 32x32 tiles with OpenGL. OpenGL draws from the top left, so Y coordinates go down the screen as they increase. Obviously this is different than a standard graph where Y coordinates move up as they increase.

I'm having trouble determining how I want to track positions for both sprites and tile objects (objects that are collections of tiles). My brain wants to set the world position as the bottom left of the object and track every object this way. The problem with this is I would have to translate it to an on screen position on rendering. The positive with this is I could easily visualize (especially in the case of objects made of multiple tiles) how something is structured and needs to be built.

Are there standard ways for doing this? Should I just suck it up and get used to positions beginning in the top left?

Here are the OpenGL calls to start rendering:

```
// enable textures since we're going to use these for our sprites
glEnable(GL_TEXTURE_2D);
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);

// enable alpha blending
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

// disable the OpenGL depth test since we're rendering 2D graphics
glDisable(GL_DEPTH_TEST);

glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, WIDTH, HEIGHT, 0, 1, -1);
glMatrixMode(GL_MODELVIEW);

```

I assume I need to change:

```
glOrtho(0, WIDTH, HEIGHT, 0, 1, -1);

```

to:

```
glOrtho(0, WIDTH, 0, HEIGHT, 1, -1);

```

# Answer
There isn't a standard way to do this; each game or engine will (and should) elect to use the coordinate model that makes the most sense for it.

That said, it's generally standard practice to *normalize* the coordinate model, so everything works the same where viable (it makes it easier to think about). That means it's generally better to have your logical world origin and rendering origins align (in the lower left or upper left, for example).

Most 3D APIs provide mechanisms to support this through the configuration of the projection matrices or similar. As you speculated, if you are using orthographic projection in OpenGL, you can just flip the parameters to `glOrtho` accordingly to adjust how your coordinate system appears.
> 1 votes

---
Tags: opengl, 2d
---


# Question
Title: How can I make a character stand on slopes?
*First of all, note that I want to understand the principle, so I would prefer explanations in plain english (but of course I have nothing against some code to complement these explanations).*

I am wondering what is the way to make a character step correctly on a slope, let's start with two screenshots of the game Limbo to show you what I mean :
So, as you can see on these pictures, it looks like the spine of the character is actually perpendicular to the horizon and not to the surface of the ground and this observation leads me to my question:
**How can you reproduce such a behavior with Sprite Kit ?** Because if I attach a physic body to a node, I have the possibility to let it rotate, so I would get something like this :

If I disable the rotation I would get something more like this :
As you can see these ways to do both present important issues and doesn't looks natural at all. **So how should I do to make it look natural ?** I thought to create several sprites and several physics bodies and then attaching them all together with joints I don't think that it will look natural because if you look at this :
Although I can physically link these nodes, how will I do to make them look real graphically ? Because in the reality, for example, the thigh and calf are linked by a knee...

**Any ideas ?**

# Answer
To expand on Josh Petrie's answer, finding the angle of the foot is also pretty straightforward.

The angle of the feet is equal to the angle of the inclined surface. Since we conveniently have two points on that slope, we can find the angle of inclination (it's also possible to use two corners of the slope's triangular shape, but gradual slopes would become over complicated; for rolling hills, this is the best solution). Ultimately the slope will be H/P (assuming the heel of the bent leg is directly beneath the corresponding hip), or arctan(H/P) rad. Using cosines, one can easily find that H = (F+T) - (Fcosθ + Tcosφ).

The angle of the foot becomes **arctan((F(1-cosθ) + T(1-cosφ)) / P)**

PS: If you want to REALLY get into, you could also find the added width to P.

PSS: The foot will only bend to far up, so keep that in mind before you try to climb an 80 degree slope.

PSSS: People don't climb hills on their heels, but they do rest on them. Keeping the foot perfectly flat up the hill could somewhat accurately depict the player standing on the balls of their toes, and allowing the heel to sink to the ground while idling could make for some very realistic movement.
> 6 votes

# Answer
There are simple solutions and tricks you can use (for example, if your slopes will all be a fixed angle, just author additional sprites for sloped movement and idle, provide a mechanism for your game code to know if you are on sloped surface, and render accordingly -- this is usually what older sprite-based games did).

A general solution, expanding on your multi-jointed sprite idea, is to use inverse kinematics to solve for the placement of a characters feet (see also).

This involves defining a logical skeletal structure for your characters, represented visually by several distinct sprites (for the torso, as many leg parts as you need, and foot). The end-effector in this system is the character's foot position on the slope, which can be computed from the (fixed) torso position and some idea of which foot is in front, based on the current walk cycle frame. Between those two known positions, an IK system can solve for the parameters to the leg joints and create a reasonable approximation of how any real biped might stabilize itself on a sloped surface.

IK is often expressed as a 3D problem, but it can be reduced to 2D space relatively easily. In 2D you don't need to futz around with nearly as many joint rotation constraints to create realistic movement as you would in 3D, which is nice.

This is the method used by many modern 2D games, especially given the trend of skeletal-based sprite compositions for characters, rather than the older technique of hand authoring every frame.
> 5 votes

---
Tags: spritekit
---


title: Libgdx - Sprites disappearing

text:
# Question
Title: Libgdx - Sprites disappearing
I'm facing a little problem and I have no idea to bypass it. I've made a dungeon generator and I'm able to spawn randomly mobs, the problem is that when they are not moving the game is fine, but at the moment they move, all other sprite (+ fps drawing on the top left) disappear. This problem was not existant when I was using the version \< 1.0 and I'm now on the 1.2 (the last). I'm using a customized Sprite class but it is working until I enter an enemy aggro circle.

What I'm doing when my game is updating is : Update player (mouvement, ...) Updating spell (reach the end, hit someone, ...) Update enemy (does the player is inside the circle of his aggro ? If so, is he behind a wall or I can see him ? If I can see him, I move toward him)

The problem is on the enemy update, when the enemy see me, everything disappear.

Here is a jar of my game to see the problem in action (commands are Z Q S D to move). Move a bit toward the guard and you'll see.

Download link

Here it's ok :

Here I'm getting the aggro :

Here is the class used and maybe causing the bug :

(update method of the main class) :

```
        @Override
    public void render() {
        Gdx.gl.glClear(GL30.GL_COLOR_BUFFER_BIT | GL30.GL_DEPTH_BUFFER_BIT);
        renderer.setView(camera);
        mouvementCamera(camera.zoom);
        camera.update();
        renderer.render();
        batch.setProjectionMatrix(camera.combined);
        player.update();
        batch.begin();
        for(int i = 0; i < player.getSpell().size(); i++) {
            Spell s = player.getSpell().get(i);
                if(s.getalive()) {
                    s.update(this);
                    batch.draw(s.getTextureRegion(s.currentAnim), s.getX(), s.getY());
                }
                else {
                    player.removeElements(s);
                    i--;
                }
        }
        for(Enemy e : enemy) {
            if(e.isAlive()) {
                e.update();
                batch.draw(e.getTextureRegion(e.current_anim), e.getX(), e.getY());
            }
            else {
                enemy.remove(e);
                break;
            }
        }
        batch.draw(player.getTextureRegion(player.current_anim), player.getX(), player.getY());
        fps.draw(batch, String.valueOf(Gdx.graphics.getFramesPerSecond()), camera.position.x + 500, camera.position.y + 200);
        batch.end();
    }

```

(player update method)

```
@Override
public void update() {
    float delta = Gdx.graphics.getDeltaTime();
    for(Cooldown cd : this.tabCd) {
        cd.update(delta);
    }

    float oldY = this.y;
    float oldX = this.x;

    if(Gdx.input.isKeyPressed(Keys.Z)) {
        if(y+collisionHeight < this.map.mapHeight * this.map.tileHeight)
            y += this.stats.speed;
        this.current_anim = TOP;
    }
    if(Gdx.input.isKeyPressed(Keys.S)) {
        if(y >= 0)
            y -= this.stats.speed;
        this.current_anim = BOT;
    }
    if(Gdx.input.isKeyPressed(Keys.Q)) {
        if(x >= 0)
            x -= this.stats.speed;
        this.current_anim = LEFT;
    }
    if(Gdx.input.isKeyPressed(Keys.D)) {
        if(x+collisionWidth < this.map.mapWidth * this.map.tileWidth)
            x += this.stats.speed;
        this.current_anim = RIGHT;
    }
    if(Gdx.input.isKeyPressed(Keys.R) && tabCd.get(0).getendCast()) {
        // directionx et directionY sont les coordonnees de la souris
        int directionX = recupDirectionX();
        int directionY = recupDirectionY();
        int centreX = calcCentre(this.x, this.collisionWidth, this.diffCollisionWidth);
        int centreY = calcCentre(this.y, this.collisionHeight, this.diffCollisionHeight);
        double norme = calcNorme(directionY, centreY, directionX, centreX);
        double newY = (directionY - centreY) / norme;
        double newX = (directionX - centreX) / norme;
        spell.add(new FireBall(x, y, 10, 10, 800, 5, newX, newY));
        tabCd.get(0).setendCast(false);
        tabCd.get(0).resetCast();
    }
    if(Gdx.input.isKeyPressed(Keys.T) && tabCd.get(1).getendCast()) {
        int directionX = recupDirectionX();
        int directionY = recupDirectionY();
        int centreX = calcCentre(this.x, this.collisionWidth, this.diffCollisionWidth);
        int centreY = calcCentre(this.y, this.collisionHeight, this.diffCollisionHeight);
        double norme = calcNorme(directionY, centreY, directionX, centreX);
        double newY = (directionY - centreY) / norme;
        double newX = (directionX - centreX) / norme;
        spell.add(new FireBall(x, y, 10, 10, 200, 5, newX, newY));
        tabCd.get(1).setendCast(false);
        tabCd.get(1).resetCast();
    }
    if(Gdx.input.isButtonPressed(Buttons.LEFT) && tabCd.get(2).getendCast()) {
        spell.add(new Attack((x + ((collisionWidth / 2) - diffCollisionWidth) - (this.stats.sizeWeapon / 2)),
                y + (collisionHeight / 2), this.stats.rangeAttack, this.stats.sizeWeapon));
        tabCd.get(2).setendCast(false);
        tabCd.get(2).resetCast();
    }

    if(gestion_collision(x, oldY)) {
        this.x = oldX;
    }
    if(gestion_collision(oldX, y)) {
        this.y = oldY;
    }
}

```

(enemy update method)

```
    @Override
public void update() {
    float playerX = this.map.player.x;
    float playerY = this.map.player.y;
    int collisionWidth = this.map.player.collisionWidth;
    int collisionHeight = this.map.player.collisionHeight;
    this.tempX = 0;
    this.tempY = 0;
    Circle circle = new Circle(this.x + (this.collisionWidth / 2),
            this.y + (this.collisionHeight / 2),
            (float)this.rayonDetection);
    if(circle.contains(playerX + (collisionWidth / 2), playerY + (collisionHeight / 2))) {
        int xPlayer = (int)playerX + (collisionWidth / 2) + this.map.player.diffCollisionWidth;
        int yPlayer = (int)playerY + (collisionHeight / 2) + this.map.player.diffCollisionHeight ;
        int xEnnemy = (int)this.x + (this.collisionWidth / 2) + diffCollisionWidth;
        int yEnnemy = (int)this.y + (this.collisionHeight / 2) + diffCollisionHeight;
        double norme = Math.sqrt((Math.pow((yPlayer - yEnnemy), 2) + Math.pow((xPlayer - xEnnemy), 2)));
        double newX = (xPlayer - xEnnemy) / norme;
        double newY = (yPlayer - yEnnemy) / norme;
        int result = checkNormeInWall(norme, newX, newY);
        if(result == 1 || result == 2) {
            if(result == 1)
                detect = true;
            if(!detect)
                return;
            getWay();
        }
        else {
                this.tempX = (float) newX;
                this.tempY = (float) newY;
                this.detect = true;
        }

        if(!collision(x, ((tempY * this.stats.speed) + y)) && !collisionInEntity(
                x + this.diffCollisionWidth,
                ((tempY * this.stats.speed) + y) + this.diffCollisionHeight,
                this.map.player.x + this.map.player.diffCollisionWidth,
                this.map.player.y + this.map.player.diffCollisionHeight,
                this.map.player.collisionHeight,
                this.map.player.collisionWidth)) {
            setY((tempY * this.stats.speed) + y);
        }
        if(!collision(((tempX * this.stats.speed) + x), y) && !collisionInEntity(
                ((tempX * this.stats.speed) + x) + this.diffCollisionWidth,
                y + this.diffCollisionHeight,
                this.map.player.x + this.map.player.diffCollisionWidth,
                this.map.player.y + this.map.player.diffCollisionHeight,
                this.map.player.collisionHeight,
                this.map.player.collisionWidth)) {
            setX((tempX * this.stats.speed) + x);
        }
    }
    else {
        this.detect = false;
    }
    setAnim(tempX, tempY);
}

private void getWay() {
    chemin = Pathfinding.generatePath(this.map.mapWidth, this.map.mapHeight,
            this.map, (int)this.x / this.map.tileWidth, (int)this.y / this.map.tileHeight);
    int xEnnemy = (int)this.x;
    int yEnnemy = (int)this.y;
    double norme = Math.sqrt( (Math.pow((yEnnemy - (chemin.y*this.map.tileHeight)), 2)
            + Math.pow((xEnnemy - (chemin.x * this.map.tileWidth)), 2)));
    this.tempX = (float)(((chemin.x * this.map.tileWidth) - xEnnemy) / norme);
    this.tempY = (float)(((chemin.y * this.map.tileHeight) - yEnnemy) / norme);
}

```

Thanks !

# Answer
I pretty much find the source of the problem. When i was launching the game, the memory of the game was litterly growing every second (+10K Ko / s). I isolated the problem and the source of it is this "part" of code :

```
protected boolean collisionInEntity(float x, float y, float xObject, float yObject, int collisionHeight, int collisionWidth) {
    Rectangle player = new Rectangle(x, y, this.collisionWidth, this.collisionHeight);
    ShapeRenderer shapeRenderer = new ShapeRenderer();
    shapeRenderer.setProjectionMatrix(map.camera.combined);
    shapeRenderer.begin(ShapeType.Line);
    shapeRenderer.setColor(new Color(0, 1, 0, 1));
    shapeRenderer.rect(x, y, this.collisionWidth, this.collisionHeight);
    shapeRenderer.end();
    Rectangle ennemy = new Rectangle(xObject, yObject, collisionWidth, collisionHeight);
    if(player.overlaps(ennemy)) {
        return true;
    }
    return false;
}

```

Have you any idea of what could be the reason of this memory leak ?
> 0 votes

---
Tags: java, libgdx, sprites
---


# Question
Title: What is the most efficient way to work with lip sync/facial expressions in XNA?
I've been searching for an answer forever, but I haven't found one. What options are there for lip sync/facial expressions in video games made with XNA? I have a few models for a game I'm building, and I would like to know if it would be better to set up an animation for every dialogue, but that would be very time-consuming and the whole collection of files would result in a massive-sized program.

I was thinking about an automated lip-sync system, but I wouldn't know where to start! Any thoughts?

# Answer
> 1 votes
Assuming you have transcripts of your audio. You could create a timestamp system that matches each word to a specific time. You could then use a system to read each word and work out mouth shapes. I. E. 'th' or 'oo' have very distinct mouth shapes. Basically read these from you transcript text and pick the correct mouth shape. Alternatively you could look into voice recognition to avoid having to timestamp all of your text. But the can get complicated quickly and is prone to errors.

# Answer
> 1 votes
I'm not experienced in this so my answer is only an idea, but you may be able to use an extension which allows the analysation of sound files making a list of floating points on how loud the voice is, then translate that to how far your model opens it's mouth. Simple to understand, looks ok in the game. Take Team Fortress 2 as an example. They don't have amazing talking animations but they seem real enough.

---
Tags: xna, c#, sound
---


# Question
Title: How can I add an impulse to specific rigid bodies at rest?
**Scenario**

Rocks falling down a rocky slope, with a flat surface at the bottom. When they land on the surface, the rocks move slightly before coming to a rest.

`GLESDebugDraw` shows the bright orange outline turning to a slightly darker orange once a rock comes to a rest, until the rock is agitated by another falling rock.

**Question:** I would like to add an impulse to the rock once it reaches the rest state. How would I implement that?

# Answer
If you have sleeping allowed (and the `b2_timeToSleep` is sufficiently short for your needs) you can use the `b2Body::isAwake` function to test if a rock is settled.

Pseudo-code:

```
For body in bodies:
  If(body is rock and not body->isAwake()) Then
    //Apply impulse
  End If
End loop

```
> 1 votes

# Answer
I've come across this problem before when I was developing some physics code for a college project. I'm going to make an assumption that there is some code handling whether or not your rock is in a rest state. If you don't have this piece of code then it can be implemented as follows:

```
float positionEpsilon = [EPSILONVAL] // Use to check if the position of the rock has changed by a significant amount

// Update the rock
void UpdateRock(Time delta)
{
    changeInPosition = [CURRPOS] - [PREVPOS] // Take the last position from the current position
    .
    .     // Some code
    .
    if(changeInPosition < positionEpsilon)
    {
        // Here you could perform an action on the rock
        // or put it to sleep and check if it's asleep
        // in another part of the code
    }
}

```

That's a general enough explanation of how I got it working in my project where I just used basic C++ to build the engine. You're using Box2D so it should be much easier to check if a body is asleep using b2Body::isAwake() function.
> 0 votes

---
Tags: physics, box2d, ios, cocos2d-iphone, rigid-body-dynamics
---