# Question
Title: Converted XWM(A) files get silence at the end
I am writing a playback mechanism for looping background music with XAudio2 and SharpDX.

I converted some perfectly looping WAV files to XWM(A) with the `xWMAEncode` command line utility (from the DX SDK of June 2010), but as soon as I play back the XWM file in a looping audio buffer, I notice a *significantly* noticable silence before it loops over.

I found out that when filling an XAudio2 audio buffer manually with a synthesized vibrato sound, no looping bug occurs. To further support this, I decoded the XWM file back into WAV, and the WAV file had exactly the same amount of silence at the end as I noticed in the playback, which turns out to be of 0,06 seconds length:

My first question is if anyone noticed the same behavior of the `xWMAEncode` utility, and if it is either a bug of the utility or even of the XWMA format itself.

I'd love to know some workaround for this if it can't be fixed by the encoding of the WAV itself.

I thought of setting the LoopLength sample of the audio buffer to exactly before the silence occurs. But for that I'd need to pray that such a silence isn't dynamic depending on the sample rate. Has anyone fixed it like this before and can provide or link me to details about this?

---

Head-shaking corner: MP3 adds silence to the start of each file, so XWM likes to put it at the end? Do we live in times were only OGG gets stuff looping correctly?

# Answer
This is 'by design'.

See the DirectX SDK documentation under the topic "xWMA Overview"

> xWMA Looping xWMA does not support loop regions or looping of arbitrary packets within an xWMA file. Only an entire xWMA file may be looped. XACT enforces this restriction, and no special treatment is needed. In XAudio2 xWMA has the following rules related to looping for the values in the XAUDIO2\_BUFFER that is passed to IXAudio2SourceVoice::SubmitSourceBuffer.
>
> If all of the xWMA file's audio data is submitted as one buffer and the user wants to loop it, the following restrictions must be met.
>
> XAUDIO2\_BUFFER.LoopBegin must always be zero.
>
> XAUDIO2\_BUFFER.LoopLength must be the size, in samples, of the entire file's xWMA data or 0.
>
> XAUDIO2\_BUFFER.LoopCount can be any value.
>
> XAUDIO2\_BUFFER.Flags must be set to XAUDIO2\_END\_OF\_STREAM.
>
> If xWMA audio data is submitted as more than one buffer the audio can only be looped manually by resubmitting the series of buffers.
>
> **Note that when looping xWMA audio, a period of silence can be** **introduced. Because of this possibility, looping xWMA audio should** **generally only be used with sounds that have smooth fade ins and outs** **(such as ocean waves or other subtle ambient loops).**
> 0 votes

---
Tags: sharpdx, audio, music, xaudio2
---


title: Filling a room with random furniture

text:
# Question
Title: Filling a room with random furniture
This is a rather complex question and I'm more hoping for general algorithms anyone might have heard of.

I wish to generate randomly sized rooms. Each of these rooms has a type and a corresponding list of furniture to be placed inside it (ie: kitchens can have fridges, both kitchens and living rooms can have TVs, etc). Each piece of furniture has it's own collider (cylinder, cube, mesh...). Are there any good algorithms to randomly lay them out?

The best idea I've managed so far is to subdivide the room into a grid the size of the smallest piece available. Then I would randomly place the furniture until every grid square is at least partially filled. However, this is hardly ideal and the rooms would more or less look like warehouses.

\[Optional\]How do I randomly place the furniture in such a way as to make it at least look slightly realistic?

# Answer
I had to solve a similar problem for my game. I did it using templates. Basically, start by labeling your room with the following:

```
enum TileState
{
    Floor, // An unoccupied free cell
    Wall,  // A cell occupied by a wall
    Edge,  // An unoccupied cell on the edge of the room (like a door)
    Object // A cell occupied by an object
}

```

Then, you can create templates sort of like this:

```
// This template corresponds to an object in the corner.
TileState[][] cornertemplate = { { Wall,  Wall},
                                 { Wall, Object} };

```

Now, you can try a bunch of random x, y locations and rotations of the template, and see if the template is *valid*. In this context, a template is *valid* whenever all the `Wall` tiles are occupied by a wall, and all of the `Object` tiles are currently free (either `Floor` or `Edge`). Whenever the template is valid, create an object at the appropriate place.

You can make more complicated templates by overlaying them on top of each other, or stringing them together. For instance, you can require a chair always be next to a table. Here is a room I generated using this approach:

In this case, the tables had a template that required all the space around them to be free of walls. The bookshelves had to be up against at least one wall, and the lamps had to be in corners.
> 7 votes

---
Tags: procedural-generation, random, content-generation
---


# Question
Title: Why should i set glClearColor and setProjectionMatrix in render method many time in LibGDX?
```
import com.badlogic.gdx.Game;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;

public class MyGame extends Game {
    public OrthographicCamera camera;
    public SpriteBatch        batch;
    //..

    @Override
    public void create() {
        //..
        batch = new SpriteBatch();

        Gdx.gl.glClearColor(0, 0, 0, 1);
        batch.setProjectionMatrix(camera.combined);
    }

    @Override
    public void render(float delta) {
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        //..
    }

```

In LibGDX Doc
**Gdx.gl.glClearColor(0, 0, 0, 1);** and **batch.setProjectionMatrix(camera.combined);**
is setting in *render()* method at a time.
I use this definitions in *create()* method at once, and it is running perfect.

So why should i use this definitions in *render()* method? is't it a performance loss?

# Answer
> 1 votes
Setting the glClearColor, as Josh Petrie said, is only necessary to do every frame if you do not know if another part of your program is changing it. Although, usually you would be drawing your own background, which would cover the entire background, so the color should not matter. (Of course, you still need to clear the screen every frame to prevent possible ghosting, but you understand that)

As for setting the projection matrix, it is important that you call this every frame, if you have a moving camera. If you never need to call `camera.update()`, which is done after you change one of the camera's attributes, then you also need to update the batch's projection matrix. This is because the batch, or as I would assume for your case, specifically the SpriteBatch does not directly use the camera's projection matrix, instead it sets its own projection matrix to the same values as the camera's matrix, like so:

```
//within SpriteBatch
@Override
public void setProjectionMatrix (Matrix4 projection) {
    if (drawing) flush();
    projectionMatrix.set(projection); <-- this line
    if (drawing) setupMatrices();
}

```

And the camera's projection matrix, or in your case, the combined matrix, is changed in every `camera.update()` call:

```
//this is in OrthographicCamera
@Override
public void update (boolean updateFrustum) {
    projection.setToOrtho(zoom * -viewportWidth / 2, zoom * (viewportWidth / 2), zoom * -(viewportHeight / 2), zoom
        * viewportHeight / 2, near, far); <-- this line
    view.setToLookAt(position, tmp.set(position).add(direction), up);
    combined.set(projection); <-- this line
    Matrix4.mul(combined.val, view.val); <-- and this line

    if (updateFrustum) {
        invProjectionView.set(combined);
        Matrix4.inv(invProjectionView.val);
        frustum.update(invProjectionView);
    }
}

```

So, unless your not ever moving your camera or changing any of its attributes, then it is safer for you to set the projection matrix every frame.

For example, the Scene2D's Stage resets it every frame:

```
public void draw () {
    Camera camera = viewport.getCamera();
    camera.update(); <-- updates the camera

    if (!root.isVisible()) return;

    Batch batch = this.batch;
    if (batch != null) {
        batch.setProjectionMatrix(camera.combined); <-- resets the matrix
        batch.begin();
        root.draw(batch, 1);
        batch.end();
    }

    if (debug) drawDebug();
}

```

# Answer
> 2 votes
> In LibGDX Doc Gdx.gl.glClearColor(0, 0, 0, 1); and batch.setProjectionMatrix(camera.combined); is setting in render() method at a time. I use this definitions in create() method at once, and it is running perfect.
>
> So why should i use this definitions in render() method? is't it a performance loss?

The clear color is part of your OpenGL context state and, once set, will not be changed or reset unless you (or some code you call) does so. Consequently, you need only call `glClearColor` once during initialization if you know you (and all code you call) will never again change it.

You *can* call it per-frame if you like, especially if your code calls out to external code you aren't in control over and whose actions cannot be determined when you write your own code (such as plugins). But you don't need to. Generally the "performance impact" of doing so will be non-measurable.

The same is true of setting the state for the projection matrix; you only need to do it once, unless you need to change it or restore it after some other code has potentially changed it.

That sample code is just that: sample code. It's design to clearly and concisely illustrate a point.

# Answer
> 0 votes
Edit: As usual, I've not paid attention and answered a GL question with DirectX code; sorry... Although the API differs, the idea is very much the same.

It will technically qualify as a performance loss, but it may be unavoidable. Ideally, you only want to notify the video card of *changes* to "whatever is current". Since you are in complete control of the process, you can reliably predict the "current state" throughout a render.

This code demonstrates two cases:

```
//Current topology doesn't matter
if (someBool)
{
    context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP);
    ...
    context->GSSetShader(...); //Activate geometry shader
    context->Draw(...);
    context->GSSetShader(NULL); //De-activate geometry shader here
}
//context->GSSetShader(NULL); //Not here; it *might* not be active
//Current topology *might* be POINTLIST
//Have to set it every time and eat the performance hit
context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_POINTLIST);

```

this adheres to reporting only changes more strictly, but the performance gain may not be noticable:

```
//If we **know** that the current topology will be POINTLIST, we can even omit the else
if (someBool)
{
    context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP);
    ...
    context->GSSetShader(...); //Activate geometry shader
    context->Draw(...);
    //Undo everything done
    context->GSSetShader(NULL); //De-activate geometry shader here
    context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_POINTLIST);
}
else context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_POINTLIST);
//Current topology is now POINTLIST regardless

```

another:

```
if (cameraMatrixDirty) //Don't "set" it, if it's already set
{
   batch.setProjectionMatrix(camera.combined)
   cameraMatrixDirty = false;
}

```

In the worst case, you have added an if() that evaluates to false every frame.
In the best case, you have saved XX redundant state calls.

Drawing A,B,C because that's how it makes the most sense to you is fine, to get the basic code written. In the end, you're asking the GPU to draw it, not yourself, so it needs to make the best sense to it. Drawing C,A,B, instead of A,B,C, may save you many state changes and produce identical on-screen results.

---
Tags: opengl, java, libgdx, rendering, projection-matrix
---


