# Question
Title: Unity rigidbody2d.velocity jumping causes weird bouncing
Im working on a game 2d game that has some platforming. I followed this video as guidance and produced the following code:

```
public class PlayerControler : MonoBehaviour

    public float maxWalkingSpeed = 10.0f;
    public float jumpForce = 5.0f;
    public float jumpInputSensitivityThreshold = 0.3f;
    public float verticalAirControl = 0.5f;
    public float horizontalAirControl = 2.0f;
    public Transform groundCheck;
    public float groundCheckRadius;
    public LayerMask whatIsGround;
    private bool facingRight = false;
    private bool isControlable = true;
    private bool canMove = true;
    private bool isGrounded = false;
    private Animator playerAnimator;

    // Use this for initialization
    void Start ()
    {
            playerAnimator = GetComponent<Animator> ();
    }

    // Update is called once per physics calculation
    void FixedUpdate ()
    {
            CheckIfGrounded ();
            CheckInput ();
            CheckHorizontalMovement ();
            CheckVerticalMovement ();
    }

    private void CheckInput ()
    {

            bool isBlockHeld = Input.GetButtonDown ("Block");
            bool isBlockReleased = Input.GetButtonUp("Block");
            bool isPerformingAttack1 = Input.GetButtonDown ("Attack1");
            bool isPerformingAttack2 = Input.GetButtonDown ("Attack2");
            float horizontalInput = Input.GetAxis ("Horizontal");
            float verticalInput = Input.GetAxis ("Vertical");

            if (isControlable) {
                    CheckFacing (horizontalInput);

                    if (isBlockHeld) {
                            if (verticalInput < 0) {
                                    playerAnimator.SetTrigger ("LowBlockPushed");
                            } else {
                                    playerAnimator.SetTrigger ("HighBlockPushed");
                            }
                    }

                    if(isBlockReleased)
                    {
                        playerAnimator.SetTrigger ("BlockReleased");
                    }

                    if(isPerformingAttack1)
                    {
                        playerAnimator.SetTrigger ("Attack1");
                    }

                if(isPerformingAttack2)
        {
            playerAnimator.SetTrigger ("Attack2");
        }

                    if (isGrounded && canMove && horizontalInput != 0) {

                            Walk (horizontalInput);
                    }

                    if (isGrounded && canMove && verticalInput > jumpInputSensitivityThreshold) {
                            Jump (verticalInput);
                    }

                    if (!isGrounded && canMove) {
                            AirControl (horizontalInput, verticalInput);
                    }
            }

    }

    private void CheckFacing (float horizontalInput)
    {
            if (horizontalInput > 0 && !facingRight) {
                    Flip ();
            } else
        if (horizontalInput < 0 && facingRight) {
                    Flip ();
            }
    }

    private void CheckIfGrounded ()
    {
            isGrounded = Physics2D.OverlapCircle (groundCheck.position, groundCheckRadius, whatIsGround);
            playerAnimator.SetBool ("isGrounded", isGrounded);
    }

    private void CheckHorizontalMovement ()
    {
            playerAnimator.SetFloat ("HorizontalVelocity", Mathf.Abs (rigidbody2D.velocity.x));
    }

    private void CheckVerticalMovement ()
    {
            playerAnimator.SetFloat ("VerticalVelocity", rigidbody2D.velocity.y);
    }

    private void AirControl (float horizontalInput, float verticalInput)
    {
            rigidbody2D.velocity = new Vector2 (rigidbody2D.velocity.x + horizontalInput * horizontalAirControl, rigidbody2D.velocity.y + verticalInput * verticalAirControl);
    }

    private void Jump (float verticalInput)
    {
            rigidbody2D.velocity = new Vector2 (rigidbody2D.velocity.x, verticalInput * jumpForce);
    }

    private void Walk (float input)
    {
            rigidbody2D.velocity = new Vector2 (input * maxWalkingSpeed, rigidbody2D.velocity.y);
    }

    private void Flip ()
    {
            facingRight = !facingRight;

            Vector3 newScale = transform.localScale;
            newScale.x *= -1;
            transform.localScale = newScale;
    }

    public void setPlayerNotControllable ()
    {
            isControlable = false;
    }

    public void setPlayerControllable ()
    {
            isControlable = true;
    }

    public void setPlayerCanMove ()
    {
            canMove = true;
    }

    public void setPlayerCanNotMove ()
    {
            canMove = false;
    }

```

In the editor I set the jumpForce to 50 and the characters rigidbody properties gravity scale to 10 and mass to 80 for a snappy jump.

The walking and jumping seems okay enough, with one issue. The first jump made by the character is good, of proper height. But if I keep the jump button pressed or hit it immediately after the character falls to the ground after previous jump, it jumps way too high, basically shoots upward like a rocket. If I let it land and wait a bit and then jump again, the jump is properly high. Any ideas what might be causing this? How can I fix this?

If any further information is needed, please leave me a comment.

# Answer
> 1 votes
Do not put input-updating in `FixedUpdate`. Probably it's not a full answer, but at least partly your incorrect jumping is because of this:

> Note also that the Input flags are not reset until "Update()", so its suggested you make all the Input Calls in the Update Loop.

# Answer
> 2 votes
Generally with jumping I use Rigidbody2D.AddForce() rather than making changes the velocity. You may find this is a far less painful way of doing jumping and it will still use your Rigidbody (it's also more natural, when you jump you apply force upwards, you don't change your velocity directly).

Try swapping out the line for:

```
rigidbody2D.AddForce(Vector2.up * 50);

```

You will have to fiddle around with your multiplier to get it right, as I remember it tends to be quite a big number.

# Answer
> 0 votes
I found what was wrong, maybe it will help future visitors.

This line of code caused problems:

```
rigidbody2D.velocity = new Vector2 (rigidbody2D.velocity.x, verticalInput * jumpForce);

```

While this one did not:

```
rigidbody2D.velocity = new Vector2 (rigidbody2D.velocity.x, jumpForce);

```

The problem was in the input sensitivity for my controls. Sensitivy on an axis is the speed with which the values returned by the `Input` reach the actual value the player inputs. I had sensitivity set to 3. So when I jumped for the first time, the input didnt reach the intended level of 1. Instead, it was around 0.18 or 0.2. By the time the character fell to the ground, if i hadn't release the button, the input value would be at 1, and the second jump would be higher.

Of course I found it only once I fixed my isGrounded problem, because in combination those two made the player jump sky-high or even jet-pack.

---
Tags: unity, physics, control
---


title: Issue with fps limiting in XNA

text:
# Question
Title: Issue with fps limiting in XNA
The game I am making runs at 60 fps, but occasionally it will drop lower than that. I want to limit the frame-rate to 30 fps so that those drops will be less noticeable.

I don't understand everything about this, so bear with me. Here is what I have in the Initialize method:

```
IsFixedTimeStep = true;
TargetElapsedTime = TimeSpan.FromSeconds(1 / 30.0f);

```

All this is doing is making the game run in slow-motion. What am I doing wrong?

Edit: I would like Update to be called the same number of times per second, but for Draw to be called only 30 times per second, instead of 60. How could this be accomplished?

# Answer
> 1 votes
**AFTER READING EDIT:** You cannot change how fast the game will do it's draw calls. What happens is that on a fixed timestep your game will attempt to do one update and one draw call at a steady rate (usually 60fps). If it cannot keep that up for whatever reason then it will lag.

On a non-fixed timestep your game will run as fast as it possibly can and you would NEED to take into account the GameTime in order to have a stable game.

If you are experiencing frame stutter then you probably need to take some time and figure out where the bottleneck is. Make sure you aren't looping unnecessarily and that you aren't drawing things that are off the screen and don't need to be drawn.

**It sounds like you weren't considering the fps when doing movement calculations.**

What you are doing is indeed slowing down the frame rate. The consequence of doing so is that now your game will have half as many updates, and most likely you are not taking the frame rate into account when considering movement, so this means everything moves at half speed.

For example if you were moving a sprite around like the following:

```
int Speed = 2;
int XPos;
public void Update(GameTime GT)
{
     XPos += Speed;
}

```

Then every time your game updates it will add a value of 2 to the `XPos` variable. Now since you used to be at 60 frames-per-second this meant that your `XPos` variable was being increased by 120 every second (2 * 60fps). But now, Since you changed the frames-per-second to 30, instead of XPos adding 120 to it's value every second it is now adding 60 (2 * 30fps). The result is that everything is moving at half the speed it was moving when you were at 60fps.

The solution to this can be very simple if you keep good coding practices. XNA provides your game with a `GameTime` variable. Inside this variable are two very useful values, `ElapsedGameTime` and `TotalGameTime`. ElapsedGameTime gives you the amount of time that has passed since your game last updated (your frame time). TotalGameTime gives you the amount of time that has passed since your game started.

Using ElapsedGameTime you can make your game run **independent of the framerate**. Borrowing from the earlier example:

```
int Speed = 120;
int XPos;
public void Update(GameTime GT)
{
     XPos += Speed * GT.ElapsedGameTime.TotalSeconds;
}

```

There are two important modifications I made to the example. The first is that the Speed value is no longer 2. When using the frame rate as a part of your calculations you need to think of **movement values as how far the object should move per second**. Since in the previous example we were moving 120 units every second (2 * 60fps), to get the same movement the Speed value had to be changed to 120 to match it.

The reason the Speed value was changed to 120 is because of the second modification.

```
XPos += Speed * GT.ElapsedGameTime.TotalSeconds;
//If TotalSeconds = 0.5 then Speed = 60.
//If TotalSeconds = 0.25 then Speed = 30.
//If TotalSeconds = 1 then Speed = 120.

```

By multiplying the Speed variable by how many seconds have passed since the last update you end up moving the XPos at a consistent rate across varying frame rates.

**TL;DR** \- Change your movement variables to take into account the ElapsedGameTime so they run at a steady rate.

NOTE: When using a FixedTimeStep you often do not have to take into account the elapsed time as it is usually steady, but it's still a good idea.

---
Tags: xna, c#, frame-rate
---


title: Programming Dynamic 3D Water/Waves?

text:
# Question
Title: Programming Dynamic 3D Water/Waves?
I'm a little bit stuck on how I might go about programming dynamic, interesting water in a game. To qualify that a little bit, I'm interested in creating water with broad, rolling waves that affect collision, physics, and the visual shape of the mesh. As an example, here's a screenshot from Wave Race 64, a 1996 jetski racing game for the Nintendo 64!

