# Question
Title: How do I correctly shift arrays on a Tetris line clear?
I'm writing a Tetris clone in C++ and I am at the last stage, I need to delete a row when it is full. Once a piece falls it is stored in a boolean array `grid[20][10]`. For example I check which row is full (or `true`), if so I call a method `deleteRow`, where `n` is a number of row:

```
void Grid::deleteRow(int n)
{
  for (j = 0; j < WIDTH; j++)
   {
     grid[n][j] = false;
   }
}

```

Once the row is deleted I call `moveRowDown`:

```
void Grid::moveRowDown()
{
  for (i = 0; i < HEIGHT; i++)
   {
    for (j = 0; j < WIDTH; j++)
     {
       grid[i+1][j]=grid[i][j];
     }
  }
}

```

This does not work, and all of the pieces disappear. What logic am I missing?

# Answer
> 2 votes
When i is 0 you copy the row 0 into the row 1, then i is 1 and you copy the row 1 into the row 2, etc. The problem is that when you copy the row 1, it has already been overriden.

You probably also have a problem when i = HEIGHT because i+1 is out of bounds.

The solution would be to iterate from the bottom row to the top row (from HEIGHT-1 to 1):

```
for (i = HEIGHT-1; i > 0; i++)
{
  for (j = 0; j < WIDTH; j++)
  {
    grid[i][j]=grid[i-1][j];
  }
}

```

---
Tags: c++, algorithm, data-structure, grid
---


# Question
Title: How do I create a custom collision map for clickable areas on a map?
Say I had a map like the one displayed above. What would be the best method of creating a collision map for each individual state where I can click individually?

# Answer
> 5 votes
Convert your image to grey-scale. Make sure you have no two states that have the same grey. (You have to tweak the image.)

Have an infrastructure that maps the grey colour to a state.

Then when you mouse-over the map, pick the pixel colour that is under the mouse pointer, and search for it in the map.

You'll know what state you want to select this way.

---
Tags: collision-detection, maps
---


# Question
Title: Overriding CoRoutine doesn't execute base code
I want to have a `CoRoutine` declared as `virtual` in parent class and then overridden in child classes.

```
protected override IEnumerator f(Vector3 to)
{
...
    yield return base.f(to);
...
}

```

What happens (or doesn't happen) is that the base code doesn't get executed. Debuggin it I step into the `base.f(to)` and the cursor just stand on function name. If I press step next control returns to the child.

I really have no clue how to handle this situation. Any clue?

# Answer
> 2 votes
IEnumerators (more specifically, yield return) are special and magic pieces of syntax sugar.

What is happening is that the compiler creates (at compile time) a class that packages all the state of the function you wrote. And then substitutes the function with a stub that creates an instance of the class and returns it.

So you're not running your code in `yield return base.f(to)`, you're just creating an object and returning it.

CoRoutines are also special and magic pieces of Unity, they iterate over what is returned and if given some special type of value it does something else special.

These things include:

* Scheduling the CoRoutine to be continued at some later point in time
* I have no idea I don't use that much Unity to be honest :)

So what you're returning from your CoRoutine (the override) is an IEnumerator, Unity doesn't know what to do with the coroutine so it doesn't do anything special and asks for the next value. Which runs the bit after your `yield return` and... stops, because there's nothing more to be done.

What you should do is this:

```
protected override IEnumerator f(Vector3 to)
{
...
    var baseVal = base.f(to);
    while ( true ) {
       yield return baseVal.Current;
       if ( baseVal.MoveNext() == False ) break;
    }
...
}

```

I don't have access to an Unity setup at this time so this is untested, I also don't know what happens with an IEnumerator that never returns a single value (or if that is even legal).

# Answer
> 1 votes
Try this instead:

```
  protected override IEnumerator f(Vector3 to)
  {
  ...
      yield return StartCoroutine(base.f(to));
  ...
  }

```

Coroutine inherits from YieldInstruction, and yielding on one will cause your coroutine to pause until the other coroutine completes.

---
Tags: unity, coroutines
---


# Question
Title: Are there definitive, unambiguous terms for hexagon tile orientations?
I have been working on a tile map editor and plan to support two orientations for hexagons. I have seen various terms used, but these all seem ambiguous to me.

* Horizontal, Vertical (ambiguous: does this mean they line up horizontally, or stack horizontally?)
* Flat, Pointed (ambiguous: Are they flat on the sides or top and bottom?)

I would like to find **unambiguous** terms for the following two orientations for hexagons -- ideally, these would be **definitive** and **succinct** (I could refer to these as "Flat on Top" and "Pointed on Top" but would prefer something more technical and authoritative).

**Edit:** I was holding out for something more technical, but it's hard to argue with Amit. For me, "pointed" sounds more formal than "pointy," so I am going to use the following (a decision reinforced by DMGregory's answer): **Flat-top** and **Pointed-Top**.

# Answer
While I don't know of any truly official convention for classifying these, in the mathematical sense, I'll take Anko's advice and write up what I do know...

Amit Patel (Red Blob Games) wrote what I'd consider the definitive guide to using hexagonal grids in games. This guide uses the nomenclature:

* flat topped
* pointy topped

So while it's not super technical-sounding, I think it's as close to authoritative as we're likely to find. The terms are also understandable and unambiguous even without specialized technical knowledge, which is a huge win.

If you want something less informal, you could try names along the lines of "staggered columns" vs "staggered rows" but I think this is substantially less clear.
> 9 votes

---
Tags: tilemap, terminology, hexagonal-grid
---


# Question
Title: How to render multiple projections of an object?
I want to display multiple projection of an object on the same screen. The projection should also change as the body rotates, kind of a dynamic projection of the body.

I am trying to make a character for pyramid hologram (as it has been named) which needs the projections.

Here is an example found on the Internet:

(Image source)

# Answer
> 1 votes
One blunt way to do this in Unity is to set up 4 cameras surrounding your object with your desired size/field of view/etc.

In your Assets folder (or a suitable subfolder), create 4 RenderTextures for the 4 views. Assign each camera's Target Texture to one of the RenderTextures.

Now drag the 4 RenderTextures into your scene and arrange them into the pattern you want the displayed on the screen. Add a 5th camera to frame & capture this layout, setting this camera's depth to render after the other 4.

You can also skip the RenderTextures and simply have each camera render straight to the framebuffer, using the Viewport Rect properties to control which part of the screen each one renders in, and rotating the cameras themselves to orient each view of the object.

Here's a quick example of this method:

Here I still have one extra camera, rendering before all the others to clear the background to black.

---
Tags: unity, projection
---


title: How to handle collision detection

text:
# Question
Title: How to handle collision detection
So the way that I am doing the movement for my game is that you can left click a unit (which is just a rectangle object), and then it is selected. While it is selected, you can right click and that will be the unit's destination.

This is the process input method:

```
    public void ProcessInput(Vector2 mouseLoc)
    {
        // SO, I have to take this mouse location, which is the location on the screen
        // And convert it to a "world" coordinate

        Vector2 distance = new Vector2(mouseLoc.X - position.X, mouseLoc.Y - position.Y);

        if (distance.Length() < speed)
        {
            position = mouseLoc;
            isMoving = false;
        }
        else
        {
            distance.Normalize();
            Vector2 toMove = new Vector2((int)(distance.X * speed), (int)(distance.Y * speed));
            position += toMove;
            bounds = new BoundingSphere(new Vector3(position, 0), radius);
        }
    }

```

I have a basic Wall class that is essentially just another rectangle object but with different properties like textures and what not.

This is my check collision method with the wall:

```
    public Boolean checkCollision(Wall wall)
    {
        if (wall.Bounds.Intersects(this.bounds))
        {
            Vector2 direction = new Vector2((position.X - destination.X) * -1,
            (position.Y - destination.Y) * -1);
            direction.Normalize();
            position += direction * 5;
            destination = position;
            return true;
        }
        return false;
    }

```

The problem is that the unit just kinda gets stuck in the wall when it hits it. I'm wondering what is the best way to fix this problem. I know that I have to move the unit out of that spot, but I'm not sure how to.

Any thoughts on how to handle this are appreciated.

# Answer
I do not know which physics engine you are using but generally , if you want to things go smooth you have two decent ways:

* Dynamically, use forces to move and let the engine handle the collisions.
* Kinematically, use your own calculations to move and handle collisions.

If you use kinematics for some of the huge bodies (you have to use kinematics for small bodies like bullets generally) and dynamics for other there will be wrong collision responses.

The answer to your question is generally, make the dynamic object kinematic on collision and move it backwards. When it is not collided anymore make it dynamic again.
> 1 votes

---
Tags: c#, collision-detection, monogame, collision-resolution
---


# Question
Title: Get enum value "string", and get int value of that
Sorry if the title is confusing, but I literally don't even know how to summarise this into a title. So here's the problem:

I have a list of combat moves for a character. I have an animation for each of those possible moves. When the "combat manager" (instantiated to manage each individual fight) works out what move the enemy and your person will make, it should tell the Animator to play the animation specific to the selected move. I'm really not sure how to go about this so:

The player's Animator has a state for each possible move, containing that move's animation. The script controlling the Animator has a public enum "CombatMove" containing every possible move **(ie. CombatMove.WhicheverMove)**. So the Combat Manager will get the name of the move **(eg. "Right Middle Jab")**, remove the spaces and search for an enum value whose name is that string **(eg. CombatMove.RightMiddleJab)**. Now it has the corresponding enum value, it retrieves the int value of that **(eg. 0)**. It then sends that int value to the Animator, where each move's transition will occur if the int value equals the move's int value on the enum. So summed up:

move's string name, turned into an enum value name, turned into its int value, used to specify which move animation should be played.

The questions:

1) How do you find an enum value whose name equals a given string?

2) How do you get the int value of that enum value?

If this is confusing, ***please comment*** what makes no sense and I will try to explain, I'm honestly so lost that I don't even know how to ask what I need to ask.

## EDIT:

IF anyone is wondering what I mean by 'int value', Fafase's answer at http://answers.unity3d.com/questions/764091/using-c-enums-to-control-an-animator.html says that each enum value has an int value by default, which can be used in animation conditions; however I have no idea how to access them, which part 2 of my problem.

# Answer
Would this do it?

```
enum CombatMove
{
   RightMiddleJab,
   LeftMiddleJab,
   RightUpperJab,
   LeftUpperJab,

   LastCombatMove,
   Unknown
}

```

