# Question
Title: Match-3 "find matches" function not returning correctly
So I'm in the process of making a simple bejeweled clone and for some reason my "find matches" function is having problems. I've broken it up so it check horizontally, then vertically and right now I'm just working with the first. At the end it should print out the gems and their coordinates (for now) but it only prints out the final gem in the matches, for every gem in that line of matches. Here's the function code. If more is needed let me know.

EDIT: Here's updated code. It should run faster due to less looping but I still get the same problem. I've also tried to add the gameobject's directly from the array but the row and col values (that otherwise are initialized) have 0 for all the values. Thanks to anyone who has an idea. Its so frustrating I'm stuck on something so simple.

```
    void RowCheck()
{
    for (int row = 0; row < gridSize; row++)
    {
        for(int col = 0; col < gridSize - 2; col++)
        {
            if(col + 2 < gridSize)
            {
                if (GemGrid[row, col] == GemGrid[row, col + 1] && GemGrid[row, col] == GemGrid[row, col + 2])
                {
                    for (int x = col + 2; col <= x; col++)
                    {
                        GameObject tempGem = new GameObject();
                        tempGem = GemGrid[row,col];
                        tempGem.GetComponent<ForGems>().row = row;
                        tempGem.GetComponent<ForGems>().col = col;
                        MatchedGems.Add(tempGem);
                    }
                    if (col + 1 <= gridSize)
                    {
                        if (GemGrid[row, col] == GemGrid[row, col + 1])
                        {
                            col++;
                            GameObject fourthGem = GemGrid[row,col];
                            fourthGem.GetComponent<ForGems>().row = row;
                            fourthGem.GetComponent<ForGems>().col = col;
                            MatchedGems.Add(fourthGem);

                            if (col + 1 <= gridSize)
                            {
                                if (GemGrid[row, col] == GemGrid[row, col + 1])
                                {
                                    col++;
                                    GameObject fifthGem = GemGrid[row,col];
                                    fifthGem.GetComponent<ForGems>().row = row;
                                    fifthGem.GetComponent<ForGems>().col = col;
                                    MatchedGems.Add(fifthGem);
                                }
                            }
                        }
                    }
                }
            }
        }
    }

```

# Answer
---

Edit

As posted in your OP's comments, your code could be better:

1. There is a useless *if*.
2. There is copy-pasted code which should be extracted.
3. The *for* you use to add your 3 first gems to the list is really hard to follow/read.
4. In `GameObject tempGem = new GameObject();` the `new GameObject()` is useless; it will eat up process and garbage collector.
5. You change the value of the iterator (`col`) *within* the `for` which is quite generally unexpected and makes the code harder to follow.

Here is a cleaned up version:

```
void RowCheck()
{
    for (int row = 0; row < gridSize; row++)
    {
        int col = 0;
        while(col < gridSize - 2)
        {
            if (GemGrid[row, col] == GemGrid[row, col + 1] && GemGrid[row, col] == GemGrid[row, col + 2])
            {
                addMatch( GemGrid[row, col] );
                col++; // Index + 1
                addMatch( GemGrid[row, col] );
                col++; // Index + 2
                addMatch( GemGrid[row, col] );
                col++; // Index + 3
                if (col < gridSize && GemGrid[row, col - 1] == GemGrid[row, col])
                {
                    addMatch( GemGrid[row, col] );
                    col++; // Index + 4
                    if (col < gridSize && GemGrid[row, col - 1] == GemGrid[row, col])
                    {
                        addMatch( GemGrid[row, col] );
                        col++; // Index + 5
                    }
                }
            }
        }
    }
}

```

Notice that I have changed the inner `for` for a `while` which implies that the iterator variable is managed within it, not by the for construct. The way it is now, it prepares for the next loop iteration.

If you still have your issue, I encourage you to use a debugger or prints to console to see if your data is properly added to your MatchedGems, and, if they are, check if your problem comes from your container.
> 1 votes

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


# Question
Title: AI movement is fragmented when following player
I'm making a 2D game with two spaceships flying around and shooting at each other. One is controlled by the player, the other by the AI.

Currently, I have the AI always try to get inside a certain radius from the player. When it is inside that radius, it stops moving. This works, but I have one problem with this. I'll present the problem after describing the implementation:

Each frame, the AI checks it's distance from the player. If the distance is **larger** than a certain number (the radius), **the AI moves in the direction of the player.** If the distance is **smaller or equal** to that number (aka the AI's spaceship is inside the given radius from the player's ship), the AI stops moving.

This works fine, except for one problem:

When I stay in place and let the AI's ship reach the radius, it works. The AI moves in my direction, and stops the moment it got inside the radius. The movement is smooth.

The problem occurs when - **after the AI had reached the radius and stopped** \- I start moving my ship. The AI senses that it's no longer inside the radius, and starts following me, but in a very fragmented fashion.

It moves for a few pixels in my direction, stops, then moves for a few pixels, than stops.

*(These 'few pixels' are the 'moving step' both ships take while moving, every frame. The amount of pixels in each step is constant).*

I figured out the reason for this problem:

**When both ships are in place next to each other** (aka the AI is inside the radius so it doesn't need to move), and then **the player's ship starts moving**, the AI senses right away that **it is now outside of the radius**. **It moves immediately one step in the player's direction**.

The next frame, the AI senses that it's once again inside the radius. So it stops.

But the player is in motion. So the frame after that, again the AI senses it's outside the radius, and moves.

This creates very fragmented motion. The AI moves a step, stops, moves another step, stops.

I know what causes this problem, but not how to fix it.

Any suggestions as to how to fix this problem? What could cause this in the design I described?

Thank you

# Answer
Instead of having the AI start/stop, have the AI accelerate/decelerate. The further away the AI is from the player, the greater the speed has to be, and the closer it gets, the slower the speed.

On that subject, you could google **steering behaviour arrive** and **steering behaviour seek**.

Also, instead of having *one* radius destination for the AI, have *two*:

1. The first one is the smallest, closest to your target (the player). Use this radius as the "target" for your AI.
2. The second one, the largest. Use this one as what triggers you AI to start to pursue the target.

So when the AI is trying to reach the player, it'll do it until it reaches the smaller radius, but it won't move again just as the player moves, it'll wait for him to be a bit further away, reducing the *player move* -\> *AI move* -\> *player move* -\> *AI move* pattern. With that and the steering behaviours, you'll get something much smoother.
> 6 votes

---
Tags: ai, motion
---


# Question
Title: moving first person camera with the mouse on right click
I am new to game development and I am trying to get the game input working. I have successfully got all the movement keys for walking/running/looking around working; however, I am having a terrible time with the mouse lol.

Basically, I am trying to move the camera with the mouse when the user holds the right mouse button down and drags. I want to rotate the camera in that direction. So dragging to the right rotates right, dragging right/down will rotate right/down, etc.. I do not want the cursor to stay in the middle of the screen (this is not a FPS). I want the cursor to stay in the location it was in when the user first right clicked.

I am guessing this is probably not nearly as complicated as I am making it but I cant seem to find anything that has helped thus far. I have found several tutorials/excerpts on it but I havent got mine working yet. Below is my code for the MouseMove event (C# - I am using SharpDX framework).

```
            if (Input.Mouse.IsRightMouseDown &&
                Input.Mouse.PositionHasChanged(new Vector2(mouseEventArgs.X, mouseEventArgs.Y)))
            {
                var deltaY = mouseEventArgs.Y - Input.Mouse.OriginalRightMousePosition.Y;
                var deltaX = mouseEventArgs.X - Input.Mouse.OriginalRightMousePosition.X;
                var angle = (float)Math.Atan2(deltaY, deltaX);

                Camera.RotationY -= (float)Math.Sin(angle) * Global.MouseRotationSpeed;
                Camera.RotationX -= (float)Math.Cos(angle) * Global.MouseRotationSpeed;

                Input.Mouse.ResetMousePositionToOriginal();
            }

```

I would appreciate any help/advice I can get!! :)

Thanks in advance!!!

# Answer
Is it otherwise working, but your cursor is the problem? The cursor is usually just a HUD overlay centered on the screen, so it may not know anything about your camera.

One solution might be to make the cursor an actual 3d object in the scene.

\[EDIT\] the targeting reticule is the correct term for the object in question.

A more complex solution would be to calculate the position of the reticule from your view frustum.
> 1 votes

---
Tags: directx, camera, game-loop
---


# Question
Title: Strange collision behaviour in 2D game even though the collision is very basic
I have a player ship (cube) and some enemy laser projectiles. When the player ship has position X values greater than 1, collision with the enemy projectiles occur but when it has lower X values, the projectiles pass through.

If the image below is too small to view, you can refer to this link.

There are two screens in the image. The above image is where the collision occurs and the below one is where the laser projectiles miss the player ship. (You can see in a larger image better the tiles. When the collider of the player ship goes below the central horizontal line, collisions do not occur). Let me post the scripts for projectiles and player ship.

**LaserProjectile**

```
public class LazerProjScript : MonoBehaviour {

    private float speed = 5.5f;

    // Update is called once per frame
    void Update ()
    {
        // translate
        transform.Translate (new Vector3 (0f, -1f, 0f) * speed * Time.deltaTime);

        // destroy the projectile once it's out of screen
        if(transform.position.y <= -10)
            Destroy(gameObject);
    }

    void OnCollisionEnter(Collision other)
    {

        if(other.gameObject.tag == "Player")
        {
            print ("lazer on collision enter!");
            print ("hit player");
            other.gameObject.GetComponent<PlayerController>().hp -= 1;
            Destroy(gameObject);
        }
        if(other.gameObject.tag == "Enemy") return;

    }

}

```

---

**Player Controller**

```
public class PlayerController : MonoBehaviour
{
    public int hp = 100;
    public float speed = 0.3f;

    // Update is called once per frame
    void Update ()
    {
        /*********************************************************/
        /********************** TRANSFORM CODE *******************/
        /*********************************************************/
        //horizontal <- || -horizontal ->
        //vertical down || -vertical up
        float h = -Input.GetAxis ("Horizontal")*speed;
        float v = -Input.GetAxis ("Vertical")*speed;

        // do not let the ship get out of the camera
        if (Input.GetAxis ("Horizontal") < 0 && transform.position.x <= -11.8) {
            h = 0;
        }
        if (Input.GetAxis ("Horizontal") > 0 && transform.position.x >= 11.8) {
            h = 0;
        }

        if (Input.GetAxis ("Vertical") > 0 && transform.position.y >= 8.2) {
            v = 0;
        }
        if (Input.GetAxis ("Vertical") < 0 && transform.position.y <= -8.2) {
            v = 0;
        }

        transform.Translate (h, v, 0);
    }
}

```

Please note that neither the player ship nor the laser projectiles are `isTrigger`, `isKinematic`. Both have their Z values 0 all the time when they translate.

I cannot identify the problem. If the collider is above X=1 axis, there's no problem. If it's below that, collision does not occur! What is this, how can I solve this problem?

**EDIT**

Well, I played with the positions a bit and it got stranger. If projectiles start moving towards the player when they are in some range, they collide but if they travel for a certain amount of time (i.e. if they are more distant than some distance) they do not collide. I changed the Y values of the projectiles and one collided with the player even though it was below the X=1, and the other just passed through.

**EDIT2**

If I do not move the player, the projectiles miss. When I *move* the player, collisions occur whatever the distance was.

# Answer
> 2 votes
I see two things suspect with your code:

1. You should not be calling `transform.Translate()` to move a projectile - it's possible that you'll translate it right over its target!

Instead, attach a `rigidbody` component, turn off gravity, and set the velocity. If the velocity is high enough, you may also need to set the collision mode to 'continuous'.
2. This code

```
if(transform.position.y <= -10)
    Destroy(gameObject);

```

is suspicious, since it relies on the absolute position to determine when an object is off-screen.

Instead, please see this post for the proper way to determine if an object is off-screen.

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


# Question
Title: Calculate shadow map to overlay hidden line-of-sight things in 2d?
Given a 2D sideview with even-sized grid squares and our hero in a known center-ish position like this

... and imagining this hero's line of sight like this...

how could one get the point values needed for the black overlay polygons as shown here? Thanks!

# Answer
> 3 votes
you can do the simple scaling trick.

yea too lazy to explain, just look at the image and ask if you don't understand

In this example I just scaled by a factor of 2. Higher values give longer shadows.

# Answer
> 1 votes
I think you will need raycasting or walltracking to solve this.

This link might help you out. It shows the basic idea behind raycasting and walltracking with some interactive examples.

edit 1: changed raytracing to raycasting on first line, comment pointed out my brainfart

edit 2: Only use raycasting on the corners of your square, the rest can be interpolated. No need to cast endless amount of rays.

---
Tags: 2d, geometry, platformer
---


title: Detecting Units on a Grid

text:
# Question
Title: Detecting Units on a Grid
I am making a little turn based strategy game in pygame, that uses a grid system as the main map to hold all the characters and the map layout. (Similar to Fire Emblem, or Advance Wars)

I am trying to determine a way to quickly and efficiently (i.e. without too much of a slow down) check if there are any characters within a given range of the currently selected character.

So to illustrate:

```
O = currently selected character
X = squares within range

```

Range of 1:

```
    X
  X O X
    X

```

Range of 2:

```
     X
   X X X
 X X O X X
   X X X
     X

```

Range of 3:

```
      X
    X X X
  X X X X X
X X X O X X X
  X X X X X
    X X X
      X

```

Now I have to tell the user who is in range, and I have to let the user choose who to attack if there are multiple enemies in range.

If I have a 5x5 grid, filled with " " for empty and numbers for the characters:

```
[ ][ ][ ][ ][4]
[ ][1][ ][ ][ ]
[ ][ ][ ][ ][ ]
[ ][ ][2][3][ ]
[ ][ ][ ][ ][ ]

```

Depending on which character the user selects, I would like to show the user which other characters are in range. So if they all had a range of 3:

* 1 can hit 2
* 2 can hit 1 or 3
* 3 can hit 2
* 4 cannot hit anyone.

So, **How do I quickly and/or efficiently run though my grid and tell the user where the enemies are?**

PS- As a bonus, if someone could give an answer that could also work for a minimum distance type range, I would give them a pat on the back and a high five, should they ever travel to Canada and we ever meet in life.

For example: Range of 3 to 5: (`-` is out of range)

```
          X
        X X X
      X X X X X
    X X X - X X X
  X X X - - - X X X
X X X - - O - - X X X
  X X X - - - X X X
    X X X - X X X
      X X X X X
        X X X
          X

```

# Answer
> 3 votes
Without more information here's the solution I propose you :

Iterate through all the enemies in the map and calculate the distance between each enemy and the player. If the distance is equal to 1, they are within range 1, equal to 2, within range 2.

If you have too many units and it is slowing you down. You need to divide your map into sections. And have your enemies/player be part of a section. Then you only iterate through all the enemies within the same section of the map as your player. If you happen to do the implementation, check out Wackidev's comment, he is pointing out a problem that you could probably run into.

# Answer
> 1 votes
you have three options:

1. iterate through all characters and filter on weather they are in range or not (most stupid but simple to implement)
2. search on the grid everything that is within range. requires links from the map to characters
3. put every character in a search tree (eg kd-tree) to quickly find everything that is within range. This requires knowledge about search trees, but they are not too difficult to understand

# Answer
> 0 votes
```
        int minRange = 2;
        int maxRange = 4;
        for(int x = playerLoc.x - maxRange; x <= maxRange + playerLoc.x; ++x) {
            for(int y = playerLoc.y - maxRange; y <= maxRange + playerLoc.y; ++y) {
                int range = Math.abs(playerLoc.x - x) + Math.abs(playerLoc.y - y);
                if(range >= minRange && range <= maxRange) {
                    addUnitToTargetList(mapgrid.getCharacterAt(x, y));
                }
            }
        }

```

If you decide to allow diagonal movement someday, you can just change the range variable's calculation.

---
Tags: python, pygame, grid
---


title: Use of the xyY color space?

text:
# Question
Title: Use of the xyY color space?
What's the use of the xyY colorspace in games? I'm not sure what's the advantage of using it in shader programming or elsewhere.

# Answer
> 0 votes
The main reasons people use the xyY color space are:

1. It cleanly separates luminance (brightness) and chromaticity (color content)
2. The chromaticity part (xy) has the same range, namely \[0, 1\], no matter how bright or dim the color is
3. All physically realizable colors lie within \[0, 1\] in xy. (The Y component is unbounded.)
4. You can convert an arbitrary reflectance spectrum to XYZ (and thence to xyY) by integrating the products of the spectrum with the color matching functions.

xyY is useful for investigating color gamuts, such as the gamut of human vision (the famous CIE horseshoe diagram), or the gamuts of various color spaces (e.g. sRGB versus Adobe RGB), where we care about chromaticity but not brightness.

However, there are some reasons why xyY is *not* a very good space in which to do image processing:

1. It's nonlinear. This means you can't easily do physically correct lighting calculations, such as adding together the contributions of multiple lights, in this space.
2. Not every point in the xy \[0, 1\] square actually represents a color. Points outside the horseshoe are invalid. That makes it annoying to do any kind of image operation on xyY space, as you have to ensure you don't generate invalid colors.
3. It's not very perceptually uniform either, so you can't easily measure perceptual distances between colors (e.g. for perceptual error estimation, or selecting complementary sets of colors, etc.) CIELAB space is better suited for this.

In short, I can't think of a reason to ever use xyY in games or shader programming. If the goal is to separate luminance and chromaticity, YCoCg is probably a better choice; it's linear (if you transform to it from linear RGB) and is cheaper to transform to and from than xyY.

---
Tags: shaders, graphics-programming
---


# Question
Title: What is the correct Order of Operations on OpenGL 2.0 Loading Texture in condense format?
I have come across a problem when I am loading a single texture onto a single quad, and this problem persisted during the planning phases of my project, before starting my development phase. I am confused on the order of operations required to load a texture.

Why am I confused? I used the order listed below and rewrote the project over and over again, and the results vary. As in, one project would load and display the texture correctly, while the other projects can't display the texture, but loads the texture just fine. Due to this, I am conflicted.

Here is the rundown on the order of operations required for me to load a texture and show it onto the screen using OpenGL 2.0.

1. Create window.
2. Set up game loop.
3. Create OpenGL 2.0 context.
4. Initialize objects and load necessary files and data. (Textures, bitmaps, etc.)
5. Set up vertex data. (In this case, a quad.)
6. Create vertex shader code.
7. Create fragment shader code.
8. Compile the codes. (Checking included.)
9. Create program.
10. Attach shaders to program.
11. Link.
12. Validate.
13. Obtain attribute and uniform locations.
14. Set up viewport.
15. Create projection matrix, be it perspective or orthogonal.
16. Create view matrix and initialize matrix state.
17. Set vertex attribute pointer.
18. Enable vertex array buffer.
19. Use view matrix as model matrix. Push/pop/transform when necessary.
20. Clear screen.
21. DrawArrays().

Are these correct in chronological order? Are there anything else I am missing? I am just stuck on the planning phase, and wanted to get the chronological order done right.

# Answer
> -1 votes
write the code, compile it, run it. when it works on all gpu's your planning was correct. If it pleases you: I have my approval that your planning is reasonable and worth testing out.

and make shure you always use ther correct active texture unit. That active texture thing (glActiveTexture) is there to confuse people how are new to opengl. you do not pass the texture id to the shader uniform, it is always the number of the texture unit.

---
Tags: opengl, opengl-es2
---


title: Lerp speed or lerp time

text:
# Question
Title: Lerp speed or lerp time
Am I right about the fact that lerping can be done over a set period of time *or* at a speed which will continue until the target is reached?

How are the formulas for the two? Is it something like this?

LERP at speed:

```
// does not use start value but instead current value
newValue= Lerp (currentValue, targetValue, Time.deltaTime * speed);

```

LERP over set duration:

```
//uses startValue and calculates the progress percentage over time
var newValue = Lerp (startValue, targetvalue, percentage);
percentage= (Time.time - startTime) / duration;

```

# Answer
> 1 votes
If you're using speed (particularly variable speed) until some target position (especially if the target can move) is reached, it's not really LERPing. That's more akin to steering.

If you do have a fixed distance to cover and a fixed speed then you can easily calculate the time to LERP over. Remember the units of `speed` are units of `distance` over units of `time`. Assuming your fundamental units agree (e.g. not mixing miles-per-hour with meters and seconds) then you can get the time to LERP over with a teensy bit of algebra, giving you `time=distance/speed`.

---
Tags: c#, unity, mathematics, lerp
---


# Question
Title: Applying scale to objects appears to have little effect when close up.
I just started out with D3D 11. My goal is to write a cube voxel engine (Minecraft style). Actually it's working pretty solid already, but when I finally tried to change the size of my cubes, I ran into a problem:

No matter how large I make my cubes, they always appear super large when I move very close to them. Although they appear in a different size when I declare them in a different size and look at them from the same absolute distance.

For example: Let's say I make my cubes have a width, height, and depth of 1.0, and another time I give them a width, height, and depth of 0.01, and both times I look at them from a distance along the z axis of -1.0. The 1.0 cubes look larger than the 0.01 cubes. But I think this is only because the "relative" distance (100 cubes vs 1 cube) is a lot larger. The problem is, when I move very close to my 0.01 cubes, they become just as large as my 1.0 cubes with the front side filling almost the entire screen. I am very confused right now, since I have no clue as to how I can make my cubes appear smaller when I get very close to them. The problem is, the smaller I make my cubes, the closer I have to be able to get to them in order to make them appear as if they were right in front of me, which always results in huge cubes. Can anybody please help me figure out how to make my cubes appear smaller?

I don't know if this matters, but here is how I make my cubes:

1) Create a mesh for each chunk of voxels. In this process, I already define my vertices in world coordinates taking into account the cube size that I want (this is working, I printed out my vertex data with different cube sizes).