In Wave Race, not only do the waves move visually, but the choppy water pushes your vehicle around and creates bumps that give the game a really fun and unique feeling. I imagine that this type of thing is pretty standard in water simulation and physics, but I think the 'arcadiness' of the water physics in Wave Race makes it a pretty decent example.

I'm not really sure what steps need to be taken to create this effect though. I imagine that the visual effect of waves would be pretty simple to do create using a vertex shader, but I'm uncertain on how to program the physical 'entity' of the water. Here are some of my exact sticking points:

* **What might the data structure of that water look like?**
* **And how does one 'animate' the physics/collision while keeping the visual mesh deformation in sync?**

I have some "starting point" ideas, like possibly using a 2D or 3D vector field for the water. But I'm still fuzzy on the general implementation of fluid simulations, especially as a gameplay element!

# Answer
My recommendation would be to approximate the surface with 2d wave simulation. That is, you have a plane and each point has a height property defined by the neighboring points and the wave equation. A google search for 2d wave dynamics algorithm gives a lot of papers and applets, so you can go crazy on that.

Getting that information to a 3d model is as simple as moving the vertices of a planar mesh up and down.

Getting the whole thing to influence physical objects will be trickier. I would experiment with applying forces the rigid bodies based on a specific point (center of mass, pivot etc) relative to the water. This point, projected on the water, will be inside 3 points of the water simulation (defining a plane), so we check if it's below or above water level and, if below, apply buoyancy force normal to the plane defined by the three points. You would also need to concern about "aerodynamics", that is how the direction and speed of the moving vehicle influence the dynamics by creating additional forces.

Having said all that, finding the proper algorithm for fluid dynamics is critical. Depending on the size of the world you might need faster implementations, or a way to break calculation into zones etc.
> 2 votes

---
Tags: physics, graphics, procedural-generation, simulations, water
---


# Question
Title: Unity2D Best way to determine degrees between two colliding entities?
I'm trying to determine the collision-direction between two objects. I'll be using this for various things such as creating blood-entities in a specific direction proportional to where the other entity is hitting an entity. What's the best/most efficient way to do this? I've been doing this but it seems unstable/not to be working.

Assuming both entities are center-pivoted, I use trigonometry to find the angle like; atan(b/a). For some reason the output angle seems to be pretty random.

Here's the method I made:

```
protected void checkCollisionDirection(Collision2D target)
    {
        Vector3 positionDifference = target.gameObject.transform.position - gameObject.transform.position;
        int quadrant = 0;
        float x = positionDifference.x;
        float y = positionDifference.y;
        float degrees = Mathf.Atan (y / x) * Mathf.Rad2Deg;

        if (positionDifference.x > 0 && positionDifference.y > 0)
        {
            quadrant = 1;
        }
        else if (positionDifference.x < 0 && positionDifference.y > 0)
        {
            quadrant = 2;
            degrees += 180;
        }
        else if (positionDifference.x < 0 && positionDifference.y < 0)
        {
            quadrant = 3;
            degrees += 180;
        }
        else if (positionDifference.x > 0 && positionDifference.y < 0)
        {
            quadrant = 4;
            degrees += 360;
        }
        hitDirectionDegrees = degrees;
    }

```

I'm open to any suggestions that can find an angle between two entities.

# Answer
> 0 votes
You just need the angle of collision? How about:

```
Vector2 collisionAngleVectorToFirstEntity (secondEntityPosition.x - firstEntityPosition.x,
    secondEntityPosition.y - firstEntityPosition.y);

```

I'm not familiar with Unity but that Vector is pointing from the second point to the first point so running that on collision gives you a angle although in the form of a vector. You might need to run something like below to get a float with your degrees.

```
float degrees = collisionAngleVector.angle();
float degrees = Vector2.toDegrees(collisionAngleVector);

```

If there is no build in functionality to find a angle in degrees from a Vector2 then you have to calculate it yourself. Luckely Java has an atan2 function since normal tangents only go from -90 to 90 degrees and you have to find out yourself to which "wind direction" you have to add that number based on the position of x and y within the vector.

```
float degrees = Math.atan2(collisionV.y/collisionV.x);

```

# Answer
> 1 votes
Instead of using `Mathf.Atan(y / x)`, which can only return angles between \[-90..90\] degrees, then compensating for angles outside that range by adding 180 degrees, simply use `Mathf.Atan2(y, x)`.

Atan2 is specifically made for the task you are solving. From the Mathf.Atan2 docs:

> public static float Atan2(float y, float x);
> Returns the angle in radians whose `Tan` is `y/x`.
> Return value is the angle between the x-axis and a 2D vector starting at zero and terminating at (x,y).

The logic seems otherwise correct.

---
Tags: unity, 2d, collision-detection, collision-resolution, trigonometry
---


# Question
Title: Unity: Trying to add a simple light to a prefab
A bit of a unity beginner here. I have a windmill prefab and I would just like to add a simple point or directional light to my prefab. I added the component for a light to the prefab and started the game, but it seems like no matter what I try, the light would not appear. I tried to move the component to the top in the Inspector window (thinking another component would overwrite the light properties).

Any ideas? Or things Im doing wrong?

# Answer
For the purpose of this answer I will assume that your windmill is a 3D model, and that you meant spotlight rather than directional light.

There are numerous reasons as to why you might no see light being projected from your windmill prefab, I'll list what I can think of here (and edit with additions if I think of more).

* The light's range or intensity are too low to reach nearby meshes and create a visible effect.
* The light is disabled (will appear greyed-out in Hierarchy).
* The light's *render mode* is set to *not important*.
* The light's *culling mask* doesn't include the correct layers for projecting light onto the environment.
* The light's *culling mask* incorrectly includes the windmill's layer when it should be ignored.
* The light uses the prefab's position as a point of origin and this position is within the model; the light has a *shadow type* other than *no shadows*; your windmill prefab has mesh-faces that are turned inward towards the light's point of origin (think inner walls, etc); the model has *cast shadows* enabled; nearby meshes that you expect to receive the light have *receive shadows* enabled. The result being that the windmill model is blocking the light by casting shadows on anything that the light might reach. The interior of the windmill will be lit-up if this is the case.

Also note that lighting effects of this nature are visible in the game window without running the game, and component order should have no impact on your light.
> 4 votes

# Answer
Did you want a light shining *on* the windmill (from outside), or a light *emanating from* the windmill?

If you meant the first, then instead of putting a light component on the existing windmill's GameObject, you simply want to create a new GameObject, a bit outside the windmill, on which to place the light component.

(You can parent that new light GameObject to the windmill to make it part of the prefab if you like.)
> 0 votes

---
Tags: unity
---


title: Edit VBO data or create a new one?

text:
# Question
Title: Edit VBO data or create a new one?
I have a question: if I have a VBO, and I have to change all the data inside it (because of resizing, ...), would it be more efficient to delete the old one and create a new one (and reallocate the memory for it), or change the data inside it using glBufferSubData?

# Answer
> 2 votes
According to OpenGL Insights there are a couple ways to efficiently stream data to a VBO. A simple but efficient method is to "orphan" the buffer (allocating a new piece of VRAM in the process) and refill the entire thing. This allows the current frame to use the old data while you can upload the new data.

```
// orphan the buffer so that we can write new data without waiting for it to be unused
// as soon as it's finished being used it will automatically be freed so we don't care about it anymore
glBufferData(GL_ARRAY_BUFFER, size, NULL, GL_STREAM_DRAW);

// fill the newly-allocated buffer with our new data
glBufferData(GL_ARRAY_BUFFER, size, data, GL_STREAM_DRAW);

```

A more performant, but complex, solution is to disable synchronization. This will give you the most control over how and when you upload the data (and also let you do partial uploads), but it makes it possible to accidentally change a buffer that's being drawn from, causing graphical glitches.

The solution to this is to have several buffers (3 is a good number) that you switch between in a round-robin fashion, ensuring that you can instantly kick off a DMA (upload) without messing with a buffer that is being accessed. It's kind of like double buffering to prevent sending a scene to the monitor before it's completely built up. The article I linked goes more into depth with this technique.

---

Apologies for the C syntax, I don't use LWJGL but from what I've seen it's pretty much directly transferrable.

---
Tags: opengl, lwjgl, vbo
---


# Question
Title: Are sockets required when developing a browser based MMOG?
I'm in the very early phases of developing a browser based MMOG, kinda like this game but not as cartoonish and with more features. I'm an experienced web developer, yet not once have I ever used websockets.

Are websockets required for something like this?

# Answer
> 4 votes
# ajax / html request

Slowpoke. Good for loading pages without navigating to another url. No good for action games but should be fine for turn based games I imagine. That is unless it's a very fast paced turn based game (think roguelike fast).

The good thing is that the server only needs to handle one request at a time. So the server code is *serial* and not concurrent. This means it's a lot less complicated. Each request is *often* processed in an infinitely short amount of time. I think the default limit is something like 15 seconds. The point being the server grabs a request, starts working on it and only it, and is done after a short while.

---

# socket

Fast and responsive, great for action games. The server needs to handle all clients simultaneously (concurrently) and ceaselessly. This means possibly more processing power and more memory. This means that you are running a process that *doesn't* stop supposedly ever (PHP isn't oft for such processes). You need a reasonably powered machine with serious bandwidth capability. This is considered more resource intensive.

The code is also far more complex and often requires threads or chunking up the work into small portions and supporting multiple user request in parallel. Both threads and chunking up the workload into small pieces make the code somewhat more complicated and harder to debug.

Please be aware that this means the devs need prior experience with either threads or what is basically an implementation of threads as a serial program. Also considering that most server CPU's nowadays have a bunch of cores, using threads is possibly preferred.

Side-note: Generally, an indie socket based game + server could cost could somewhere in the tens of thousands of dollars to develop. This is because of the graphics and client-side programming any game would require plus the added costs of developing a stable server.

# Answer
> 4 votes
Websockets are a very elegant and fast way to implement asynchronous communication between client and server. But they are far from the only. When low latency isn't that important for you, you can substitute it with XmlHttpRequest (aka "AJAX").

But for a real-time action-oriented game, WebSockets are usually the superior solution.

---
Tags: mmo, browser-based-games, websocket
---


title: XNA texture garbage collection

text:
# Question
Title: XNA texture garbage collection
I use a

```
 Dictionary<string, Texture2D>

```