# Question
Title: how to stop camera at the end of world map when zoomed in
Im building a tile-based game, and Im trying to implement zooming in on the center of the screen. My problem is, when I get to the edge of the map and im zoomed in, Im noticing that my camera doesn't scroll all the way to the very last tile when zoomed in. If my zoom scale value is 1(not zoomed in), the camera moves to the last edge of the tile map just fine.

I have a feeling my matrix math is wrong, and I should be setting the position of the camera differently. It could also be that my tile map edge checking is incorrect. I currently limit the user to zoom in by a factor of 2 at maximum

Heres my code:

```
public class CameraPositionComponent : PositionComponent
{
    private Vector2 mOrigin;
    private Viewport mViewport;
    private Matrix mMatrix;
    private float mZoom;

    public CameraPositionComponent(int x, int y, Viewport viewport, Entity owner) :   base(x, y, owner)
    {
        mZoom = 1.0f;
        mViewport = viewport;
        mPosition = new Vector2(viewport.Width / 2, viewport.Height / 2);
        mOrigin = new Vector2(viewport.Width / 2, viewport.Height / 2);
        mMatrix = Matrix.CreateTranslation(1, 1, 1);
    }

    public Matrix Matrix
    {
        get { return mMatrix; }
        set { mMatrix = value; }
    }

    public float Zoom
    {
        get { return mZoom; }
        set { mZoom = value; }
    }

    public Vector2 Origin
    {
        get { return mOrigin; }
        set { mOrigin = value; }
    }

    public Viewport Viewport
    {
        get { return mViewport; }
    }
}

public class CameraTouchComponent : TouchComponent
{

    public CameraTouchComponent(Entity owner) : base(owner)
    {

    }

    public override void Update()
    {
        GameTime gameTime = ServiceLocator.GetService<GameTime>();
        Camera camera = mOwner as Camera;
        CameraPositionComponent positionComponent = camera.PositionComponent;

       /////input handling here
      ////zoom/drag etc..

        if (positionComponent.Position.X < positionComponent.Viewport.Width / 2)
            positionComponent.Position = new Vector2((positionComponent.Viewport.Width / 2), positionComponent.Position.Y);
        if (positionComponent.Position.Y < positionComponent.Viewport.Height / 2)
            positionComponent.Position = new Vector2(positionComponent.Position.X, positionComponent.Viewport.Height / 2);
        if (positionComponent.Position.X + positionComponent.Viewport.Width/2 > TileMap.Width)
            positionComponent.Position = new Vector2(TileMap.Width - positionComponent.Viewport.Width/2,
                positionComponent.Position.Y);
        if (positionComponent.Position.Y + positionComponent.Viewport.Height / 2 > TileMap.Height)
            positionComponent.Position = new Vector2(positionComponent.Position.X,  TileMap.Height - positionComponent.Viewport.Height / 2);
        //positionComponent.Origin = new Vector2((positionComponent.Viewport.Width / 2) / positionComponent.Zoom, (positionComponent.Viewport.Height / 2) / positionComponent.Zoom);

        Layer layer = LayerManager.GetLayerOfEntity(mOwner);
        layer.Matrix =  Matrix.CreateTranslation(new Vector3(-positionComponent.Position, 0)) *
                  Matrix.CreateScale(positionComponent.Zoom, positionComponent.Zoom, 1) *
                   Matrix.CreateTranslation(positionComponent.Origin.X, positionComponent.Origin.Y, 0); ;

    }
}

```

All the bounds checking stuff seems wrong to me as well.

# Answer
for anyone else wondering how to do this. Try this:

http://www.david-gouveia.com/portfolio/limiting-2d-camera-movement-with-zoom/
> 0 votes

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


# Question
Title: Unity 5 - Error with code to make pitch changes based on distance
I really need help. It's 2:00 AM here and my brain is half dead so I can't, for the life of me, find out what's wrong with this code anymore. It's supposed to find the distance between the game object to which it's attached (the target), and another game object (the player). Then, depending on the that distance, it should change the pitch of an AudioSource inside a child (in the player). However, the pitch only changes when I'm practically over the gameobject. So, for about 9/10 of the way, nothing changes in the pitch, but when I'm right there the pitch suddenly changes (but not to maximum value of Clamp function).

What's going on? I want the pitch to, at first, stay at 0. But soon after you walk some steps in the right direction, the pitch must change gradually (and in a evenly manner), as (player) gets closer to (target). =|

ps.: The script is inside a instantiated prefab, that's why I used FindGameObjectWithTag and FindChild. Also, I'm using Unity 5.

```
<!-- language: lang-cs -->

[four blanks]using System.Windows.Controls;
[more indented code]

using UnityEngine;
using System.Collections;

 public class ProximitySensor : MonoBehaviour {
     public GameObject player;
     private Transform playerTrans;
     private Transform targetTrans;
     public Transform beepTrans;
     public AudioSource beepSound;
     private float distanceCurrent;

     void Start () {

         targetTrans = transform;
         player = GameObject.FindGameObjectWithTag("Player");
         playerTrans = player.transform;
         beepTrans = playerTrans.FindChild ("beepController");
         beepSound = beepTrans.GetComponent<AudioSource>();

     }

     void Update () {

         distanceCurrent = Vector3.Distance (playerTrans.position, targetTrans.position);
         beepSound.pitch = Mathf.Clamp ((1 / distanceCurrent), 0.1f, 3.0f);

     }
 }

```

# Answer
```
beepSound.pitch = Mathf.Clamp ((1 / distanceCurrent), 0.1f, 3.0f);

```

Working backwards:

```
The maximum distance is (1 / 0.1f) = 10.0
The minimum distance is (1 / 3.0f) = 0.33

```

I suspect you have accidentally ignored the exponent on "2.94"

```
1 / 3400.774 = 2.94E-4 == 0.00029405 //clamped for a good, long while

```

Try:

```
float percent = Mathf.Clamp((distanceCurrent - distanceMinimum) /
  (distanceMaximum - distanceMinimum), 0.0f, 1.0f); //Percentage between min and max
percent = 1.0f - percent; //invert so larger distances decrease pitch
//beepSound.pitch = beepMin + ((beepMax - beepMin) * percent);
//beepSound.pitch = 0.1f + ((3.0f - 0.1f) * percent);
beepSound.pitch = 0.1f + (2.9f * percent);

```

This lerps the pitch based on the inverse-lerp of distanceCurrent.

If you prefer a curved function rather than linear:

```
percent = 1.0f - percent;
percent *= percent; //squared; 1=1 and 0=0, but 0.5 (distance) now equals 0.25 (beep)

```

or:

```
percent = sqrt(percent); //square root; 1=1, 0=0, 0.25 = 0.5

```
> 1 votes

---
Tags: unity, sound, audio
---


# Question
Title: Switching renderer off/on for an object in unity using C#
I have a GameObject called 'Stone' that is rendered on Game Play. I have attached a C# script called RenderOff to to make 'Stone' invisible on Game Play.

**RenderOff.cs**

```
using UnityEngine;
using System.Collections;

public class RenderOff : MonoBehaviour {

    void Start () {

        this.gameobject.renderer.enabled = false;

    }

}

```

It has errors - **Type 'RenderOff' does not contain a definition for `gameobject' and no extension method`gameobject' of type \`RenderOff' could be found**.

What does that mean ?

# Answer
`gameObject` is case-sensitive.

If you're using Unity 4.x, you should be able to disable a renderer like so:

```
this.gameObject.renderer.enabled = false;

```

If you're using Unity 5.x, the shortcut to `.renderer` has been removed. Instead, you'll need to call:

```
this.gameObject.GetComponent<Renderer>().enabled = false;

```

Note too that you can also get away with not using `this.gameObject`, and just use `gameObject` instead:

```
gameObject.GetComponent<Renderer>().enabled = false;

```
> 5 votes

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


# Question
Title: Hundreds or even thousands of "slow" running CPUs emulated on GPU?
# Introduction

This question is specific to GPU programming. It's not primarily about the game idea.
However, to better understand the question i will detail what it is i want to achieve in my game.

Development will happen with an NVidia GeForce GTX 980, no AMD/ATI specific hardware is available, in case it matters.

I haven't written a single line of code yet but i would do so in C# using one of the DirectX libraries in existence for .NET, such as SharpDX.
I don't possess all the required knowledge on the subjects i am about to ask about, please forgive my ignorance and/or incorrect nomenclature.
Also, please bare in mind that while I am not educated on the subject, i am absolutely willing to learn. I am merely considering/researching my idea at this time.

# The basic idea (*the game*)

The "game" won't be graphically intensive, instead it will be computationally intensive running a "simulated world" running hundreds or even thousands of small programs on the GPU.
Each program is independent from each other except for basic intercommunication, which is detailed below.

The only "heavy" graphics i can think of right now is displaying each virtual machine and possibly some blinky lights as they communicate and/or runs instructions. Drawing lines between machines that are "physically" connected to each other. Sort of like a map of the world.
As well as drawing the command line of course. But nothing fancy, most computation time would be dedicated to the simulation.

My basic idea is to have a network of computers in a sandbox like "game" controlled from a command line. The command line that the player uses is a separate "computer", the one where the player is sitting at in the "game" world.
This is the game interface, it has the power to create computers in the simulated (on GPU) network, as well as "physically" interacting with the simulated network, such as powering on/off computers (Terminating GPU threads and starting new ones), uploading programs to run on a specific computer, "plugging in" network cables and altering the computers hardware.

The players computer would run on the CPU.

The network should all be capable of communication between each computer, as well as the players computer.

I want each computer to run a CPU architecture, such as x86. Obviously x86 may be too ambitious, i would be fine with the most basic architecture.
**IF** an architecture, any in existence, would "too much" then a scripting language would be fine as well but optimally, a compiler would be used. Such as a C compiler for the architecture emulated.

Each computer would have ONE compiled program running each. That program would have to take care of everything that computer does, including IO, network communications, bla bla.
As i've pointed out already, speed isn't important. Each machine could run at 20 Hz (IPS, Instructions Per Second) each, higher speeds would of course be better.

Each machine would have it's own memory, storage medium and CPU and would be upgradable, so each machine could be different in speed, memory capacity and storage capacity.
The storage should be saved between game sessions, optimally the storage would be saved on the real world (physical) storage of the computer's hard drive, in case the game stops unexpectedly then each machines "physical" storage would survive... Even if a corruption would occur because a write operation never finished. /details...

# Questions

1. Is this viable/possible?
    * Is there a specific approach that is more viable than all others? Why?
    * Which approach is easier? Taking into account my lack of knowledge on the subject of writing CPU emulators.
    * GPU/CPU intercommunications, especially where each machines storage is concerned... Is it a good/bad idea?