2) When rendering, each frame, I take the view projection matrix from my camera and send it to the shader. My vertex shader then simply does the following to my world coordinate vertices:

```
vout.pos = mul(float4(vin.pos, 1.0f), vpMatrix);

```

I also made some screenshots to show my problem. I just made a simple 32x3x32 map with different textures at each height.

1) Cube size 1.0, distance 10.0:

2) Cube size 0.1, distance 10.0:

3) Cube size 1.0, close distance:

4) Cube size: 0.1, close distance:

As you can see, at a distance of 10.0, the size difference is noticeable. But the closer I get, the less the size difference appears. A cube size of 0.1 at a close distance is still way too large. Almost as large as a cube size of 1.0 (which should be 10 times bigger?). I can go lower and lower on the cube size, but it just stays way too big at close range. And at some point, I can't go any lower. So, is there a way to make my cubes at a close distance look just a little bit bigger than the cubes seen in the second picture (cube size 0.1 at distance 10.0)?

Here is another screenshot of a more complex "map" proving, that I should actually be rendering stuff correctly:

# Answer
> 1 votes
I think there is a problem with your "close distance"

Because even if your object is very small, when you get extremely close to it, it will look large.

Is your "close distance" same in picture 3 and 4? Or do you get closer to them manually? If you are navigating manually, if your step\_length is very small, then it is possible to come very close to a very small object, which will make it appear large.

Edit: Can't comment so I post this as an answer.

# Answer
> 1 votes
Make your player taller. Currently you are not tall enough to give the illusion of size you want.

The reason you can get so close is obvious if you imagine real life, because even while standing against a wall, your relative height is what determines your perception of size, not the distance.

# Answer
> 0 votes
I am not sure I understand your problem, but it always helps to check your matrices. Have you transposed them before sending to shader (edit: base on your implementation, you might need to)

---
Tags: directx, camera, scale
---


title: lerp z rotation towards mousepointer

text:
# Question
Title: lerp z rotation towards mousepointer
I am trying to get `transform.rotation.z` to chase the mouse pointer at a rotation speed. But I get a very weird results and can't figure out what I am doing wrong.

```
var mp = Input.mousePosition;
var camZ = Camera.main.transform.position.z;
// Grab the current mouse position on the screen.
// Subtract the cams Z from the mouse Z to get ground plane.
var mousePos = Camera.main.ScreenToWorldPoint (
                           new Vector3 (mp.x, mp.y, mp.z - camZ));
//Rotates toward the mouse
var targetEuler = new Vector3 (0, 0,
      Mathf.Atan2 ((mousePos.y - transform.position.y),
                   (mousePos.x - transform.position.x)) * Mathf.Rad2Deg - 90);
transform.eulerAngles = new Vector3 (0, 0,
      Mathf.Lerp (transform.eulerAngles.z, targetEuler.z,
                  Time.deltaTime * rotationSpeed));

```

# Answer
> 0 votes
OKi was way off. This is how i got it to work.

```
                        rotationTarget = Camera.main.ScreenToWorldPoint (Input.mousePosition);

                    var _lookRotation = Quaternion.LookRotation (transform.position - rotationTarget, Vector3.forward);

                    _lookRotation.x = 0.0f;

                    _lookRotation.y = 0.0f;

                    transform.rotation = Quaternion.Slerp (transform.rotation, _lookRotation, Time.deltaTime * rotationSpeed);

```

---
Tags: unity, mathematics, rotation, lerp
---


# Question
Title: How do I move the camera in 2D LWJGL openGL?
I am making a top-down rpg game with the LWJGL but I can't figure out how to make the camera follow the player. I've tryed using GLU.gluLookAt() but it seems to be designed for 3D and when I try it with my game everything currently on the screen disappears. I have no idea where the camera gets moved to. Please explain simply how to use GLU.gluLookAt() or a better alternative to move the camera.

```
public class Camera {

    public float x = 0;
    public float y = 0;

    public void moveCamera(float toX, float toY){
    GLU.gluLookAt(x+toX, y+toY, 0.0f, 0.0f, 0.0f, 0.0f, 0f, 1f, 0f);
    }
}

```

# Answer
The first three arguments of gluLookAt are position of your camera. The next three is the point the camera is looking at. So you have to move *looking at point* as well as the position of camera.

```
GLU.gluLookAt(x+toX, y+toY, z, x+toX, y+toY, 0.0f, 0f, 1f, 0f);

```

Don't forget to move away camera on z axis (but I'm not sure if it will be problem).

Another way is to make translation (glTranslatef) before you draw your game.
> 0 votes

---
Tags: opengl, java, camera, lwjgl
---


title: LWJGL Jumping Down

text:
# Question
Title: LWJGL Jumping Down
I'm currently building a little game using LWJGL, and I got a Game class which contains my game loop, instances etc... And a Player class which contains a constructor (for x and y coords), logic method for calculations, key presses etc... and a render method for drawing the player on the screen. For some reason, when I press UP (Key.UP) the player jumps down the floor, and the goes up to the floor (inverted, instead of jumping up and then falling down to the floor). I would really appreciate if you could tell me what the problem is.

**Game.java:**

```
import static org.lwjgl.opengl.GL11.*;

import java.io.IOException;

import org.lwjgl.LWJGLException;
import org.lwjgl.input.Keyboard;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import org.newdawn.slick.opengl.Texture;
import org.newdawn.slick.opengl.TextureLoader;
import org.newdawn.slick.util.ResourceLoader;

public class Game {

    static Texture bgTexture;

    static Player player;

    public static void main(String[] args) throws LWJGLException, IOException {
        // Initialize
        Display.setDisplayMode(new DisplayMode(640, 480));
        Display.create();

        glEnable(GL_TEXTURE_2D);
        glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
        glEnable(GL_BLEND);
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
        glViewport(0, 0, 640, 480);
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        glOrtho(0, 640, 480, 0, 1, -1);
        glMatrixMode(GL_MODELVIEW);

        bgTexture = TextureLoader.getTexture("PNG", ResourceLoader.getResourceAsStream("res/background.png"));

        player = new Player(50, 200 - 64);

        while (!Display.isCloseRequested()) {
            glClear(GL_COLOR_BUFFER_BIT);

            drawBackground();
            player.render();

            Display.update();
            Display.sync(60);

            if (Keyboard.isKeyDown(Keyboard.KEY_ESCAPE)) {
                Display.destroy();
                System.exit(0);
            }
        }
    }

    public static void drawBackground() {
        bgTexture.bind();

        glBegin(GL_QUADS);
        glTexCoord2f(0, 0);
        glVertex2f(0, 0);
        glTexCoord2f(1, 0);
        glVertex2f(bgTexture.getTextureWidth(), 0);
        glTexCoord2f(1, 1);
        glVertex2f(bgTexture.getTextureWidth(), bgTexture.getTextureHeight());
        glTexCoord2f(0, 1);
        glVertex2f(0, bgTexture.getTextureHeight());
        glEnd();
    }

}

```

**Player.java**

```
import static org.lwjgl.opengl.GL11.*;

import java.io.IOException;

import org.lwjgl.input.Keyboard;
import org.newdawn.slick.opengl.Texture;
import org.newdawn.slick.opengl.TextureLoader;
import org.newdawn.slick.util.ResourceLoader;

public class Player {

    public double x, y, xspeed, yspeed;

    private Texture pTexture;

    public Player(double x, double y) throws IOException {
        this.x = x;
        this.y = y;
        pTexture = TextureLoader.getTexture("PNG", ResourceLoader.getResourceAsStream("res/player.png"));
    }

    public void logic() {
        x += xspeed;
        y += yspeed;

        yspeed -= 0.4;

        // Collision detection
        if (y <= 480 - 64) {
            y = 480 - 64;
            yspeed = 0;

            if (!Keyboard.isKeyDown(Keyboard.KEY_RIGHT) && xspeed > 0) xspeed = xspeed * 0.7;
            if (!Keyboard.isKeyDown(Keyboard.KEY_LEFT) && xspeed < 0) xspeed = xspeed * 0.7;
            if (Keyboard.isKeyDown(Keyboard.KEY_UP)) yspeed = 8;
        }

        // Moving
        if (Keyboard.isKeyDown(Keyboard.KEY_RIGHT)) xspeed = 4;
        if (Keyboard.isKeyDown(Keyboard.KEY_LEFT)) xspeed = -4;
    }

    public void render() {
        logic();

        glPushMatrix();
        pTexture.bind();
        glTranslated(x, y, 0);

        glBegin(GL_QUADS);
        glTexCoord2d(0, 0);
        glVertex2d(0, 0);
        glTexCoord2d(1, 0);
        glVertex2d(pTexture.getTextureWidth(), 0);
        glTexCoord2d(1, 1);
        glVertex2d(pTexture.getTextureWidth(), pTexture.getTextureHeight());
        glTexCoord2d(0, 1);
        glVertex2d(0, pTexture.getTextureHeight());
        glEnd();

        glPopMatrix();
    }

}

```