call example..

```
        CombatMove move;
        if( findCombatMove("RightUpperJab", out move) == true )
        {
            // do something with move
            int intValue = (int)(move);
        }

```

.

```
    static bool findCombatMove( String text, out CombatMove move )
    {
        for( int c = 0; c < (int)CombatMove.LastCombatMove; ++c)
        {
            String enumAsString = ((CombatMove)(c)).ToString();

            if (enumAsString == text)
            {
                move = (CombatMove)(c);
                return true;
            }
        }

        move = CombatMove.Unknown;
        return false;
    }

```

It would be a lot of string compares though. Could you not pass the enum directly instead of the string ?
> 1 votes

# Answer
You can override the size of the enum, if needed:

```
enum CombatMove : int //implied, 32-bits, max value 2147483647
{
   RightMiddleJab = 0, //0
   LeftMiddleJab = 1,  //1
   RightUpperJab = 3,  //3
   LeftUpperJab,       //4
}

```

And since you can cast them, there is probably no reason to refer to them by name:

```
CombatMove combatMove = CombatMove.LeftUpperJab;
int combatMoveValue = (int)combatMove;

```

I don't know exactly what you are trying to index, both types are arbitrary:

```
using System.Collections.Generic;
Dictionary<CombatMove, AnimationClip> AnimationClipsByEnum;
AnimationClipsByEnum[CombatMove.RightMiddleJab].ClearCurves();

```

**Strings**

If you really do have a good reason, you can use the `System.Enum` class:

```
string[] CombatMoveNames = System.Enum.GetNames(typeof(CombatMove));

```

The dictionary for strings:

```
using System.Collections.Generic;
Dictionary<string, AnimationClip> AnimationClipsByName;
AnimationClipsByName["RightMiddleJab"].ClearCurves();

```

Parsing a string back into to an enum:

```
    string combatString = "RightMiddleJab";
    try
    {
        CombatMove combatMove =
           (CombatMove)System.Enum.Parse(typeof(CombatMove), combatString);
    }
    catch (System.ArgumentException)
    {
        Debug.Log("Invalid enum string: " + combatString);
        throw;
    }

```
> 2 votes

---
Tags: animation, unity, combat
---


title: Finding dead ends in maze

text:
# Question
Title: Finding dead ends in maze
I am creating a maze type puzzle game where there is a grid and the user can create their own maze but I need help in writing an algorithm which finds the following things:

1. How many dead ends are there. (*It should return 4 tunnels which are marked red*)
2. How many of those dead ends don't lead to the exit. (*It should return 3 tunnels as only 1 dead end leads to the **END** point*)
3. Which dead ends lead to the end. (\*3rd dead end only)

I am new to writing algorithms so I haven't written code for this yet. How can I identify dead ends, and which ones don't lead to the exit?

# Answer
One of many possibilities and the one I'd use is:
**1.** Start a Flood Fill from the start square, to find which squares are connected to it;
**2.** For each square marked with the flood fill verify how many walkable neighbors it has. Dead-ends should only have one walkable neighbor.
**3.** If said dead-end is connected to the exit of the maze, mark it as so;

A pseudo-code could look like this:

```
function flood_fill(square)
  if (square.walkable == false) return;
  count = 0;
  foreach(neighbor in square.neighbors) {
    if (neighbor.walkable) {
      count += 1;
      flood_fill(neighbor);
    }
  }
  if (count == 1)
    square.dead_end = true; // Or you could add it to a list

//And in the required section of the code
flood_fill(maze.start)

```

Addendum: Since you did not specify how to know if a square leads to the exit I left it out the pseudo-code.
> 3 votes

# Answer
There are multiple way you can write this. It just depends on your personal preference and if you are wanting visuals to the implementation of the algorithm. An example is you could have all squares in the grid in an array and have a variable move throughout the array in whatever fashion you find fit. If it finds a square labeled "e" it is at the exit, if it finds one labeled "d" it could be a dead end. In this example you would have to marl the starting position as well so you know not to include it as a dead end.

So essentially you'd just have to have the algorithm move throughout the array determining if the square that it is currently in is part of the maze, if not then move back. Continue that until it has made it through the grid. Just make sure you are only mov ok no from squares adjacent to one another which is easy enough. If it finds that it cannot go any direction but back from where it came then it can mark it as "d" for dead-end unless it has made it to the exit.
> 0 votes

# Answer
The easiest way to do this and find the literal "end" of a dead end is to count the walls. This is presuming that you cannot have loops and you define walls for your cells.

Iterate through your cells and just find all with 3 walls as those are the only cells which are a dead end, as the can only have one exit it *must* have only 3 walls.
> 0 votes

---
Tags: algorithm, maze
---


# Question
Title: Locust Swarm algorithm for path finding (devour and move on)
I need to model a locust swarm that **devour** food stacks and **move on** to next stacks. I searched for articles and found few articles. These papers is about optimization applications but I want to convert it to a path finding algorithm to **reach multiple targets** (like randomly seeded many food stack). Swarm should split when food stack is not enough to feed them( multiple objective problem). How can I do this?

x: position v: velocity vector

# Answer
> 2 votes
Is this what you want?

As for finding the closest food stack, calculating the center of the swarm and using a simple A\* algorithm to search all other food stack from the lowest minimum distance to the highest works, or even just a lookup table to map food stacks with their nearest neighbours (Only works if your food stacks are static and regrow).

## EDIT

To further answer the question:

The above solution might or might not work based on the new requirements stated in the comments. Or rather, it works, but becomes quite a heavy computation quite quickly.

You can assign N swarm members to stay at the food stack, and let the rest search for another stack. However, I would predict that the swarm members would spread out quite quickly, to the point where individual swarm members are searching for stacks. The Goal-Based Vector Field Pathfinding can handle that, but the A\* might suffer.

If you want to take this aproach, you should really create a lookup table, or assign a array with the closest M stacks (Where M is some constant) to a field (so for each path-finding node in the world), which would use up a lot of memory.

Assigning swarm members to swarms might also help (Where every swarm gets a food stack assigned). This way the A\* algorithm can operate on N members at once, as long as no member made it to the stack you can just make all members move in the same direction.

### Best case