2. Networking... Can several CUDA/OpenCL threads communicate with each other as a network?
    * Taking CPU emulation into account, is communication still possible? If my compiled program running on a machine writes to a specific memory address in the emulation, can that then be transmitted to another GPU thread for reading in emulated memory?
    * Buffering... Suppose several machines "send" packets to one machine, is it possible to have a stack? I "know" how to approach the problem in C#/.NET but i've never actually written a GPU program besides the most simple of things, such as Game of Life type deals and it was quite a while ago.
3. Is there something within this idea that isn't possible?
4. On a scale from 1 to 10, how difficult would it be to do this GPU side vs keeping it CPU side? (That is, comparatively speaking if i had the knowledge to do it on the CPU)
5. **Should i continue researching/implementing my idea or do you think i am wasting my time?**

Thank you for your time.

# Answer
That is not what the GPU is for. You will be facing a lot of pain, and won't get much in result.

As others have pointed out, the GPU is designed to run the exact same program on multiple sets of data at the same time, and get the results when they finish.

As so, the GPU is not designed for branching, inter-thread communication and so on.

Do this in the CPU instead, where this kind of stuff is much easier to implement. You will probably even be wasting a lot of CPU cycles preparing data for your GPU program, possibly even much more than what the actual program will consume.

I understand that you may consider your GPU wasted since you're not using it for this task. However, remember that the GPU is a special purpose hardware, which is designed for that specific purpose. There are other processors, such as the BIOS, and the sound card processor that you're not using, yet you don't see that as a problem.

If you're worried about creating many threads, and thread thrashing, consider using fibers or coroutines if your language supports them, to run all those processes in one thread (or as many threads as cores your CPU has)
> 4 votes

# Answer
As with every "Will it be fast enough" question, the proper answer is: Profile it.

Below is my speculation on your case.

I have no experience with CPU emulation, I will base my performance guesses on the performance of Lua, which is said to be the fastest scripting language.

---

First off, I think using the GPU is not suitable. Your usage defeats what the GPUs are made for: One program running on a lot of threads. Also GPUs don't support intercommunication and conditionals very well.

But your expectations are quite low. 20Hz for lets say 10 000 computers. Nowadays you can count with a 3GHz CPU, with multiple cores. For simplicity lets assume you only have a single thread for this virtual simulation. I am also going to assume that the Lua code(or the one of your choice) is 10 times slower, than compiled C/++ code(Can be improved with LuaJIT, but will be worse due to constant switching between computers and cache misses, etc.).

20 * 10 000 * 10 = 2 000 000 Hz needed to simulate your virtual computers. or 2 000kHz. or 2 MHz. And you can safely assume a computer with a ~3GHz core.

Please bear in mind that due to cache misses, memory operations, and because you probably underestimated your instruction needs you will need much more than 2MHz, but you are safe as long as you don't need more than ~1500 times more power.

I think this idea is viable performance-wise. I would recommend using Lua, so you don't have to reinvent the wheel, and have a solid base to build on. Its also easier to program for starters(if you want your players to program them).

This is pure speculation. If you want a real answer, profile it.

As to whether you should research further or not, you should create a simple prototype(throwaway), which will test both if your game is fun and if its viable performance-wise.
> 2 votes

---
Tags: gpu, gpgpu, emulation, cuda
---


# Question
Title: Implementing FSM on multiple class UNITY3D
I am recently implementing design patterns on my project, while researching around I came across many advance techniques like HFSM ,Behaviour trees.

I did implemented behavior trees wherever required in project, though I am quite confused over how to implement FSM on multiple classes of same game object.

For example, suppose my object is running and he has following classes,

```
Score.cs,

Inputs.cs,

MovementController.cs

PlayerController.cs

xyz.cs,

Abc.cs

```

Coming to my main point,how can I implement state machine which will dynamically change code in the above multiple scripts as state changes.

The only work around I can think of is using one main game manager script which will pass event to this scripts as state changes and all the classes will catch events and will run accordingly. But problem with this approach is this,code will fall if multiple coroutines are running on given scrips and how all scripts will get on same paper at once?

# Answer
I found it a little bit difficult to follow the entire thread of your question.

However at the most basic level, in a simple FSM you could either just query the current state of your StateMachine (i.e. assuming its a singleton manager class etc : StateMachine.Instance.GetState ) and then do the necessary long-winded if or switch statement logic depending on which state is returned.

Alternatively, for something a bit more loosely coupled and dynamic you could just have each relevant Class subscribe to a OnStateChanged event equivalent and react to specific states with callbacks.

There isn't a right way to implement a FSM, however you can take a steer from one of the many online resources eg:

http://www.reddit.com/r/Unity3D/comments/2f6esc/c\_need\_help\_understanding\_a\_finite\_state\_machine/

http://www.voidinspace.com/2013/05/a-simple-finite-state-machine-with-c-delegates-in-unity/

------ EDIT UPDATE ------

The idea is that if you're going to roll your own GameStateManager in the Unity engine, then each state would essentially have it's own methods such as Update etc. These methods would execute sequentially as per the norm.

You could manage your state transitions with a State stack container. This way multiple states could be queued up and pushed into the stack, and then executed in order i.e. GameState--\>MenuState--\>ControlsMenuSubState etc. At the end of each frame you could then do some bookkeeping and check if it's OK to roll onto the next state i.e. pop the current state and then execute the next state object on the GameState stack.

It does sound like you're overcomplicating things by coupling each class to each State of the game. The classes generally shouldn't know or care which state they're in as it's the State's job to call into other classes, not the other way around.

Unity's normal Scene methodology is also suitable. You could just use Scenes to transition between major games states, and then use the Unity GUI for Overlay states such as Inventory or Menu states which need to run in the current state. All you would need is at least 1 object to maintain your meta game state between scene transitions.
> 0 votes

---
Tags: c#, unity, design-patterns
---


# Question
Title: Understanding animations of controllable characters
I am a newbie trying to learn basics of Unity3D (5) before starting to do the real thing. Even though I tagged it as Unity3D, the logic should be the same for every kind of game engine. So I will be glad if you share your experience even though you do not use Unity.

Assume that you are importing the "Lamp" character (fbx) of Pixar. (Jumping, moving forward by little jumps, etc..)

OR

Assume that you are basicly importing a humanoid model with animations from Unity Asset Store. (I know that they generally include controllers too, assume that there are no controllers)

In unity, I want to make the character jump so I use jump animation. But I really want to make it jump. Also when I move it forward I really want it to move forward by appying a force or setting it's velocity. These will probably will not match the animation and even if they match, my own physics manipulations will be mixed with the animation's transformations. Even if I put the animation/object into another GameObject, it changes the position and/or rotation of the parent gameobject. So, animation changes those values and I also change them myself... The result will be the combination of all which is very hard -if not impossible- to sync or calculate.

The same thing is valid for almost every animation including Jumping. For example, the animation jumps and I also make the object jump.. It will create a double jump.. If I only let animation does that, I won't be able to control how it really behaves and If I make the animation look like it's crouching (actually jumping, but transformed to 0,0 in every frame, so in Unity changing the vertical position will fix it...) it will be hard to sync too.

What am I missing here? What is the guideline here?

# Answer
> 1 votes
The Unity Mecanim animation engine uses the concept of Root Motion to drive it's animations (assuming the animation contains the appropriate data).

If you'd rather move/rotate the gameObject yourself then you can disable an animation's root motion in each individual animation during the asset import process in the 'Animation' tab. That would allow you to then drive the animations transforms using a script etc.

I believe what you're looking for is in the following reference material : http://docs.unity3d.com/Manual/ScriptingRootMotion.html

Basically, if you override the 'void OnAnimatorMove()' method in a MonoBehaviour script which is attached to your animated gameObject, then the Animator component will recognise that the gameObject's animations are to be "Handled By Script".

---
Tags: unity, animation, unityscript, fbx, rigging
---


# Question
Title: How can I implement hexagonal tilemap picking in XNA?
I have a hexagon tiled map in which I need to check when a hexagon is clicked. The hexagons aren't actually touching, rather they have a slight gap in between each of them.

Does anyone know how could I go about checking whether a hexagon is clicked without over complicating the whole thing?

# Answer
Take a look to this picture

As you can see there is a relatively intuitive way to map x,y rectangular coordinate system to the hexagonal one.

We may talk about "rect" irregular hexagons ie hexagons inscribed in ellipses or hexagons obtained from regular hexagons scaled in both directions disproportionately (no rotations-shearings).

A rect hexagon can be defined by the height and width of the circumscribing rectangle plus the width of the inscribing one. (W,w,h)

The easiest way to find out the hexagonal index is to partitionate the space as follow:

The rectangle width is w + (W - w)/2 = (w + W)/2, its height is h/2; the width of the green rectangle is (W-w)/2. Is easy to find out where in which rectangle the point falls:

u and v are the reminder coordinates that indicates where the point is whithin the i,j rectangle: Using w we can say if we are in the green area (u \< (W-w)/2) or not.

if it is the case we are in the green area we need to know if we are in the upper or lower half of the hexagon: we are in the upper half if i and j are both even or both odd; we are in the lower half otherwise.

In both cases it is usefull to trasform u and v so they vary between 0 and 1:

if we are in the lower half **and** v \< u

or

if we are in the upper half **and** (1-v) \> u

then we decrement i by one

Now we simply have to decrement j by one if i is odd to see that i is the horizontal hexagon index (column) and the integer part of j/2 is the vertical hexagon index (row)
> 13 votes

# Answer
Regular hexagons have six axes of symmetry, but I will assume your hexagons only have two axes of symmetry (*ie.* all angles are not exactly 60-degrees). Not necessarily because yours don't have the full symmetry, but because it may be useful to someone else.

Here are the parameters of one hexagon. Its centre is in `O`, the largest width is `2a`, the height is `2b`, and the length of the top edge is `2c`.

```
         Y ^
           |
       ____|____
      /  b |   |\
     /     |   | \
    /      |   |  \
---(-------+---+---)------>
    \     O|   c  / a      X
     \     |     /
      \____|____/
           |

```

This is the row/column layout, with the origin at the centre of the lower left hexagon. If your setup is different, translate your `(x,y)` coordinates to fall back on this case, or use `-y` instead of `y` for instance:

```
col 0
 | col 1
 |   | col 2
 |   |  |
 __  | __    __    __    __
/  \__/  \__/  \__/  \__/  \__
\__/  \__/  \__/  \__/  \__/  \
/  \__/  \__/  \__/  \__/  \__/
\__/  \__/  \__/  \__/  \__/  \
/  \__/  \__/  \__/  \__/  \__/_ _ line 2
\__/  \__/  \__/  \__/  \__/  \ _ _ _ line 1
/ .\__/  \__/  \__/  \__/  \__/_ _ line 0
\__/  \__/  \__/  \__/  \__/

```

The following code will then give you the row and column of the hexagon containing point `(x,y)`:

```
static void GetHex(float x, float y, out int row, out int column)
{
  // Find out which major row and column we are on:
  row = (int)Math.Floor(y / b);
  column = (int)Math.Floor(x / (a + c));

  // Compute the offset into these row and column:
  float dy = y - (float)row * b;
  float dx = x - (float)column * (a + c);

  // Are we on the left of the hexagon edge, or on the right?
  if (((row ^ column) & 1) == 0)
      dy = b - dy;
  int right = dy * (a - c) < b * (dx - c) ? 1 : 0;

  // Now we have all the information we need, just fine-tune row and column.
  row += (column ^ row ^ right) & 1;
  column += right;
}

```

**Edit**: if your coordinate system merges rows 0 and 1 into a single row, as well as rows 2 and 3, and so on, then you can adjust it using this formula:

```
row = (row - (row & 1)) / 2;

```
> 15 votes

# Answer
You could fit 3 rotated rectangles inside the area of the hexagon, and if done properly it would fill the area exactly. Then it would be simply a matter of checking for collision on the three rectangles.
> 1 votes

# Answer
You probably don't need to de-register clicks between the tiles. That is to say, it won't hurt and might even help the player if you allow the spaces between tiles to be click-able as well unless you are talking about a large space between them that is filled with something that logically shouldn't be clicked. (Say, the hexes are cities on a large map where in-between them are other click-able things like people)

To do the above, you can simply plot the centers of all the hexes, and then find the nearest one to the mouse when clicked on the plane of all the hexes. The nearest center on a plane of tessellated hexagons will always be the same one you are hovering over.
> 1 votes

# Answer
I've already answered a similar question, with identical goals, over on Stack Overflow I'll repost it here for convinience: (NB - all code is written and tested in Java)

This image shows the top left corner of a hexagonal grid and overlaid is a blue square grid. It is easy to find which of the squares a point is inside and this would give a rough approximation of which hexagon too. The white portions of the hexagons show where the square and hexagonal grid share the same coordinates and the grey portions of the hexagons show where they do not.

The solution is now as simple as finding which box a point is in, then checking to see if the point is in either of the triangles, and correcting the answer if necessary.

```
private final Hexagon getSelectedHexagon(int x, int y)
{
    // Find the row and column of the box that the point falls in.
    int row = (int) (y / gridHeight);
    int column;

    boolean rowIsOdd = row % 2 == 1;

    // Is the row an odd number?
    if (rowIsOdd)// Yes: Offset x to match the indent of the row
        column = (int) ((x - halfWidth) / gridWidth);
    else// No: Calculate normally
        column = (int) (x / gridWidth);

```

At this point we have the row and column of the box our point is in, next we need to test our point against the two top edges of the hexagon to see if our point lies in either of the hexagons above:

```
    // Work out the position of the point relative to the box it is in
    double relY = y - (row * gridHeight);
    double relX;

    if (rowIsOdd)
        relX = (x - (column * gridWidth)) - halfWidth;
    else
        relX = x - (column * gridWidth);

```

Having relative coordinates makes the next step easier.

Like in the image above, if the **y** of our point is **\> mx + c** we know our point lies above the line, and in our case, the hexagon above and to the left of the current row and column. *Note that the coordinate system in java has y starting at 0 in the top left of the screen and not the bottom left as is usual in mathematics, hence the negative gradient used for the left edge and the positive gradient used for the right.*

```
    // Work out if the point is above either of the hexagon's top edges
    if (relY < (-m * relX) + c) // LEFT edge
        {
            row--;
            if (!rowIsOdd)
                column--;
        }
    else if (relY < (m * relX) - c) // RIGHT edge
        {
            row--;
            if (rowIsOdd)
                column++;
        }

    return hexagons[column][row];
}

```

---

A quick explanation of the variables used in the above example:

m is the gradient, so **m = c / halfWidth**

---

## NeoShamam's addition to the above

This is an addendum to SebastianTroy's answer. I would leave it as a comment but I don't enough reputation yet.

If you want to implement an axial coordinate system as described here: http://www.redblobgames.com/grids/hexagons/

You can make a slight modification to the code.

Instead of

```
// Is the row an odd number?
if (rowIsOdd)// Yes: Offset x to match the indent of the row
    column = (int) ((x - halfWidth) / gridWidth);
else// No: Calculate normally
    column = (int) (x / gridWidth);

```

use this

```
float columnOffset = row * halfWidth;
column = (int)(x + columnOffset)/gridWidth; //switch + to - to align the grid the other way

```

This will make the coordinate (0, 2) be on the same diagonal column as (0, 0) and (0, 1) instead of being directly below (0, 0).
> 1 votes

# Answer
If all your hexagons are made using the same proportions and placing, you could use some sort of overlay asset for the collisions, something along the lines of:

Then, all you have to do is place the collision image where your hexagon is, get the mouse position relative to the left corner, and see if the pixel of the relative position is NOT white (which means there is a collision).

Code (not tested):

```
bool IsMouseTouchingHexagon(Vector2 mousePosition, Vector2 hexagonPosition,
    Rectangle hexagonRectangle, Texture2D hexagonImage)
{
    Vector2 mousePositionToTopLeft = mousePosition - hexagonPosition;

    // We make sure that the mouse is over the hexagon's rectangle.
    if (mousePositionToTopLeft.X >= 0 && mousePositionToTopLeft.X < hexagonRectangle.Width &&
        mousePositionToTopLeft.Y >= 0 && mousePositionToTopLeft.Y < hexagonRectangle.Height)
    {
        // Where "PixelColorAt" returns the color of a pixel of an image at a certain position.
        if (PixelColorAt(hexagonImage, mousePositionToTopLeft) == Color.White)
        {
            // If the color is not white, we are colliding with the hexagon
            return true;
        }
    }

    // if we get here, it means that we did not find a collision.
    return false;
}

```

You could obviously perform a rectangle collision check beforehand (of your whole hexagon image) to improve performance of the whole process.

The concept is quite simple to understand and implement, but only works if your hexagons are all the same. It could also work if you only have a set of possible hexagon dimensions, which would then mean that you would need more than one collision overlay.

If find it to be a very simplistic solution to what could be a lot more complete and reusable (using maths to really find the collision) but it's definitely worth a try in my opinion.
> 0 votes

# Answer
There's an article on Game Programming Gems 7 called **For Bees and Gamers: How to Handle Hexagonal Tiles** which would be exactly what you need.

Unfortunately I don't have my copy of the book with me at the moment, otherwise I could have described it a little.
> 0 votes

---
Tags: c#, xna, hexagonal-grid
---


# Question
Title: Entity Component System, How to decouple components need for entity as parameter?
I use Artemis entity system framework, C# port. I have problem with figuring out a good way to handle items and using them.

Game is AI driven mostly, so it's not the player that is interacting, but AI. AI is basically Entity with `AIBehaviorComponent` that is ran by `AISystem`. AI has helper functions that allows it to find all items (ie. Entities with `InteractiveComponent`) and then it can pathfind to it and use that item. AI is using `BehaviorTree` that is stored in it's component.

I have `InteractiveComponent`that allows player and AI to `Use` entity. I have this thing working, but it looks a bit dirty solution. `Use` method is interface that is implemented by Item object that is tied to that component. This way i can have item made with:

```
new InteractiveComponent(new AwesomeItem());

```

Calling `Use` requires me to:

1. Get entity ref
2. Find component 'InteractiveComponent\`
3. interactiveComponent.use(me)

`me` is (this) Entity. The AI entity that is calling the use. I am passing entity to `Use` method, because using something can alter the entity. It could add component to it, check if it has certain component and then modify the data or remove components, it could even remove the entity.

---

So, I'm bit lost here. This works, so it's "ok" i guess, but it looks very dirty. I have not found a way to allow somekind of `InteractiveSystem` to take care of item using without adding huge complexity issues ( Those arise quickly when you try to force Entity system to do something it does not easily allow ).

So, question is:

**How to decouple this so, that i don't have to pass Entity to component?**

I just don't feel good about the current code but so far it's the best solution we have come up with.

# Answer
> I am passing entity to Use method, because using something can alter the entity. It could add component to it, check if it has certain component and then modify the data or remove components, it could even remove the entity.

So you're passing the `Entity` to `Use` because `Use` could (effectively) "do anything" with the entity, but you want to come up with a way to *not* pass the entity?

This is pretty straightforward: *change your design*. Define more concretely what you want `Use` to be permitted to do to a thing, and pass it a reference to some interface exposing what it is allowed to do. Otherwise accept that your current design needs the entity in `Use` because `Use` is allowed to do almost anything to an entity.

There are lots of different ways you could reorganize this to make it look or feel different, but fundamentally if your fixed principle is that "using a a thing can *mutate the using entity*, you're going to need to give it the entity, and what you have now seems like a reasonably straightforward approach to that (your dependencies in `Use` are explicit; this is a *good thing*).
> 1 votes

---
Tags: entity-system
---


# Question
Title: Unity: how do I edit a second scene when my objects are still in the first?
I have my game set up so that objects like the `Canvas` and the main character are set to `DontDestroyOnLoad`; they're only initiated in the first scene. However, this means that when I load my second scene in the editor, those objects aren't there yet.

I could copy and paste them over, but then the objects in the second scene will be duplicates of the ones in the first.

This is a problem because I can't, for instance, create a public variable on the character controller and attach an object from the second scene to it. The character doesn't exist in scene 2 yet and the object doesn't exist in scene 1.

# Answer
Prefabs are the way forward. In my opinion, every single entity should be a Prefab, even if you're going to only instantiate it once into the scene hierarchy (like a management singleton class etc). This'll save you many headaches down the line. A change to the Prefab will propagate to every instance in the entire project.

Additionally, take a look at the new SceneManager API in Unity5. Could be useful for your project : http://blogs.unity3d.com/2014/08/04/multi-scene-editing/

For gameObjects you wish to have in each scene such as a singleton manager etc, then you could use a simple pattern such as this:

```
public class myClass : MonoBehaviour {
     public static myClass i;

     void Awake () {
         if(!i) {
             i = this;
             DontDestroyOnLoad(gameObject);
         }else
                 Destroy(gameObject);
     }
...

```
> 3 votes

# Answer
The most efficient way to do this is through prefabs. In each scene you can just drop the prefab in and be off and running. The great thing is that when you need to make a change to an object, you can just jump into your prefabs and make the change to the prefab. This prevents you from having to go to every scene individually to make the change. It's a huge time saver.
> 0 votes

# Answer
The best approach varies a lot depending on exactly what you are doing. You could make the shared object a prefab like most other answers are suggesting; that approach could work well for many kinds of objects. (fyi those explanations are forgetting to mention a crucial bit you need; every scene needs to instantiate the prefab)

However you could also call GameObject.Find() or GameObject.FindWithTag() when initializing objects in the new scene; that's slightly less direct for a reference, but could also work well.
> 0 votes

---
Tags: unity, scene
---


# Question
Title: What degree do you need to become a game designer,programmer,developer.etc
I was wintering what degree do you need in order to become a game designer,programmer or developer. P.S i mean people who work for companies such as riot or ubisoft,etc

# Answer
> 3 votes
Well I mean, I believe something like computer science would help. But I think publishers and development studios mainly look for good experience. I'm completely new to game development and I don't have the money to be a full time student. But I'm developing a few very small, but professionally made and presentable games in my spare time to create a portfolio. That should be a good start to getting hired somewhere

You also may want to consider revising your question to be a bit more specific. Do you know what kind of work you want to do? Coding? Animation? Design? There's a LOT that goes into game development. I would recommend researching different career paths in the game industry first.

---
Tags: education
---


# Question
Title: How do i draw depth complexity(overdraw) in directx 11?
I want to read the stencil value in the shader so I can set colors for different depths.

What I understand. Make a loop after the scene is rendered but before is is presented. so a loop with the number of colors(k) and in the loop, use the code:

```
 md3dImmediateContext->OMSetDepthStencilState(RenderStates::DrawDepthDSS, k);

```

This is what I know. What are the other steps? like to send the depth to the shader?

..I have this code for the shader

```
   Texture2D<uint> txStencil : register (t0); // set the corresponding register
float4 PSStencil(float4 pos: SV_Position) : SV_Target
{
    uint stencil = txStencil.Load(int3(pos.xy, 0));

    // debug output
    if (stencil == 1) return float4(0, 1, 0, 1);
    else return float4(0, 0, 0, 0);
}

```

But how do I send the shader the stencil value?

# Answer
1. Clear the stencil to 0, set it to always pass, and increment for passes and z-fails.
2. Draw scene to offscreen target. (are you only outputting solid colors based on stencil?)
3. The stencil is now filled with the number of times the GPU tried to shade each pixel
a. Discard color buffer??
4. Set the stencil to decrement only on passes and only pass when stencil is \>0. The last stencil values to reach 0 will be the "top layer" so we need to render them in reverse order.
5. Activate the appropriate "layer-shader" (or update a color value in a constant buffer)
6. Draw a fullscreen quad. Pixels that have stencil \>0 will be filled with the color and the stencil value decremented for each.
7. Activate the (bottom - 1) layer-shader (or update the color in a constant buffer)
8. ...
9. Lastly, activate the top-most layer shader (or update the color in a constant buffer)
10. Draw a fullscreen quad. Pixels that have stencil \>0 will...

You could draw the quad instanced and supply a per-instance color and/or use the SV\_InstanceID semantic to index into an array of colors. Each instance represents a layer and you can render every layer with one DrawInstanced(...) call.

**Edit:** Misread part of your question. The second parameter of OMSetDepthStencilState() sets a constant value used for comparison. You can set up DrawDepthDSS to only render pixels whose stencil value exactly matches the parameter, using the layer's 1-based index as the second parameter.

```
stencilFunction = GREATER; //Member of DrawDepthDSS
OMSetDepthStencilState(..., 5); //Render only stencil>5 pixels
stencilFunction = EQUAL; //Member of DrawDepthDSS
OMSetDepthStencilState(..., 1); //Render only stencil=1 pixels (top layer)
OMSetDepthStencilState(..., 10); //Render only stencil=10 pixels (9 layers deep)

```

IIRC, the default function is ALWAYS and the parameter is ignored. The source of the color is arbitrary. As it is written, you appear to be copying the depth/stencil buffer and then wanting to sample it. Needing or wanting to do so usually indicates a wrong turn somewhere along the way. Please consider the usage I've presented; the stencil is good at counting up and down, so I make it count up, then down. I tell it what to do and don't ask it for anything.
> 1 votes

---
Tags: directx11
---


# Question
Title: What is a good clock implementation for a multiplayer game?
In cases where players need to send out their times for game state sync, can everyone send out their default timestamp implementation or should something like NTP be used? http://en.wikipedia.org/wiki/Network\_Time\_Protocol

# Answer
> 1 votes
Try Event Driven (No timer needed except for scheduled events):

**Client side.** when client moves or does something. It sents request to server to update itself what's happening.

**Server Side.** Server updates client if any changes occur on his chat room or when something happens on map where players Range of sight needs to be affected, etc.

If you still insist on timer. Use a singular server time. Players just sync server time for it's own when game starts. Then runs it's own timer. It then syncs only when it communicates again to the server when it needs to.

If your game is not server dependent (or not at network at all), example chess with one of the player (or stand alone player) Use your system time as basis for your timer.

---
Tags: timer
---


# Question
Title: Using old planes in video game; copyright?
So i'm developing a small video game for class and for reasons we need to stay away from copyright material. I was wondering if I would have to worry about old WW2 planes being considered copyright material? I could just make some fantasy inspired planes, but i believe having them in the game could be a lot of fun.

# Answer
> 2 votes
> a small video game for class?

I think that copyright issues are not going to be a problem, unless you are going to try and sell it or make it something more than a project for a class. I would say do it, and there should not be any issue with it. If it blows up into something huge later, then read on...

> I was wondering if I would have to worry about old WW2 planes being considered copyright material?

For an actual commercial game, I would say, you have two ways to go about it...

1. You can contact the IP holder (ie Boeing) and ask them if you can use one of their products in your game. This can be a huge pain (getting brand names to do much of anything), and even though you are giving them free advertising, it will cost you a pretty penny and many companies want to have the final say before your game is released and will reserve the right to withdraw their IP on a whim whenever they so wish.
2. You can take some artistic licenses and make your own plane that is loosely based on the one from real life (instead of using the 'Boeing P-12', just call it a 'P-17' or something other than the 'Boeing P-12').

I would strongly suggest against using trademarked products in your game without doing one of those above things... namely the second one (which has the least amount of risk and wasted time associated with it).

If for your class, you make a small project and it has some ww2 period historically accurate planes in it (even by model name), I just don't see that being a problem, but even in the worst case scenario, the IP holder MUST first ask you to take the infringing content out of your game (before they try and defend their IP in court), - if that happens, do it, and then just change the name and the assets a little bit to something non-infringing, then you should be golden.

I am not a lawyer and this is not legal advice.

# Answer
> 2 votes
Typical copyright laws apply. If you are using content created by someone else, you should ALWAYS get permission and pay any licensing and/or royalty fees. The licensing agreement will spell out, in great detail, exactly how and how-not, to use the content. The minimum requirement for most/all agreements is "giving credit" although the specific wording is usually vague. You are required to accept a license agreement when installing software and when creating accounts on content sites; you should **read them**! Many people just click next, next, next, finish, and get disappointed, or in trouble, later. A good rule-of-thumb is that the licensing fee is always cheaper than a lawsuit.

There are sites with "free" content. That means that you do not have to pay money for access to them, but does not automatically imply that you may use and/or redistribute them for your own profit.

Content that YOU MAKE, may be "free", not free, and even "free" stops as soon as YOU make money. If your product will cost money, you are probably restricted from using most/all "free" content, including "game engines", "development tools", textures, models, sounds. Unity, a development tool, is "free", but forces you to display their splash screen to your end users. This could also manifest as a "watermark" across every texture you create until you buy "pro".

Since you state that this is for educational purposes only and have no intention of selling the finished product, you can probably "borrow" just about anything you want.

---
Tags: copyright
---


# Question
Title: GestureDetection Issues - How do I make my Actor jump on Swipe?
I've been trying to solve this for hours now, In theory I totally understand how the GestureDetector works but I'm trying to integrate it with the Libgdx SuperJumper Tutorial (for now).

Here: https://github.com/libgdx/libgdx-demo-superjumper/tree/master/core/src/com/badlogicgames/superjumper

I know that you need to define a class which extends the Androids Gesture Listener Interface and the methods that come along with it, I know that when the user flings I need to change velocity.y and I know when he's in the air I'll need to slow it down in decrements. But I just seem to be making him Jump and he never comes back down. Now though, he does nothing because I've been tinkering to hard. All i want So that instead of him jumping automatically, he would jump on swipe.

This is the code I have so far (Bob.Java, MyGestureListener.Java and World.java). I'll post the relevant code only, Any help would be appreciated.

Bob.Java

```
public Bob (float x, float y) {
        super(x, y, BOB_WIDTH, BOB_HEIGHT);
        this.state = BOB_STATE_IDLE;
        this.stateTime = 0;
        this.setGrounded(true);
        this.setFacingRight(true);
        Gdx.input.setInputProcessor(new GestureDetector(new MyGestureListener(this)));
    }

    public void update (float deltaTime) {
        velocity.add(World.gravity.x * deltaTime, World.gravity.y * deltaTime);
        bounds.x = position.x - bounds.width / 2;
        bounds.y = position.y - bounds.height / 2;

        if (position.x < 0) position.x = World.WORLD_WIDTH;
        if (position.x > World.WORLD_WIDTH) position.x = 0;

        stateTime += deltaTime;
    }

```

world.Java

```
private void updateBob (float deltaTime, float accelX) {
        if (bob.state != Bob.BOB_STATE_HIT && bob.position.y <= 0.5f) bob.hitPlatform();
        if (bob.state != Bob.BOB_STATE_HIT) bob.velocity.x = -accelX / 10 * Bob.BOB_MOVE_VELOCITY;

        if (bob.state != Bob.BOB_STATE_HIT && bob.state == Bob.BOB_STATE_JUMP && MyGestureListener.fling)
        {
            bob.velocity.y = deltaTime * Bob.BOB_JUMP_VELOCITY;
            bob.stateTime = 0;
        }

        bob.update(deltaTime);
        heightSoFar = Math.max(bob.position.y, heightSoFar);
    }

```