Thank you so much.

# Answer
The coordinate (0,0) is the top-left of the screen.

```
if (Keyboard.isKeyDown(Keyboard.KEY_UP)) yspeed = 8;

```

This means that your player accelerates downwards on `KEY_UP`, and

```
yspeed -= 0.4;

```

means "gravity" pulls the player to the top of the screen.
> 0 votes

# Answer
Do you know where the (0,0) coordinate is located on your screen?

because if (0,0) is located in the top left corner, jumping up would result in a decreased Y-value.

That would explain the jumping down with increasing the Y-value.
> 0 votes

---
Tags: java, lwjgl
---


# Question
Title: Unity score on touch adding up incorrectly
I'm currently working on a game where a user can click an object and this should increase their scored by 1. Unfortunately it seems to be increasing it by more than 1 sometimes and I can't figure out why. The code to increase the score is below:

```
            if (Input.GetButton ("Fire1")) {

        Vector3 clickedPosition = Camera.main.ScreenToWorldPoint (Input.mousePosition);
        RaycastHit2D hit = Physics2D.Raycast (clickedPosition, -Vector2.up);

        if (hit && !this.touched && (hit.rigidbody && hit.rigidbody.Equals(this.rigidbody2D))) {
            this.touched = true;

            this.rigidbody2D.isKinematic = true; //reset
            this.rigidbody2D.isKinematic = false;
            Vector3 hitPoint = this.transform.InverseTransformPoint (hit.point);
            rigidbody2D.AddForceAtPosition(new Vector2(maxVel,topForce), new Vector2(hitPoint.x,hitPoint.y));
            if(!scored){
            score+=1;
            scored = true;
            }

        }
    }
    if (this.transform.position.y < this.previousYPosition) {
        this.touched = false;
        scored = false;
    }

    this.previousYPosition = this.transform.position.y;
      }

```

As you can see I've tried adding a number of booleans to try and ensure it only updates if certain conditions are met. What's weird is that sometimes it doesn't only add one and sometimes it adds more. I can only assume the update is being called multiple times, but then as far as I am aware it should fail my if conditions.

I've also tried moving this to the OnMouseDown method and moving the boolean checks into FixedUpdate() instead, and although this is slightly better, it still doesn't seem to be correct.

Any advice?

# Answer
> 0 votes
`Input.GetButton()` will return true for each frame that the "button" is down.

`Input.GetButtonDown()` or `Input.GetButtonUp()` will return true only on the frame that the button goes down or up respectively.

---

As an aside if your score is rising unpredictably it would require that your `touched` and `scored` flags are being reset.

1. If you have posted all of the code that handles these variables then that means that "`this.transform.position.y < this.previousYPosition`" is evaluating to `true` under some circumstances?!? Are you detecting a bounce, or the effects of some other code that is manipulating it's position? If the latter then maybe you could reset the flags in that other block of code rather than checking for its effects.
2. If there is other code manipulating these flags one approach that is guaranteed to provide insight is to change the variables to properties, then apply a breakpoint to the setter. This will allow you to step though to the code that call calling the setter and examine the circumstances of that call.

# Answer
> 0 votes
Most likely this.touched is getting set to false.

Solution, use MouseUp?

Additional advice: if you are not yet stepping through code while it's running, I recommend learning about breakpoints.

---
Tags: unity
---


# Question
Title: How to calculate a bounding rectangle of a polygon?
```
Polygon poly = new Polygon();
poly.getPoints().setAll(5d, 15d, 15d, 25d, 5d, 30d);

```

How do I calculate the Polygon's height and width? There is no poly.getWidth() or poly.getHeight() method in javafx.

# Answer
As lealand raised "width" and "height" are somewhat vague terms.

Here is a straightforward approach to finding the width and height of the AABB:

```
double minX = Double.MAX_VALUE;
double maxX = -Double.MAX_VALUE;
double minY = Double.MAX_VALUE;
double maxY = -Double.MAX_VALUE;

double[] points = poly.getPoints().toArray();

for(int i = 0; i < points.length; i += 2) {
    double x = points[i];
    double y = points[i + 1];
    minX = Math.min(minX, x);
    maxX = Math.max(maxX, x);
    minY = Math.min(minY, y);
    maxY = Math.max(maxY, y);
}

double width = maxX - minX;
double height = maxY - minY;

```
> 4 votes

# Answer
A polygon doesn't have a height in width, as it's simply a collection of vertices. In fact, these properties only really make sense as we commonly use them when you have four (as in a rectangle).

You'll have to define and write your own methods for calculating these properties. For example, the width might be defined as the maximum distance between any two vertices, and the height might be the length between the mid-point of that line and the third vertex.
> 0 votes

---
Tags: java, 2d, physics
---


# Question
Title: Having trouble compiling UnrealScript with defaultproperties
Have just started scripting in Unreal Script and am following the instructions of the opening chapter of a book on the subject. I have set the development tools up as described in the book such that it is now possible to compile the scripts for UDK before adding them to a level. My issue is: the very first script the book asks you to compile is the following:

```
class AwesomeActor extends Actor
placeable;

defaultproperties
{
    Begin Object Class=SpriteComponent Name = Sprite
        Sprite = Texture2D'EditorResources.S_NavP'
    End Object
    Components.Add(Sprite)

}

```

And when I hit F9 in the compiler I get the following error message: Error, BEGIN OBJECT: Must specify valid name for suboject/copmponent: Begin Object class=SpriteComponent name = Sprite

My question: As far as I'm aware I've copied the code from the book veribatim including capital and smaller case letters but I'm getting this error and I was wondering if anyone knew why and if so how I would fix it?

# Answer
As mentioned in the comments, the issue was syntax-related, as the white space between the operators and operands was causing parsing issues. To quote the official documentation for UnrealScript:

> As mentioned previously, the rules of the defaultproperties block is slightly different from the standard unrealscript syntax. The general differences are:
>
> ...
>
> Spaces should be avoided (such as between variable name, assignment operator, and value).

https://udn.epicgames.com/Three/UnrealScriptDefaultProperties.html
> 1 votes

---
Tags: udk, scripting
---


# Question
Title: How to convert a SDL window to a SDL surface? SDL 2
I am trying to make a paint program and there is a sdl function called IMG\_SavePNG() which requires a surface and destination file. How can I turn what I see in the window to a surface?

# Answer
To achieve this in SDL, you need to use the SDL\_GetWindowSurface() funcion. This function will return the surface associated with the window. You can then pass the surface to the `IMG_SavePNG` function to take a screenshot.
> 3 votes

---
Tags: c++, software-engineering, sdl
---


title: What does [dynamic] do in HLSL

text:
# Question
Title: What does [dynamic] do in HLSL
Here's an example (this if() is inside of a for loop, which itself has the \[unroll\] attribute):

```
[dynamic]
if (n.x > 1.0f || n.x < -1.0f || n.y > 1.0f || n.y < -1.0f || n.z < 0.0f || n.z > 1.0f)
{
    break;
}

```

I've never seen this before, but I stumbled across this in a shader I'm trying to convert to glsl. Searches turned up nothing but the SM 5 dynamic linking ability. I looked at the available if() attributes, and there's only \[branch\] and \[flatten\] listed.

# Answer
As per Microsoft's reference:

http://msdn.microsoft.com/en-us/library/bb313968(v=xnagamestudio.31).aspx

`dynamic` does not exist as a valid attribute. In this case, the compiler should have emitted a warning, stating that the attribute was unrecognized.
> 2 votes

---
Tags: hlsl
---


# Question
Title: What is the role of tessellation in terrain?
I'm relatively new to graphically programming and I've been looking into ways to render larger heightened terrain. I keep seeing comments directing me to disregard things such as geometry clipmaps, in favor of tessellation.

From what I've read however, tessellation adds inner and outer triangles between a set of vertices. So from what I understand, you would lose the 1 to 1 relationship between height points and vertices. Additionally, the new vertices would be interpolated and therefore somewhat similar looking between points of similar height.

Is this the case or is there something I'm missing. Is tessellation exclusively the way to go or can it (/should it) be combined with other techniques?

# Answer
> 6 votes
When rendering terrain, for efficiency you usually want to reduce the level of detail of geometry in areas far from the camera. As the camera moves around, you would adjust the level of detail to keep the area near the camera at high detail.

Geomipmapping, geometry clipmaps and suchlike are ways of managing this on the CPU. Although the GPU always does the actual rendering, you have to do a certain amount of CPU work each frame to decide which terrain chunks to draw at which LOD. You also have to take care of avoiding cracks when two adjacent chunks are drawn at different LODs. This tends to add a good deal of complexity to the algorithm, as well as using more memory and performance to deal with the extra crack-filling geometry.

The potential advantage of tessellation is that you would move this work onto the GPU. You could code a hull shader that would choose the appropriate level of detail for each patch and automatically generate the geometry for it. You would not need to store any terrain geometry, just the heightfield in the form of a texture to be sampled by the domain shader. On the CPU, you would simply render a single quad-patch (four vertices) for each terrain chunk—potentially including the whole terrain in one draw call. Because the tessellation hardware allows you to independently set tess factors for each edge of a patch as well as the interior, anti-cracking is easy to accomplish.

There's no reason why you would need to lose the 1-to-1 relationship between height samples and vertices. If each chunk is 64×64 height samples, and you draw it using a single patch with tessellation factor 64 (the maximum) then it will have one tessellated vertex per height sample. As the camera gets farther away you would reduce the tess factor, and then the resulting geometry will interpolate between height samples and/or not use all of them, but that's what would happen in any other LOD scheme as well. You could also increase tessellation beyond the number of height samples (e.g. a patch with 16×16 height samples, but tess factor 64). This could be useful for extra smoothing, e.g. if you implemented bicubic interpolation for the heightfield, or adding extra detail, such as from a detail map or noise function, or procedural destruction (as seen in some games where explosions will leave craters in the terrain).

As for whether tessellation is "exclusively" the way to go, that is difficult to answer. It's a tradeoff: it will reduce CPU overhead in managing and submitting terrain draw calls, but it will increase GPU usage, which you may or may not want to do. Also, tessellation is only available on DX11-class GPUs—which is all the new desktop/laptop GPUs being sold for the past several years, as well as the new consoles, but not mobile GPUs (yet) or the last-generation consoles. So it's wise to consider the minimum hardware requirements for your project before going all-in on tessellation.