for storing textures and every texture in the game is a reference to a texture from this dictionary. However when all references are gone, does the GC dispose of the textures (I don't think so as they are still accessible)?

And if it doesn't, how can I count the references to the textures so I can dispose of them manually?

# Answer
Because textures are unmanaged resources, you can not garbage collect them like most objects. Use a ContentManager for this task instead. Once you want to release the textures of a content manager, you should call Unload(); like this:

```
Texture2D apple = Content.Load<Texture2D>("apple"); //Content is the default Content manager
//...
//When you don't need them:
Content.Unload(); //removes every loaded texture which were loaded with this content manager.

```

So you could create multiple ContentManagers, for example one for the main menu, one for the game screen, and load the relevant resources with them.
> 2 votes

---
Tags: xna, c#, .net
---


title: Rendering mountains around a tile layer

text:
# Question
Title: Rendering mountains around a tile layer
When making a 2D Pokémon game, I just faked elevation by putting mountain tiles underneath the land. Now my tiles are 3D models, so I'm using layer properties to define their elevation. What I don't know though is how to generate a 'mountain' around them.

The tilemap is kinda' like this:

```
Layer 1: Layer 2: Layer 3:
....     \\\\     \\\\
....     \..\     \\.\
....     \..\     \\\\
....     \\\\     \\\\

```

Layer 2 has y-offset set to 1, and Layer 3 has y-offset set to 2. All they do right now is float in the air. What I'm trying to do is render a mountain around them.

# Answer
> 0 votes
You can create 3D ""tile"" objects.

During Loading read your 2D tile map and wherever there's a mountain tile paste your 3D mountain object over it.

You can make this very fancy and detect the size of mountainous areas pasting various large mountains objects.

---
Tags: tilemap, three.js, tiled
---


title: XML format for dialogs with choices

text:
# Question
Title: XML format for dialogs with choices
I'm trying to figure out a good way to implement dialogs (that is, talks, not UI's). My thoughts so far:

* I see a dialog as a tree of sentences (or better, a forest), so I think that XML is a good choice.
* There would be a XML file for each NPC. And more files for generic NPC's. Example: Peter.xml, Linda.xml, Citizen.xml, Soldier.xml, etc.
* These files would look like this:

```
<?xml version="1.0" encoding="UTF-8"?>
<dialog npcName="skeleton">
<ops>
 <q>Hi, how are you?</q>
 <a>Oh, thank you! It's been so long since I was last asked about that...</a>
 <a>Well, so and so. And you?</a>
 <ops>
  <q>Oh, I'm fine. But you look starving. I'll fetch some food for you.</q>
  <a questActivate="eggToSkeleton">Don't worry. In fact, I have no stomach,
        so the groceries would fall to the ground if I tried to eat. For example:
        if I ate an egg, it would break for sure.</a>
  <q>I was wandering how a skeleton can talk. And how can be 'so and so'.</q>
  <a>What? Haven't you ever heard about undead?</a>
  <q objectCondition="egg, inInventory" objectAction="egg, destroy"
           questComplete="eggToSkeleton">I have an egg just here. Let's try to
          see what happens.</q>
  <a>*The skeleton eats... well, it puts the egg into its mouth. When its
          bony fingers release the egg, it begins to roll down and finally
          crashes to the ground, leaving an orange splash among the green
          blades of grass.*</a>
  <a>Just as I told you. But... thanks.</a>
  <farewell mode="polite"/>
 <ops>
 <q>Begone, monster! You are an unnatural being!</q>
 <a>Yes, I know. But it is not my fault, and I can do nothing about that. I
      can't even commit suicide!</a>
 <farewell mode="rude"/>
</ops>
</dialog>
```

I have no experience with XML and I haven't found sample codes for this purpose. Am I on the right path?

# Answer
> 1 votes
Overall, yes.

The answer nodes should contain the sub-questions rather than the `<ops>` section.

The `objectAction` and `questActivate` should be sub-nodes of answers rather than attributes as one answer could have more than one action.

Conditions should also be sub-nodes of questions or answers as there could be multiple conditions and can become complex.

```
<q text="simple question">
  <a text="yes">
     <if object="egg" count="1"/> <!-- answer only avail. if egg==1 -->
     <action object="egg" add="-1"/>
     <action quest="the egg" add="-1"/>
     <action object="gold" add="500"/>
     <q text="Good job">
       <a text="Bye."/>
     </q>
  </a>
  <a>
     <text style="angry">NO! A VERY LONG <i>COMPLEX</i> TEXT</text>
     <q text="some other question">
        ....
     </q>
  </a>
</q>

```

Or something along those lines.

---
Tags: xml, dialogue-tree
---


# Question
Title: How do I add Different Screens to my C#/XNA Game?
I'm working on a Pong clone in XNA. Gameplay-wise, I have it where I want it to be. I want to add a title screen and some other screens to it like a menu, as well as a screen for the Winning/Losing results.

I've tried the Game State Management Example on the App Hub site, but It's very complicated and I haven't been able to make sense of it. Is there a simpler way?

I'm hoping for a solution that can be used in other projects too.

Plus I'd like to know how to actually create menu items (basically, how do I display the different options on it, and highlight them, etc).

# Answer
I'd recommend continuing to battle it out learning the sample. Once you groc how to implement it, you get all the nice things it does (screen fades, pause control, etc.) for nothing.
> 6 votes

# Answer
I would seriously consider sticking it out with the game state management example. It is a great framework for your first game. If you were designing one that can be re-used, with menu items etc. you'd probably end up with something similar.

The basic idea is to have a stack of screens (`GameScreen` is the base screen class, The `ScreenManager` is the 'stack' manager in the sample i think).

i.e. start with a title screen. Pressing a button pushes the main menu screen onto the stack.

While any screen is transitioning on, render it as such (menu items can use the transition amount to decided where to render, so they appear to slide on-screen).

Always direct input to only the top screen, even while transitioning on (so fast menu selectors can easily get into the game while the menus are transitioning on).

Once the top screen is fully transitioned, only render that screen.

So during gameplay you could end up with the following on the screen stack:

TitleScreen, MainMenuScreen, GamePlayScreen, PauseMenuScreen.

In that state, the pause menu gets rendered, and that's the screen the player controls. To 'exit' the screen, simply pop it off of the stack (or start it transitioning off), then it's the gameplay screen that gets input and is rendered.
> 4 votes

# Answer
maybe this method not the best, but for pong game could be enough, and is easy to understand.

Make a enum with your states:

```
 enum States { Menu, Playing, Pause, Lost, Win, Intro }

```

In your update method:

```
 void Update(gameTime time)
 {
     switch (State)
     {
        case States.Intro: UpdateIntro(gametime); break;
        case States.Menu: UpdateMenu(gametime); break;
        case States.Playing: UpdatePlaying(gametime); break;
        ....
     }
 }

```

In your draw method is the same but with DrawMethods.

I'd recommend that the State variable is a property this way:

```
 States State {
    get {return _state;}
    set {
      if (_state!=value) {
          OnStateChanged(_state, value);
          _state=value;
      }
    }
 }

 void OnStateChanged(States prev, States next)
 {
      if (prev == States.Menu && next == States.Playing)
      {
          ResetGame();
      }
 }

```
> 3 votes

# Answer
I'm using this example myself right now - I found it easiest to recreate the classes myself, then take chunks of code over a bit at a time to see exactly how each method / class communicates with the rest. Now I've got all the pieces in play and an understanding of what they're doing. It's really the best example of screen management out there.
> 2 votes

# Answer
Since it wasn't mentioned in the question (nor the answers) -- the original, and best Game State Management class can be downloaded and learned from here - http://xbox.create.msdn.com/en-US/education/catalog/sample/game\_state\_management

It's applicable in both XNA 4.0 and MonoGame 3.2, Enjoy.
> 1 votes

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


# Question
Title: Getting name fragments for a name generator
Back again to ask more about name generation -- this time about the dictionary of syllables which I apparently need to reliably generate a name. For reference, my last question.

I've written a little bit of code which, given a file, uses the first line to determine how long the name can be (with multiple options for variability), then builds one from the syllables given in the rest of it. It works decently enough, given example syllables in an example file. For those wanting to try out a set of syllables of their own, I've made a version on Ideone.com. `stdin` contains the list of lengths and syllables.

That's where I'm having an issue, though. What should I use for the syllables? I've looked around, but I've been unable to find a good list of names to draw from. Maybe it's just that I'm bad at this or something, but I can't really get a good list of syllables that make names. To add to that, I have to do it by hand, and I'd much rather make a program to split a list of names into syllables, but I can't get that to work. I'll post the source for my attempt once I'm home.

In short, how can I get a good list of syllables for use in a name generator? Is there pre-existing code I can use or modify and pass it a list of names to chop into syllables, then save those to a file? If not, how would I go about writing my own?

# Answer
> 2 votes
I suggest you base yourself on some syllable-based languages then add the missing syllables, such as "K\_" single consonants and so on.

For example:

Add arbitrary rules for names of creature races / game region. (eg: sand area names all end in ?i and start with m? and never have any p? or ?e, at most one single-consonant in a name) to give some ""consistency"" / familiarity to the player.

Then add a function to turn those syllables into the user's writing system (eg: English letter spellings). This is the part that will have to be localized for different languages.

Also, you might need to add a localized black-list to invalidate obscene words that will randomly come up and their close-enoughs syllables, and in multiple cultures across the world. although it could be hilarious without you could end up with your game pulled off the shelves if its not 18+. Make sure to check within names for matching obscene words even when surrounded by extra syllables.

You're opening a big can of cultural problems with random name generation. For example in your previous question one name was "Gozidi" with can sound awfully close to 'big member down there' in French with a tiny bit of stretch. That's an innocent enough example that will only cause some giggling but you can imagine some more offensive things accidentally coming out and people getting quite upset.

Drama you can do without when all you want to do is create a fun game. It's something to keep in mind.

---
Tags: procedural-generation
---


title: Game ladder using Apple Game Center

text:
# Question
Title: Game ladder using Apple Game Center
I'm implementing a turn based game where players can meet other players in matches via Apple Game Center. Each match has two players.

I want to make a global ranking of all players using Apple Game Center. This ranking serves two purposes:

* each player will know his/hers ranking.
* a player can be matched to another player with a similar skill.

My current thinking is something like this:

* A win gives +1 points
* A lose gives -1 points
* An aborted match, or not accepting a match gives -1 points.
* 0 is the minimum score.
* The leaderboard will present the score of each player.
* Players will be placed in groups according to their score. Each group can cover a range of scores, and players will be matched with players from the same group.

I have the following questions:

* Do you like my suggested scoring solution?
* Is it possible to accomplish an effective match making with this approach? I mean, some groups can have very few participants. Maybe only one. Of cause you can try to do a match making with a lower group, but that can also be empty, and it will take time. How shall I solve this?
* I've not released the game, and I don't know how many players it will have. Is it possible to make the grouping dynamic in some way? More players requires more groups.
* Is it possible to make players that does not accept matches to lose points? I only want to have active players in top of the ladder.

So far I've only found this input: https://stackoverflow.com/questions/9355799/can-i-make-a-ladder-systemlike-battle-net-with-using-just-game-center

# Answer
> 1 votes
I've made a scoring system almost exactly the same as you have with Game Center expect I use a more advanced rating algorithm (http://en.wikipedia.org/wiki/Elo\_rating\_system). I will answer your questions in order:

* Yes I think your idea sounds good.
* I've heard that apple automatically will pair people from different groups if there is no people in the same group. Nevertheless, you could define the groups by separating them with |. For example if you want players to match people with a score of +- 100 you could make something like GKMatchmakingObject.gruops = (int)player.score/100-1| (int)player.score/100 | (int)player.score/100+1
* Edit: NO, you will probably need an external server for tracking players online.

Yes there should be away to get an NSArray of all players in a specific leaderboard. That way you could for example use array.count and from that way increase the gap to +- 200 or +-300 if array.count is \< 100. \- Finally, yes. There is a delegate callback for when people decline which you could use for this purpose.

---
Tags: leaderboards, scoring
---


# Question
Title: Reasonable texture Formats for VertexTextureFetch in GL
Wich is a reasonable GL version that have support for vertex textures fetchs(VTF) in OpenGL ? (for example GL 3.0, 3.1, 3.3) What textures formats should I expect to be supported in average video cards when doing such vertex fetch.

Is that possible with GL ES 2?

# Answer
It is technically possible with OpenGL ES 2 but almost no device currently support it. You'll have to check GL\_MAX\_VERTEX\_TEXTURE\_IMAGE\_UNITS on devices.

For small "textures" you can use a small array of uniforms.

A lot of (old) desktop video cards still in use only supports GL\_LUMINANCE32F\_ARB and GL\_RGBA32F\_ARB or don't support any VTF at all.

If you are going to need large table lookups to generate vertices on OpenGLES I recommend doing it on the CPU directly using multiple vertex buffer objects:

* One for the static data.
* One for that data that needs to be updated by the CPU frequently.

This will minimize memory transfers.

With proper code CPUs on mobile are generally fast enough and in some cases faster than the GPU to process complex vertex shaders. Using the GPU is generally better because it runs in parallel while the CPU is doing other things but if the CPU is idle anyway then there's no loss and can gain by better balancing the CPU\<-\>GPU loads.

Some examples can be found on Apple's dev site (https://developer.apple.com/library/ios/documentation/3DDrawing/Conceptual/OpenGLES\_ProgrammingGuide/TechniquesforWorkingwithVertexData/TechniquesforWorkingwithVertexData.html) or just google.
> 1 votes

---
Tags: opengl, shaders, opengl-es2, vertex
---


# Question
Title: How can I mark levels as "complete" in a way that prevents cheating?
My first thoughts about marking levels complete is to just write the information to a file upon level completion and load that in once the app is opened up again. But how could I keep this safe from tampering and prevent cheating?

# Answer
Storing the completion information in a local file is a simple and perfectly acceptable method of doing so. Fundamentally, this is what every game will do to track progress (in some fashion, although the specific formats used for the data and the storage mechanism will differ).

Protecting the file from tampering is more difficult. If there's no compelling reason (no advantage to be gained by the player, no rewards, et cetera) you can usually get away with not caring.

But if you *do* care, and you and if you can reasonably expect that your platform is closed (consoles and non-jailbroken-iOS devices, for example) you also don't need to worry too much. The user will not normally be physically capable of accessing the file to tamper with it (provided you use the appropriate OS APIs to store the data in "private" locations and public ones (for example, storing this file in the user's iCloud Drive on iOS is probably not a great idea).

If you are absolutely concerned about tampering to the point where is *must not* happen (for example, where there is an advantage to be gained by a player who has more levels completed), you need to store the data server-side. Anything stored client-side can ultimately be compromised and shouldn't be trusted: it's the user's machine, in the user's hands. The control dynamic is just not in your favor.

It's not strictly impossible to hack files stored server-side, either, of course, but it's much more difficult if you've got a reasonable accounting system.
> 19 votes

# Answer
You can create a **replay file as proof of work** while the player is playing. Start the game, save the starting conditions including the name of the level and the pseudorandom seed, record the exact timestamped input states (mouse movements, key or button presses, etc.) that your game's input layer passes to its logic layer, and stop recording once the objective is achieved. You can compress an input log with run-length encoding (RLE) so that only changes in the button states (presses, releases, and the like) cause log events. From the initial conditions and input log, you can verify completion of the objective by replaying the inputs into the game's physics and AI.

Logs like this have several applications that are familiar to players of video games, especially emulated games. Players can rewatch a game locally from a log to look for strategy flaws or to brag to local friends. Your game's attract mode can consist of logs for selected levels. Netplay in games using the GGPO engine is structured similarly, with a delay of a few frames between the input and the game engine in order to allow time for the other player's input to arrive through the Internet. And you can require leaderboard participants to upload the log, and then your server will run it in fast-forward on a cut-down copy of the game with no graphics engine. To prevent a replay attack where one player uploads another's log, the information used to seed the game's pseudorandom number generator can include the player's leaderboard user ID. This way the server can compare them, and a manually edited file will desynchronize.

Some extremely dedicated players will manually construct an input log that constitutes a proof of work. This is called a "tool-assisted speedrun". If you don't want TAS on your public leaderboards, you can require plays at the highest competition tiers to be done while connected to the Internet. The server would send a key value every few seconds, and the client would send the input log in real time as if it were netplay, encrypted with that key. This key changes every few seconds, and in games using some sort of random element, it may reseed the pseudorandom number generator. If sustained lag between sending a key and receiving the corresponding input packets exceeds several seconds, we can assume that the user is trying something "funny".
> 9 votes

# Answer
If you want to do this totally in the client side and you don't consider the private storage provided by your platform to be secure enough (e.g. if there's actual money involved in completing levels), what you need is a proof of work. Your save file must contain an information that is designed such that creating the information is difficult to calculate unless you've completed the associated level, but easy to verify by a third party that does not necessarily have completed that particular level (preferably without having to know the solution itself). The larger the difference in the difficulty of calculating the proof of work before and after completing the level, the more secure the proof of work is.

Unfortunately though, this proof of work must be such that it's tied to the gameplay, so there is no generic way this can be done for arbitrary games, and your game executable must not contain the solution to the game in any way, or otherwise it's quite easy to extract the proof of work from the executable. In most cases, you almost always going to have to specifically design your gameplay around this particular requirement to make a proof of work to be cheat-proof, so you'll also lose some creative freedom.

For example, say a game of Sudoku, the proof of work could be the completed Sudoku board (note that the board must be generated by a trusted third party, because most Sudoku board generation algorithm need to precalculate the solution, this weakening the proof of work if it's done on the client). Or a game of factoring a large composite number, the proof of work is the prime factors (I'd call such a game RSA vs NSA).

To be truly secure though, your game has to contain some random elements, because if your game is totally deterministic, it's possible to cheat be copying the proof of work from someone else that have completed the level (this is a replay attack).

The goal of proof of work is to make cheating at least as difficult as creating a bot for the game. So, to cheat on a Sudoku game, you'll need to have a Sudoku solver, etc.

This is extremely hard. If it's a single player game, it's better keep your creative freedom and don't worry about cheating. It's their game, they've bought it and if they cheat, that doesn't affect your bottom line. Or turn it to a server based game, and do all your important game logic in the server.
> 3 votes

# Answer
If you prefer using an external file to hold save information and it is in a place that would be tamper-able by users you may want to read up on how encryption works and use that to prevent anyone from being able to make meaningful changes to the file. Something like a Feistel Cipher should be a good starting point and would be sufficient to stop someone without alot of time and know-how from changing a save file. http://en.wikipedia.org/wiki/Feistel\_cipher

Aside from that Josh has hit the nail on the head when it comes to client and server side storage.
> 1 votes

# Answer
If someone is able to pick through the binary and find out the algorithm - you'll never really be able to prevent that, so don't bother.

To stop simply use a cryptographic hash!

Suppose you have this:

```
function computeHash(levels) {
    code = "";
    for(level in levels) {
       code = hash(code+level+level.isComplete()+"MAGICSALT")
    }
}

```

It's really simple but it means you need to write a code at the end of the file, you then parse that file as usual, and do `computeHash(levelListReadFromFile);`

IF that hash = code read in the file then it is VERY PROBABLY "legit". By this I mean ... someone with a hex editor wont crack it, it'll take someone who knows their stuff.

Always favour local storage BTW - unless it's an MMO obviously, people don't want you using their data, go on trains, and do all kinds of stuff. I hate programs that require internet access for no good reason.
> 0 votes

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


# Question
Title: Array Rectangle Collision Handling Inconsistency XNA 4.0
I made a simple collision detection prototype.Here's the code for the Player class's collision handler:

```
public void handleCollision(GameObject OtherObject)
    {
        if(this.CollidesWith(OtherObject))
        {
            if(OtherObject is Stage)
            {
                float rightEdgeDistance = OtherObject.BoundRect.X - (Position.X + this.BoundRect.Width);
                float leftEdgeDistance = OtherObject.BoundRect.X + OtherObject.BoundRect.Width - Position.X;

                float TopEdgeDistance = OtherObject.BoundRect.Y - (Position.Y + this.BoundRect.Height);
                float BottomEdgeDistance = OtherObject.BoundRect.Y + OtherObject.BoundRect.Height - Position.Y;

                float Left_Right_SmallerDistance = Math.Min(Math.Abs(rightEdgeDistance), Math.Abs(leftEdgeDistance));
                float Top_Bottom_SmallerDistance = Math.Min(Math.Abs(TopEdgeDistance), Math.Abs(BottomEdgeDistance));

                float smallerDistance = Math.Min(Math.Abs(Left_Right_SmallerDistance), Math.Abs(Top_Bottom_SmallerDistance));

                if (smallerDistance == Math.Abs(leftEdgeDistance))
                {
                    Position.X = OtherObject.BoundRect.X + OtherObject.BoundRect.Width;
                    Velocity.X = 0;
                }
                else if (smallerDistance == Math.Abs(rightEdgeDistance))
                {
                    Position.X = OtherObject.BoundRect.X - this.BoundRect.Width;
                    Velocity.X = 0;
                }
                else if (smallerDistance == Math.Abs(BottomEdgeDistance))
                {
                    Position.Y = OtherObject.BoundRect.Y + OtherObject.BoundRect.Height;
                    Velocity.Y = 0;
                }
                else if (smallerDistance == Math.Abs(TopEdgeDistance))
                {
                    Position.Y = OtherObject.BoundRect.Y - this.BoundRect.Height;
                    Velocity.Y = 0;
                }
            }
        }

```