MyGestureListener.java

```
package com.wilson.game;

import com.badlogic.gdx.input.GestureDetector.GestureListener;
import com.badlogic.gdx.math.Vector2;

public class MyGestureListener implements GestureListener {

    private Bob bob;
    public static boolean fling;

    MyGestureListener (Bob bob)
    {
        this.bob = new Bob(bob.position.x, bob.position.y);
    }

    @Override
    public boolean touchDown(float x, float y, int pointer, int button) {
        return false;
    }

    @Override
    public boolean tap(float x, float y, int count, int button) {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public boolean longPress(float x, float y) {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public boolean fling(float velocityX, float velocityY, int button) {
         if(Math.abs(velocityX)>Math.abs(velocityY)){
                if(velocityX>0){
                        //right
                }else{
                        //left
                }
            }else{
                if(velocityY>0){
                    //down
                }else{
                    if (bob.state == Bob.BOB_STATE_IDLE || bob.state == Bob.BOB_STATE_WALKING);
                    bob.state = Bob.BOB_STATE_JUMP;
                    fling = true;
                }
            }
        return false;
    }

    @Override
    public boolean pan(float x, float y, float deltaX, float deltaY) {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public boolean panStop(float x, float y, int pointer, int button) {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public boolean zoom(float initialDistance, float distance) {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public boolean pinch(Vector2 initialPointer1, Vector2 initialPointer2,
            Vector2 pointer1, Vector2 pointer2) {
        // TODO Auto-generated method stub
        return false;
    }

}

```

My assumption is that when the user flings on the screen, the state of the character will change, depending on the state of that character change the velocity for the y axis but it doesn't do anything. HELP IS NEEDED.

# Answer
You have to return true from `touchDown`.

Documentation says:

> The GestureListener can signal whether it consumed the event or wants it to be passed on to the next InputProcessor by returning either true or false respectively from its methods.

So, if you return false from touchDown, that is the first even raised in all cases, it stops event handling. If you return true, it continues to other events ( ie. fling, longPress etc).

So, change touchDown to this:

```
@Override
public boolean touchDown(float x, float y, int pointer, int button) {
    return true;
}

```

---

EDIT: The way you are initializing the `MyGestureListener` is wrong. You are creating new instance of Bob and all the changes to bob inside `MyGestureListener` will only affect that instance. It means that the "Bob" you have in `Bob.Java` is not the same, thus no matter what gestures you record, those changes never affect the main bob.

Change this:

```
MyGestureListener (Bob bob)
{
    this.bob = new Bob(bob.position.x, bob.position.y);
}

```

to this:

```
MyGestureListener (Bob bob)
{
    this.bob = bob;
}

```
> 2 votes

# Answer
In Bob's update method you do nothing with his velocity. He has no way of actually moving, with the code you have shown. You should do something along the lines of this before you reset the bounds:

```
position.add(velocity.x * deltaTime, velocity.y * deltaTime);

```
> 1 votes

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


# Question
Title: Suboptimal A* Pathfinding Solution Example using Manhattan Distance Heuristic
I believe using an overestimating heuristic with A\* is not *guaranteed* to find the shortest path. Assuming an agent can travel as a bird using euclidean distances, the manhattan distance provides just such an overestimate; and hence is inadmissable. Can an example graph be provided wherein the use of A\*, with a manhattan distance heuristic, can be shown to give a different result than it would by using the euclidean distance?

# Answer
Imagine you're travelling from A to D:

The distance from A to C + the Manhattan distance from C to D (which is equal in this case to the distance from C to D) is less than the distance from A to B + the Manhattan distance from B to D.

I haven't included numbers, but hopefully this is apparent from looking at it -- the Manhattan distance from B to D is the equivalent of going down from B to C and then to D (assuming B and C line up on the vertical axis and C and D line up on the horizontal axis).

So, A\* with Manhattan distance for the heuristic would return A-\>C-\>D, when it should return A-\>B-\>D

---

*EDIT: In case anyone's wondering how we can be sure A-\>C-\>D is longer than A-\>B-\>D by just eyeballing it: angle B is wider than angle C (also eye-balling, unfortunately, but B is closer to A than C is to D, so hopefully that helps). So A-\>B-\>D is closer to a straight line than A-\>C-\>D. The shortest distance between two points is a straight line, so A-\>B-\>D is the shortest. By now you're probably wondering why I didn't just give each edge a length and be done with it -- and so am I.*
> 4 votes

---
Tags: path-finding, geometry
---


# Question
Title: What is DirectX 11's equivalent of D3DCAPS9::MaxVertexIndex of DirectX 9?
I'm porting a DirectX 9 program to DirectX 11. How do I get the value in DirectX 11 that is retrieved using

`D3DCAPS9::MaxVertexIndex`

in DirectX 9?

Thanks in advance.

# Answer
> 1 votes
The place to start is on MSDN's page on Direct3D feature levels.

The row 'Max Vertex Index' indicates the value you are after:

```
11.1: 2^32 – 1
11.0: 2^32 – 1
10.1: 2^32 – 1
10.0: 2^32 – 1
9.3: 1048575
9.2: 1048575
9.1: 65534

```

# Answer
> 0 votes
Since there is no value for this listed in the Direct3D 11 Resource Limits I don't think there is a limit. However according to the documentation 9\_1 feature level devices only support 16-bit index buffers.

---
Tags: directx, directx11, directx9
---


# Question
Title: Why do Unity networking libraries fail when building for the Windows Store?
I am using Lidgren and RSA in my networking framework, but things like IPAddress are "nonexistent" when I try building for windows store. RSA classes don't work, either.

Why is this? How could I still have a networked game on the Windows Store?

# Answer
> 1 votes
The *Getting Started* page for building Unity apps for Winows store specifically says Unity **doesn't support** networking on Windows Store platforms.

It does mention that WWW functions work correctly though. If you're desperate, try porting your networking to HTTP.

---
Tags: c#, unity, networking, windows-8
---


# Question
Title: DontDestroyOnLoad() doesn't work in Unity
I have a problem with DontDestroyOnLoad() in Unity. It does not work!

My code:

```
private static PlayerSpawningScript instance;

public void Awake()
{
    Debug.Log ("PlayerSpawningScript awake");
    Debug.Log ("Instance: " + instance);
    if (instance == null) {
        Debug.Log ("Initializing PlayerSpawningScript instance");
        instance = this;
        DontDestroyOnLoad (gameObject);
    }
    if (instance != this) {
        Debug.Log ("PlayerSpawningScript instance exists. Destroying new copy.");
        Destroy (gameObject);
    }
    Debug.Log ("PlayerSpawningScript instance: " + instance);
}

public void OnDestroy()
{
    Debug.Log ("Destroying PlayerSpawningSceript instance: " + instance.ToString ());
}

```

Basing on the console output, I successfully create an instance in scene1, but when I change the scene, it gets destroyed - I know this because I get "Destroying PlayerSpawningScript (...)" before the new scene is loaded, and the same script set up in scene2 does not find an existing instance (which held data saved in scene1) and sets up itself as the instance instead of getting `Destroy`ed. What am I doing wrong?

# Answer
> 6 votes
Check if your gameObject has a parent object in the hierarchy.

If it has, then everything is as intended. Your object itself isn't explicitly destroyed by Unity. But its parent may very well be destroyed. It is to be expected that when an object is destroyed, all of its children are destroyed too. That's when your object is destroyed.

**Put your object in the root of the hierarchy in the editor and check if the problem persists.**

# Answer
> 0 votes
I seems to me that Awake is called when the object is loaded when scenes change, in that case you explicitally call destroy.

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


# Question
Title: Unity5 UI - How to trigger button click event while preventing menu item deselect event?
So I've got a load menu using Unity's new UI system, basically just a list of save games you can select with a mouse click along with a couple of buttons at the bottom to delete or load the selected game file.

I've been disabling the Load Game and Delete Game buttons using the interactable attribute whenever a saved game item in the list is deselected:

```
deleteButton_LoadPanel.GetComponent<Button>().interactable = false;
loadButton_LoadPanel.GetComponent<Button>().interactable = false;

```

This disables the buttons fine, but when I click on a saved game and then click a button, the deselect event for each save file is triggered BEFORE the onclick event for each button. This is no good.

If I have no deselection event for each individual save file I can click on each save file and then click the load or delete buttons and every thing works fine, but the buttons never get disabled which is not ideal.

My question is: **How can I disable the buttons when an item is deselected, but still trigger the onclick event when they are selected? Are there any workarounds to this?**

# Answer
> 1 votes
Sounds like what you're looking for is more along the lines of a Toggle Group

> A Toggle Group is not a visible UI control but rather a way to modify the behavior of a set of Toggles. Toggles that belong to the same group are constrained so that only one of them can switched on at a time - **pressing one of them to switch it on automatically switches the others off**.

This also requires that you use `Toggle`s instead of `Button`s.

The styling of the toggle can be made to match that of your buttons now.

---
Tags: unity, gui
---


title: Directx displaying selectable text

text:
# Question
Title: Directx displaying selectable text
I am new to direct x and following this tutorial : brayzarsoft (part 14) I was able to display text. However, using this method the text is rendered to a texture.

When you look at games that have chat/consoles, you can select/copy/paste the text. How do they achieve this effect? Is it by using the winapi or do they code the whole system to be able to do this with texture?

# Answer
There are very few resource on the web concerning this, but here is what I have been able to get :

**WIN32 :** You can use win32 controls, but you won't be able to customize the look/feel and will have very limited features

**The big studio way :** Custom code everything using Os event. Just thinking of a textbox gives me a headache. Displaying. The textbox's background, after each presse key calculate the width in pixel of the char, place it beside the last one and we are not talking about selection/copy/paste yet...

**The small team way** Use libraries like CEGUI to do this part of your game.
> 2 votes

# Answer
Most games use an entirely separate system to do this, such as Scaleform, though there are some exceptions.
> 1 votes

---
Tags: directx, directx11, fonts, text
---


# Question
Title: trouble getting the lighting and material set up right
I am having some trouble getting the lighting and material set up. Below I have setup lighting and material, however, when ever I turn on spectular reflection for material the sphere that I am rendering turns white with only a little of its colour in the corners. But if I don't turn it on I get approximately the right colour. I understand that specular reflection property of material is suppose to reflect light and make the object look shiny. But with a specular reflection value of {0.1,0.1,0.1,1} the difference seems to be really great. I don't think the picture below is what I want. Could anyone tell me what I am doing wrong here?