You can of course just create a vector field for every food stack with a weight, If you store the closest M stacks again. However, this would take up A LOT of memory (Multiple vector fields, so `struct { int dx; int dy; int weight }` ~= 12\*M bytes PER NODE. This *REALLY* doesn't work for large world. If the world is small, this is the solution, but if the world is large, I think I can't help further.

---
Tags: algorithm, path-finding, multithreading
---


title: Nifty TextRenderer object is null

text:
# Question
Title: Nifty TextRenderer object is null
Im new to nifty and Im trying to change text control using nifty in JME application following this tutorial.

Below is my TextRenderer code:

```
Element element = nifty.getScreen("loadlevel").findElementByName("loadingtext");
TextRenderer textRenderer = element.getRenderer(TextRenderer.class);
textRenderer.setText("loadingText");

```

Below is my nifty GUI code code for loadLevel scene:

```
<screen id="loadlevel" controller = "jmebase.TestLoadingScreen">
        <layer id="loadinglayer" childLayout="center" backgroundColor="#000000">
            <panel id = "loadingpanel" childLayout="vertical" align="center" valign="center" height="32px" width="70%">
                <control name="loadingbar" align="center" valign="center" width="100%" height="100%" />
                <control id="loadingtext" name="label" align="center"
                         text="                                                  "/>
            </panel>
        </layer>
    </screen>

```

I printed value of for both element and textRenderer. **element is initialised properly** but **textRenderer object is null**. I googled lot and lots of people got this issue but none provided appropriate solution. Anyone know how to fix it. Im really stuck need help.

# Answer
`getRenderer` is going to return `null` if the element does not contain the class you're trying to retrieve. In this case, the element doesn't contain a `TextRenderer`, so it returns `null`.

You can avoid the error:

```
Element element = nifty.getScreen("loadlevel").findElementByName("loadingtext");
if(element == null)
    return;

TextRenderer textRenderer = element.getRenderer(TextRenderer.class);
if(textRenderer == null)
    return;

textRenderer.setText("loadingText");

```

To get your expected result of setting the text, you need to ensure the element you're locating is properly configured.
> 1 votes

# Answer
First off, the tutorial you linked is outdated. I also can't find any reference to Nifty in it.

I'm using Nifty 1.4 and cannot reproduce your problem. I can set the text via `TextRenderer` from the label.

However, you should avoid using renderers directly if you can achieve the same with a `NiftyControl`:

```
Element loadingtext = screen.findElementById("loadingtext");
Label label = loadingtext.getNiftyControl(Label.class);
label.setText("new text");

```

If this doesn't work for you, there might be a problem with your version of Nifty.

Also note: A text element is not the same as a label control. The Nifty manual explains this in detail: https://sourceforge.net/projects/nifty-gui/files/nifty-gui/1.3.2/nifty-gui-the-manual-1.3.2.pdf/download
> 0 votes

---
Tags: jmonkeyengine, nifty-gui
---


title: Player collision with object

text:
# Question
Title: Player collision with object
I have an FPS controller and I want to change the camera when it collides with a box collider. I think I did it properly but it didn't work. Here's my code:

```
using UnityEngine;
using System.Collections;

public class change_camera : MonoBehaviour
{
  public Camera Playercamera;
  public Camera Topcamera;

  void OnCollisionEnter(Collision col)
  {
      if (col.gameObject.name == "FPSController")
      {
          Playercamera.enabled = false;
          Topcamera.enabled = true;
      }
  }
}

```

Thanks in advance.

# Answer
> 1 votes
As people said in comment, you need to provide more information. Here is a list of stuff you can check:

* Are Playercamera and Topcamera properly set in the editor
* Did you add your script to the objects you want to react to collision
* Did you add a collider component to these objects
* Did you check the "Is trigger" option (if yes, you should use OnTriggerEnter instead

Something you can try is to write a debug line in your function

```
void OnCollisionEnter(Collision col)
{
    Debug.Log("Collision detected");
    if (col.gameObject.name == "FPSController")
    {
        Playercamera.enabled = false;
        Topcamera.enabled = true;
    }
}

```

This will write the text "Collision Detected" in you console if the function is called properly

---
Tags: unity, collision-detection, camera
---


# Question
Title: How to restart the game when pressed enter in XNA
If the following code allows the game to exit when pressed esc ..

```
if (gamePad.Buttons.Back == ButtonState.Pressed
    || keyboard.IsKeyDown(Keys.Escape))
{
    this.Exit();
}

```

Then this code should allow the game to restart when pressed enter...

```
if (gamePad.Buttons.Back == ButtonState.Pressed
    || keyboard.IsKeyDown(Keys.Enter))
{
    this.Reset(); //<< PROBLEM HERE!!
}

```

What do I put here? Because Reset is not the keyword for it... I'm a beginner so if this is so wrong and stupid I am sorry.

# Answer
> 2 votes
XNA does not have a built-in function to restart the game, so you will need to do this yourself. You could even write a function within the `Game` class so that you could actually call `this.Reset();`.

```
private void Reset() {
  // Reset all variables
  health = 100;
  score = 0;
  level = 1; // etc.
}

```

Obviously, the implementation will be different depending on the details of the game, but will include resetting the important variables like score, player position, etc.

# Answer
> 0 votes
A Windows-Only solution to ACTUALLY restart the game:

In the Program.cs main method, you're probably doing something like:

```
MyGame game = new MyGame();
game.Run();

```

The Run method is blocking, and will not return until the game exits. To restart the game you could simply have a global static variable that you set to false at the initialization of the game, and in your Enter-Clicked method sets to true. Then check on return of the Run method if that value is True, and if so, run the thing again. So basically:

```
do
{
   Program.ShouldRestart = false;
   MyGame game = new MyGame();
   game.Run();
}
while (Program.ShouldRestart);

```

and in your Enter-Clicked method:

```
Program.ShouldRestart = true;
this.Exit(); // Assuming 'this' is the instance of the game.

```

Keep in mind, this won't completely restart the whole process, so any static variables you have will maintain their current values between "restarts".

Hence, why you should avoid static variables as much as possible.

# Answer
> 0 votes
You can try to add this line:

```
gameStateManager.getLevel(1).LoadContent();

```

It may help you to achieve GAME RESTART, but I'm not 100% sure because I'm new as well.

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


# Question
Title: How to create a normal map for my dice texture?
I have this simple dice texture and would like to create a normal map for it where the black dots are are dents and the edges are trimmed(like on a actual dice) I'm using unity5. I need a explanation on how to create the normal map in PhotoShop CS5 or a code solution. Thanks in advance.

Here is the dice texture I'm using.

# Answer
> 0 votes
*I won't describe how to actually use the different tools in Photoshop, because that's very much artist related and out of the scope of this site.*

A (tangent space) normal-map represents the local normal, or the orientation of that part of the face. If your brain can realize it and know exactly what combination of colours to use to draw it, you can draw it manually in Photoshop. My brain can't do that, and I'm sure the amount of artists that can do it is close to zero.

Since it's an orientation, it can be inferred from height information.

This is why you need a height-map first.

A typical height map is a grey-scale image, where white colour represents the highest height, and black represents the lowest height. All the greys in-between represents various other heights.

Using your texture as a guide, you can draw something like this with Photoshop (I used line, rectangle and brush tools):

After that, you can use a tool to easily convert the produced image from a height-map to a normal-map, I used this online tool to produce this normal-map:

I think you could also use NVIDIA Texture Tools for Adobe Photoshop to produce the normal-map.

## Summary

1. Use your texture as a guide
2. Draw a height map
3. Use a tool to convert the height map to a normal map

## PS

I know the aforementioned NVidia tool can produce a texture to a normal map. It's simple and fast, but the results are of a lesser quality than producing the height-map yourself.

# Answer
> 1 votes
Unity can create a normal map from a simple greyscale image where white is the highest and black is the lowest. That means the albedo texture you have there might already serve as a simple normal map.

Just create a copy of the image file, go back into the unity editor and drag the image into the "normal map" slot of the standard shader. There will be a warning that it is not imported as a normal map with an offer to fix it. Do that. Then go into the image asset and check "create from greyscale". For more information, check the documentation.

You should now have the dimples shaded as cylindrical holes.

To make them look more like spherical holes, go into your favorite image editing program and replace the dimples in your normal-map with radial gradients from white to black.

---
Tags: unity, normal-mapping
---


# Question
Title: How to optimize this branching instruction?
I have an outline shader, which samples my texture 8 times to compute the outline.

The problem is, that there's transitional alpha values between picture and background. To cut them off I'm using the following function instead of just sampling my texture by calling `texture2D()`.

```
vec4 texSample(sampler2D sampler, vec2 pos)
{
    vec4 color = texture2D(sampler, pos);

    if (color.a < 0.5)
    {
        color.a = 0.0;
    }

    return color;
}

```

The question is: are there any ways to optimize this check or even avoid it at all?

# Answer
> 1 votes
There's really not much room for optimization here, having divergent branches over such a small if body is probably not affecting your performance really at all.

You could use something like `discard` which might convey your intention better, but ultimately will not change your performance.

Taking from this post, here's an example usage.

```
if (color.a < 0.5)
{
    discard;
}

```

As a final side-note, if this shader is causing you performance issues you should look somewhere besides the shader. There's really nothing wrong here. You could make sure you're properly using mip-maps, I think that's a common source of slow down in OpenGL-ES because they're not generated by default.

This post has a link to a tutorial on mipmaps and how to generate them.

# Answer
> 0 votes
Use the built-in glsl function step to set any alpha value below 0.5 to 0.0.

```
color.a *= step(color.a, 0.5);

```

---
Tags: shaders, glsl, opengl-es
---


# Question
Title: Dynamic navigation mesh generation algorithm
I'm working on a 2D game (top down / zelda like view)

I'm struggling with navigation mesh generation, in complex scenarios my homemade algorithm is lost and too slow...

I would really love to see a detailed explanation of Hertel-Melhorn Algorithm (if you have any ressources). I'm open to suggestions for other good algorithms, as long as I can process round and square obstacles.

My map is randomly generated and obstacles can be added anytime.

* I don't want to use a grid system, my entities are positionned freely.
* My map is big so I can't store precalculated paths / I just need pathfinding to be efficient

I'm working with Javascript, I can't use c++ library like detour/recast

---

## Edit

I am looking for serious documentation of fast triangulation algorithm

If I understand the process of navmesh generation :

1. Input walkable area(s) as polygons
2. triangulation of walkable area
3. (Optionnal) merge triangles to big convex polygons
4. Output a node graph

# Answer
I'm afraid this answer won't be satisfactory for you.

1. You say you have obstacles, and if i understand right, these would be *inside* a surrounding, large polygon? The Hertel-Melhorn algorithm works on a single polygon only, not on a polygon holding polygons inside. Additionally, having multiple obstacles (polygons) for partitioning on the outside creates a "compare each polygon to each other" situation. And that sounds very exponential = expensive.
2. You say you want to include round obstacles. Seen from outside, a circle is concave, implying that *each* of it's vertices is a partition point, and the same of course goes for each other round obstacle as well. It seems this pretty much nullifies the advantage of partitioning in the first place?

A bad path for the logic may be that you want to first create a large, full data set for the entire scenario, and apply navmesh thinking on that - have that as a basis for all objects' all navigation, and maybe for a loger period of time, while yet having moving (or at least appearing/disappearing) obstacles. As partitioning is a "global" thing, each minor change somewhere would cause an entire arena re-partitioning?

Perhaps it would still be more sensible to apply local-to-the-moving-object pathfinding grids (small, isolated ones) with high granularity, such that only take into consideration what is relevant for (very nearby to) the object in question, at it's very current position and only for the next few moments. And then have a larger scale similar, for general (main goal) movement directions?

Also to note: Moving objects do often not have to follow grid points (or node points) exactly. This depends on what they are. You can still make them dislike turning, react slowly, aim n points ahead, calculate curves/polynoms to follow in the grid, etc.
> 1 votes

# Answer
I believe, if you are creating a voxel mesh up 2D, you should create a class that takes a 2D position (Vector2), and one byte (0-255). Every position, there is a value from 0 to 1, and there is a function in the script the AI that makes it surround a position, and a script that do it an interaction between the positions of enemies and items from the list, and when are with a distance, I know it, 10, it calls the function or void AI and passes the corresponding position.
> 0 votes

---
Tags: javascript, navmesh
---


title: Circular fighter motion algorithm

text:
# Question
Title: Circular fighter motion algorithm
Is there an algorithm to make ships take semi-circular patterns? I need something like the below image:

Big Blue- Command Ship Small blues - fighters Red lines - path of movement

I want the fighters to zip around the command ship while avoiding obsticles such as space debris and eachother. I need at most a dozen fighters zipping around each ship and there would be up to a dozen command ships zipping around at a slower pace. All the fighters should return to the ship every once in a while for repair and rearming.

I chiefly need the circular path and I need to keep the path centered constantly on the command ship despite any movements. **Are there any circular path finding algorithms? (and a better question; is there an official term for this kind of algorithm/path?)**? Also note that I am developing this as an RTS for mobile, so the least expensive the operation the better.

# Answer
> 1 votes
Here is something that just popped into my mind: Have you seen the simulation of 3-body system? The two fighting ships can be two of the bodies, and a 3rd (invisible) body is there to create the chaos. Take a look at this video to get a feeling what it's going to look like in practice:

https://www.youtube.com/watch?v=VX9IdCnNWJI

Also since you are not actually simulation a 3-body system, you should be able to change the parameters and customize the final look quit easily.

---
Tags: algorithm, path-finding
---


# Question
Title: Can I use xna tutorials to learn monogame?
Can I use xna tutorials to learn monogame? I can't find any good monogame tutorials but there are tons of xna tutorials available and from what I have seen they are pretty much the same thing.

# Answer
Yes.

The MonoGame API is intended to be exactly the same as XNA. In most cases this is entirely true. If MonoGame doesn't work just like XNA it's usually considered a bug.

The exception to the rule is the way the Content Pipeline works. Although, once you get your head around it things are fairly similar.
> 4 votes

---
Tags: c#, xna, monogame
---


title: Psudo 3D(2.5D?) Projectile motion

text:
# Question
Title: Psudo 3D(2.5D?) Projectile motion
I'm trying to simulate a ball coming at the screen with a projectile motion arc in 2d space. Is there a set of equations to deal with this. I would imagine the equation would need to take in the initial vertical and horizontal angles of the projectile as well as it's initial velocity and the desired start and end scale of the projectile.

# Answer
The basic implementation of projectile physics doesn't require any trigonometry.

First of all, you need to model the movement of your object with a velocity vector. A velocity vector is a structure which stores the velocity of an object on the x-axis and y-axis as spearate values. To move the object by a velocity vector, add the x- and y-value to its x- and y- position every logic-tick.

Gravity is then added to the simulation by subtracting the gravity from the y-axis of the velocity vector every logic-tick.

You didn't mention any programming language in your question, so here is a simple pseudo-code implementation in two dimensions which can be easily adapted for 3d by adding a z-coordinate which behaves like the x-coordinate:

```
// ball position:
float ball.x = [horizontal start position]
float ball.y = [vertical start position]
float ball.z = [depth start position]
// ball velocity vector:
float ball_velocity.x = [intial horizontal speed]
float ball_velocity.y = [initial vertical speed]
float ball_velocity.z = [initial depth speed]
// gravity constant:
const float gravity = [desited gravity constant]

function tick() {
      ball_velocity.y -= gravity;
      ball.x += ball_velocity.x;
      ball.y += ball_velocity.y;
      ball.z += ball_velocity.z;
}

```

To add perspective scaling to the simulation, simply divide the size of the ball by the distance to the camera. Assuming your camera is on z = 0, your draw function would look somehting like this:

```
function draw() {
     float ballDrawSize = ball.radius / ball.z;
     graphics.drawBall(ball.x, ball.y, ballDrawSize);
}

```
> 1 votes

# Answer
You could start with the 2d equation for the arc of the projectile, represented by some function of time:

```
function getPosition(time) {
    return {
        x: xInitial + xInitialVelocity * time,
        y: yInitial + yInitialVelocity * time + 0.5 * gravity * time * time
    }
}

```

Then to create the 2.5D effect, map the position by multiplying the x position by the cosine of some `angle`. This angle represents the angle around the y-axis, to make it appear like a projectile is going in or out of the screen. Assuming xInitialVelocity \> 0, an angle of 0 represents the projectile going to the right of screen. An angle of 90 -\> projectile coming straight out of the screen. 180 -\> left of screen and 270 -\> away from screen.

```
function getPositionPsuedo3D(time, angle) {
    position = getPosition(time);
    return {
        x: position.x * cos(angle),
        y: position.y
    }
}

```

You would also need to set the scale of the ball so it appears to be getting larger or smaller based on the time and angle:

```
function getScale(time, angle) {
    return 1 + sin(angle) * someScaleFactor * time;
}

```
> 0 votes

---
Tags: projectile-physics, 2.5d
---


title: How to create UI for 2D games?

text:
# Question
Title: How to create UI for 2D games?
I'm working on a game using Haxe + Flambe but I'm having a hard time making the UI part of it (main screen, level selection, etc).

And I began to think... is there another way?

I would love to have something like Flash, I mean, WYSIWYG like to make the UI. Just because I don't want to spend my time coding the screens until they look like what's on my mind.

**So the questions are:**

How do people work?

Is there something visual to make the UI for games that'll be programmed on Haxe (it doesn't matter if using OpenFL, Flambe or other)?

# Answer
> 1 votes
There is this haxe ui builder you might want to check out.

In general however, if such a tool doesn't exist or doesn't give you what you want, what might help is to create the UI using an image editing program (like Flash/Animate or Photoshop). You can edit and fine tune it until you are happy with it, and when you are done write the code manually. This way you only really have to write the code once, and you already know what it's going to look like.

---
Tags: flash, ui-design, flixel, haxe, flash-develop
---


# Question
Title: Unity move canvas slightly with smartphone acceleration
I'm developing an AR-App with the Samsung-GearVR. To get a smooth UI, I thought about creating a UI, which is not completely fix, I thought it could be nice, when the UI is slightly behind my head movement, but still lerps to the correct position, when my head is not moving. (A lot of 2D-Sidescroller got this style of camera, which is not fixed on the character, but instead is following the character with a bit of delay, I want this effect for my canvas.)

First off I changed my canvas to `World space`, which works fine, then I was thinking about the `Input.acceleration` method, but it does not really give you the actual acceleration, but the actual rotation of the phone. Now I'm struggling, because I don't know, how to get the current acceleration. Is there some better way to achieve this effect or do I have to build something with the `Input.acceleration` method?

# Answer
> 0 votes
u need Input.gyro.userAcceleration

**Edit:** for some Android devices I had to manually call Input.gyro.enabled = true; not sure if it's the same for Samsung-GearVR

---
Tags: c#, unity, mobile, hardware-acceleration
---


# Question
Title: How to limit and direct player's view in VR?
We are making a VR game where the player will look at the world through the eyes of his character who sometimes moves on his own, so the player is only observer.

The character will rotate his body on his own and we need to change the orientation of player's camera to look where the character looks. For example, the girl takes his hand and leads her way. It would be very unrealistic if the player's head will be turned 180 from his body and he will walk backwards.

It'll allow us to avoid exhausting head rotations. Is it a good idea to guide his view by force by limiting camera euler angles relative to the direction of the body?

# Answer
When someone leads you by your hand, your body can't rotate but your head can.

Separate the two interactions of rotating body and rotating head when it comes to the girl grabbing their hand. Make it a prompt for the player to look at the girl directly with both his body and head facing forward before this interaction can start.

Once they do this, lock their body rotation so that he can only look around using the VR and let the girl grab their hand. This maintains the human control needed to limit the Simulation Sickness risk providing the natural head movement, but at the same time allowing being led by the hand to restrict the body movement (like it *should*).
> 5 votes

# Answer
I think it's best not to force the players viewpoint to do anything. You'd make users disoriented at best and make them sick at worst.

Maybe trying to build some kind of cue similar to what FPS games do when you're taking damage from the side with a red flash on that side of the screen. I think that you could quite easily play on people's natural inclination to look at what they see in their perephrial vision.
> 5 votes

# Answer
I totally agree with @Blue and @Dar Brett about not messing with the player view. Aside from their excellent suggestions, let me add one thing.

Maybe you could preserve the full immersion better if you allow the player to turn her body by using inverse kinematics? Consider that the player model is connected to the hand of the girl and if the player turns the upper body then the arms of the player and the girl are stretched and bent to follow the movement? Maybe even the girl could say something if the player turns too much and ask why she is pullin the wrong way?

As you're using unity I'd personally recommend NOT using the built in IK system for any procedural animations. I have some really great experience using an asset from the asset store, Final IK, if you use that package something like this becomes a lot easier to accomplish.
> 1 votes

---
Tags: unity, game-design, user-experience, oculus, virtual-reality
---


title: How to make a temporary collision?

text:
# Question
Title: How to make a temporary collision?
I have a key and door system working, the character(ball) picks up the key and when it is within the collider it sets the text("press E to open") on the screen to active so that they can open the door. This only needs to be there while the door is closed. How Would I fix this. Thank you so much in advance.

```
    //GameObject E is the canvas text to instruct the player to press E to open the door.
public GameObject E;
//Door is the door itself, I assigned this manually because the door consists of the doorframe and door.
public GameObject Door;
private bool Unlock;
// Use this for initialization
void Start ()
{
    E.SetActive(false);
    Unlock = false;
}

// Update is called once per frame
void Update ()
{
    if (Unlock)
    {
        if (Input.GetKeyDown("e"))
        {
            Door.GetComponent<Animation>().Play();
            E.SetActive(false);
            CodeManager.GotKey = false;
        }
    }
}
void OnTriggerEnter(Collider other)
{
        if (CodeManager.GotKey)
        {
            if(other.gameObject.CompareTag("Player"))
            {
            E.SetActive(true);
            Unlock = true;
            }
        }
}

```

# Answer
> 1 votes
The simple solution is to add a bool property to the door indicating if its open or not. Then you simply check:

```
if(ohter.gameObject.CompareTag("Player") && Door.isClosed)
{
//Do logic here
}

```

You can even set the isClosed to false when the open animation has finished using a Animation Event.

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


title: How can I implement gravity?

text:
# Question
Title: How can I implement gravity?
How can I implement gravity? Not for a particular language, just pseudocode...

# Answer
As others have noted in the comments, the basic Euler integration method described in tenpn's answer suffers from a few problems:

* Even for simple motion, like ballistic jumping under constant gravity, it introduces a systematic error.
* The error depends on the timestep, meaning that changing the timestep changes object trajectories in a systematic way that may be noticed by players if the game uses a variable timestep. Even for games with a fixed physics timestep, changing the timestep during development can noticeably affect the game physics such as the distance that an object launched with a given force will fly, potentially breaking previously designed levels.
* It doesn't conserve energy, even if the underlying physics should. In particular, objects that *should* oscillate steadily (e.g. pendulums, springs, orbiting planets, etc.) may steadily accumulate energy until the whole system blows apart.

Fortunately, it's not hard to replace Euler integration with something that is *almost* as simple, yet has none of these problems — specifically, a second-order symplectic integrator such as leapfrog integration or the closely related velocity Verlet method. In particular, where basic Euler integration updates the velocity and position as:

```
acceleration = force(time, position) / mass;
time += timestep;
position += timestep * velocity;
velocity += timestep * acceleration;

```

the velocity Verlet method does it like this:

```
acceleration = force(time, position) / mass;
time += timestep;
position += timestep * **(**velocity **+ timestep * acceleration / 2)**;
**newAcceleration = force(time, position) / mass;**
velocity += timestep * **(**acceleration **+ newAcceleration) / 2**;

```

If you have multiple interacting objects, you should update *all* their positions before recalculating the forces and updating the velocities. The new acceleration(s) can then be saved and used to update the position(s) on the next timestep, reducing the number of calls to `force()` down to one (per object) per timestep, just like with the Euler method.

Also, if the acceleration is normally constant (like gravity during ballistic jumping), we can simplify the above to just:

```
time += timestep;
position += timestep * **(**velocity **+ timestep * acceleration / 2)**;
velocity += timestep * acceleration;

```

where the extra term in bold is the only change compared to basic Euler integration.

Compared to Euler integration, the velocity Verlet and leapfrog methods have several nice properties:

* For constant acceleration, they give exact results (up to floating point roundoff errors, anyway), meaning that ballistic jump trajectories stay the same even if the timestep is changed.
* They are second order integrators, meaning that, even with varying acceleration, the average integration error is only proportional to the square of the timestep. This can allow for larger timesteps without compromising accuracy.
* They are symplectic, meaning that they conserve energy if the underlying physics do (at least as long as the timestep is constant). In particular, this means that you won't get things like planets spontaneously flying out of their orbits, or objects attached to each other with springs gradually wobbling more and more until the whole thing blows up.

Yet the velocity Verlet / leapfrog method are nearly as simple and fast as basic Euler integration, and certainly much simpler than alternatives like fourth-order Runge-Kutta integration (which, while generally a very nice integrator, lacks the symplectic property and requires *four* evaluations of the `force()` function per time step). Thus, I would strongly recommend them for anyone writing any sort of game physics code, even if it's as simple as jumping from one platform to another.

---

**Edit:** While the formal derivation of the velocity Verlet method is only valid when the forces are independent of the velocity, in practice you can use it just fine even with velocity-dependent forces such as fluid drag. For best results, you should use the initial acceleration value to estimate the new velocity for the second call to `force()`, like this:

```
acceleration = force(time, position, velocity) / mass;
time += timestep;
position += timestep * **(**velocity **+ timestep * acceleration / 2)**;
velocity += timestep * acceleration;
**newAcceleration = force(time, position, velocity) / mass;**
**velocity += timestep * (newAcceleration - acceleration) / 2**;

```

I'm not sure if this particular variant of the velocity Verlet method has a specific name, but I've tested it and it seems to work very well. It's not quite as accurate as fouth-order Runge-Kutta (as one would expect from a second-order method), but it's much better than Euler or naïve velocity Verlet without the intermediate velocity estimate, and it still retains the symplectic property of normal velocity Verlet for conservative, non-velocity-dependent forces.

**Edit 2:** A very similar algorithm is described e.g. by Groot & Warren (*J. Chem. Phys.* 1997), although, reading between the lines, it seems that they sacrificed some accuracy for extra speed by saving the `newAcceleration` value computed using the estimated velocity and reusing it as the `acceleration` for the next timestep. They also introduce a parameter 0 ≤ *λ* ≤ 1 which is multiplied with `acceleration` in the initial velocity estimate; for some reason, they recommend *λ* = 0.5, even though all *my* tests suggest that *λ* = 1 (which is effectively what I use above) works as well or better, with or without the acceleration reuse. Maybe it's got something to do with the fact that their forces include a stochastic Brownian motion component.
> 65 votes

# Answer
Every update loop of your game, do this:

```
if (collidingBelow())
    gravity = 0;
else gravity = [insert gravity value here];

velocity.y += gravity;

```

For instance, in a platformer, once you jump gravity would be enabled (collidingBelow tells you whether or not there is ground right below you) and once you hit the ground it would be disabled.

Besides this, to implement jumps, then do this:

```
if (pressingJumpButton() && collidingBelow())
    velocity.y = [insert jump speed here]; // the jump speed should be negative

```

And pretty obviously, in the update loop you also have to update your position:

```
position += velocity;

```
> 14 votes

# Answer
A proper frame-rate independent\* newtonian physics integration:

```
Vector forces = 0.0f;

// gravity
forces += down * m_gravityConstant; // 9.8m/s/s on earth

// left/right movement
forces += right * m_movementConstant * controlInput; // where input is scaled -1..1

// add other forces in for taste - usual suspects include air resistence
// proportional to the square of velocity, against the direction of movement.
// this has the effect of capping max speed.

Vector acceleration = forces / m_massConstant;
m_velocity += acceleration * timeStep;
m_position += velocity * timeStep;

```

Tweak gravityConstant, movementConstant and massConstant until it feels right. It is an intuitive thing and can take a while to get feeling great.

It's easy to extend the forces vector to add new gameplay - for instance add a force away from any nearby explosion, or towards black holes.

\*edit: these results will be wrong over time, but may be "good enough" for your fidelity or aptitude. See this link http://lol.zoy.org/blog/2011/12/14/understanding-motion-in-games for more info.
> 9 votes

# Answer
If you want to implement gravity on a slightly bigger scale, you can use this kind of calculation each loop:

```
for each object in the scene
  for each other_object in the scene not equal to object
    if object.mass * other_object.mass / object.distanceSquaredBetweenCenterOfMasses(other_object) < epsilon
      abort the calculation for this pair
    if object.mass is much, much bigger than other_object.mass
      abort the calculation for this pair
    force = gravitational_constant
            * object.mass * other_object.mass
            / object.distanceSquaredBetweenCenterOfMasses(other_object)
    object.addForceAtCenterOfMass(force * object.normalizedDirectionalVectorTo(other_object))
  end for loop
end for loop

```

For even bigger (galactic) scales, gravity alone won't suffice to create "real" motion though. The interaction of star systems is to a significant and very visible extent dictated by Navier-Stokes equations for fluid dynamics, and you'll have to keep the finite speed of light - and thus, gravity - in mind too.
> 6 votes

# Answer
The code provided by Ilmari Karonen is almost correct, but there is a slight glitch. You actually compute the acceleration 2 times per tick, this does not follow the textbook equations.

```
acceleration = force(time, position) / mass; // Here
time += timestep;
position += timestep * (velocity + timestep * acceleration / 2);
newAcceleration = force(time, position) / mass;
velocity += timestep * (acceleration + newAcceleration) / 2;

```

The following mod is correct:

```
time += timestep;
position += timestep * (velocity + timestep * acceleration / 2);
oldAcceletation = acceleration; // Store it
acceleration = force(time, position) / mass;
velocity += timestep * (acceleration + oldAcceleration) / 2;

```

Cheers'
> 1 votes

# Answer
Pecant's answser ignored frame time, and that makes your physics behavior differently from time to time.

If you are going to make a very simple game, you can make your own little physics engine -- assign mass and all kinds of physics parameters for every moving object, and do collision detection, then update their position and velocity every frame. In order to accelerate this progress, you need to simplify the collision mesh, reduce calls of collision detection, etc. In most cases, that's a pain.

It's better to use physics engine like physix, ODE and bullet. Any of them will be stable and efficient enough for you.

http://www.nvidia.com/object/physx\_new.html

http://bulletphysics.org/wordpress/
> -4 votes

---
Tags: software-engineering, physics
---


title: Invisible mesh. Are my normals, normal?

text:
# Question
Title: Invisible mesh. Are my normals, normal?
I'm creating this mesh during runtime in Unity3D.

The mesh shape is ok, but as you can see on this screenshot, the mesh is not correctly rendered: it's only rendered when the camera is looking back at the mesh, but I don't want to rotate the mesh or modify the camera position.

I know I can create a simple shader to activate backface culling... But I don't need a custom shader. I want to understand what I do wrong.

All my normals are set to `-Vector3.forward`:

```
        normals[vert_idx] = -Vector3.forward;
        normals[vert_idx + 1] = -Vector3.forward;
        normals[vert_idx + 2] = -Vector3.forward;
        normals[vert_idx + 3] = -Vector3.forward;

```

Are normals the only things involved in this problem? Or should I look to triangles order, vertices order or something?

Thanks.

# Answer
> 1 votes
Triangles have a direction in which they face. They are transparent from the other direction.

Which direction each triangle faces is determined by the order in which you state the three vertices it consists of. When you would like the triangle to be visible from the other side, pass the vertices in reversed order. If you would like them to be visible from both sides, you need to create two triangles.

Normals are a different topic. They determine how the object is shaded. But calculating them yourself is optional. You can leave that to Unity by calling `mesh.RecalculateNormals()` after setting up all triangles.

---
Tags: unity, 3d-meshes, normals
---


# Question
Title: Most Efficient Way to Store player stats/data in Unity C#?
I am looking at storing player data in Unity from a script that I'm writing in C# and I would like to get an opinion on the best way to store the player's stats/data about the player like hours played, etc.

I know that I can set up a database, and that is one way that I'm going to store the most important data like username/password (of course using hashing and not the actual password).

What I would like to know is really about player data/stats about the player's character. Should I also store that data in the database or should I just have a file that I write over each time the player performs and upgrade, etc. or what other way can I effectively manage that data?

I am wanting to store things like the player's level, XP earned toward next level, currently active character, etc.

**Edit:** This will be for an MMORPG, so there will be many different pieces of data being stored.

# Answer
> 0 votes
When this is for an online game, you should definitely store that information online on your server. When you store the character state on the client, your players will edit it to cheat.

The MM in MMORPG stands for "Massive Multiplayer", as in "Too many players to store in regular flatfiles". You will definitely need a database which is used by your server to persist the state of any offline players. Usually you would keep the data of all currently playing characters in memory and only persist them to the database when they disconnect. You might also want to persist them every few minutes in case of a sudden server crash.

# Answer
> 0 votes
I think you should not update database whenever something changed by player. You should update database in a sufficient frequency. Before updating database you should hold frequently changed data in the memory; a database updater thread can update/store database for instance at 1 hz.

---
Tags: unity, c#, databases, data, storage
---


# Question
Title: Mesh/Path reduction to simulate traveled path to target
I generate that kind of mesh during runtime to display the path to follow to a target (think at something like the path your GPS shows you when you are travelling):

I need to reduce the displayed path going from one end to the other to simulate the travel the player did. What can I do to achieve such effect?

I can think about vertex modifications at runtime directly from a Monobehaviour class, or a shader(?). Are there any other (smarter?) moves to do here? Is Vertex modification the wiser choice for that kind of case?

Thanks.

# Answer
**Option 1:** Draw the mesh as per the current state from the initial player position to the current position. For this, create quads for all fully-traversed segments, and then determine which line segment the player is currently on, and how far (`playerSegmentRatio=(0.0->1.0)`) the player has travelled along the length of that segment. For that segment, draw using something like `drawSegment(playerSegmentRatio)` (whereas all the others would be drawn at their full length, i.e. `drawSegment(1.0)`).

**Option 2:** Use the stencil buffer to mask the object according to player's current position.

**Option 3:** Mask by modifying the UV co-ordinates on the end points, using a PNG texture that has just two pixels: one filled, one transparent. You might need to add more vertices to the segment the player is currently in, in order to control where the transparent part (the part that hasn't been travelled yet) begins and ends.

Personally, I think Option 1 is the easiest.
> 1 votes

---
Tags: unity, 3d-meshes, vertex
---


# Question
Title: How do I use delta-times to determine the speed of a frame-by-frame animation?
I have a character spritesheet with 8 images. How do I animate it?

At the moment, the sprite changes to a different image every frame, which makes the animation speed vary with framerate. I have a delta time that calculates the time in ms between each frame. Is there a smart way to make sprite animations use it?

I'm using JavaScript and canvas on my own engine, for practice.

# Answer
> 1 votes
Assuming pseudo code (in my example I use lua code) , and an anim class , consider the following anim update (using delta time dt) called in your update or draw cicle (it depends on engine..)

```
function anim:update(dt)
    if anim.started then
        anim.accum = anim.accum+dt
        while anim.accum > anim.frameTime then
            anim.accum = anim.accum-anim.frameTime
            if anim.aType=="loop"then
                anim.curFrame=(anim.curFrame+1)%anim.nFrames
            end
        end
    end
end

```

where `anim.accum` is an accumulator initilized to zero. `anim.frameTime` is the time (ms?) of each frame.(i.e: to increase anim speed reduce `anim.frameTime`). `Anim.curFrame` is current frame index (I leave to you how to recover a frame from your spritesheet, given an index, cause it depends on your spritesheet logic). `anim.nFrames` is animation total frames number.

Edited : thanks to Jon comment

# Answer
> 0 votes
If you measured the `time` in ms from the start of the animation, the formula would be:

```
var frame_nr = Math.floor(FPS * time / 1000);

```

This way if your `time` was say 500 \[ms\] and your `FPS` was 60, the `frame_nr` would be 30. You'd need to handle the case when the `frame_nr` exceeds your animation's length.

If you wanted the animation to loop, you could use the modulo operator:

```
var frame_nr = Math.floor(FPS * time / 1000) % frames.length;

```

So at half a second and 60 FPS and 30 frames long animation, the `frame_nr` would wrap back to 0.

Otherwise, if the animation was to be played just once, before you used a `frames_nr` to refer to an actual frame, you'd have to test for:

```
if (frame_nr < frames.length)
    draw_frame(frames[frame_nr]);
else
    ... // animation ended

```

Finally, to measure `time` you'd have to initialize the variable to 0 when your animation starts, and then at each frame accumulate the delta you already have available.

---
Tags: javascript, animation, spritesheet
---


# Question
Title: How can I reduce writes-per-second when saving player data to a database?
Consider a game where the player has some profile or save data stored in a database. What I want to understand is, for things that effect the users score or level, there could be so many factors that this has to be persisted to the database and if it is, this could be many writes per second per player potentially, which could be expensive or slow.

How can I reduce the load on the database while still maintaining critical player information?

# Answer
> 2 votes
In the context of a game like an MMO (a class of game that often uses databases as the persistent storage), this problem is fairly common. Player data is *very* important, and you will certainly have it in-memory while the player is actively playing because it's way faster to access there.

However, you *really* don't want a server crash to cause player data loss, so you want to serialize the players state as often as possible. However, you also don't want to overload your database with too many writes.

There are lots of solutions to this problem. One that I'm familiar with, having worked on some MMOs, is to define two types of player save events: low priority and high priority. What each makes a save low or high priority depends on your game, but generally things that are economically impacting (anything involving real money transactions, or things involving the player gaining important items, et cetera) would be high priority. Things like current world position would be lower priority.

High priority saves get queued *immediately* when the relevant event happens. Low priority ones happen in the background at fixed(ish) intervals.

Note the term "queued:" Rather than a save immediately going to hit the database, the saveable data is bundled up, serialized into a save *request* and sent off to dedicated type of server that *eventually* saves the data to the main character record. These servers themselves may still store the pending saved state in a database (just in case *they* crash), but it's usually easier to deploy *more* of them to handle scaling, and they're usually way simpler and less prone to churn and bugs.

The main downside here (other than having to, you know, write all this infrastructure) is that the system is only eventually consistent. Without some careful though going in to how the save queue servers manage and prioritize the queues of pending saves, a crash of a game server can still result in *apparent* data loss for the player.

You can attempt to alleviate this by implementing a system wherein the login servers direct the queue server grid to flush the pending saves for a user that's about to log in, ensuring the most up-to-date data. If the queue management can easily prioritize and discard "old" pending saves, this can really help with the eventual consistency problems while still being fairly good at keeping load off the main character record database.

---
Tags: architecture, databases
---


# Question
Title: Is window creation decoupled from a game engine?
I'm new to game development, and I was wondering about a architecture question.

The window creation code in C++ is given by doing the following:

1. Fill out a WNDCLASS struct
2. Register the window class using the struct by calling RegisterWindow(WNDCLASS)
3. Get a handle to the window from calling CreateWindow()
4. Handle Windows events in your WndProc function, and call TranslateMessage, and DispatchMessage to forward messages in the message queue when retrieved from PeekMessage().

Then, in a game you might have a Game engine which contains a simple game loop like so:

```
while (running)
{
    ProcessInput();
    UpdateState();
    RenderStates();
}

```

My question is how do you include the window creation with the game engine. Do you decouple the two? If you decouple the two, how do you handle input to the WndProc function if it has no idea about the GameEngine class to set particular flags about keys that are pressed?

# Answer
> 1 votes
Whether or not you decouple your window creation from your engine code is up to you. You *can* do it both ways. If you don't handle window creation in your code, you'll expect the user of your code to handle it. That will include forwarding window events to you somehow -- probably by calling interface methods on your game engine object you define for them.

But if you're going to handle it yourself, you can associate an instance of your game engine with a `HWND` using `SetWindowLongPtr` and `GetWindowLongPtr` with the `GWLP_USERDATA` flag. These functions let you store and recover a pointer-sized blob of data with a specific `HWND`, so once you create your window, use them to shove the game engine pointer in there, and then you can recover the game engine pointer from that window in the `WNDPROC` when handling appropriate messages and call the appropriate game engine functions.

---
Tags: c++, architecture
---


# Question
Title: Why when releasing a DirectX Texture it fail
I have an instance where a class creates a DX9 texture via

```
UINT usage = D3DUSAGE_RENDERTARGET;
HRESULT hr = D3DXCreateTexture (m_D3DDevice,
                                200,
                                200,
                                0,
                                usage,
                                D3DFMT_X8R8G8B8,
                                D3DPOOL_DEFAULT,
                                &m_texture)

```

Where m\_texture is `IDirect3DTexture9*` and hr = S\_OK after creation.

But when I come to cleaning it up in the destructor via

```
if (m_texture != NULL)
{
    hr = m_texture->Release();
}

```

hr = S\_FALSE

Why would it fail to release a texture?

# Answer
> 4 votes
`Release` does not return an `HRESULT`, it returns a `ULONG`. That `ULONG` is the new reference count on the object (after the release).

`hr == S_FALSE` in your code because `Release` is returning 1 (which is what `S_FALSE` is defined as), which means there's one pending reference count to the object after you release it (that's not *necessarily* a problem, it could be an internal D3D reference).

The return code from `Release` is intended only for diagnostic purposes. But, tldr, it's not failing, it's working fine.

---
Tags: c++, textures, directx, directx9
---


# Question
Title: How to implement map scrolling inertia formulae
I'm looking for a mathematical formulae to calculate map scrolling inertia. Basically I have an HTML5 Canvas displaying part of a map and I capture the `mousedown` / `mousemove` / `mouseup` to calculate my new offset.

And when I scroll the map I want the map to continue scrolling for a few moments after the user stopped dragging the cursor.

I do have a sample implementation but I'm not really satisfied with it. I'd be looking for a nice clean math formulae to achieve this. I'd like my map to behave for example like in Civ-5 when you scroll the map around.

Here is part of my implementation: (working jsfiddle: https://jsfiddle.net/CowWarrior/dkxnj5d8/1/)

```
//mouseup
stopMapDrag: function (e) {
    var movementX = (e.pageX - this.startX);
    var movementY = (e.pageY - this.startY);
    this.mapOffsetX = parseInt(this.mapOffsetX) + movementX;
    this.mapOffsetY = parseInt(this.mapOffsetY) + movementY;
    this.isDragging = false;
    this.displayMap();

    //calculate last vector
    ui.vectorX = parseInt(e.pageX - ui.absStartX);
    ui.vectorY = parseInt(e.pageY - ui.absStartY);

    //show inertia
    setTimeout(function(){ ui.dragInertia(2); }, 30);
    console.log("(vectorX:" + ui.vectorX + ", vectorY:" + ui.vectorY + ")");

    $('#canViewport').css('cursor', 'default');
},

//need to find a good formulae for inertia
dragInertia: function (factor) {
    var movementX = parseInt(ui.vectorX / factor);
    var movementY = parseInt(ui.vectorY / factor);
    ui.mapOffsetX = parseInt(ui.mapOffsetX + movementX);
    ui.mapOffsetY = parseInt(ui.mapOffsetY + movementY);
    ui.displayMap();

    if (factor < 8)
        setTimeout(function(){ ui.dragInertia(factor * 1.2); }, 30);
},

```

# Answer
**Math.acos() solution**

I have something very close to what I am looking for but I beleive there is an even better way of doing this.

I started by plotting a graph using Desmos. I was actually looking for a less steep curve at the beginning but I think this is close enough to what I'm looking for. In this representation the Y axis is the velocity and the X axis is the time.

The full fiddle of my solution is here: https://jsfiddle.net/CowWarrior/kkodtxm9/23/

I ended up changing almost nothing of the `mouseup` event:

```
stopMapDrag: function (e) {
    [...]

    //show inertia
    setTimeout(function(){ ui.dragInertia(0); }, 50);
    console.log("(vectorX:" + ui.vectorX + ", vectorY:" + ui.vectorY + ")");

    $('#canViewport').css('cursor', 'default');
},

```

However my `dragInertia` function now look like this:

```
dragInertia: function (iteration) {
    var multiplier = Math.acos(iteration) * 0.33;
    var movementX = parseInt(ui.vectorX * multiplier);
    var movementY = parseInt(ui.vectorY * multiplier);
    ui.mapOffsetX = parseInt(ui.mapOffsetX + movementX);
    ui.mapOffsetY = parseInt(ui.mapOffsetY + movementY);
    ui.displayMap();

    if (iteration < 0.9)
        setTimeout(function(){ ui.dragInertia(iteration + 0.1); }, 50);
},

```

Please submit your answers if you have something even better to propose. I'm somehow not entirely satisfied with what I want.
> 1 votes

---
Tags: javascript, html5, maps, mathematics
---


# Question
Title: How do I handle objects with a width and height in grid-based pathfinding?
I'm using the Jumper library for Love2D to do grid-based pathfinding, which worked fine until I wanted to make larger enemies (with larger collision boxes). How do i do that?

My initial idea was to make a new map for each entity that needed pathfinding I could make a new map, with all the objects scaled up in size, but that seems way to complicated.

To give an example, I could have a wall with a passageway that is wide enough that my player has no trouble walking around it, but a giant ogre would have to walk around.

# Answer
> 0 votes
Store inside each entity not only its `position`, but also its `size`. Then you can reconstruct the collision map from your entity list, something like this:

```
-- [ Assign 0 to everything in the map. ]

-- Then block out a 1 for each square within the entity's size
for _, entity in entities do
  local pos = entity.position
  for xIncrement=0,entity.size.x do
    for yIncrement=0,entity.size.y do
      map[pos.x + xIncrement][pos.y + yIncrement] = 1
    end
  end
end

```

The entity's `position` represents its top-left corner and the `size` the number of squares it occupies in the `x` and `y` directions.

Then just use jumper as usual.

# Answer
> 0 votes
One way to implement this is to use clearance, and have all of the tiles around obstacles contain numbers represent their proximity to the object for example a map that looked like this:

```
map = {
{0,0,0,0}
{0,1,1,0},
{0,1,1,0},
{0,0,0,0},
}

```

would look like this:

```
map = {
{1,1,1,1}
{1,2,2,1},
{1,2,2,1},
{1,1,1,1},
}

```

---
Tags: path-finding, grid, lua, love2d
---


# Question
Title: In game engine, how to get the vertices buffers of different vertex formats for render from the mesh file properly?
I'm a fresher on engine programming. I have a question of how we can get the vertices buffers of vertex formats from the mesh file.

For example, in OBJ file or FBX file, we save the positions, normals separately. So the whole mesh file is **a structure of different arrays** which contain the different attribute of the vertices.

But when we offer those data to the graphics card, we'll offer **an array of vertex structs**, here the vertex struct contains the position, normal, UV... for one vertex.

So, suppose we want to generate different vertex buffers for different shaders from the mesh file(the struct of arrays), then I think we can use 2 solutions:

1. generate a different array of structs, here the different struct will be the different formats of vertices. The problem is: It takes a lot of memory to save the different vertex buffers.
2. generate a general array of struct, here the struct contains all of the vertex attributes we can get from the mesh file, and use offset to get the correct data for different vertex format. The problem is: will it be slow for shader program to access the vertex data?

Which one is the better way to do? Or is there any better solution? Again, I'm just a fresher, So I hope my description is clear enough for the problem :-)

Thank you all very much!

# Answer
> 1 votes
If you have lots of different input formats then #2 would probably make more sense, however you might end up with a lot of overhead (however I think more modern systems like UE4 do something like this), which leaves #1. However, most games typically do not vary the vertex formats between shaders or have models that have multiple input formats (You are more likely to duplicate your shaders for each input type).

For example, all skinned models might use the skinned vertex format, and any shaders that can work on skinned models would use that vertex format.

---
Tags: graphics-programming, vertex-buffer, vertex-arrays, vertex-attribute
---


# Question
Title: Simple heart container script for 2D game (Unity)?
I'm attempting to create a simple mobile game (C#) that involves a simple three-heart life system. After searching for hours online, many of the solutions use OnGUI (which is apparently horrible for performance) and the rest are too complicated for me to understand and add to my code. The other solutions involve using a single texture and just hiding part of it when damage is taken. In my game, however, the player should be able to go over three hearts (for example, every 100 points).

Sebastian Lague's Zelda-Style Health is what I'm looking for, but even though it's a tutorial there is way too much going on that I don't need or can't customize to fit in mine.

What I have so far is a script called `HealthScript.cs` which contains a variable `lives`. I have another script, `PlayerPhysics.cs` which calls HealthScript and subtracts a life when an enemy is hit. The part I don't get is actually drawing the hearts.

I think I understand what needs to happen, I just am not experienced enough with Unity to know how.

1. The Start function should draw three (or whatever `lives` is set to) hearts in the top right corner. Since the game should be resolution-independent to accommodate the various sizes of Android devices, I'd rather use scaling rather than `PixelInset`.
2. When the player hits an enemy as detected by `PlayerPhysics.cs`, it should subtract from `lives`. I think that I have this working using `this.GetComponent<HealthScript>().lives -= 1` but I'm not sure if it actually works. This should trigger a redraw of the hearts so that there are now two hearts.
3. The same principle would apply for adding hearts when a score is reached, except when `lives > maxHeartsPerRow`, the new hearts should be drawn below the old ones.

I realise I don't have much code to show but believe me; I've tried for quite some time to figure this out and have little to show for it. Any help at all would be welcome; it seems like it shouldn't take that much code to put an image on the screen for each life there is, but I haven't found anything yet.

Thanks!

# Answer
> 1 votes
Yeah, a simple for loop will suffice for this.

```
for (int i = 0; i > Hearts; i++) {

  int col = i % 9;
  int row = Mathf.Floor(i / 9f);

  GUI.DrawTexture(new Rect(10 + (74*col), 10 + (74*row), 64, 64), heartTexture, ScaleMode.ScaleToFit);

}

```

Also, note the names / values may be changed, if your hearts are smaller, or you'd like less space in between hearts, I would recommend it.

# Answer
> 0 votes
You can use `GUILayout` which is from before the 4.6 beta to accomplish this. I would create a new area in the top right corner, then have a flexible space inbetween the left bound and the last heart. You can create a new row by having a vertical area. This is how I'd make the hierarchy

```
-BeginArea
| -BeginVertical
| | -BeginHorizontal
| | | -FlexibleSpace
| | | -Heart (if available)
| | | -Heart (if available)
| | | -Heart (if available)
| | -EndHorizontal
| | -BeginHorizontal
| | | -FlexibleSpace
| | | -Heart (if available)
| | | -Heart (if available)
| | | -Heart (if available)
| | -EndHorizontal
| |
| | ...
| |
| -EndVertical
-EndArea

```

To create the first row of hearts, just loop draw one for every `min(maxHeartsPerRow, hearts)`. You will then have `(hearts - mod(hearts, maxHeartsPerRow)) / maxHeartsPerRow` more rows. Then, until you are on the last row, fill each row with `maxHeartsPerRow` hearts. The last row you need to draw `mod(hearts, maxHeartsPerRow)` hearts.

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


title: Can't set up a PS3 controller in Unity

text:
# Question
Title: Can't set up a PS3 controller in Unity
So I connected a ps3 controller to my computer via USB cable, when I press play I am able to move by using arrows on the left of the ps3 controller and also I am able to shoot and aim by triangle and circle but when I try setting up the 2nd Horizontal axis in the Input Manager by changing the "X axis" to 5th axis (so I could use sticks to move) and changing type to joystick axis I am not able to move. Also I tried creating a second "Mouse X" and also setting it to joystick axis and changing the "X axis" to "4th axis (joysticks)" nothing happens again, I tried pressing everything but it doesn't work. Anyone knows how I can make it work?

# Answer
> 1 votes
The PS3 controller is not directly compatible with PC. You will need a driver and a program to translate the controls to the format used on a PC.

If you search the net, most articles will refer to an app called MotionInJoy but I've read many reports online that it is adware (maybe worse) and it's advised to avoid it. I've not used it but better safe than sorry.

I have used pcsx2 to emulate the XBOX controller using my standard 6-axis controller for games that only work with XInput and this app should also work to emulate your PS3 controller (doesn't work in windows) as an XBOX controller (does work on windows). I can confirm that pcsx2 works well.

You will need to download the official driver for the XBOX controller and the pcsx2 app, then configure pcsx2 to map your PS3 controls to the XBOX controls.

See this forum post for full instructions.

PS: Some folks in that thread also mention BetterDS3 as another option instead of pcsx2. I've not tried it but if you are having trouble getting pcsx2 to work, you might want to try that one. It may be a little simpler to get it working, though pcsx2 wasn't very complicated and is more flexible/useful.

# Answer
> 1 votes
I had your same problem. In my case It got fixed by closing unity and reconnecting the PS3 controller before starting Unity again. Maybe it helps

---
Tags: unity, c#, controllers, playstation3, axis
---


# Question
Title: (Optimization) Efficiently discovering if a new day has been reached
I'm making an in-game clock/calendar system. In-game time is 12x real time. In addition, in-game events can fast-forward time. I also have in-game events that reset or trigger at the turn of each day.

My issue: I don't want to perform an end-of-day check every time there's a frame update, like:

```
void Update(float _delta) {
    gameTimeInSeconds += _delta * timeScale; // time scale is 12.
    while (gameTimeInSeconds >= currentDay * 86400.0)
        NextDayReached();  // increments currentDay, and updates in-game events.
}

```

It feels inefficient to make the check on every frame. Is there a more efficient way to determine when a new day has been reached?

Or am I worrying over an ultimately tiny issue?

# Answer
> 1 votes
This is unlikely to be an issue. A single branch 60 times a second is not even a blip on the radar for a profiler.

However if you have arbitrary events that trigger at certain points (not just on turn of day) then you can make newDay a fixed recurring daily event.

Then the update loop will be:

```
void Update(float _delta) {
    gameTimeInSeconds += _delta * timeScale; // time scale is 12.
    while ((event = eventQueue.getNextTriggeredEvent(gameTimeInSeconds)) != null);
        event.handle();
}

```

# Answer
> 1 votes
In native code, where you're using a `while` loop you've set up in `main`, this is exactly how all checks are done. There *is in fact no other way to do it,* under these circumstances, since the native `while` loop runs as fast as possible and only acts when some condition is met (like yours).

In non-native framework code or for certain platforms (like JS), there may be ways to use the underlying native event loop to do this more efficiently, like JS `setInterval()` \- you don't want to be running conditionals in the interval handler 30-60 times every second, when you could rather be calling the handler only when the native interval triggers. Native is more efficient, typically. HTH.

---
Tags: optimization, timer
---


# Question
Title: Canvas slowly degrades in performance after a while
I was creating a simple game and was shocked to see how the performance started to degrade. It never happened to me before, most probably because I use images and not the context drawings. So I used this function and the whole game becomes so slow, it just cannot be played after 30 seconds.

```
Office.prototype.draw = function(){
 for(var i = 0; i < this.tables.length; i++){
  for(var j = 0; j < this.tables[i].length; j++){
   Canvas2D.ctx.rect((373 * j) + 75, (370 * i) + 250, 170, 20);
   Canvas2D.ctx.fillStyle = 'green';
   Canvas2D.ctx.fillRect((373 * j) + 75, (370 * i) + 250,
    this.moneyBar[(i*4)+j], 20);

   // Draw the experience bar.
   Canvas2D.ctx.rect((373 * j) + 75, (370 * i) + 270, 170, 20);
   Canvas2D.ctx.fillStyle = 'yellow';
   Canvas2D.ctx.fillRect((373 * j) + 75, (370 * i) + 270,
    this.expBar[(i*4)+j], 20);

   // Draw the tables.
   Canvas2D.drawImage(sprites.items[0], new Vector2(
    (250 * j) + 50, (250 * i) + 200));
  }
 }
}
```

So as you can tell from the code, there is the multidimensional array table which has bars on top displaying moneyBar and expBar. If I am to use Canvas2D.ctx.stroke() inside the for loop, the game performance drops right away. Outside of the loop, it keeps up a bit, then it degrades. If I don't use stroke at all, works better, but degrades anyway. So I am really confused as to why this degrades so fast. Also am using requestAnimationFrame and have used the same engine in previous games and performance never degraded.

If I was to remove fillStyle, keeps up 3-4 seconds more. There are 8 tables in all, which means the for loops run 8 times per draw.

Vector2 function.

```
function Vector2(x, y) {
    this.x = typeof x !== 'undefined' ? x : 0;
    this.y = typeof y !== 'undefined' ? y : 0;
}

```

# Answer
> 3 votes
You are using `rect` to draw the background of the bars, but you forgot the `beginPath`. So the rect calls pile up and make the drawings slower and slower each frame.

To explain a bit further, each non-direct draw command (`arc`, `rect`, `lineTo`, `XXXTo`) is used to build the current path. If you never use `beginPath` to reset the current path, the next frame will just resume building the path with the new commands : path gets bigger and bigger, and slower and slower to draw.

You can use `beginPath` then `rect` then `fill`, or rather use `fillRect`, which is faster.

# Answer
> 1 votes
Since i can't comment to get more information i'll do my best here.

Have you tried clearing the canvas before each draw ?

You could also change your code to due batch drawing instead of consecutive drawing calls as you are currently making;

Another thing that may degrade the performance the fill style changes in your loop. Try to make all drawing calls for each fill style instead of change fill style in each iteration like this:

```
Canvas2D.ctx.fillStyle = 'green';
for(var j = 0; j < this.tables[i].length; j++){
            Canvas2D.ctx.rect((373 * j) + 75, (370 * i) + 250, 170, 20);
            Canvas2D.ctx.fillRect((373 * j) + 75, (370 * i) + 250,
                this.moneyBar[(i*4)+j], 20);
}

Canvas2D.ctx.fillStyle = 'yellow';
for(var j = 0; j < this.tables[i].length; j++){
            // Draw the experience bar.
            Canvas2D.ctx.rect((373 * j) + 75, (370 * i) + 270, 170, 20);
            Canvas2D.ctx.fillRect((373 * j) + 75, (370 * i) + 270,
                this.expBar[(i*4)+j], 20);
}

for(var j = 0; j < this.tables[i].length; j++){
            // Draw the tables.
            Canvas2D.drawImage(sprites.items[0], new Vector2(
                (250 * j) + 50, (250 * i) + 200));
}

```

---
Tags: javascript, html-canvas
---


title: Prevent player from jumping on a mesh

text:
# Question
Title: Prevent player from jumping on a mesh
I am working on a game and I have a mesh that I use to block hallways and prevent the player from going that direction. They are placed vertically with slight angles. I'm having a problem that the player can jump up on these. The player needs to be on the ground all the time otherwise they will be able to avoid dying indefinitely. I have tried moving and rotating and no matter how its placed I can always seem to jump on it. I want to avoid adding more to the scene then what is necessary so I don't want to add another mesh or extra collision of some kind just to keep the player away from those points as that mesh already has collision. Unless it turns out that is actually a good way to handle this.

Is there a way I can prevent the player from jumping on these items? Or is there some other way I can handle if the player does jump up on them. Like maybe start damaging the player after a few seconds until they get down? What is a proper way of handling this?

# Answer
You could modify the existing collider on the mesh so that it is less "realistic" (aka less form-fitting) but better blocks the area in question.

You could also just remove the collider altogether and place a box collider in it's place that completely encompasses the mesh and the air above it, so that the player cannot jump on it.

Both of these examples would use the same number of colliders as you already have, so you're avoiding the addition of extra collision objects as you wanted.

---

An alternate solution is to modify the Slope Limit of your character controller (assuming you're using a character controller). If the existing mesh is at an angle as you said, changing the slope limit can make that angle unable to be walked upon. The character should slide right off.
> 2 votes

# Answer
The appropriate way is as you want to avoid. That is to add a tiny rigid mesh to the object and thus, the scene. It wouldn't need to be more than a couple hundred bytes I'm guessing.

That being discounted, you could capture the point from where the player jumped and move them back in that direction by other means. That would be ugly and will "feel" buggy however.

Damaging them while they are on the object is another option, but how that is done is entirely up to your health system. You can probably find examples of how to detect the object you're standing on from the standard character controller scripts.

Ultimately, the right answer is still probably just to eat your peas and supply an extremely simple additional collision mesh for the barrier and swap it when needed.
> 0 votes

---
Tags: unity, 3d-meshes, jumping
---


# Question
Title: Making a GUI shader in GLSL c++/opengl/freeglut
How do you make a shader that will draw ontop of everything else? Im using an approach where I draw square faces in 3d space to simulate a 2d box, but when I make a 3d object, it will clip over the 2d boxes as I move around.

How do you go about making 2d boxes that are drawn directly onto screen, but without clipping thru stuff in 3d space.

Im using openGL and glsl, swapping between shaders as I call objects draw call.

# Answer
> 2 votes
To do that you simply call `glDisable(GL_DEPTH_TEST);` before drawing your GUI and after drawing your scene/screen.

That way, you draw your GUI on top of the scene and is unaffected by depth test.

For the shader, i think a basic shader will do.

---

I hope i remember it correctly.

---
Tags: opengl, glsl
---


# Question
Title: How can I get Unity to tell me the battery status of my OS X laptop?
How do I get battery status on an OS X laptop in Unity?

This is un-Googlable: I keep finding either mobile stuff (iOS or Android) or people complaining about laptop battery life.

# Answer
> 2 votes
I don't think Unity exposes this in a platform-agnostic fashion. You will have to call down to the lower level APIs.

There are two ways I can think of offhand to get this. The first is to use the `Process` class to execute the OS X `pmset` tool and parse the output. `pmset -g batt` displays battery status to stdout, which you can parse for what you need.

The other is to use platform invoke to call the IOPowerSources functions directly. You'll need three functions at least (`IOPSCopyPowerSourcesInfo`, `IOPSCopyPowerSourcesList` and `IOPSGetPowerSourceDescription`), so it may be easier to write a small library that calls them in C and exposes a single entry point for you to invoke. I seem to recall there being restrictions on P/Invoke in the free version of Unity in the past, so this may not be an option for you if that still applies.

This thread on StackOverflow also discusses the issue, although it does not address anything Unity specific.

---
Tags: unity, macos
---


title: glUniformMatrix4fv - INVALID OPERATION?

text:
# Question
Title: glUniformMatrix4fv - INVALID OPERATION?
I'm attempting to manually setup a matrix in my vertex shader purely because I like to learn as much as possible about anything I do usually.

So the problem is that I'm getting an GL\_INVALID\_OPERATION when too me my code seems clear as crystal complete.

```
const GLfloat modelviewmatrix[] = {
    1.0f , 0.0f , 0.0f , 0.0f,
    0.0f, 1.0f, 0.0f , 0.0f ,
    0.0f, 0.0f, 1.0f, 0.0f,
    0.0f, 0.0f, 0.0f, 1.0f
};

GLint locationID = glGetUniformLocation(ShaderPrograms, "modelviewMatrix");

std::cout << "location->" <<locationID << std::endl;
glUniformMatrix4fv(locationID, 1, GL_FALSE, modelviewmatrix);

GLenum error;

error = glGetError();

if (error != GL_NO_ERROR)
{
    std::cout << "not working" << std::endl;
}

if (error == GL_INVALID_OPERATION)
{
    std::cout << "INVALID OPERATION" << std::endl;
}
if (error == GL_NO_ERROR)
{
    std::cout << "No Error! -> CODE CHECKING <-" << std::endl;
}

if (error == GL_INVALID_VALUE)
{
    std::cout << "NO VALUE" << std::endl;
}

if (error == GL_OUT_OF_MEMORY)
{
    std::cout << "NO MEMORY" << std::endl;
}

if (error == GL_STACK_OVERFLOW)
{
    std::cout << "NO OVERFLOW" << std::endl;
}

if (error == GL_INVALID_FRAMEBUFFER_OPERATION)
{
    std::cout << "invalid framebuffer <-" << std::endl;
}

if (error == GL_OUT_OF_MEMORY)
{
    std::cout << "Out of Memory" << std::endl;
}

```

//VERTEX SHADER

```
#version 330 core

layout (location = 0) in vec3 position;

uniform mat4 modelviewMatrix;
uniform mat4 projection;

void main()
{

    gl_Position = modelviewMatrix * vec4(position.x, position.y, position.z, 1.0);
}

```

What could be causing the problem , why is it causing it . how did you find out and what did you use too figure it out please?.

OpenGL 3.30+ , GLSL 3.30 core , Win10 64bit.

**figured out what the problem was I was using glUseProgram after I was doing uniforms instead of doing that before.**

full source here -\> http://pastebin.com/zD7YEDjp

# Answer
figured out what the problem was I was using glUseProgram after I was doing uniforms instead of doing that before.
> 6 votes

# Answer
You get invalid operation, because you don't use the uniform "projection" in the shader, thus OpenGL deletes it to save memory.

This can be solved by simply referencing it with `projection;`, you don't need to use it.

Like this:

```
#version 330 core

layout (location = 0) in vec3 position;

uniform mat4 modelviewMatrix;
uniform mat4 projection;

 void main()
{

    gl_Position = modelviewMatrix * vec4(position.x, position.y, position.z, 1.0);
    projection;
}

```
> 4 votes

---
Tags: opengl
---