and here's my Player class's Input Handler method I made:

```
public void inputHandler(GameTime gameTime,GameObject OtherObject)
    {
        Velocity = Vector2.Zero;

        if (Keyboard.GetState().IsKeyDown(Keys.W))
            Velocity.Y -= moveSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds;
        if (Keyboard.GetState().IsKeyDown(Keys.S))
            Velocity.Y += moveSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds;
        if (Keyboard.GetState().IsKeyDown(Keys.A))
            Velocity.X -= moveSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds;
        if (Keyboard.GetState().IsKeyDown(Keys.D))
            Velocity.X += moveSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds;

        handleCollision(OtherObject);
        Position += Velocity;
    }

```

Also here's my Update method In the Main Game Class.

```
protected override void Update(GameTime gameTime)
    {
        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
            this.Exit();

        for (int i = 0; i < 3; i++)
            player.Update(gameTime, stage[i]);
        powerUp.Update(gameTime,player);
        base.Update(gameTime);
    }

```

It works, but when I use array it becomes buggy for some elements of the arrays as in the character can still move a bit inside of the rectangle when I press the key to go down and it will stay outside of the top of the rectangle only if I let go of the key and vice versa.

The rectangles are an array of 3. If I were to move and test the 3rd box. It will work perfectly.But if test the 2nd, it will sink in a bit and the 1st a bit more than the 2nd. I use for loop for the update and draw the array elements. I see that the pattern is, the 1st is the first one to be checked in the Main Update method is will suffer the worst collision handling, while the last one will always be perfect. I tried other ways to handle the collision but to no avail. Why is that? And how can I counter this? Help please!

# Answer
You call the player's Update() function 3 times per Main.Update(), where you probably want to call it only once.

Calling it 3 times will presumably attempt to move the player 3 times per frame, only doing a collision test with a single object for each of these three movements, so that each subsequent Update() can move through the previous obstacles in the loop.

Instead, you should run all your collision tests between the player and the obstacles first, then move the player only once at the end with the resulting velocity.
> 0 votes

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


# Question
Title: supporting multiple resolutions on mobile (cocos2d, ios)
I am looking into ios game development and the first question that comes to mind is how to support the growing number of iphone resolutions.

I have seen the Unity strategy of normalized screen coordinates, but all of the cocos2d tutorials I look at seem to hard code pixel positions. How does this work with iphone 4 , 5, 6, 6+ all having different resolutions? (4 vs 6 is a major difference)

Is there a common practice for dealing with this?