```
      glEnable(GL_LIGHTING);
      glEnable(GL_LIGHT0);
      GLfloat ambientLight[] = {1.0, 1.0, 1.0};
      GLfloat diffuseLight[] =  {1.0, 1.0, 1.0};
      GLfloat specularLight[] = {1.0, 1.0, 1.0};
      GLfloat position[] = { 10.0f, 10.0f, 10.0f, 1.0f };

      glLightfv(GL_LIGHT0, GL_AMBIENT, ambientLight);
      glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuseLight);
      glLightfv(GL_LIGHT0, GL_SPECULAR, specularLight);
      glLightfv(GL_LIGHT0, GL_POSITION, position);

      GLfloat materialColor[] = {1, 0, 0, 1.0};
      GLfloat materialSpecular[] = {0.1, 0.1, 0.1, 1.0};

      //The color emitted by the material
      glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, materialColor);
      glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, materialSpecular);
      glMateriali(GL_FRONT_AND_BACK, GL_SHININESS, 10);
      // Perform OpenGL calls necessary to set up this material.

```

# Answer
> 0 votes
glEnable(GL\_NORMALIZE); seems to work!

---
Tags: opengl, materials
---


# Question
Title: Effect of graphics card on game programming
I know the question can be pretty funny to some, but I have been thinking, does a gaming graphics card like agtx and a professional graphics card like quaddro have any effect on game development during texture rendering, materials, importing assets, shader compilation, etc..

# Answer
> 1 votes
In practice, the same features should be exposed to you, so it shouldn't make a difference in terms of *functionality*. It may be worth developing with a consumer (gaming) graphics card just to be more like the users who'll eventually play it, but your users will have such a variety of different cards it may not make a difference, really :) (And you'll want to test the end product on a variety of consumer cards anyway).

For a detailed description of the actual differences, the accepted answer to this SO question is informative: Difference between Quadro and GeForce

Ultimately, you don't have to work differently in any way. But you *may* have better performance in *some* of your asset creation tools (which doesn't seem to me to relate to your particular concerns -- actual rendering/importing/shader-compilation).

# Answer
> 0 votes
The boards are simply made for different tasks it's just a question of time efficiency. Otherwise, there is no "effect" on the end product

Think of it as a calculator. 1+1 will always equal 2 whatever calculator you use but some calculator does some type of calculations faster than others.

---
Tags: graphics
---


# Question
Title: How do I rotate and object around itself, and translate it at the same time?
I have this animated gif of my problem.

I have a sprite object with a box collider, and I'm trying to rotate it around its center.

My rotation script consists of this :

```
this.transform.Rotate (0, 0, Time.deltaTime * rotateSpeed);

```

and in the translation script this is the code :

```
this.transform.Translate (0, -tranSpeed * Time.deltaTime, 0);

```

but as you see in the gif it does not give me the effect I desire. Can anyone give me what am I supposed to do to be able to rotate it around its center? Thank you.

# Answer
From the docs on transform.Translate:

> public void Translate(float x, float y, float z, **Space relativeTo = Space.Self**);
>
> If **relativeTo is left out** or set to Space.Self the movement is applied **relative to the transform's local axes**. (the x, y and z axes shown when selecting the object inside the Scene View.)

So because you have not specified a space in which to apply the translation, it is applied relative to the object's current facing direction. As the object turns, so does its direction of travel.

You can fix this by setting transform.position directly, or telling transform.Translate to move relative to Space.World:

```
this.transform.Translate (0, -tranSpeed * Time.deltaTime, 0, Space.World);

```
> 3 votes

# Answer
It seems like your transformations might be accumulating over time. As repeatedly "stepping forward" and "rotating around your axis" will cause the black bar to walk in circles. I'm unfamiliar with Unity, but there are some general approaches that might be applicable:

1. You could try recalculating the object's position from its starting position, rather than from its current position.
2. You could try to make the translation transformation independant from the object's orientation. Right now, it seems the translation is using the black bar's orientation to calculate the local X-axis. Instead of a local coordinate system, you'll want to use the world coordinate system.
3. As a general remark, it is important to know that transformations are not commutative! This means that the order in which you apply them, can cause different results. As a general rule, transformations are mostly applied in this order: 1. scaling -\> 2. rotation -\> 3. translation. This makes sure your scaling and rotation don't cause a change in position. It also makes sure your scaling aligns with the local axes of the object.
> 0 votes

---
Tags: c#, unity, rotation, movement
---


# Question
Title: How to orthogonalize the "up" vector in a camera based on "eye", "look" and "up" vectors?
Given a camera position defined as (eye, look, up), where "up" not quite at right angles to eye-\>look, how would I re-orthogonalize "up"?

I've had a hunt around, but did not find anything, yet if I recall correctly, this being a fairly classic problem for which there is an easy solution.

# Answer
> 2 votes
I assume `eye` and `look` are in global space and `up` is in local space. Then you can use this:

```
tmp = (look - eye) * up
up = normalize(tmp * (look - eye))

```

`tmp`, `look`, `eye` and `up` are 3D vectors.
`*` means cross product. `-` means usual vector subtraction.
`normalize()` is normalization function, which returns same vector but with `lenght == 1`.

If for some reason `look` is in local space, use `look` instead of `(look - eye)` in these expressions.

---
Tags: opengl, graphics-programming
---


title: XNA Rendering Blocks

text:
# Question
Title: XNA Rendering Blocks
I am currently building a little game in XNA and found something strange. I want to draw many blocks next to another (1x1x1 with a texture on the side)

So what happens when I do it this lines appear:

When I move the camera the lines change the position or disappear completely. I know this is because the side of the blocks are drawn but i do not know why. Does anybody of you know a solution for my problem? (removing the sides of the cube does not count)

# Answer
> (removing the sides of the cube does not count)

Sorry dude, that is what you have to do if you want this to be efficient and work every time. The reason you're getting those lines is slight depth buffer inconsistencies (also known as z-fighting). The sides of the blocks are almost at exactly the same depth as the tops of the nearer blocks.

Ideally, in a block-based game, for performance you really ought to delete non-visible faces. Here's some pseudocode of how you might do it:

```
// Generate a mesh of a 3D grid of blocks.
Mesh GenerateMesh(Block[, , ] blocks)
    Mesh out_mesh;
    // Loop through every block.
    for x = 0 : blocks.max_x:
        for y = 0 : blocks.max_y:
            for z = 0 : blocks.max_z:
               Block block = blocks[x, y, z];
               // Check each face of the block
               for face = 0 : 6:
                   Block neighbor = block.GetNeighbor(face);
                   // If the neighbor doesn't exist, add the triangles
                   // from that face.
                   if (!IsOccupied(neighbor)):
                        out_mesh.AddVertices(block.GetFace(face));
   return out_mesh;

```
> 1 votes

---
Tags: xna, c#, 3d
---


# Question
Title: String of coordinates into an ArrayList?
I have a String with coordinates which looks like this: (These coordinates are loaded from a text files and tells the position of entities)

```
String coords = "0,0 0,1 5,2 7,4 10,5"

```

My question is, how can I turn this String into an ArrayList of Points, where ID 0 is a Point(0,0) and so on?

I tried splitting the String, but without any real success.

# Answer
This should do the trick.

1. Split coords using "whitespace"
2. Foreach resulting array
3. Split the pairs to x y
4. Parse strings to int
5. Create point
6. Add to list

---

```
String coords = "0,0 0,1 5,2 7,4 10,5"
String coordsArray[] = coords.split("\\s+") // Results "0,0","0,1","5,2","7,4","10,5"
List<Point> points = new ArrayList<Point>();
for(String s : coordsArray)
{
    String coordXY[] = s.split(",");
    int x = Integer.parseInt(coordXY[0]);
    int y = Integer.parseInt(coordXY[1]);
    points.add(new Point(x,y));
}

```
> 3 votes

---
Tags: java
---


# Question
Title: Unity: Can't press space to unpause. Is this a Unity UI bug? Or maybe poorly written code?
So I think I have a bug with my pause menu. For the sake of simplicity I've boiled down what I'm trying to acheive: When the player first starts up the game there's a UI menu with one button: 'Start Game' that they have to press to start the game. They can then pause and bring up this menu again at any time by pressing space. The player can resume the game either by pressing 'Start Game' or by pressing space again.

The problem right now is that when the player presses space again to unpause, nothing happens - unless they click anywhere on the screen. It's sort of complicated to explain but I'll try my best.

Say the player previously started or unpaused the game by clicking the 'Start Game' button. If they pause the game again, they can only unpause the game by pressing space if they click somewhere on the screen. This works if the player clicks somewhere on the screen before or after they press pause.