---
Tags: terrain, level-of-detail, tessellation
---


title: DirectX11: Drawing multiple objects

text:
# Question
Title: DirectX11: Drawing multiple objects
How can I draw many different objects on screen at once, with multiple vertex buffers, using `DrawIndexed()`? (Drawing the same object is simple, and I'm not looking to instance)

...but I am looking to transform two different vertex buffers. (Yes I am using indexed vertices)

# Answer
You can bind multiple vertex buffers at once. However, unless you use instancing or similar (passing transform data in a constant buffer, for example, which becomes cumbersome beyond a certain number of objects and which is effectively the same as instancing anyway), all the buffers bound at a given draw call share the same bound transformation.

In other words, your options are:

* use instancing (which you have discarded for some unspecified reason)
* use constant buffers to emulate instancing (which may also be off the table for the above)
* make multiple draw calls, one for each buffer into which you were able to pack all the objects that can share a transform
* pre-transform all your objects on the CPU, write their final world-space vertices into the buffer, and draw that (somewhat silly)
> 1 votes

# Answer
Creating an `OBJECT` class did the trick. It allowed for object data separation and the member support I was looking for.
> 0 votes

---
Tags: c++, directx11, transformation, index-buffer, draw-order
---


# Question
Title: Dealing with interpolation and object creation/destruction
I've implemented a game loop similar to that in Glenn Fiedler's Fix Your Timestep! article. I have an update step running at 50Hz and a render step running at 60Hz (monitor refresh rate). To keep things smooth, the update step produces snapshots that the render step can interpolate between with a constant latency of 20ms. These snapshots contain all the information needed for the rendering step to build skeletons and other transformations, but not anything involving physics, AI, or networking.

Actually interpolating between the snapshots is pretty simple, but something I've forgot about until now is how to deal with renderables being created or destroyed. What would be an elegant method to go about interpolating between snapshots when a renderable may only exist in one of them?

# Answer
> 2 votes
It's a Great article that Fiedler did.

You don't have to worried about that. The `Alpha` value you have for interpolating two render states is like an optional info, a hint you have to improve your animation as much as possible, but you don't have to interpolate the 100% of your renderables (visual and animated objects). You first should prioritize most visible and easy to interpolate features like: Camera movement (very important), Characer animations, dynamic objects, particles...

Then precisely with a visible object being "destroyed" it should have solved his way to disappear from your game world a bunch of frames before that particular frame when you decide to destroy it; using a death animation or particle effects. You can even keep it invisible if you need it or morphed|converted to other class|object|entity.

Is the same inverted with an object born|creation.

There are things you don't need or you can't interpolate; like a Boolean (true|false) value. The algorithm try to improve the **visual** side of your game as smooth and pleasant as possible while keeping consistent game-play logic, so go ahead and good luck with the implementation!

---
Tags: game-loop, c, interpolation
---


# Question
Title: Dynamic entities using classes and objects
I'm trying to create a program which involves the creation of several characters/entities.

At the moment I have a Base Entity class an Entities class and a Main class. I can handle one entity alright, however I am trying to create each one editable through a standard function call.

```
Main Class: http://pastebin.com/AjgEBSke
Entity Class: http://pastebin.com/5y2wD3Qc
BaseEntity Class: http://pastebin.com/VfqRgeng

```

I feel a little confused on how to dynamically call and edit each specific character without limiting myself to lots of 'if' statements. I have tried to restart this project several times...

Basically I'm creating a private object in a class. That class will be used to talk to that private object, Save, load and edit etc.

Then in a seperate Entities class I create an instance of that object, this is where I think im getting caught up. As far as I know, I need to handle everything I want to do in that entity in this entity class.

I give the entity/object an ID, and a default name which I want to be able edit later. I also want to eventually be able to call that entity from other classes to 'draw' it, have it return the values I need to draw it, Name, body type etc (other variables in the object).

I have managed to interact with a specific instance of the object class by checking if the String is equal to an objects ID and then doing something, this however I feel is not dynamic and I'll just get into a bigger mess.

Ideally I think I want to be able to enter the object's class' instance name as a string and have it handle everything.

Sorry this has been rather long, if you know of any articles or information on how I'd learn to create dynamic entities to do what I need to do, that'd be great.

Im probably looking more for an explanation of the concept of what I'm trying to do as i've only just really sketched up this code. So this code might be a little pointless at the momemnt. Ive attempted it a few times, trying to set things up better each time, however ultimately fail when I try to make things behave dynamically. If i'm going about this completely the wrong way then please tell me as I'm still learning and don't want to get into the habit of doing things badly.

# Answer
> 1 votes
I think your question is just a little bit vague. Where exactly do you need lots of if-statements for?

That being said, it sounds like you are having trouble with object-oriented programming. I often rush into a project, only to restart it later, with a better specification (and by that I mean a worked out diagram with classes and methods).

I'm not sure if you want to be able to assign ID's at runtime or just do it at code-time (the word 'dynamically' suggests run-time, but the abundance of if-statements suggest code-time. For code-time ID's, you might want to consider making subclasses. For runtime, I wouldn't understand the problem.

This answer is a kind of a rant, but I hope it still is useful in one way or another.

# Answer
> 1 votes
You are looking for Polymorphism: http://www.adobe.com/devnet/actionscript/learning/oop-concepts/polymorphism-and-interfaces.html

First basic concept is that you don't need to identify every entities with IDs or Names as long as you plan to use that fields for visualize it or debug. Every field|variable|property you define in a class has is independent memory space for every instance you create.

After that using Polymorphism as explained in the article above, you could define multiple subclasses inheriting from your base clase, that behave different each one according of is methods implementation. Such methods that were defined before on it's base class.

---
Tags: actionscript-3
---


# Question
Title: Create a tornado like particle movement, based on velocity
For context i'm using Java and Minecraft Forge, however the concept should be fairly standard. To spawn particles you use this function...

```
world.spawnParticle("largesmoke", posX, posY, posZ, velocityX,  velocityY, velocityZ);

```

This works fine, however I am trying to give the particle a velocity which will rotate it around a point (the player) and give the effect of a tornado (obviously more will have to be spawned, I also have the random position setup to each particle).

In short, I would like to find a way to give it a tornado like velocity.

Thanks

# Answer
> 2 votes
It is not possible to give anything a velocity such that it will rotate around a point, with a constant velocity you can only make an object follow a straight line.

If it is possible to modify the velocity of your particles after they have been created then you can create some with a velocity which is tangent to a circle around your player and then accelerate them toward the player with |a| = |v|^2 / r to achieve uniform circular motion.

If you can not modify your particles velocity after creating them but you can make them disappear fairly soon after they are created, then you could make lots as above surrounding your player and possibly make it seem that they are rotating even though they are not, creating new particles after the old ones have disappeared. If you have access to the position and time that they will disappear at then you could also consider creating new particles with a modified velocity at the position that the previous particles disappeared at.

Make sure that all of your particles rotate around the player in the same direction to make it look more like a tornado. One way to do this is to just use the vector from the player to the particle's initial position rotated 90 degrees around the up axis as the particles initial velocity, scaling if you need to.

# Answer
> 0 votes
I'm not familiar with Minecraft Forge, but Every 3D game engine particle system should have a set of objects or helpers that interact with your particle systems affecting them by forces. For example gravity can be a linear force field given a vector or radial force field given a position.

You need to link your particle system with a force field around a line or cylinder while the force should point inside to the cylinder; Then spawm particles around the center (1.5 character width aprox.) perpendicular to the force field.

If your game engine doesn't support those type of force field try following trick with similar effect:

Spawn a bunch of particle system around a circle on the base or your character then rotate these positions where the particles are spawn (posX, posY, posZ). The effect is like a fountain, with spirals.

Last option, because I think this will slow down performance, if you have access to modify particles velocity in real time implement the solution given by @Alex:Taking a normalized vector from particle position to character position vertical axis, multiply it by acceleration, then add it to current particle velocity vector.

---
Tags: java, minecraft-modding
---


# Question
Title: Rendertarget and alphablending problem (Offscreen particle rendering)
Today, I have implemented soft particles by rendering them to a separate render target and blending that with the scene, which worked as expected with additive blended particles. In that case I render the particles to a rendertarget while blending them additively, then drawing that rendertarget in fron of the scene while blending additively, works like a charm, I even save some render time if I use a smaller render target. In the case of alpha blended particles, I have a serious issue. First I draw them with a blend state set up for alpha blending:

```
D3D11_BLEND_DESC bd;
bd.RenderTarget[0].BlendEnable=true;
bd.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA;
bd.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
bd.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
bd.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ZERO;
bd.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_INV_SRC_ALPHA;
bd.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
bd.RenderTarget[0].RenderTargetWriteMask = 0x0f;
bd.IndependentBlendEnable=true;

```

(This is it after reading the GPU Gems article on this subject.)

The render target which I draw them to is cleared by zero for all channels. When I draw this rendertarget to the screen I use a blend state set up for alphablending (it is used for all the 2d images and definetly works well) and I get this: It seems as if I have depth writing turned on but I made sure it is turned off. If I draw the rendertarget with these alpha blended particles on it, but with no blending (for the RT) I get this: Which seems correct, it just doesn't blend how I want to. On GPU gems there are sure some well described formulas for the blending, but if I set the blendstate descibed there I won't get the results they get. Could someone help me with what I am missing?

# Answer
> 0 votes
because you first blend particle color with black render target use src\_alpha

so the image in the render target is multiply alpha yet
when you use the render target you should not multiply alpha again or it will dark the part of the image where alpha is low

---
Tags: directx, directx11, particles, alpha-blending
---


# Question
Title: Creating a vehicle using a physics engine
What is the theory behind creating a generic 3D vehicle in a physics engine?

What I would like to know is what parts should I stick together to make the vehicle, how they parts should stick together, and how to make the vehicle have the feel and movement of what you expect of a vehicle.

I'm not looking for any code, or how to do it with a specific engine. Just the theory behind how it is done.

# Answer
The only physics engine I know is ODE so I'll roughly explain how would go with an engine like this one. I think this here could also be applied to something like bullet physics.

So, *since your question is quite vague*, here is something to start with:

One has first to determine what are the basic parts of the vehicle:

* four wheels, represented conceptually by cylinders
* the car, represented conceptually by a box

Then how are these items held together?

* a hinge holding each of the rear wheels to the car
* a hinge-2 holding each of the front wheels to the car

A hinge-2 is a hinge that has 2 axes, and is the type used to link front wheel to a car : it allows the wheel to roll on the road and it allows it turn in the direction it wants to go.

Obviously, these hinges have parameters: wheels don't have limits when they roll on the road, but the front wheels can't turn at 360 degrees.

Then, depending on the behaviour you want to achieve, you'll have to set the front wheels or the rear wheels - or all of them - as motors (or as brakes).

You'll have to tune the friction parameters between your wheels bodies and your "ground" bodies to get the behaviour you'll need.

And finally, each frame of your simulation, you'll have to set the the maximum force to apply on each hinge and the requested speed.
> 2 votes

---
Tags: 3d, physics, car
---


# Question
Title: GL_TEXTURE_CUBE_MAP min/mag filter problem
I found it hard getting min/mag filtering to work with cubemap texture. In the screenshot-attachment I've created a cube using a cubemap texture, and also a grid of planes using a 2D texture. For both the cubemap and 2D texture I use GL\_LINEAR\_MIPMAP\_LINEAR, for min-filter. For 2D texture it works, but for the cubemap it doesn't.

Below, I've listed the code for how I set up my cubemap texture. I would be glad if someone could help me out with this, thanks in advance :)

```
levels = floor(log2(max(width, height))) + 1;

glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS);
glGenTextures(1, &id);
glActiveTexture(textureUnit);
glBindTexture(GL_TEXTURE_CUBE_MAP, id);

glTexStorage2D(GL_TEXTURE_CUBE_MAP, levels, internalFormat, width, height);

for (GLenum target = GL_TEXTURE_CUBE_MAP_POSITIVE_X, i = 0; target <= GL_TEXTURE_CUBE_MAP_NEGATIVE_Z; target++, i++)
{
    glTexSubImage2D(target, 0, 0, 0, width, height, format, GL_UNSIGNED_BYTE,    cubeMapList[i]->pixels);
}

glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glGenerateMipmap(GL_TEXTURE_CUBE_MAP);

```

# Answer
> 1 votes
Looks like it's working normally to me. The top face of the cube, which is screen-space narrow similarly to the far end of the plane, appears similarly filtered.

The other faces of the cube do not display any blurriness because they are wide enough in both dimensions to not require minification. Remember, mipmapping isn't *intended* to make distant textures blurry. It's intended to blur (rather, low-pass-filter) distant textures *as required to avoid aliasing*.

If you want everything to be *consistently* blurry at distance, then what you want is a *depth-of-field* effect, which is considerably more complex to implement.

If you don't specifically want blurring but just want surfaces to be more consistent with each other, try using *anisotropic filtering*, which eliminates the effect of surfaces which have different scales in the two texture axes (like the top of the cube or the plane) getting blurred along both axes equally. It's mipmapping extended to operate independently in both axes.

---
Tags: cubemap
---


# Question
Title: How to build an iPad game without an Apple device?
I am an experienced PC/mobile app developer trying to build an iPad app but I don't have access to a physical device. I have a PC and an Android phone (whatever good that is!)

The app is essentially a conversion of a Flash-based software. I'm going to use Adobe AIR to target the iPhone/iPad (Adobe has built support for this natively). I have build an Android app using this process and it has been seamless. Since I'm not going to use XCode (unless needed) and Adobe has an iPhone Simulator integration.

Is there any way I can build an iPad app without a physical iPad/iPhone device? Are there emulators on the PC/MacOSX side that I could use and would I be able to build a functioning app?

What I can do:

1. Install MacOSX on my Windows machine and turn it into a Hackintosh. Nothing wierd here, it would work like a normal mac and support XCode and everything.
2. Build the app in Adobe AIR or XCode
3. Test on a iPad/iPhone Emulator on my Hackintosh or PC

In the worst case I'll have to:

1. Spend like $400 or whatever and buy a physical iPad/iPhone.
2. Borrow an apple device from a friend.

# Answer
> 5 votes
It is highly not recommended to make an iPad game without a device.

The simulator is decent, but some things cannot be tested properly on it. For example, In App Purchases cannot be tested without a device. And believe me, you *want* to test those things.

You also won't get much of an idea of its performance on the simulator since it may run much faster or much slower than a device, depending on your host system's specs.

---
Tags: ios, iphone, flash, macos
---


# Question
Title: Grid collision - finding the location of an entity in each box
I am trying to implement grid-based collision in a 2d game with moving circles. The canvas is 400x400 pixels. Below you can see the code for my Grid class. What I want it to do is check inside which box the entities are located and then run a collision check if there are 2 or more entities in the same box.

**Right now I do not know how to find the position of an entity in a specific box.** I know there are many tutorials online, but I haven't been able to find an answer to my question, because they are either written in C/C++ or use the 2d array approach.

Code snippets and other help is greatly appreciated. Thanks.

```
public class Grid {

ArrayList<ArrayList<Entity>> boxes = new ArrayList<>();
double boxSize = 40;
double boxesAmount = 10;
...
...
public void checkBoxLocation(ArrayList<Entity> entities) {

      for (int i = 0; i < entities.size(); i++) {
// Get top left coordinates of each entity
            double entityLeft = entities.get(i).getLayoutX() - entities.get(i).getRadius();
            double entityTop = entities.get(i).getLayoutY() + entities.get(i).getRadius();

// Divide coordinate by box size to find the approximate location of the entity
            for (int j = 0; j < boxesAmount; j++) {   //Select each box
                if ((entityLeft / boxSize <= j + 0.7) && (entityLeft / boxSize >= j)) {
                    if ((entityTop / boxSize <= j + 0.7) && (entityTop / boxSize >= j)) {
                        holdingBoxes.get(j).add(entities.get(i));
                        System.out.println("Entity " + entities.get(i) + " added to box " + j);
                    }
                }
            }
        }
    }
}

```

# Answer
> 1 votes
The purpose of the box is just to speed up finding potential collisions. You don't want to think of positions within the boxes at all. Use your normal collision code once you've determined which entities are potentially colliding.

---
Tags: java, 2d, physics
---


# Question
Title: Handling latency in realtime music/rhythm-based games
Suppose I am making a co-operative multiplayer music-based rhythm game -- two players, side by side, move their cursor/avatar left and right with their mouse and attempt to hit or dodge obstacles that are coming towards them.

The problem here is that if there is latency in the connection, say 200ms from player B, then by the time player A receives the movement from player B, it will have been too late -- the players' position on the track will be ahead of where it was when it was sent.

There is also a problem with running them in a sort of lockstep where the two players wait for each other to acknowledge their respective inputs -- the music must continue playing without delay on both players' clients, otherwise it will sound very choppy and the player actions might not line up well with the rhythm, which isn't what we want.

How can we deal with this latency?

# Answer
> 1 votes
I would suggest first reading this great article about networking. It explains fairly well the kind of lockstep issues that you are experiencing.

Here is a great series of articles explaining fast-paced networking. These are actually the same techniques that I employ in my own game engine.

Now I cannot suggest one solution over another for your exact implementation. It is up to you to decide which technique works for you.

---
Tags: networking, multiplayer, latency
---


# Question
Title: Severe color banding while applying SSAO
I'm trying to implement SSAO together with deferred shading. The deferred shading works just fine, and so does calculating the AO as seen in the first image below. However, taking AO into consideration when combining the light with gbuffer data produces color banding as seen in the second figure.

The third image shows a result after messing around, ending up multiplying the final color by 3, increasing the overall light intensity. The light banding is somewhat alleviated, and further increasing the light intensity reduces banding even more. This is of course not a solution but perhaps a step in the right direction.

Nevertheless it got me thinking. For the resulting texture I'm using an RGBA8\_UNORM format, which gives me 256 distinct values for the various channels, right? I store the AO in a single 8 bit channel texture. The only light affecting the mesh is ambient light, and the color of the mesh is a single shade of green. Doesn't this mean that the already low bits of the render target have to store even more shades when AO is applied? This makes sense considering that increasing the precision of the AO map doesn't fix the problem, but not so much when simply increasing the intensity of the final color reduces the banding. **How is this generally handled when using deferred shading?** I should note that attenuating the final color with the normalized horizontal pixel value in \[0,1\] produces similar banding, which is perfectly vertical instead.

Can it be something that has to do with gamma correction (I don't explicitly do it myself)? Is that something one must do when using deferred shading?

**Edit:**

It turned out that DXUT made the back buffer SRGB (meaning that it handles gamma correction), but gamma was never corrected at the beginning, resulting in incorrect gamma handling. Correcting gamma while sampling textures resulted in clearer, but darker colors. Increasing ambient light to compensate for the darkness resulted in less banding while still having dimmer surroundings. Another bonus is that the colors don't look as washed-out as before.

It's not completely perfect however, but maybe HDR rendering can take care of that (big maybe, I don't much about it at all). Also, colors of the mesh are constant, which probably contributes. I believe having high-frequency textures makes the little banding that's left less apparent.

# Answer
The main problem in this case was that gamma was not handled correctly. As Nathan pointed out, textures using sRGB formats in D3D11 will handle gamma correction automatically. DXUT made the back buffer sRGB, which means that gamma was ultimately handled incorrectly. Manually correcting for gamma at the beginning of the pipeline when sampling textures fixed much of the banding (after increasing ambient light due to darker colors).

To anyone who experiences similar banding: **make sure that gamma is properly handled**. You can use sRGB formats on both render targets and textures to get free gamma correction when reading/writing. Note that this is only required for color data that is already "prehandled" (textures from photoshop etc) and not normal data and stuff like that.
> 1 votes

---
Tags: deferred-rendering, ssao
---


title: Geometry Shader input vertices order

text:
# Question
Title: Geometry Shader input vertices order
MSDN specifies (link) that when using `triangleadj` type of input to the GS, it should provide me with 6 vertices in specific order: 1st vertex of the triangle processed, vertex of an adjacent triangle, 2nd vertex of the triangle processed, another vertex of an adjacent triangle and so on... So if I wanted to create a pass-through shader (i.e. output the same triangle I got on input and nothing else) I should return vertices `0`, `2` and `4`. Is that correct?

Well, apparently it isn't because I did just that and when I ran my app the vertices were flickering (like changing positions/disappearing/showing again or sth like that). But when I instead output vertices `0`, `1` and `2` the app rendered the mesh correctly.

I could provide some code but it seems like the problem is in the input vertices order, not the code itself.

So what order do input vertices to the GS come in?

# Answer
> -1 votes
Probably you are giving the vertices in the wrong order like you said. Anyway returning the vertices 0,2,4 will give you the correct triangle.

I think the problem is that your input vertices are not given in the right winding direction. Swapping 2 vertices in a triangle will reverse the normal vector of that triangle resulting in a invisble triangle (it will be removed using back-face culling).

If there's a way to test what values are returned from the shader that could help. Because debugging numbers using feedback from visual flickering is not that easy =D.

Edit: You need to isolate the problem, why do you think the shader is problem in the first place? Just give 6 vertices to the shader and check if the shader recieves all the coordinates in the order you would expect. Then check if vertex 0, 2 and 4 would give the requested triangle. If all that is correct, I think the problem is not in the shader. You might give the wrong vertices to the shader, or the problem is located when you use the coordiantes the shader returned...

---
Tags: hlsl, geometry-shader
---


# Question
Title: How much does it cost to license vehicles for a racing game?
I've looked and looked, and even contacted some companies but I never got anywhere. Does anyone know? I just need to see if I can do it financially.

# Answer
> 2 votes
1. First of all it largely depends on a car company in question. Ferrari and Dacia are in much different leagues.
2. Secondly it largely depends on companies interest in self-promoting at a given time. Some racing games (Ferrari Virtual Race, BMW M3 Challenge, etc) were created because car companies ordered them. Some are joint effort - "NFS: Porsche Unleashed" and "Mercedes-Benz World Racing" come to mind. Ford had some too iirc.
3. Thirdly some might be not available at all. Some car companies have exclusive contracts and their cars could be used only in certain games for amount of time, iirc Porsche had such a deal with EA - hence no Porsches in GranTurismo 2 and other games of that era.
4. Companies might be VERY picky about how their cars are displayed and perform in the game in game and if they do not like it - no deal. Iirc in NFS6 FerrariF50 was one of the cars that was undamageable, cos Ferrari refused to see their cars damaged.
5. From 3rd hands I heard Lamborghini asked for 400\`000$ for a limited range of their cars to be used in a German racing game in 2004 - deal was not made.

In the end, the answer is - it depends. You need to get in contact with car company and make a deal. Only then you know who pays whom and how much.

P.S. Sorry, no proof links here. Speaking from my own limited knowledge.

---
Tags: game-design, licensing, vehicle
---


title: Quaternion Lerp never reaches target

text:
# Question
Title: Quaternion Lerp never reaches target
I seem to have misunderstood something about how LERP works. Im not sure what is missing. The object is rotating as it should, but it cant seem to get it to end. The transform.rotation dont seem to reach its target even if it has done so visually.

```
Quaternion rotationTarget;
    Vector3 travelTarget;
    float rotationLerpProgress;
    float rotationLerpDuration = 1f;

    // Use this for initialization
    void Start ()
    {

    }

    // Update is called once per frame
    void Update ()
    {
            if (Input.GetMouseButtonDown (0)) {
                    var ray = Camera.main.ScreenPointToRay (Input.mousePosition);
                    RaycastHit rayHit;
                    if (Physics.Raycast (ray, out rayHit)) {
                            var rayHitPoint = rayHit.point;
                            travelTarget = rayHitPoint;
                            var rotationDirection = rayHitPoint - transform.position;
                            rotationDirection.y = 0;

                            rotationTarget = Quaternion.LookRotation (rotationDirection);
                            rotationLerpProgress = Time.deltaTime;
                    }
            }
            if (transform.rotation != rotationTarget) {

                    if (rotationLerpProgress < rotationLerpDuration) {

                            transform.rotation = Quaternion.Lerp (transform.rotation, rotationTarget, rotationLerpProgress / rotationLerpDuration);
                            rotationLerpProgress += Time.deltaTime;
                            print (string.Format ("({2}) - progress: {0} - duration: {1}  ", rotationLerpProgress, rotationLerpDuration, rotationLerpProgress / rotationLerpDuration));
                    } else {

                            print (string.Format ("setting rotation ({0}) to target ({1})", transform.rotation, rotationTarget));
                            transform.rotation = rotationTarget;
                    }
            } else {
                    print ("rotaton is at target! :)");
                    if (transform.position != travelTarget) {
                            rigidbody.AddForce (Vector3.forward);
                    }
            }

    }

```

# Answer
Lerp really never reaches the "end". As it gets closer and closer the values add more decimals. So if you are lerping from 0-1 you may reach 0.999999 but never actually reach "1". You can get around this by rounding up near the end or using a larger value for the percentage of the lerp.
> 1 votes

# Answer
Actually as stated here: http://docs.unity3d.com/Documentation/ScriptReference/Input.GetMouseButtonDown.html

Input.GetMouseButtonDown(0) is reset each frame and will not return true until the user has released the mouse button and pressed it again.

The update will immediately run when Start runs. Try using a bool to trigger it (something like this):

using UnityEngine; using System.Collections;

```
public class NewMonoBehaviour : MonoBehaviour
{

    Quaternion rotationTarget;
    Vector3 travelTarget;
    float rotationLerpProgress;
    float rotationLerpDuration = 1f;
    float rotationLerpCurrent;
    bool inTransition;

    // Use this for initialization
    void Start()
    {
        rotationLerpCurrent = 0;
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            inTransition = true;
            var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit rayHit;
            if (Physics.Raycast(ray, out rayHit))
            {
                var rayHitPoint = rayHit.point;
                travelTarget = rayHitPoint;
                Debug.Log("rh: " + rayHitPoint);
                var rotationDirection = rayHitPoint - transform.position;
                rotationDirection.y = 0;

                rotationTarget = Quaternion.LookRotation(rotationDirection);
                rotationLerpProgress = Time.deltaTime;
            }
        }

        Debug.Log("tr: " + transform.rotation + " rt: " + rotationTarget);
        Debug.Log("ea tr: " + transform.rotation.eulerAngles + " rt: " + rotationTarget.eulerAngles);

        if (inTransition)
        {

            if (transform.rotation != rotationTarget)
            {

                if (rotationLerpProgress < rotationLerpDuration)
                {

                    transform.rotation = Quaternion.Lerp(transform.rotation, rotationTarget, rotationLerpProgress / rotationLerpDuration);
                    rotationLerpProgress += Time.deltaTime;
                    print(string.Format("({2}) - progress: {0} - duration: {1}  ", rotationLerpProgress, rotationLerpDuration, rotationLerpProgress / rotationLerpDuration));
                }
                else
                {

                    print(string.Format("setting rotation ({0}) to target ({1})", transform.rotation, rotationTarget));
                    transform.rotation = rotationTarget;
                }
            }
            else
            {
                print("rotaton is at target! :)");
                if (transform.position != travelTarget)
                {
                    rigidbody.AddForce(Vector3.forward);
                    inTransition = false;
                }

            }

        }
    }
}

```
> 1 votes

# Answer
To add to Trevor's answer, directly using the time delta as the lerp amount doesn't quite work.

You need to use:

```
Quaternion qResult = Quaternion.Lerp(
    qCurrent, qTarget, (float)(1 - Math.Exp(-k * t)));
// k = excitation constant (lower k (~1-2) for sluggish movement, higher k (~10)
//     for move snappish behavior)
// t = time delta

```

This will give you a more reliable and consistent movement based on time step.

This is taken from some C#/XNA code but the implementation is the same.
> 1 votes

# Answer
I assume that the problem is that you're holding down mouse button 0, which causes the interpolation to re-start every frame, according to the line:

> rotationLerpProgress = Time.deltaTime;

Which means that `if (rotationLerpProgress < rotationLerpDuration)` will always evaluate to false, since `rotationLerpProgress` is being reset to `Time.deltaTime` every frame.

Since the above conditional never evaluates to false, you never hit the `transform.rotation = rotationTarget;` line in its "else" block, which would be the correct way for this movement to complete.

Additionally, you never reach your target through repeated Quaternion.Lerp calls (you're using `rotationLerpProgress / rotationLerpDuration` == `Time.deltaTime / 1.0f` == `0.0016` every frame, assuming 60 fps). Doing this, each frame the orientation will move 1.6% of the way from where it currently is toward its target orientation -- forever approaching the desired orientation, but never actually reaching it.

The correct solve for this problem is to not reset the `rotationLerpProgress` variable every frame, but only when a new turn operation is commenced.

(For most games, the ideal behaviour would be to not use an interpolation here at all -- to rotate the object at a specific rate, not over a specific duration. So that a short turn would take a shorter time than a longer turn. But I assume that you're using a constant duration regardless of turn-distance for a reason which makes sense for your game.)
> 0 votes

# Answer
It can take slightly more time to complete because you use new rotation as a starting parameter for lerp. So when it visually completes rotation, it waits before "progress" reaches "duration".

If you want complete accuracy, you need to store an original rotation on click:

```
if (Input.GetMouseButtonDown(0)) {
    //.....
    originalRotation = transform.rotation;
}

```

and then use lerp like this:

```
transform.rotation = Quaternion.Lerp(originalRotation, rotationTarget, rotationLerpProgress / rotationLerpDuration);

```

Also rigidbody.AddForce makes object move in world space. Use relative instead:

```
rigidbody.AddRelativeForce(Vector3.forward);

```
> 0 votes

# Answer
This is how i made it work.

```
        if (Input.GetMouseButtonDown (0)) {
                    target = Camera.main.ScreenToWorldPoint (Input.mousePosition);
                    rotateToTarget = true;
                    print ("NEW TARGET: " + target);
            }

            if (rotateToTarget == true && target != null) {
                    print ("Rotating towards target");
                    float step = rotationSpeed * Time.deltaTime;

                    targetRotation = Quaternion.LookRotation (transform.position - target.normalized, Vector3.forward);
                    targetRotation.x = 0.0f;//Set to zero because we only care about z axis
                    targetRotation.y = 0.0f;

                    player.transform.rotation = Quaternion.Slerp (transform.rotation, targetRotation, Time.deltaTime * rotationSpeed);

                    if (Mathf.Abs (player.transform.rotation.eulerAngles.z - targetRotation.eulerAngles.z) < 1) {

                            rotateToTarget = false;
                            travelToTarget = true;
                            player.transform.rotation = targetRotation;
                            print ("ROTATION IS DONE!");
                    }
            }

```
> 0 votes

---
Tags: unity, quaternion, lerp
---


# Question
Title: What kind of calculations do I have to make for projectiles?
I could never find out, how to create projectiles in a 2D game. Does it need linear algebra? If not, what to do to calculate its path?

I just simply want to create a projectile that follows a straight line, for every possible angles (0-359) in general. Later I want to create parabole or circular trajectories if I can.

# Answer
> 3 votes
Calculating the trajectory of a projectile can be done in two ways: analytically and numerically.

Analytical calculation is where you integrate position with respect to time and get equations such as `x = x_0 + vt + ½at^2`. You can use these equations to solve for time of impact, distance traveled, maximum height, etc. or just find the displacement at any given time.

Numerical calculation is much better suited for games. Your standard simple little physics simulation using Euler is an example of a numerical integrator:

```
a.y = -9.81;
v += a * dt;
x += v * dt;

```

Normally, this combined with a collision detection system is all a game would need to simulate a projectile. It works well because arbitrary input can be provided and the system will automatically correct itself without having to change the math like an analytical solution would.

---

To "launch" a projectile at a certain direction and speed, you can calculate the velocity like this (assuming direction is in radians):

```
v.x = cos(direction) * speed;
v.y = sin(direction) * speed;

```

# Answer
> 1 votes
A direction vector and speed is all you need to begin with.

---
Tags: 2d, projectile-physics
---


# Question
Title: Forcing one projectile to follow close behind an initial projectile
I'm shooting out a projectile and I want another projectile to closely follow it. I can't simply shoot out the second projectile at a slightly lesser time because the first projectile may change trajectory.

All I want is the second projectile to be closely following behind the first projectile.

My first idea was to plot the points every frame to follow the first projectile. However, as the speed of the first projectile increases, the following projectile lags behind.

# Answer
> 3 votes
If the first projectile has a position and a velocity vector, then you can set the 2nd one's position like this:

bullet2\_position = bullet1\_position - (normalized\_bullet1\_velocity * trailing\_distance);

You can still apply all the physics you want to the 1st projectile, you just don't need to repeat it all for the 2nd.

# Answer
> 1 votes
What you are looking for is a sort of velocity match between the two objects. You can obtain it by checking the target (first projectile) velocity and modifying the second one according to this.

The pseudo code is something like:

variables: `target_velocity`, `this_velocity`, `time_to_match` and `max_acceleration`. First and second values are the current velocities of projectiles and other twos are used to tweak the behavior of the chase. Of course you should use vectors (but I suppose you do, since it's the only way to manage these things).

Then at every update:

```
 result_acceleration = target_velocity - this_velocity;
 result_acceleration /= time_to_match;
 if (result_acceleration.magnitude() > max_acceleration)
 {
   result_acceleration.normalize();
   result_acceleration *= max_acceleration;
 }

```

Then the `result_acceleration` value is applied as usually within a physics engine to current `this_velocity` of following projectile. In your case the `time_to_match` variable should be enough small to keep the two objects tights (eg. 0.05-0.1).

# Answer
> 1 votes
Your first idea was good. All you have to do, is take into account the distance between the points the first bullet traveled on each frame, and make sure the second one travels the same distance each frame, meaning that it might "skip" some of the points plotted by the first projectile, or plot some points of its own to match the speed of the first projectile.

# Answer
> 0 votes
```
positions = [leader.position]
each frame:
     leader.update()
     positions.append(leader.position)

     # Loop backwards through the logged positions to find the one
     # the desired distance away.
     d = 0
     i = len(positions) - 1
     while i > 0 and d < follow_distance:
         d += distance(positions[i - 1], positions[i])
         i -= 1

     # Make sure we have enough total distance to start following.
     if d >= follow_distance:
         # In the loop we probably overshot backwards, interpolate
         # forward to the right position.
         p = (d - follow_distance) / distance(positions[i], positions[i + 1])
         follower.position = positions[i] * (1 - p) + positions[i + 1] * p

         # Clear out unneeded positions.
         del(positions[0:i])

```

A trivial optimization would be using a deque instead of a list (I don't know if Flash has deques).

The second projectile is going to act really weird though. Like, if it's following a parabola, it's going to slow and come to a stop in mid-air, then continue upwards very slowly, then fall very fast. Is that really what you want?

# Answer
> 0 votes
If you are sure you don't want to just spawn another close behind and follow normal physics, then save the first projectile's previous position with the desired delay and use that value.

---
Tags: mathematics, physics, projectile-physics
---


# Question
Title: SetFloat() in HLSL shader (effect) has no effect - variables stay at 0
I have a problem wherein I'm trying to set two simple float variables in my shader. I have a dozen other shaders in this project where it works fine, but for some reason, I've got a bug in this one that I just can't spot.

Here's what I'm doing; I'll edit it down for brevity but try to stay complete. Any suggestions are very welcome!

First, I store the video width and height in the class that represents my shader, and then call functions that set the variables.

```
    _hVideoWidth           = _ptrEffect->GetParameterByName(0, "videoWidth");
    _hVideoHeight          = _ptrEffect->GetParameterByName(0, "videoHeight");

    pShader->_videoWidth  = pCameraManager->_backBufferWidth;
    pShader->_videoHeight = pCameraManager->_backBufferHeight;
    pShader->SetActive();

    _ptrEffect->SetFloat(_hVideoWidth,  _videoWidth);
    _ptrEffect->SetFloat(_hVideoHeight, _videoHeight);

```

Then I do my drawing:

```
    UINT cPasses;
    pShader->GetEffect()->Begin(&cPasses, 0);
              // Drawing code here
    pShader->GetEffect()->End();

```

My shader will use the videoHeight/Width in order to scale it to the viewport. If I hardcode the width and height, it all works perfectly.

```
cbuffer VideoData : register(b0)
{
    float    videoWidth;
    float    videoHeight;
}

VertexShaderOutput UILineVertexShaderFunction(VertexShaderInput input)
{
        VertexShaderOutput output;

    output.Position = input.Position;

    // Convert pixel coords to (-1, +1)

    output.Position.x = output.Position.x / videoWidth  * 2.0f - 1.0f;
    output.Position.y = output.Position.y / videoHeight * 2.0f - 1.0f;
    output.Color    = input.Color;

    return output;
}

```

The mystery, however, is that at this point the shader has videoWidth and videoHeight still as zero. If I just hardcode those two expressions to 1280 and 1024 respectively, it works perfectly.

So, there's SOMETHING about the way I'm setting the videoWidth and videoHeight. I've confirmed that at the point I call SetFloat() they are in fact passing in the right values, but they just never seem to make it to the shader variables.

Any suggestions or anything obvious? Even a guess would help, I've been looking at this one for a while!

Thanks, Dave

# Answer
> 1 votes
Besides calling `Begin()` and `End()` around the draw calls, you have to also call `BeginPass()` and `EndPass()` for the effect system to set up all the shader parameters and state.

---
Tags: 3d, shaders, hlsl, directx9
---


# Question
Title: Should I use threads to check sockets for multiplayer game?
In a multiplayer game does the code to get/send info from/to sockets reside in the game loop or does it belong in its own thread?

# Answer
Most programming languages or network libraries have APIs for asynchronous IO operations where read- and send operations return immediately. Read-operation return only the data which was buffered since the last call and send-operations are executed in background. When you have such an API available, there is usually no reason to add another layer of threading on top of it (these APIs usually use threading behind your back anyway).

But when you don't have any non-blocking APIs available or those which are available are insufficient for some reason, you should definitely write your own asynchronous networking code which uses a separate thread for each network connection.
> 1 votes

# Answer
It is typically in another thread, with some form of lock-free queue passing messages between the network thread and the main thread's game logic. This is almost required in some OSes which have inefficient networking stacks or other limitations making a separate thread required to handle more than a few sockets efficiently, particularly older versions of Windows (which still isn't stellar in this domain). Linux and some BSDs can be made quite efficient without threads, but it can still be advantageous to use threads in games for networking (especially if your network tic rate does not match your frame rate, which usually it won't).
> 0 votes

---
Tags: networking, multiplayer, socket
---


title: Create texture the size of my mesh

text:
# Question
Title: Create texture the size of my mesh
I programmatically create a Mesh and want to generate a texture that patches coloured squares together so that the patchwork perfectly matches the vertices.
The mesh's dimensions are expressed in floats, the texture dimensions are expressed in pixels.

```
myMeshFilter.mesh = BuildMesh();
// todo: how to find out the values instead of ??
myMeshRenderer.sharedMaterials[0].mainTexture = BuildTexture(??, ??);

private Texture BuildTexture(int width, int height){
    var texture = new Texture2D(width, height);
    var pixels = textures[TileType.Grass.Value]; //array of 64*64 pixels
    var tileWidth = width/NumberOfColumns;
    var tileHeight = height/NumberOfRows;

    //todo: do this for all the tiles instead of only the first;
    texture.SetPixels(0,0, tileWidth , tileHeight, pixels);
}

```

In the editor, you can set the pixel-to-unit ratio, but not sure how to set this on generated textures.

My current implementation assumed that setting and using my source texture's pixel to unit ratio in my calculations would do the trick, but I noticed that it doesn't and I Googled far and wide and have mostly become more confused with every hit.

I think I need the camera to translate my mesh's corner values to pixels, but not sure and wouldn't know how.

**UPDATE**
Pointing the UV's of the mesh to the correct points in the texture would be a solution (and probably a rather performant one), but would restrict me in my possibilities if I want the tiles to have visual-only 'overflows'.
eg: grass tile next to dirt tile would have a bit of grass over the dirt.

# Answer
> 1 votes
What you need to do is programmatically unwrap the UV map of the mesh to fit your texture, or, if you want to generate the texture as well, then use the UV vector array to create the texture. You do this by creating a Vector2 array and set the UV vectors respectively to it's vertices. Check this link for an example.

After setting up the UV map it's really just filling in the polygons given by the 2d vertices with the given texture or color.

---
Tags: unity
---