# Answer
Cocos2D-x 2.x and 3.x have very easy solution for multi-resolution problem ( either iDevices or Android devices) (and I think cocos2d-iphone should have a similar mechanism (maybe with different signature).

In fact you just need to set your `DesignResolution` and then just imagine your target device will has this resolution.

If target device really has this resolution ( or some other but with same ratio) cocos2d will handle to fix screen and your game looks same in all devices.

And when ratio of target device is different, you have many option ( as cocos2d language, `policy`) to manage that.

For example if you use `Exact fit` policy, cocos2d will force your game ( and design) to fit target device screen (without that black boarder).

> Exact fit
>
> The entire application is visible in the specified area without trying to preserve the original aspect ratio. Distortion can occur, and the application may appear stretched or compressed.

For more detail just take a look at the official wiki.
> 1 votes

# Answer
I am quoting here from one of my previous posts which you can find here.

1. The easiest solution would be to create the graphics at the size of the highest resolution, but older iPhones have little memory so this solution would only work (smoothly) on the newer models. Instead you should target 2 resolutions. 1920 x 1080 for the iPhone 6(+) and 1136 x 640 for the 5(S). In this way you will only have to downscale for the iPhone 6. This downscaling should not have a huge effect on performance since the hardware in the iPhone 6 is more than capable.
2. Generally you would want the experience to be the same across all devices. The iPhone 5 and up all have a 16:9 aspect ratio. Unfortunately the iPhone 4(S) doesn't. For these you will either have to downscale the content a little further and have an empty space on the top/side or have some content falling off. The latter probably isn't the best idea so downscaling and having a little extra space on top seems like the best solution.

The whole image is the screen of the iPhone 5(S), cut off area 2 and you get the screen of the iPhone 4(S). Now, if you want to have the same content visible on the iPhone 5 and 4 then you will need to keep the same aspect ratio. The 5 its aspect ratio is 16:9. When we apply this to the iPhone 4 then you will get area 1. The grey areas will not have any content. You can fill this up with a nice background or display an UI.
> 0 votes

---
Tags: ios, cocos2d-iphone
---


title: Intersperse 2D with 3D opengl

text:
# Question
Title: Intersperse 2D with 3D opengl
I want to be able to draw 3D objects as well as 2D objects in an openGL environment. Normally, I would draw my 3D stuff, disable the depth buffer and depth mask, then draw my 2D stuff.

However, this creates a hassle. What if I have a single `draw()` function that is supposed to draw 3D and 2D? I would need to separate it, which I really don't want to do. I want to be able to do stuff like `draw3D(...); draw2D(...); draw3D(...);`

So is there a common way of doing this? I can think of a few solutions but would prefer to do it a standard way.

Here's a visual of the problem. My 2D text is interfering with my 3D environment:

# Answer
> 1 votes
It is pretty complicated stuff going on and its not that simple as it look bcs of the way of opengl buffering system works.The best way to do it is just draw 3d and then 2d. You might create some kind of ArrayList which will keep track of all 2d drawing requests. And when 3d is done you execute them all.

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


# Question
Title: How can I map regions on a world map image?
I am trying to use a map of the real world, but I need to have a way to break it down by countries and regions. Ideally down to a province level. I figure that I'd need to be able to define polygonal regions on the image and export the points that represent the bounding polygon, so that I could check for clicks inside, and do other things with it. I'm having a hard time finding a tool that will let me do this, that is, load in an arbitrary image and start defining polygons on it to be exported. Or am I going about this the hard way? Using XNA/Monogame currently if that matters in your answer. Thanks

# Answer
> 8 votes
You *could* use polygons, or you could do a quick and dirty hack and just get a political map like this one:
(source: freeusandworldmaps.com)
. Then, pick a unique color for each country and flood fill it in paint or photoshop. Then, you have a simple file that just has the mapping of countries/provinces to particular colors. Just something like this:

```
# Country,      #Unique RGB color
"Afghanistan",     (0, 0, 0)
"Albania",         (1, 0, 0)
...
"United Kingdom",  (255, 0, 0)
"United States",   (0, 1, 0)
...
"Kingdom of Zzyx", (0, 255, 0)
"ZZZland",         (0, 0, 1)
...

```

Then, when the player clicks on the map, just sample the color image, and find the color associated with it. Of course, this will be limited to the resolution of the selection image. This also gives you control over the political boundaries you want to select. For instance, if you just want to select continents, you could use an image like this:
(source: zonu.com)

---
Tags: xna, 2d, monogame, image
---


# Question
Title: Draw multiple triangle strips in one draw call DirectX
I'm running into a bottleneck where I'm drawing many basic disconnected colored triangle strips in DirectX 9 (XNA). The problem comes with drawing them all in seperate draw calls, so I'd like to batch them all together into a single buffer and draw them in one draw call.

I understand that in DirectX10 and above, there's a way to draw many triangle strips in the same draw call by inserting a special "cut" index (-1) into the index buffer after every line strip.

Is there a way to do this without the use of the cut index? (Which as far as I know, isn't present in directx 9?)

# Answer
> 5 votes
If the triangle strips, while being disconnected, are all sharing the same material (shaders, textures, shader constants) then you can join them together with a degenerate triangle. Since degenerate triangles have zero area they should not show up. The only case they would is if you are drawing wireframe.

You make a degenerate triangle by defining the two of the three vertices as being the same. This is a bit complicated in triangle strips where you only use two vertices to define each triangle.

Look at the following diagram:

Triangle strip A,B,C is connected with triangle strip E,F via a degenerate triangle D. Triangle D would be defined as two points of C, then two points of E. In this way it is a zero-area triangle, but it is still connected.

You can find information on this stack overflow article where the wireframe problem is illustrated.

---
Tags: xna, directx, graphics, performance
---


# Question
Title: Standard key bindings for movement along three axes?
I understand that the WASD keys are standard for moving a character along two axes (left/right, up/down) because in the QWERTY layout, they are arranged like the arrow keys. I want to make a game where the character can move along three axes, i.e. also front/back. Are there standard key bindings for this as well?

# Answer
For something with rotation its generally wasd for throttle and roll,
shift+wasd or uhjk for strafe orthogonal to forward.
Or
ws throttle
ad strafe
qe roll

For purely translation, then wasdec or wasdqe.

But its ultimately the situation that dictates what is best used.
Don't think "I should use the standard", think "Does the standard suit this?"
> 0 votes

# Answer
WASD is just a de facto standard for FPS games. If you play an FPS from the pre-Half Life era, you'll end up with all sorts of variations. That said, the analogue from 5DoF to 6DoF is jump/duck, which varies for each game. Case in point, Quake used jump and duck for up/down movement underwater, even though it used arrow keys for forward/back and turning, with alt+left/right for strafe.

The original 6DoF FPS, Descent, had flight-sim like controls and used the +/- keys for up/down.
> 0 votes

---
Tags: keyboard, axis
---


# Question
Title: Resizing a Framebuffer Object (ie: its attachments) on Screen Resize
I have been experimenting with some post-processing effects and I have been using FBOs to store stuff.

The problem is, I attempt to resize them when I change resolution. I get no errors, however the image has been stretched so that I only see about the bottom-left quarter of it on my screen.

I have looked over the internet and and found issues such as not using `glTexStorage` because it is immutable, and being sure to call `glViewport` after binding a framebuffer. As far as I can see I'm not missing anything simple like that.

Here are some (very dark) screen shots showing the issue:

Please excuse the horrible graphics. I am working on a bloom filter and these images only contain the bright bits so it looks dark and weird.

My FBOs are initialised with a blank texture attached to GL\_COLOR\_ATTACHMENT0. Here is the rough pseudo code (in java). (my actual code is abstracted behind a game engine I'm writing)

Generating texture:

```
    // Creates the texture

    this.id = glGenTextures();

    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

    glBindTexture(GL_TEXTURE_2D, this.id);

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

    // Set up texture scaling
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, magnification);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minification);

```

Filling it with data: (`data` is a ByteBuffer filled with 0s)

```
    glTexImage2D(GL_TEXTURE_2D, 0, colorMode, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
    glGenerateMipmap(GL_TEXTURE_2D);

```

Binding the framebuffer:

```
   glBindFramebuffer(GL_FRAMEBUFFER, this.id);
   glViewport(0, 0, width, height); // width and height taken from width and height of framebuffer texture

```

Resizing the framebuffer:

```
    // stores new width and height to be used with glViewport
    this.width = width;
    this.height = height;
    // resize renderbuffer
    if(renderbuffer != 0) {
        glBindRenderbuffer(GL_RENDERBUFFER, renderbuffer);
        glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, width, height);
        glBindRenderbuffer(GL_RENDERBUFFER, 0);
    }

    glBindTexture(GL_TEXTURE_2D, texture);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
    glGenerateMipmap(GL_TEXTURE_2D); // do i need this?

```

Thanks very much in advance if you can spot an issue with my code. Let me know if you need the full source as well.

I have a couple of ideas for issues:

* is it possible to resize the renderbuffer like that?
* do I have to re-attach the textures after resizing them
* should i just re-create the entire framebuffer/renderbuffer/textures instead of resizing them.

# Answer
To be safe I'd delete and recreate the entire FBO.

Some drivers have strange stability issues when recycling/resizing FBOs. I've had entire screen flickers and occasional crashes.

Switching attached textures to another of the same size & type seem to work fine all the time on all drivers but with some drivers it is much faster (more than 100x) to have multiple FBO objects and never re-attach textures, just switch between entire FBOs, with the same depth buffer attached to all of them.
> 6 votes

# Answer
Double check if you are truly using viewport correctly.

You're not rebinding the texture to the FBO.
That SHOULDN'T be necessary, however the spec makes no guarantee that glTexImage won't screw up any attached framebuffers, so assume that it can.

If that doesn't work then its the way you're sampling from it.

For simply allocating a texture with undefined content, use null as the data pointer, much faster.

Absolutely never use mipmaps with a framebuffer unless you know for sure you will be minifying it, otherwise you'll use a ton of memory.
> 0 votes

---
Tags: opengl, java, textures, lwjgl, frame-buffer
---


# Question
Title: Unity2D: Apply gravity to some items, when everything else is gravity-free?
Sorry for the incredibly vague title: Let's say you have an NPC, and when he dies he'll spawn items, coins for example. Instead of just pushing the coins in random directions it would look a lot neater if they coins arced to the ground (see picture below)

The red circle represents a dead npc, the black lines represents gold coins.

Every entity in my game has a RigidBody2D with gravity set to 0, otherwise they'd fall to the bottom of the gray box.

Is it possible to 'pretend' that the ground around the dead npc has collision?

I thought about maybe adding a collision-box below the coins which follow the coins in the X-dimension only, but I'm not sure how to set the coins to only collide with these boxes (and perhaps left and right walls)

# Answer
The answer is to not have a collide-box on the item/coin itself, but it still needs a rigidbody2D to simulate gravity.

We start by finding the objects startposition upon construction. We add a force to it, to push it upwards, to simulate that the item/coin is being 'thrown' out of the dead NPC:

```
startPosY = gameObject.rigidbody2D.transform.position.y;
startForce.x = 75;
startForce.y = 400;
rigidbody2D.AddForce(startForce);

```

Now we want to simulate 'bouncing', as if it was bouncing across the floor. We do so by checking if it's intercepting the 'startPosY' we stated in the beginning. If it's intercepting, stop it (enabling its kinematic-boolean and disabling it) and apply a smaller force to it:

```
if(rigidbody2D.transform.position.y <= startPosY && startForce.y > 0.05)
{
    rigidbody2D.isKinematic = true;
    rigidbody2D.isKinematic = false;
    startForce.x *= 0.7f;
    startForce.y *= 0.7f;
    rigidbody2D.AddForce(startForce);
}

```

At some point we would like to stop the bouncing. Since we don't want the item to slide down to the bottom of the level, we disable its gravity:

```
else if(startForce.y < 0.05)
{
    rigidbody2D.isKinematic = true;
    rigidbody2D.isKinematic = false;
    rigidbody2D.gravityScale = 0;
}

```

I still have to play around with perhaps modifying the 'startPosY' so all coins don't stack up on one X-axis. Also it sometimes keeps going into the statement

```
if(rigidbody2D.transform.position.y <= startPosY && startForce.y > 0.05)

```

because the position so happens to be under startPosY for consecutive frames.
> 1 votes

# Answer
You can probably use layers to apply collisions on certain objects with designated layers.

The basic idea is to define a layer for the collision ground and the coins so that coins will only collide with the ground (or the objects in the same layer) and not other objects. Upon collision, you will want to check the layer of the other collision:

```
function OnCollisionEnter2D(coll: Collision2D) {
{
    if (coll.gameObject.layer == LayerMask.NameToLayer("LAYER_NAME"))
    {
         Debug.Log("Collision occurred in LAYER_NAME");
    }
}

```
> 0 votes

# Answer
You can assign object/prefabs a Tag. by checking specific tag (e.g. 'Coin') to collide with floor and allow only this to be bounced. Quoting Varaquilex above

```
function OnCollisionEnter2D(coll: Collision2D) {
{
    if (coll.gameObject.tag == "Coin")
    {
         Debug.Log("Collision occurred for Coin");
    }
}

```

Of course you may want to tag and check the floor as well.
> 0 votes

---
Tags: unity, physics
---


# Question
Title: Porting WP8 to IOS GraphicsDevice Error (Monogame/Xamarin)
I seem to be having a problem porting to IOS. I have my game working on WP8 and Android with any major issues but when trying to run on iPhone I seem to get an error when initialising the GraphicsDevice

below is a screenshot to the problem. has anyone else had this issue and is there a workaround/fix? Thanks in advance! :)

https://i.stack.imgur.com/59k09.png

# Answer
> 1 votes
Most issues relating to the graphics devices and the SpriteBatch should be fixed in the development branch of the Github repository. If you compile the project, which is very easy, you can use that dll instead of the normal one (or whatever the Mac equivalent of a dll is). In addition, we are very close to porting Monogame to the Xamarin iOS Unified API, which may be the addition that fixes your error as well.

In short, you can compile the current development branch, and you should probably follow Pull Request #3139 to watch for news of the port being completed. Once this occurs, most issues should be fixed, if not all, and you should be able to compile cleanly for all three mobile platforms.

---
Tags: xna, ios, monogame, windows-phone-8, xamarin
---


# Question
Title: DirectX 10 - dimension of vertices passed to vertex shader
I'm trying to learn DirectX programming. Looking at different tutorials there is something about vertices that I find a bit confusing.

I know that DirectX uses vertices with four elements (x, y, z, w). I saw many tutorials (example http://msdn.microsoft.com/en-us/library/ff729721(v=VS.85).aspx) passing XMFLOAT3 as vertices positions omitting the w component.

How does this works? Assuming that passing XMFLOAT3 or XMFLOAT4 doesn't change DirectX behavior (true?) should I set the w to 1 in the vertex shader or does DirectX assume it to be 1 by default?

# Answer
Very good post thats explain it:

https://andrewharvey4.wordpress.com/2008/09/29/xyzw-in-opengldirect3d-homogeneous-coordinates/

Just in few words: 3x3 matrix is not enough to represent translation (move vector to new place), it just enough for rotation, just for it every one using 4x4 matrices, and w term should be 1.0 if you want translation affect your vertex , otherwise only rotation will be applied.

Usually w term is omitted just assumed it 1.0 (not worth storing it for every vertex in mesh)
> -2 votes

---
Tags: directx, directx11, directx10
---


title: Isometric Collision Detection

text:
# Question
Title: Isometric Collision Detection
I am having some issues with trying to detect collision of two isometric tile.

I have tried plotting the lines between each point on the tile and then checking for line intercepts however that didn't work (probably due to incorrect formula)

After looking into this for awhile today I believe I am thinking to much into it and there must be a easier way.

I am not looking for code just some advise on the best way to achieve detection of overlap

# Answer
I'll come straight out and say that I don't know how to solve the problem you have described in the question (collision detection between iso-tile-shaped rectangles), but I can tell you how others have solved it in the past:

The way it's done in other games is to separate the *game world* from the *screen world*. When you're starting out, it common to imagine them being the same thing, but then it leads to problems like the one you're describing.

The general idea is that the *game world* is stored completely in memory, behind the scenes, it's just numbers, references, and logic. The fact that you are drawing the game world in isometric is irrelevant. Your game world shouldn't have the concept of isometric, or square, or even if the screen is being draw as 3D. All of that is taken care of when you draw the game world to the screen (aka the *screen world*). The game world should be stored and maintained in the simplest way that makes sense for the game, in isometric games, you typically completely ignore the fact that it's iso and instead store the positions as if you were using an axis-aligned grid. Most games will have methods for converting coordinates between the two worlds, I call mine `ScreenToWorld(x, y)` and `WorldToScreen(x, y)`. The conversion is often done with Matrix math, but can be achieved other ways. You'll use ScreenToWorld when you use the mouse, and WorldToScreen when you draw.

There are several advantages to splitting the *game world* and the *screen world*. One of the advantages is that collision detection and movement all happens in the game world, and is therefore usually quite straight forward because you're not dealing with a slanted grid, or skewed coordinates, or where the screen is, etc. In your case, you'd be dealing with axis-aligned rectangles and squares. Once the game world has been updated, then you draw a representation of the game world to the screen, keyword: representation. It may seem counter-intuitive at first, but your screen is only a representation of what's going on in the game world. This makes things like dedicated servers and terminal-like clients possible.

FreeCiv is actually a great example of all these things. You can view the same exact world as any of: a square North/South Grid, Isometric, or even Hex. Every game you run has a dedicated server running in the background, even for single-player games, therefore the client is also just a display port, nothing more.

Long story short: Separating the game world and logic from the screen world simplifies the game logic, reduces the game\<-\>display coupling, and in turn, makes collision detection between "iso" tiles easier to handle and easier to visualize.
> 23 votes

# Answer
John's answer is quite right, but I will try to explain it in a different way:

There IS no isometric collision detection.

Collision detection does not care what your projection matrix / transformation looks like. Collision detection should not matter if you render things at all (after all, objects which are off the screen can still collide, right?)

It is a more philosophical question: Does a tree falling down in a forest still actually collide with the ground when there's nobody there?

Conventional wisdom would say: Yes. It doesn't matter how you look at it. Things collide in world-space, not view-space.
> 9 votes

# Answer
You can try allocating an array of pixels composing a bitmap of each getRGB() values of each individual pixel. Than compare the values with an if statement as the borders of the tile are a separate color value than that of what the tile represents(water, sand, grass). That for a basic isometric grid. Or you can have two layers of the map itself. One layer containing sort of like a green screen drawing the outline of each representative of an colliding object and the other layer will be the map itself.

You not composing a bitmap array of each pixel of the map layer instead you want to calculate a set of colors representing the effects it has when an object collides / intersects the border of the maintaining color value. Either you want values to decrease in value or increase of velocity in which the object is moving. Each object that moves is just a duplicate of memory stored in a different spot.

I would look into pixel perfect collision and the understanding of bitmap arrays. Each rectangle is a bounds of containing replicating data sort of like imprinted memory each event is triggered depending on where a object is rendered in a location or vector. Every point on the screen is on a 2D plane only that the depth of shadow providing an illusion that the object represents itself as 3D. Transformation of shapes in a skew give it sense the object is at an angle. There is a center point of where the camera presents it view everything is carried around this center point moving away from it decreasing in size or moving closer to it increasing in size.
> 0 votes

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


# Question
Title: Port sandbox flash game to Android and iOS
I'm want port my sandbox game to Android and iOS. Game written in AS3 (i'm use my simple 2d engine on stage3d). What do you recommend I use?

* Haxe + OpenFL
* MonoGame + Xamarin (C#), or other 2D engine in C# for mobile?
* LibGDX + robovm (Java)
* or AIR? It's slowly (seems).

I'm know C#, but don't know Haxe and Java. Game render many sprites: tiles (walls/blocks/liquids), background, entities, particles + lighting system.

My game: http://www.youtube.com/watch?v=y\_KbvZCljnA

# Answer
> 1 votes
I strongly recommend Haxe + OpenFL. Haxe is a language based on ActionScript. There are a few differences but its the closest to what you know. The language manual and API reference at http://haxe.org are great resources.

OpenFL is the Haxe implementation of the Flash API, you can find info on OpenFL at http://openfl.org (this is the best place to start, make sure to check out the API reference). OpenFL doesn't implement the entire flash API but it should suffice for most of your needs. You should also check out OpenFL's feature matrix at http://www.openfl.org/documentation/technical-overview/feature-matrix/ to see what's supported or not.

Lastly you'll need Lime...this is the program that compiles Haxe to various targets including PC, MAC, HTML5, iOS and Android (and even some game consoles). Lime is a command-line tool but its fairly easy to pick up. OpenFL.org has installation instructions for the entire suite of tools. You can get started at the following link http://www.openfl.org/documentation/getting-started/installing-openfl/

If you need to ask further questions about OpenFL make sure to join the community forums at openfl.org.

---
Tags: 2d, android, ios, flash, porting
---


# Question
Title: Rotate can I rotate an object to a target angle using Euler Angles?
How do I rotate an object from its current angle to the desired angle in increments on 1 axis? The problem is the wraparound at 360 degrees What I have so far (Note: pseudocode):

```
double MaxSpeed = 5;

double CurrentAngle = -170;
double DesiredAngle = 40;

double Distance = DesiredAngle - CurrentAngle; //How do I calculate this value considering angle wraparound?

CurrentAngle += Mathd.clamp(Distance, -MaxSpeed, MaxSpeed); //Caps the rotation speed
```

# Answer
> 1 votes
If your problem is simply to deal with the fact that -10, 350, and 710 are all equivalent angles, that you may potentially get any desired angle, and that you never want to make a total rotation over 180 degrees, then:

```
double Distance = DesiredAngle - CurrentAngle;

// Let's bring Distance to its closest equivalent in the [-180..180] degrees range
while (Distance < -180) Distance += 360;
while (Distance > 180) Distance -= 360;

CurrentAngle += Mathd.clamp(Distance, -MaxSpeed, MaxSpeed); //Caps the rotation speed

```

# Answer
> 0 votes
If you want rotation with lineal speed from one vector to another **in shortest path** I can suggest about using quanterions with SLERP http://en.wikipedia.org/wiki/Slerp

If you want just rotate around x,y,z axis thats could be done with rotation matrix http://en.wikipedia.org/wiki/Rotation\_matrix

Nevertheless can you add your rotation code to question?

---
Tags: rotation
---


# Question
Title: How do teams prevent overwriting work in source files?
It occurred to me the possibility that while, for example the game engine, is being worked on simultaneously by multiple people how is overwriting prevented?

Let's say **developer one** is working on `Audio.cpp` and **developer two** is also working on `Audio.cpp`, how is this generally managed in large teams to combat overwriting? (In other words to stop **developer two** from opening the file until **developer one** is finished)

# Answer
Most software development teams (not just in game development) solve this issue using **version control software**. Examples are

All these tools have some differences, but the basic workflow is usually like this: There is one central repository for the project with the complete codebase. When a developer wants to join the project, they perform a "checkout". The version control software copies the codebase to their local machine. The software remembers the current version ("revision") of the codebase. When a developer made their changes and wants to put them onto the main repository, they perform a "commit". Their changes are uploaded to the central repository, and a new revision number is created.

When another developer now wants to commit their changes but the revision they once checked out is no longer the most recent one, the version control system won't let them. The developer first needs to "pull" the revisions which happened in the meantime. This updates their local copy to the most recent version on the central repository. When there are conflicts (intermediate revisions made changes to a file they also changed), the software might ask them to resolve the conflict by editing the conflicting files manually (a "merge") in case it doesn't manage to automatically do that. After they have done that, they can commit their changes as a new revision.
> 69 votes

# Answer
Developers don't use *the same* file.

Each developer has his own version of the file, and they use a special kind of software to manage their work. If they both make changes to it, the one that tries to overwrite the changes done by the other developer will encounter *a conflict* which must be resolved, otherwise the software I talked about starts complaining. In other words, the developer that causes the conflict, needs to combine their work with the other developer's work, and only then can the file be "saved".

This is a simple explanation for a part of the otherwise not so simple concept of version control.
> 13 votes

# Answer
In addition to the points raised in the other answers about version control and handling conflicts with merges, there are at least two other ways that team members can avoid overwriting each other's work:

* Some version control systems (e.g. SVN) allow locking of files. This means that one team member can take exclusive ownership of a file for some length of time, preventing other team members from making conflicting edits (or, really, any edits) until the file is subsequently unlocked.

However, this is generally used infrequently, as it can cause a number of problems. It can reduce productivity (by limiting who can work on files at any particular time), and can cause problems if someone forgets to unlock a file. Also, at least for SVN (I'm not sure about other VCSs), locking a file doesn't prevent someone else making changes to their working copy, it only prevents them committing their changes - this can result in wasted effort if a developer modifies the file only to discover they can't commit their changes because it is locked.
* Teams can try to assign tasks to developers in such a way that they don't have more than one person working on any particular file at a given time. For example, developers could each be responsible for a particular part of the project (e.g. 3D rendering, network, audio, etc) - if the codebase is well modularised, then the developer assigned to the network code should have little need to touch the files dealing with audio.

Of course, there will always be some overlap that must be managed some other way.
> 9 votes

---
Tags: project-management, version-control, teamwork
---


title: VBO -> How should it be done?

text:
# Question
Title: VBO -> How should it be done?
I'm very new to OpenGL/LWJGL. I'm reading a lot of VBOs.

I'm sorry if I can't concretise my concern, but i'll try it:

1. Why should I use VBOs? Whats the difference between using VBOs and glBegin() and glEnd()?
2. My Game is organized like this:

* One huge map
    * some static objects like trees on this map
    * Enemies and Characters

Enemies and Characters are spawned on the fly

and my gameLoop is like this: statemanager.render()=\>Map.render()

Where Map has an Enemy\[\] and Character\[\], where both of them have a Tree of Meshes and Mesh has the Vertex-Arrays.

```
public class Tree<T>
{
  T data;
  T child;
}
abstract class MoveableObject
{
  Tree<Mesh> meshTree;
  public Vector3f pos;
  public Vector3f rot;
}

public class Mesh
{
  Vector3f[] vertices;
  Vector3f[] colors;
  Vector3f[] normals;
}

```

Where and how should I setup the VBOs? For example A map and the statics never change, can I setup a VBO once for them instead of setting it up every frame?

Most OpenGL Tutorials show prototypes of the methods, but never explain the parameters of these methods. It's hard to understand how they actually work, if you've never worked with it before. (Yes, I alread did that Triangle/Cube Tutorial)

# Answer
> 3 votes
TLDR: VBOs makes a huge difference in performance.

One simple reason to use them would be that OpenGL ES (mobile devices) don't support `glBegin(...)`/`glEnd()` so you have to use `glDrawArrays()` but not necessarily VBOs.

The main reason to use VBOs is that it allows the OpenGL driver to keep the vertex data in GPU memory, rather than CPU memory which forces the GPU to copy the data over the device bus (PCIe) every time you want to draw something.

So when you want to draw the map all the data is already in the 3D card's memory and the only thing that gets sent over the (slow) bus is essentially a single command:

* Draw N triangles starting at address M

Rather than:

* Mode: Triangle
* Here's a color
* Here's a normal
* Here's a texture coordinate
* Here's a vertex
* Here's a color
* Here's a normal
* Here's a texture coordinate
* Here's a vertex
* Here's a color
* Here's a normal
* Here's a texture coordinate
* Here's a vertex
* Here's a color
* Here's a normal
* Here's a texture coordinate
* Here's a vertex
* ...

Note: this is a simplified explanation and yes there's 3D hardware that actually work this way with commands sent one-by-one like this.

Even if today's drivers pack everything between glBegin and glEnd into a buffer and send it over to the GPU in one block you're still making a whole bunch of OpenGL calls wasting CPU time, flushing caches for the buffer, and sending all that vertex data over the bus every time you draw something which keeps the memory bus busy, often preventing the CPU from doing other work at the same time.

Using VBOs leaves the device bus and CPU memory bus free. Letting the GPU do its thing in its own memory while the CPUs are doing something else with its memory like updating AIs, decoding & mixing audio, etc.

---
Tags: java, lwjgl, vbo
---


# Question
Title: How do I calculate the bounce vector of a ball hitting the starting point of a segment?
I have a ball (with parameters x, y, radius) that travels on the screen (with vectors directionX directionY) and can collide with a segment with random slope (with parameters startX, startY, stopX, stopY).

After i detect the collision i split code for calculate bounce vector in two different situations: first situation is ball in the middle of the segment (which is now working properly) and second is ball colliding the segment corners (starting or ending point) of a segment. Now,my algorythm is more or less working but sometimes there is some wrong behaviour and bounce is wrong or even no bounce (ball pass through the line without bounce)

This is the code i'm currently using:

```
       if (Math.pow(line.startX - x, 2) + Math.pow(line.startY - y, 2) <= Math.pow(radius, 2) || Math.pow(line.stopX - x, 2) + Math.pow(line.stopY - y, 2) <= Math.pow(radius, 2)) {
          // ball has hit the corner of the segment
           if (Math.pow(line.startX - x, 2) + Math.pow(line.startY - y, 2) <= Math.pow(radius, 2)){
               //calculate bounce vector with starting point of segment
                float x1 = x - line.startX;
                float y1 = y - line.startY;
                float c1 = (float) (-2 * (directionX * x1 + directionY * y1) / (x1 * x1 + y1 * y1));
                directionX += c1 * x1;
                directionY += c1 * y1;

           }
           else{
               //calculate bounce vector with ending point of segment
                float x1 = x - line.stopX;
                float y1 = y - line.stopY;
                float c1 = (float) (-2 * (directionX * x1 + directionY * y1) / (x1 * x1 + y1 * y1));
                directionX +=  c1 * x1;
                directionY +=  c1 * y1;
           }
        }

      else
            {
 //other code for calculating bounce vector after collision inside segment.

```

}

# Answer
You need to change the collision of `a ball against an infinitely thin line` to an `infinitely small point (ray) against a thick segment with two round ends`

You transfer the ball's thickness to the segment. Both end points become circles.

The collision then becomes a 2D ray-cast operation.
> 1 votes

---
Tags: java, 2d, collision-detection, vector, collision-resolution
---


# Question
Title: Separation of axis theorem implementation at normals
This might be more of a math question, but it relates to the development of a simple physics engine I am trying to create.

I have been stumped on this for about a week now, and have been unable to find an answer in any of the SAT tutorials. (http://www.metanetsoftware.com/technique/tutorialA.html#toc, http://gamedevelopment.tutsplus.com/tutorials/collision-detection-using-the-separating-axis-theorem--gamedev-169, etc.)

I understand how SAT is supposed to work, however I am little confused on the math. First, I am finding my normals like so:

```
Block.prototype.findNormals = function () {

        var axisVectors = new Array();
        var vertices = this.Properties.Vertices;
        var keys = Object.keys(vertices)

        for( var i = 0; i < keys.length; i++) {
            var last = {x: 0, y: 0};

            axisVectors.push({xComponent: -(vertices[keys[i]].y - last.y), yComponent: (vertices[keys[i]].x - last.x) });

            last = {x: this.x, y: this.y};
        }

        return axisVectors;
    }

```

I am then precede to project each vertex of the shapes I am testing on those normals.

The problem occurs, and the part of the math that I am not fully understanding, is when I have a situation like so:

```
axis = (-5, 6)
vertex = (6, 5)

math.dot(vertex, axis)

```

This results in 0.

Thus my min value for shape1 is always 0. And this results in a false collision.

Can anyone explain the math a little better?

# Answer
> 1 votes
Your normals are supposed to be the face normals of a polygon. If your vertices are an oriented array in counter clockwise order, then you can easily compute the normal of a face by a 90 degree rotation.

So if we have an edge on a polygon made of the vertices a and b, we know that the edge is oriented from a to b going around the polygon in CCW order. To rotate the edge such that we end up with a vector that points outward from the polygon (of unit length), we need a 90 degree clockwise rotation and one normalization.

Here's the rotation matrix for that in column major:

$$ \begin{bmatrix} cos( 90 ) & sin( 90 ) \\ -sin( 90 ) & cos( 90 ) \\ \end{bmatrix} $$

If you compute sin and cos and multiply this matrix with a vector { x, y } you realize that all you're doing is flipping the x and y component and negating the new y component.

We can write a function for this:

```
Vector ComputeNormal( Vector a, Vector b )
{
    Vector ab = Normalize( b - a );
    return Vector( ab.y, -ab.x );
}

```

Don't forget to normalize your normals.

---
Tags: collision-detection, mathematics, javascript, algorithm, separating-axis-theorem
---


# Question
Title: Is the standard collision detection in Slick2D too heavy for broadphase?
I was wondering two things about the built in shape detection of Slick2D. When executed on a lot of shapes, how performant are the `intersects` and `contains`methods, and what kind of algorithm is behind those.

I have implemented SAT collision detection but I don't want to execute this detection on all my entities. So I thought I would use the built in methods to look for entries which are near my player, and for those do the SAT detection.

But if the built in methods are as good as or better than SAT, this wouldn't be good. Also if the built in methods need more time or are kind of heavy for the cpu.

What is the proper way to have my collision detection on the smallest amount of game objects. How would I filter only the near objects?

# Answer
> 1 votes
All collision detection methods can benefit from pruning the list of objects to test before testing.

One of the ways is to partition your world so you can query the objects that may intersect with some area (false positives are allowed) then only do the collision test on those objects. For example store the axis aligned bounding box in a grid and knowing that you can just index into the grid to know which objects are in each grid cell and you don't have to worry about those across the world.

---
Tags: java, collision-detection, slick
---


# Question
Title: Idle+Walk animation problem and double-button input axes
I have 2 problems with unity3d.

First, I created an animator and attached it to player. In animator I put 2 condition, Speed and Running (first is float, second is boolean). Default Animation is Idle. Then player press W, I want animation to fade from idle to walk and when he stop press the button, I want the animation to fade from walk to idle. Here is my problem.

1. When I press W, he make walk animation, but after it he play half of idle animation and after it he enter again in walk animation. How can I loop the walk animation until he release W? And if he release, even if the animation isn't totally played, I need the animator to make transition to idle.
2. How can I make this "transition"? Then I release W, he just go from walk to idle animation without any transition (and it is a kind of wear).

Second, How can I put 2 input buttons on axes? I mean: If he press W, there should go vertical axes. When he press W+Left Shift, there should go running axes. How can I attach 2 buttons to 1 axes?

I am new in unity and I want to figure out how to work with this things.

# Answer
Just set your walk animation in the Unity inspector to loop, and use `animation.CrossFade` for the transition.

```
if (...) {
  animation.CrossFade (Run.name);
} else {
  animation.CrossFade (Idle.name);
}

```

You can use this for idle animations as well:

```
if (!animation.isPlaying)
  animation.Play(Idle.name);

```
> 1 votes

---
Tags: unity
---


# Question
Title: How to prevent overlapping of gunshot sounds when using fast-firing weapons
So I am now trying to find sounds for my guns but when I grab a gun sound effect and play it in my game a lot of the sounds are either terrible sounding or have this horrible echoing effect because as a gun shoots sometimes the previous sound is playing still.

```
public void shoot(float x, float y, float direction){

    if(empty){
        PlayHUD.message = "No more bullets!";
        return;
    }

    if(reloading){
        return;
    }

    if(System.currentTimeMillis() - lastShot < fireRate){
        //AssetsLoader.lmgSound.stop();
        return;
    }

    float dx = (float) (-13 * Math.cos(direction) + 75 * Math.sin(direction));
    float dy = (float) (-14 * -Math.sin(direction) + 75 * Math.cos(direction));

    float dx1 = (float) (-13 * Math.cos(direction) + 75 * Math.sin(direction));
    float dy1 = (float) (-14 * -Math.sin(direction) + 75 * Math.cos(direction));

    PlayState.effects.add(new MuzzleFlashEffect(x + dx1, y + dy1, (float) Math.toDegrees(-direction)));

    PlayState.projectiles.add(new Bullet(this, x + dx, y + dy, (float) (direction + (Math.toRadians(MathUtils.random(-accuracy, accuracy))))));

    if(OptionState.soundOn){
        AssetsLoader.lmgSound.play(OptionState.volume);
    }

    bulletsInClip--;
    lastShot = System.currentTimeMillis();

}

```

Here is the code for where the sound plays. Every time this method is called the sound is called but it happens so often in this case that there is this terrible echoing. Any idea on how to fix this?

# Answer
> 4 votes
This problem is usually a sound design problem, not a coding problem. These problems occur mostly because of insufficient use of random variations in sound samples.

* You should first make sure you are using a pool of different recordings of the same sound and play a random one each time you fire a bullet, or make small random variations of the pitch on the fly via code.
* If the problem still exists, check if your variations are distinct enough or not.
* If you are doing this but still not satisfied, you should enlarge your sound set, manually introduce more variety using a sound editor, and manually introduce more random variety with code.

Some other solutions may be:

* Check if the sound effects include reverb and especially early reflections. Earl reflections are the first bounce of sound from a surface and usually heard as multiple reflections of the original sound in a few miliseconds. Playing many of such sounds in a very short time would result in accumulation of these effect and you can get strange echos effects.
* Check if your sounds are very long or too realistic samples to be perceived as real by our brain. I don't know what weapon are you talking about but, you may try digital sounds that don't exist in real life. Of course use them also with sufficient random variation.

# Answer
> 1 votes
I'm not familiar with libgdx, but judging from your code what you could do is to stop the currently playing sound, and only then play it again.

```
    if(OptionState.soundOn){

       //Stop sound here

       AssetsLoader.lmgSound.play(OptionState.volume);
    }

```

# Answer
> 0 votes
To prevent echoing, **avoid overlapping all the sounds** :

1. Check if bullet sound has finished playing
2. Stop the current sound and play the next/reset

```
if (bulleSoound.isPlaying()) {
       bulletSound.reset();
} else {
      bulletSound.play();
}

```

As **GuneyOzsan** says, you certainly can randomize by adding more bullet sounds

---
Tags: libgdx, sound, sound-effects
---