However, If the player previously unpaused the game by pressing space, they can pause and unpause by pressing space indefinitely (until they unpause by pressing 'Start Game'). Is this a bug with the Unity UI system (I'm using Unity 5.0)? Or maybe with my code?

Here's my code:

```
public class GameController : MonoBehaviour
    {bool paused;
    public GameObject canvas; //in the editor I set this to reference the canvas that
                              //the 'Start Game' button is on

    void Awake()
        {PauseGame ();}

    void Update()
        {if (Input.GetKeyDown (KeyCode.Space))
            {PauseGame ();
            Debug.Log ("Pressed 'Space'");}
        }

    public void PauseGame()
        {paused = !paused;
        if (paused == true)
            {Time.timeScale = 0;
            canvas.SetActive (true);
            Debug.Log ("'Pause' Called");}

        else
            {Time.timeScale = 1;
            canvas.SetActive (false);
            Debug.Log ("'Unpause' Called");}
        }
    }

```

\*The 'Start Game' button calls the PauseGame() method from the GameController script

**Update**

I wrote some debugging lines to figure out what was happening. Apparently, if the player previously unpauses by pressing 'Start Game' then pauses again, when they try to unpause by pressing space the game does indeed unpause but then immediately pauses again. However it only does this if the player previously unpaused by pressing 'Start Game' (and can be remedied by clicking somewhere on the screen before or after pausing). This doesn't happen if the player previously unpaused by pressing space.

**Update**

Apparently the 'Unpause' is being called by the event system, and the 'Pause' is being called by pressing space. I guess Unity has it built in that if a player previously clicked a UI button, pressing space will click that button again when the option is available. Does anyone know how to alter this?

# Answer
I solved it myself! Sorry that I had to take up space in the GameDev stack exchange site but I guess if anyone else has this problem they'll know how to solve it. **The problem was with the event system**. If the 'Send Navigation Events' bool is true under the 'Event System' script component of the 'Event System' game object then the game object of the button last clicked will be considered 'selected' and pressing space will click that button again.

Basically what was happening was that pressing space was both pausing and unpausing the game because the 'Start Game' button was "selected." Pressing space called the function on that button as well as the the function in the Update() message in the GameController script. This can be solved by ***unchecking*** the **"Send Navigation Events"** box on the **Event System**.
> 4 votes

# Answer
Try this: start your game in the editor, click on the play window, then (without clicking off the window) use space to pause the game. Then immediately hit space again to unpause.

If this works, then you're fine. What you're seeing is the fact that Unity play windows don't get keystrokes (or mouseclicks, for that matter) unless they have focus.
> 0 votes

---
Tags: unity, gui, bug
---


title: Movement in gameloop

text:
# Question
Title: Movement in gameloop
I wonder what the best way is to move the player. Is it best to always check for movement like I do in the first example of is it better to only access the movement function via the input function like the 2nd example?

```

-EXAMPLE 1-
while(running)
{
    while(event)
    {
      player.input();
    }
    logic();
    render();
}
logic()
{
    player.move();
}

```

```

-EXAMPLE 2-
while(running)
{
    while(event)
    {
      player.input();
    }
    logic();
    render();
}
player.input()
{
    player.move(direction);
}
player.move(int dir)
{
    if(dir == left)
    {
        xvel += 1;
    }
}

```

I hope I explained it right. Thanks in advance.

# Answer
> 1 votes
I assume you mean whether you should be doing **active polling** or listening to **events**.

1. **Active Polling** means that you check the state of your input devices on every update. For example, the *Logic()* (or *Update()* or *Tick()*) function of your character could contain: *if (input.isPressed(KEY\_RIGHT)) { positionX += 10; }*.
2. **Events** on the other hand let you react to events generated by your input device. For example, if you press the *right arrow key* on your keyboard, a *KeyboardKeyEvent(KEY\_RIGHT, ACTION\_PRESS)* event might be launched. You can then register your character object to listen for these events.

In the first case, you will be checking all buttons every frame. Let's say you have 50 objects in your gameworld, and they need to respond to five different keys on average. If you are running at 60 frames per second, you'll be launching 50 * 5 * 60 = 15000 polling function calls per second.

In the second case, the input device (or some manager component inbetween) takes the initiative to contact all objects that are interested in listening to keyboard event. Let's say you still have 50 objects in your gameworld, they still respond to five different keys on average, and you are still running at 60 frames per second. The important thing to note is, that object code is only called when an event happens. Let's say you press 10 keys every second (which would be a lot). This means the number of calls made will be 50 * 10 = 500.

For **active polling**, the number of calls relates to the the amount of buttons that an object responds to, the amount of objects in your gameworld and the framerate of your game. For **events**, the number of calls relates to the amount of actual, physical button presses and the amount of listeners.

Events are a great choice for checking input, as **input events occur sporadically** (aka. relatively far and few inbetween).

An additional advantage of events is:

* you can apply filtering in some management component, so that you need to send even fewer events (eg. an object might only be interested in the space bar, and only in key presses (not releases or holds)). This further decreases the number of calls.
* once you've registered yourself, no more checking is required in your logic code. You are guaranteed that a callback will launch when input is detected, and you can cleanely handle that button press in a separate functions

Some disadvantages are:

* you need to register all of your objects beforehand, meaning you have quite a bit more initialialization work
* an eventing mechanism can be more tricky to set up. You'll need to implement a management component where objects can register themselves. This management component should be intercepting actual input events from input devices (eg. GLFW keyboard events if you were doing OpenGL in c++) and call the correct callback methods of the listeners.

# Answer
> 0 votes
In your EXAMPLE 1, you're gathering all your player input first, and then doing the move as part of logic().

In your EXAMPLE 2, you're moving the player-object as part of gathering the input.

EXAMPLE 2 is ok if there's nothing else that influences the player besides the user input.

But usually what happens to each game object (including the player) might be affected by various things going on. If you keep working on Example 2, you might find more and more "logic" crammed into "input".

Here's a pattern that has served me well in many things (software design, code structure, major life decisions, &c): Gather, Analyze, Act.

So I'd go with EXAMPLE 1 as the "better" layout.

---
Tags: c++, game-loop
---


title: Platformer collision advice

text:
# Question
Title: Platformer collision advice
I've been trying to implement collision for a platformer but I can't find a good way to get the collision of certain sides without it get glitchy. So i try to get the collision of the top rectangle first which works, but any other side has a problem. I have looked at days worths of tutorials and articles but they were either too complex or not calculating collision for one side of a rectangle. I am truely stumped and can't find a solution that works for me.

What I need:

* working collision that wont give the bullet through paper problem \*simple gravity (I have a way of doing this)
* the collision allowing me to know what side is touching what

Now I don't want to do the method where the player is made up of several small rectangles because of possible future problems and the fact that it's not acurate. Can I have a small bite of code that shows how I can handle collision in these cases? Also, here's my current way of doing in OpenGL + Java:

```
public class AABBDemo {

        public AABBDemo() {
                try {
                        Display.setDisplayMode(new DisplayMode(640, 480));
                        Display.setTitle("test");
                        Display.create();
                } catch (LWJGLException e) {
                        e.printStackTrace();
                }

                glMatrixMode(GL_PROJECTION);
                glLoadIdentity();
                glOrtho(0, 640, 480, 0, -1, 1);
                glMatrixMode(GL_MODELVIEW);

                Rectangle A = new Rectangle(100, 100, 50, 50);//player
                Rectangle B = new Rectangle(100, 300, 90, 20);//enemy

                int leftA, leftB;
                int rightA, rightB;
                int topA, topB;
                int bottomA, bottomB;

                int xVel = 0;
                int yVel = 1;

                int size = 50;

                boolean jumping = false;
                float jump = 0;
                boolean jumped = false;

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

                        A.setX(A.getX() + xVel);
                        A.setY(A.getY() + yVel);

                        if(jumping)
                        {
                           A.setY((int) (A.getY() - jump));

                           jump -= 0.3f;

                           if(jump < -5)
                              jump = -5;

                        }

                        if(!jumping)
                           jump = 10;

                        if(A.getX() < 0 || A.getX() + size > 640 || check_collision(A, B))
                        {
                           jumping = false;
                           A.setX(A.getX() - xVel);
                           A.setY(A.getY() -  2);

                        }

                        if(Keyboard.isKeyDown(Keyboard.KEY_D))
                           xVel = 2;
                        else if(Keyboard.isKeyDown(Keyboard.KEY_A))
                           xVel = -2;
                        else
                           xVel = 0;

                        if(Keyboard.isKeyDown(Keyboard.KEY_W) && !jumping && !jumped)
                        {
                           jumped = true;
                           jumping = true;
                        }

                        if(!Keyboard.isKeyDown(Keyboard.KEY_W))
                           jumped = false;

                        glBegin(GL_QUADS);
                        glColor3f(1, 0, 0);
                        glVertex2i(A.getX(), A.getY()); // Upper-left
                        glVertex2i(A.getX() + A.getWidth(), A.getY()); // Upper-right
                        glVertex2i(A.getX() + A.getWidth(), A.getY() +A.getHeight()); // Bottom-right
                        glVertex2i(A.getX(), A.getY() + A.getHeight()); // Bottom-left
                        glEnd();

                        glBegin(GL_QUADS);
                        glColor3f(0, 1, 0);
                        glVertex2i(B.getX(), B.getY());
                        glVertex2i(B.getX() + B.getWidth(), B.getY());
                        glVertex2i(B.getX() + B.getWidth(), B.getY() + B.getHeight());
                        glVertex2i(B.getX(), B.getY() + B.getHeight());
                        glEnd();

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

                Display.destroy();
                System.exit(0);
        }

        public boolean check_collision( Rectangle A, Rectangle B )
        {
            //The sides of the rectangles
            int leftA, leftB;
            int rightA, rightB;
            int topA, topB;
            int bottomA, bottomB;

            //Calculate the sides of rect A
            leftA = A.getX();
            rightA = A.getX() + A.getWidth();
            topA = A.getY();
            bottomA = A.getY() + A.getHeight();

            //Calculate the sides of rect B
            leftB = B.getX();
            rightB = B.getX() + B.getWidth();
            topB = B.getY();
            bottomB = B.getY() + B.getHeight();

            //If any of the sides from A are outside of B
            if( bottomA <= topB )
            {
                return false;
            }

            if( topA >= bottomB )
            {
                return false;
            }

            if( rightA <= leftB )
            {
                return false;
            }

            if( leftA >= rightB )
            {
                return false;
            }

            //If none of the sides from A are outside B
            return true;
        }

        public static void main(String[] args) {
                new AABBDemo();
        }

}

```

# Answer
Here is an `Intersects(A,B)` method implementation taken from C# Rectangle.cs

```
public bool Intersects(Rectangle a, Rectangle b)
{
    return (b.X < a.X + a.Width)   &&
           (a.X < (b.X + b.Width)) &&
           (b.Y < a.Y + a.Height)  &&
           (a.Y < b.Y + b.Height);
}

```
> 0 votes

---
Tags: opengl, java, collision-detection
---


title: How to approach animations and OpenGL

text:
# Question
Title: How to approach animations and OpenGL
There are tons of tools and instructions for making 3d models and animations in various software products. My question is: in video-game engines, when would you use a pre-rendered animation, and when would you use armature data in the model to manipulate your model in to the desired action?

Secondary questions: Are there any games that even use the model's rigging, in-game, or is everything pre-rendered?

Are there any human-readable file formats that contain armature data?

Lastly, from a OpenGL-level and up perspective, how would you implement a system for animating something like walking?

I am building an OpenGL graphics engine from scratch as a personal project, so if answers can cater to that context, it would be fantastic.

# Answer
> 3 votes
Yeah, most games use a model's rigging and apply animation tracks to the bones in real time based on things happening in the game or player input. Animations can also be blended between to make new animations or transition from one animation to another. Animations can also be combined such that the lower half of a body is playing one animation and the upper half is playing a different animation. There is also something called parametric animation where a lot more of the animations are derived from a smaller set of animated bone data. There is also various levels of physics based animation such as ragdoll and inverse kinematics. I've specialized as an animation programmer at previous employers, check out this more detailed info based on my experiences and observations: http://blog.demofox.org/2012/09/21/anatomy-of-a-skeletal-animation-system-part-1/

---
Tags: opengl, graphics
---