title: How to unify vertices in 3ds max?

text:
# Question
Title: How to unify vertices in 3ds max?
I want two vertices of editable spline become one. Neither `fuse`, nor `weld` helps: vertices remain separate.

Here is a video: http://youtu.be/bp3OJPeKapc

# Answer
Disclaimer: I'm using 3DS 2013, and I haven't used 2012 before so I don't know that what follows is accurate in 2012.

To get the vertices to fuse/weld, I did the following: 1) Place the two vertices near each other, but not directly on top of each other (helped to make sure I did in fact get both selected. 2) Select both vertices 3) Click Fuse. 4) Click Weld without deselecting anything. This caused them to become one vertex.

Notes: Upon clicking Fuse, the two vertices move to be the same point, but if you try to move it, it shows that it is really two vertices right on top of each other. I did try manually moving them on top of each other, selecting both, and clicking Weld, but it only worked if they were exactly aligned. I think I remember hearing that there is a setting somewhere that dictates how far away your points can be and still be welded.

Hope that helps!
> 1 votes

# Answer
Yes that option (while you're at the vertex editing level) is called Area Selection, tick it and choose the maximum radius of how close vertices can be to your selected vertex for the weld option to execute on.
> 0 votes

# Answer
Make sure that both vertices that you are trying to weld are end points to their respective splines. Sometimes, especially if you are working from CAD data, splines will double back on themselves and what looks like the end point is not actually the end of the spline.
> 0 votes

---
Tags: 3dsmax, splines
---


title: Designing progression levels

text:
# Question
Title: Designing progression levels
I'm new here so forgive me if I have some lingo wrong.

I am designing an app for hockey players that trains them in stickhandling skills. The app tracks time you watch videos/do the exercises.

We want to have the players progress through levels (34 levels), so we can celebrate their progress and give them something to chase after. The truth is the more they drill, the better they actually become, so it really benefits them.

My problem is I don't know how to really design the levels. You train by running through a playlist, let's say that's a standard 4 minutes of training (Somewhat high intensity, too). My thought was doing the first playlist gets you the first level, and it's pretty easy through the first 5. Then it gets tougher each 5 levels until the last 4-5 are really difficult.

Is there some kind of formula for this to design it so the levels make sense vs. just guessing? We want them to train and progress through the levels, not being too hard or too easy.

# Answer
"Levelups" are a form of positive reinforcement. Positive reinforcement is used as a reward to motivate the player to perform a certain behavior, in your case to watch more videos and do more exercises.

It's important for positive reinforcement to be applied soon after the player performs the desired behavior the first time. That means the first levelup should happen very early to show the player "You are doing the right thing - continue doing it!". Maybe even after the first positive action the player performed (first video watched / first exercise performed).

It is then important that you keep giving the player reinforcements so they continue the behavior. However, when you repeat the same form of reinforcement too often, the player will get used to it and you will have diminishing returns. That means you need to gradually reduce the frequency of positive reinforcement. But it is important to never remove them completely: The moment where another reward event seems unattainable (with justifiable effort), the player will quit.

Finding the right balance is more of an art than a science. You will have to do rigorous playtesting to find it.
> 4 votes

# Answer
Jesse Schell's "Art of Game Design" has a good section on this subject. He uses this graph to illustrate the problem:

The idea is that you need to keep a player's skills in balance with the challenges you give them. If the challenge is too low vs player skill, the player may get bored and stop playing your game. If it's too high, they may become frustrated/anxious and stop playing your game. To further complicate things, this is a moving target, since the player should be getting more skilled as they play your game.

A few of Schell's proposed solutions to this problem:

* Let skilled players get through the easy stuff quickly. Maybe you could have a way to "test out" of early challenges. Or have a "skip" button.
* Create "layers" of challenge - you could rank players A-F based on how well they do. Novices can either get a C and continue, or keep practicing until they get an A.
* Have difficulty levels: easy/medium/hard.

There are lots of ways to tackle the problem. Definitely something you'll want to test for in play testing sessions.
> 4 votes

# Answer
I recommend that if your overall goal is to get them to watch a large percentage of the videos, structure the videos themselves like pick-able items. Give each video a challenge rating, but don't force a linear progression, so that they can pick and choose for themselves which challenge to watch, and they can skip around as their interest changes. Then just attach some gamified badges & points to watching videos through to the end.

The point being, you want to avoid at all costs making the process be a grind, so the more choice you allow for them to mix & match as their interests allow, the more they'll keep up their interest level on their own.
> 0 votes

---
Tags: game-design, progression
---


# Question
Title: Is glDrawArraysInstanced in OpenGL parallel when drawing those instances?
Is `glDrawArraysInstanced` in OpenGL parallel when drawing those instances?

I cannot figure out by referring to its reference and numerous online tutorials.

\[Update\] To be more clear, I mean, for example, we have 100 instances. Are the drawing of those 100 instances parallel? For example, we have the 100 commands "glDrawArrays(mode, first, count);"? Is execution of those 100 commands sequential or parallel?

I think it should be sequential. GPU begins to draw the second instance, only AFTER the first instance drawing finished.

Or `glDrawArraysInstanced` just save the time for "giving your GPU the commands"?

\[Update 2\] The reason I wanted to know the answer, is that: If it is sequential, personally I think drawing thousands of tree leaves in this way is time consuming. I may draw them in one shader program with some algorithm tweak.

# Answer
According to the docs, `glDrawArraysInstanced` has the same effect as:

```
if ( mode or count is invalid )
    generate appropriate error
else {
    for (int i = 0; i < primcount ; i++) {
        instanceID = i;
        glDrawArrays(mode, first, count);
    }
    instanceID = 0;
}

```

So it's basically a for-loop... But we need to take a step back and ask the real question, does the GPU draw things in parallel ? Roughly speaking what happens is the following:

1. The CPU batches draw commands to the GPU command buffer.
2. GPU starts parsing the commands at the same time with the CPU.
3. GPU executes the draw calls by fetching vertices from buffers
4. Data is managed in blocks so it can be processed by vertex shaders.
5. Vertex shader is executed per vertex in parallel.

It's not only about draw calls executed together, they may be executed together if they use the same shader for example. But in the end it's about making the GPU stages as busy as possible. The GPU is parallel in nature but many factors come into play to decide if two calls will be executed in parallel.

\[Edit\] Regarding your update, it's possible that the GPU execute multiple render calls together and only perform what is needed to be sequential in a sequential manner. For instance nothing prevents executing the vertex shader for two draw calls in parallel and only do the blending in a sequential order.
> 5 votes

# Answer
After your comment... not as good an answer as concept3D's but perhaps more to the point of what you're trying to achieve in a sense.

The trade-off you face is between hardware instancing, which allows for repeated but independently moving parts of a complex geometry such as a tree, or static batching which will allow massive vertex counts without necessarily repeating geometry, but which won't allow independently moving parts in a single batch (not without re-uploading the entire, massive batch).
> 1 votes

---
Tags: opengl, gpu, instancing
---


title: new graphicsdevice returning null

text:
# Question
Title: new graphicsdevice returning null
I tried to make a collision box visible (for testing) with `spriteBatch.Draw`(with a blank texture) in my `TileSprite` class. I needed a `GraphicsDevice` for this so these are my variables:

```
Texture2D blankTexture;
GraphicsDevice GraphicsDevice;

```

I used this code as my `LoadContent()`:

```
public void LoadContent()
{
    blankTexture = new Texture2D(GraphicsDevice, 1, 1, false, SurfaceFormat.Color);
    Color[] color = new Color[1];
    color[0] = Color.White;
    blankTexture.SetData(color);
}

```

I have one `TileSprite` constructor in my `TileSprite` class which looks like this (NOTE: this constructor is partially taken from another abstract class, named `Sprite`):

```
public TileSprite(GraphicsDevice gd, Texture2D textureImage, Vector2 position, Point frameSize, Point currentFrame)
    : base (gd, textureImage, position, frameSize, currentFrame)
{
    GraphicsDevice = gd;
    bCollisionRect = new Rectangle((int)position.X, (int)position.Y, frameSize.X, frameSize.Y);
}

```

And then I use this code in my `Draw` method to draw the box:

```
spriteBatch.Draw(blankTexture, bCollisionRect, Color.White);

```

And I have another line of code in the `Game1 : Game` class (variables like `textureImage` are written as variables in the beginning of the `Game1` class):

```
tileSprite = new TileSprite(this.GraphicsDevice, textureImage, position, frameSize, currentFrame);

```

I tested this and I saw that my `GraphicsDevice` was returning `null` on a `new TileSprite` that used a GraphicsDevice from `DrawableGameComponent`.

# Answer
> 3 votes
Typically, you would use the GraphicsDevice object that is created in your Game class. You should be able to create a second Graphics Device, however, I think there is a access issue when you attempt to create a second GraphicsDevice using the same adapter.

> When you create a new XNA Framework game using XNA Game Studio Express, the game derives from Game and contains a member variable that is a GraphicsDeviceManager. This GraphicsDeviceManager automatically creates the best device that is available for the application and exposes it as the GraphicsDeviceManager.GraphicsDevice property.

So what you are going to want to do, is pass the Game.GraphicsDevice object to this class in order to use the same one that is already initialized.

**As requested in comments, an example:**

```
public class TileSprite
{
    GraphicsDevice GraphicsDevice;
    Texture2D BlankTexture;

    public TileSprite(GraphicsDevice gd)
    {
        GraphicsDevice = gd;
    }

    public void LoadContent()
    {
        BlankTexture = new Texture2D(GraphicsDevice, 1, 1, false, SurfaceFormat.Color);
        Color[] color = new Color[1];
        color[0] = Color.White;
        BlankTexture.SetData(color);
    }
}

```

Then in your Game class:

```
TileSprite tileSprite = new TileSprite(this.GraphicsDevice);

```

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


# Question
Title: Shading Languages vs Materials in 3D editors
There are many 3d packages which are able to construct materials. Autodesk Maya, 3ds max, Houdini, etc.

There are languages which are able to construct materials as well, like GLSL and Cg.

How does first group correspond to the second? Are there workflows, where they are used simultaneously?

From my experience, constructing materials in 3d packages is way faster than writing code in GLSL. They also have scripting systems for more customization. Do shading languages have their own benefits?

# Answer
Well, Shading languages like GLSL and HLSL is what all the "material" code ultimately get translated to in the end. Shaders are the actual programs which are run *directly on the GPU*, and to create them, you use a shading language.

3D packages are generally used to make it easer for you to make realistic looking graphics, and writing shaders by hand is a little cumbersome, as one would require knowledge of shader programming, Lighting mathematics, physics, and so on. What you call materials is just an abstraction provided by the package so that you can design surfaces and graphics in an intuitive, easy and fast way.

It is seen that in most cases, scenes created with 3D packages can be created using a fixed set of commonly used shaders (phong shading, diffuse, specular colors, reflections, simulating roughness and other common things). These are the things 'materials' save you from rewriting.

Though writing shaders directly can be cumbersome, provided you have all the prerequisite knowledge to do so, you can fine-tune and create effects which are otherwise not so much possible with what 3D packages provide with their "material" interface. Shaders give you full control.
> 9 votes

# Answer
Shaders let you do much more than just materials.

With vertex shaders you can modify geometry.

With geometry shaders, hull shaders and domain shaders you can effectively define new primitive types (classically, patches)

With pixel shaders the options are nearly endless, you can define an entire scene in a pixel shader rendered in a fullscreen pass, perform raytracing, deformation, blurs and many other effects which are simply not easily categorised into 'material'.
> 1 votes

---
Tags: 3d, shaders, materials
---


# Question
Title: What is the easiest way to Implement a 3rd Person Camera in C++/DirectX9
I'm pretty new to C++ and DirectX9 and I want to Implement a Third Person Camera. After some reading about Quaternion-based Cameras I decided to try Implementing it. But it really blow my mind, so I ask here what is the easiest way to Implement a TP-Camera?

Here are the things the Camera should do:

* Follow coordinates stored in a 3DVector (x, y, z)
* Rotate around the Object (Smooth)
* Maybe some type of 'spring' = Slowly moving back to the normal Pos behind the Object after Rotating

Apologise for my bad english: I'm german and still in school!

Thanks in Advance!

**EDIT:**

After some trying I've got it.

The biggest problem I considered was the right extracting of the "direction" Vector from the World-Matrix.

During my research I've found mostly something like this:

```
D3DXVECTOR3 direction;
direction.x = worldMatrix->_13;
direction.y = worldMatrix->_23;
direction.z = worldMatrix->_33;
D3DXVec3Normalize(&direction, &direction);

```

That does *NOT* work for me! Instead I did this:

```
D3DXVECTOR3 direction;
direction.x = worldMatrix->_13;
// Consider the .y after the .z!
direction.z = worldMatrix->_23;
direction.y = worldMatrix->_33;
D3DXVec3Normalize(&direction, &direction);

```

For scaling:

```
// The tenfold of the average distance
D3DXVec3Scale(&direction, &direction, 10.0f);

```

Setting the Positions:

```
cameraPos = targetPos - direction;
// For a top-view
cameraPos.y = targetPos.y + 5;

```

For Rotations you should create a temporary world-Matrix (from the position of the target) and rotate it how you want and extract the direction.

The Smoothing of the Rotation really depends on YOUR game!

This sort of 3rd Person Camera is really easy to make and it does it's job!

Really GREAT thanks to "jheriko" who gave me the right answer!

# Answer
What will help you is having the transform matrix for the object you want to follow. You can extract the foward vector from this matrix - depending on your coordinate system and matrix handedness this will be one of the rows or columns with the 4th component removed (assuming you use 4x4 transform matrices, with no scale factors - scale factors are horrible for many reasons... but if you have scale factors you can normalise the row/column after removing the 4th component.)

Once you have this you can position the camera directly behind the object by subtracting this from the object position. To move the camera in and out you can scale the vector, and to rotate around the object you can make an x and y rotation (or xz/zy etc. depending on handedness etc.) which you apply to a copy of the object matrix before extracting the forward direction.

Finally to smooth the movement the simplest solution is to track the previous offset and angles and lerp towards them by some framerate dependent amount described by a^(b.dt) where dt is the delta time and a, b are parameters you choose. a = 0.9 and b = 30 gives you the effect of moving 90% towards the position as if you were doing it every frame at 30 fps. this is called an 'infinite impulse response' filter and is a classical hack for this sort of smoothing.

this might not be ideal, you may want to pick a minimum distance and constrain the angles too, otherwise the camera may pass through the object. if you are inside of a dense world clipping against or fading intervening objects will become important too.

sorry this is long, but its not a trivial problem, as you seem to have discovered.

hope this helps. i can provide more depth of detail if necessary.

(p.s. no quaternions necessary - they really don't help for this problem)
> 1 votes

---
Tags: c++, camera, directx9
---


# Question
Title: Trying to make a respawn trigger, but any rigid body (or collider probably) keeps triggering it. Any ideas?
I'm trying to make it so that if any object passes through with the matching tag it will reload the level. However, any rigid body (or collider) is setting it off which is not the desired behavior.

```
using UnityEngine;
using System.Collections;

public class DamageAuroa : MonoBehaviour {

    public int PHP; //PHP = Player Health from PlayerHealth.cs script.
    public int Damage; //Amount of damage.
    public string Level;

    void Start()
    {
        PHP = GameObject.Find("Player").GetComponent<PlayerHealth>().PlayerHP;
    }

    void OnTriggerEnter(Collider coll)
    {
        if (coll.gameObject.tag == "Player")
            PHP = PHP - Damage;

        if (coll.gameObject.tag == "Ball")
            gameObject.SetActive(false);
            Application.LoadLevel(Level);

        if (PHP <= 0)
            Application.LoadLevel(Level);

    }

}

```

Any idea why this happens? Or is it something wrong with Unity? Probably just an end user issue.

# Answer
This:

```
if (coll.gameObject.tag == "Ball")
            gameObject.SetActive(false);
            Application.LoadLevel(Level);

```

You're missing parenthesis there. Application.LoadLevel isn't affected by the `if` condition, so it's firing every time.

Turn it to this:

```
if (coll.gameObject.tag == "Ball")
     {
            gameObject.SetActive(false);
            Application.LoadLevel(Level);
}

```
> 1 votes

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


# Question
Title: How to handle sounds muting in settings?
I have a easy and specific question.

Let's say that in my game I use singleton for playing/pausing/changing volume of specific sounds (SimpleAudioEngine in cocos2d-x).

What is the best way to handle *mute* button, which is displayed in the upper corner of the screen? Should I just volume everything down and do not care about checking the state of this setting before playing any kind of sound?

1) This is called when an object is destroyed

```
if (!UserDefault::getInstance()->getBoolForKey(MUTED, false))
{
    SimpleAudioEngine::getInstance()->playEffect("shouting.ogg", /* other arguments */)
}

```

I think that not playing a sound at all is bad practise (if muted is on - like in the above example), because when the user changes this setting while eg. his hero is getting shot, nothing will be played - even if it supposed to take 5 seconds and the option was changed after 2,5 seconds.

But if I only volume everything down - then the rest of the shout will be heard.

# Answer
> 1 votes
*Adding to ZEKE answer.*

There are situations where changing a setting gives a temporary weird behaviour, and that is acceptable. In this case, really, it depends.

Is your game based on the sound? Do you expect the player to use the mute/un-mute feature often?

If the answer is *yes* to any of these, you'd probably want to play the sound, but set the volume to 0 when it is muted in any case. In this case, the "weird behaviour" could be an issue.

If the answer to both of these question is *no*, I would suggest you wrap the `SimpleAudioEngine` into one of your classes (for instance `MyAudioEngine`) that will relay calls to it. In this case, the "weird behaviour" is probably not an issue.

This class will offer the same services, but the "play" will be different, the "play" will check if the sound is muted by the user, and will *not play* it if the user has muted the game; the `if` you wrote in the OP will be encapsulated in the `play` function. This will allow the end user classes to just don't care about the mute state, (because, in fact, they don't care) and the code that calls the play sound methods will be cleaner. With this you'll still have to set the volume to 0 for sounds that are already playing when the user wants to mute.

This said, since the library you're using seems to be open-source, you *could* go in there and add the feature directly to `SimpleAudioEngine`. The advantage would be that you'd have one less class to build and carry around, and all your code base would work right away. The downsides to it would be that if you update the 3rd party library, you face chances of changes in the original code base and you'd have to re-implement the feature in the new version.

# Answer
> 1 votes
I'm not exactly sure what you mean by:

> his hero is getting shot, nothing will be played - even if it supposed to take 5 seconds and the option was changed after 2,5 seconds.

If you only check for `muted` when you first play a sound, it will continue to play even after you pressed the mute button.

**The solution** for this, is setting the `volume` of the sound to *zero* when you press the mute button. This way; the sound will be muted, and you won't need to create unnecessary sounds.

*TL;DR: Do both.*

---
Tags: c++, cocos2d-x, sound, audio
---


# Question
Title: How to decide the direction of movement, when navigating a fixed path in a 2d overworld?
Suppose, I have a 2D overworld like in Super Mario Brothers 3, but without junctions or intermediate nodes. Only a single, contiguous path of level nodes, which should be **navigated with the arrow keys**.

Currently, the path is calculated automatically by the order of which the nodes appear. Each node has at most two edges, which extend from the center of each node.

Now there are multiple possible layouts of said path. In the following pictures, "**P**" is the position of the player. Directions formatted as `code` will denote arrow key presses.

## Axes-aligned paths

This is the trivial case, since each possible direction is aligned with the arrow keys. `down` moves the player down, `left` moves him left.

## Angled paths

Here it gets a little trickier, since the possible directions are not aligned with the arrow keys anymore. Pressing `left` is ambiguous, the only option would be to use `up` and `down` to move the player up-left and down-left respectively.

## Axes-aligned and angled paths mixed

In this case, `left` could be used to move the player either to the left or to the up-left. But here it would be more intuitive to use `left` for left and `up` for up-left movement.

## Arbitrary paths

This is where I am kinda lost. Both possible paths lead up-left. Now I could say, since one node is "more left" than the other, let `left` walk the player to that node. The other node is "more up", so `up` can walk him there. But what if such a situation doesn't exist? For example, when one node is both "more left" and "more up" than the other one?

---

## Some approaches I had

* **Give directions a priority**, so when ambiguous situations exist, `left` gets picked over `up` for example. That means, `left` will always move the player to the most left node, no matter where the other node is. But with this I think I have to implement a lot of `if`-checks and it would also be not as intuitive for the player.
* **Add direction markers**, so paths leading from one node to another are only connected at their direction specific markers. This will be more intuitive, since you can simply look at the markers and know, that the left marker is mapped to `left`.

But this looks rather ugly and unnatural, because the edges don't originate from the center of the node anymore. Furthermore, I think this will cause the same problem as before. I need to decide beforehand, which marker is connected to which other marker. So I basically relocated the problem to another point in the logic.
* **Restrict placement**, so the nodes are only placed in such a way, that the path ends up axes-aligned. Since I'm free to place the nodes anywhere I want, this would be the easiest solution. But that would make the layout of the world map rather boring. I guess this could be my fall-back approach, when everything else fails.
* **Decide by angle of an edge**. Divide a circle into four sectors at `(2k + 1) * PI/4` with `k = 0..3`. Each sector defines one direction. An edge is now mapped to this direction, when the edge lies in that sector. If two edges are in the same sector, the one closer to the main-axis (x or y) in that sector is mapped to that direction. The remaining edge is then mapped to the direction of the next closer sector.

This one came to my mind, while writing this question, so I haven't given it much thought yet. I find this the most elegant approach so far. But I already see two problems where there is some ambiguity:

\- If an edge lies exactly on a dividing line between two sectors (e.g.: at 45°)

\- If two edges are symmetrical around an axis (e.g.: at 30° and 330°)

---

## Questions:

1. How could I generalize the decision-making with arbitrarily connected paths?
2. Are my presented approaches reasonable?
3. What approach would be the most promising? Or is there a better one, which I haven't thought of yet?

***Thanks in advance for your time! I look forward to your suggestions :)***

# Answer
I would not overthink this: since you need some way to connect the paths to the nodes, extend that class to include the preferred direction of movement. That way you can manually tweak the movement so it feels natural to the player.

Pseudo code:

```
class Path
{
     Node Target;
     Direction DirectionToTarget; //enum north,northeast,east etc.
                                  //could also be an array of directions.
}

class Node
{
   List<Path> Connections;

   void AddConnection(Node target, Direction d, bool twoway)
   {
      Connections.Add(new Path() { Target=target, DirectionToTarget=d });

      if(twoway) //if two way, add path back to me.
      {
          target.Connections.Add(new Path() { Target = this, DirectionToTarget=Opposite(d)});
      }
   }

}

```

You might even extend it so into a path going southwest the directions south, southwest and west are accepted. If there is a path west *and* southwest from a node, you might treat the keys west, northwest for the west direction and the keys southwest and south. It gives yourself full control of all movements.
> 2 votes

---
Tags: movement, logic, control
---


title: Check elapsed time in Unity?

text:
# Question
Title: Check elapsed time in Unity?
How can I check the elapsed between two intervals? I want to do the following: "start time counter when `Input.GetButtonDown("Fire1")` , stop counter when collision is detected\` And then Debug.Log the elapsed time?

# Answer
> 6 votes
Store Time when the Fire1 button goes down, and then check the difference between that stored value and Time.time when the collision is detected:

```
private float fire_start_time;

void Update() {
    if(Input.GetButtonDown("Fire1")) {
        fire_start_time = Time.time;
    }
}

void OnTriggerEnter(Collider other) {
    Debug.Log("elapsed time: " + (Time.time - fire_start_time));
}

```

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


title: Question of tilesheet efficiency

text:
# Question
Title: Question of tilesheet efficiency
For a 2d side scrolling game made in Java, should I make a sprite sheet for my character walking left *and* for walking right, or should I just do the one, and flip it when it loads?

Also, the way I've been doing it, both left and right would be in the same image file, if that makes any difference.

# Answer
> 2 votes
Performance-wise, flipping it at load time will be fine.

(Or at instance-render-time, for that matter, if the platform lets you do that.)

But you might want separate sprite sheets for left and right anyway, so they can be slightly different, not exact reflections. For example, a little bit of lighting always from the left (for both left- and right-running) can add some visual consistency.

---
Tags: java, 2d, spritesheet
---


# Question
Title: Storing component vectors to avoid matrix and quaternion inaccuracies?
I read that I "should really be storing the component vectors (rotation, translation, scale) in addition to the quaternion and matrix forms." The reason for this is that, over time, compound numerical numerical errors can build up over time from floating point limits.

This seems a bit excessive to me. I was planning on creating a Transform class that just manipulated a glm::mat4 model matrix. But now I'm concerned that this might not be the best way, however I don't really understand why. Could someone explain why and now numerical errors can build over time using quaternions?

And what should I really be doing instead? Store component vectors, but convert euler rotations to quaternion using glm::angleAxis while setting rotations, and then return a glm::mat4 model matrix that combines these things upon request? That's a whole lot of matrix math flying around every frame. I guess I could check to see the glm::mat4 has changed before assembling a new one but maybe there's a better way.

One advantage I'd have by storing the component vectors is trying to return what the current component vectors actually are. Pulling that from a glm::mat4 seems tedious. I know I can decompose a matrix, but I don't want all the decomposed components when I'm just trying to return, for example, a rotation. But... as I understand it, it needs to be decomposed fully in order to get any of the component vectors. In other words, it's all or nothing.

To restate my questions:

1. What sort of use case makes matrices and quaternions lose their accuracy over time and why?
2. How can I avoid this problem (or what should I be doing)? Hoping for something fast AND accurate.

# Answer
**Short answer: To store position, use a single `vec3`. To store rotation, use a quaternion and normalize it after every multiplication or after every `n` (1-1000) multiplications.**

**You shall only use `mat4`s when it comes to *drawing* or *transforming lots of vertices*: Convert `vec3+quaternion` pair to `mat4` and pass it to your shader or use it to transform vertices directly.**

---

**Detailed explanation:** * Floating-point math:

Floating-point math is not so accurate. If you compute a long mathematical equation using `float`'s, result can be inaccurate. `5.0` can become `5.00000003` or `4.99999998` and so on.

See Drop's answer for more detailed and precise explanation.

* Quaternions:

A quaternion stores rotation as 4D *direction*. So, `[1,2,3,4]` is same rotation as `[2,4,6,8]`. Only *proportions* matter here. Quaternions **always** rotate models correctly. Except one case: when a quaternion suddenly becomes `[0,0,0,0]` because of these inaccurate calculations. In this case you lose your rotation. To prevent this, you must normalize your quaternions after `n` multiplications. `n` can me 1 for simplicity. Or something like `1000`.

* Matrixes:

Matrixes **do** lose their precision after big amount of calculations. To be valid translate+rotate matrix, a matrix must have it's 4th row equal to `[0,0,0,1]`. Also, 3 rotation vectors (each one is composed from first 3 numbers in corresponing column (1st, 2nd or 3rd)) must be orthogonal and must have lenght equal to `1.0`. If any of these conditions is not met, matrix starts to behave strangely. It may change scale or proportions of your models or disort them. If you want to restore your matrix to the valid state, you must *orthogonalize* it and fix the 4th row . Orthogonalization requires some tricky and relatively expensive calculations.

* Quaternions vs Matrixes:

Quaternions are a lot faster to multiply than martixes. If you normalize a quaternion too seldom, it will only lose *precision*. Your models will be still rotated correctly. Everything will break only if a quaternion will become `[0,0,0,0]`. If you orthogonalize a matrix too seldom, it will slowly start to disort your models more and more. Normalization is **a lot** faster than orthogonalization.
> 4 votes

# Answer
> Could someone explain why and now numerical errors can build over time using quaternions?

**"`float` is not real"**

Floating point types are an approximation of real numbers implementable on binary machines. For example: there is a real number `0.1`, however, there is no IEEE-754 floating point number that is exactly `0.1`, as this value cannot be represented exactly in this system. The closest representable value is `0.0999755859375`. If you are performing operations on floats they slowly accumulate some minor errors.

See canonical: "What Every Computer Scientist Should Know About Floating-Point Arithmetic".

See also: Wiki - IEEE-754 floating point

> Should really be storing the component vectors (rotation, translation, scale) in addition to the quaternion and matrix forms

I don't see how storing original vectors can help to overcome floating point types limitations. Vectors will acummulate errors the same way quaternions or matrices do. They will probably accumulate even more errors, because you will need to convert them to quaternions/matrices and back, additionally to quaternions/matrices operations, this increasing number of operations performed (supposing you want to perform your transforms with quaternions/matrices). It will also introduce performance and memory overhead.

> Hoping for something fast AND accurate

No free cookies. Precision is often an antonym of performance. You will need to find a right balance between them.

> And what should I really be doing instead?

There is no such thing exist. Neither "best ways", nor "should". Think critical, try, measure and find a right performance/precision/convenience balance in context of your application.

Few illustrative examples: You are doing gamedev: `float`s will do the trick, and most of the time you will never notice any errors. Scientific calculations: `double` or `long double` is probably your way. You are building a Mars rover, aircraft flight controls or a national banking system: well, here you probably shouldn't use floats at all.

We are on GameDev site, so just remember that "float is not real"... but it is very close.
> 0 votes

# Answer
Right, if you keep rotating a matrix, say, by 1 degree around some axis, after 360 successive steps, it will be *almost* back where you started, but not exactly. You'll see some 0.999xxx and some 1.00xxx's and the like.

Same with quaternions.

But it takes a while before these are significant.

One approach that I like is occasional renormalization.

Just once every few thousand frames seems to be enough (in my engine).

For a quaternion, just divide it by its absolute value. See http://www.mathworks.com/help/aeroblks/quaternionnormalize.html.

For a matrix, for unscaled rotation or rotation & translation, you can normalize the first two columns of the mat3 top left corner (make the absolute value equal 1.0), and let the third column of the mat3 be the dot product of the first two.

(Depends on handedness and row-column-ness, but that's the gist.)

Cumulative translation can also become "off" from the mathematical ideal, but it doesn't cause distortions in the same way that a renormalized rotation can.
> 0 votes

---
Tags: opengl, mathematics, rotation, glm
---


# Question
Title: Displaying smooth borders given a coarse grid-based map
I've been messing around with different algorithms trying to make a grid based map look smooth, I have tested with various shader based methods and wrote a few of my own but none of them look right.

A grid based map:

The result I'm trying to achieve

So my question is, are there any algorithms or known methods out there to achieve this?

# Answer
> 1 votes
You could try with a simple filter:

```
//<![CDATA[
var input = [
  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0,
  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0,
  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0,
  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,
  1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0,
  1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0,
  1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0,
  1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0,
  1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0,
  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0,
];

function Texture(w, h) {
    this.width = w;
    this.height = h;
    this.getTexAt = function(i, j) {
        return this[j * this.width + i] ? "red" : "green";
    };
}
Texture.call(input, input.length / 12, 12);

var canvas = document.createElement("canvas");
canvas.width = input.width * 20;
canvas.height = input.height * 20;

function rect(g, x, y, cx, cy, fillStyle, strokeStyle, strokeStrength) {
    g.beginPath();
    g.moveTo(x, y);
    g.lineTo(x, y+cy);
    g.lineTo(x+cx, y+cy);
    g.lineTo(x+cx, y);
    g.closePath();
    if(fillStyle !== undefined) {
        g.fillStyle = fillStyle;
        g.fill();
    }
    if(strokeStyle !== undefined) {
        if(strokeStrength !== undefined)
            g.lineWidth = strokeStrength;
        g.strokeStyle = strokeStyle;
        g.stroke();
    }
}

function paintTexture(tex) {
    var g = canvas.getContext("2d");
    var w = canvas.width;
    var h = canvas.height;
    var size, offX = 0, offY = 0;
    if(w / tex.width < h / tex.height) {
        size = w / tex.width;
        offY = 0.5 * (h - tex.height * size);
    } else {
        size = h / tex.height;
        offX = 0.5 * (w - tex.width * size);
    }
    for(var j = 0, y = offY; j < tex.height; ++j, y += size)
        for(var i = 0, x = offX; i < tex.width; ++i, x += size)
            rect(g, x, y, size+1, size+1, tex.getTexAt(i, j));
}

function subsample(tex, sw, sh) {
    if(!sw || sh < 0) sw = 2;
    if(!sh || sh < 0) sh = sw;
    var out = [];
    for(var j = 0; j < tex.height; ++j) {
        for(var subj = 0; subj < sh; ++subj) {
            for(var i = 0; i < tex.width; ++i) {
                var sample = tex[j * tex.width + i];
                for(var subi = 0; subi < sw; ++subi) {
                    out.push(sample);
                }
            }
        }
    }
    Texture.call(out, tex.width * sw, tex.height * sh);
    return out;
}

function erode(tex, sw, sh) {
    if(!sw || sh < 0) sw = 1;
    if(!sh || sh < 0) sh = sw;
    var out = tex.slice(); // hack: copy data
    for(var j = sh; j + sh < tex.height; ++j) {
        for(var i = sw; i + sw < tex.width; ++i) {
            // <--- Adjust to your filter criteria --->
            var count = 0;
            for(var v = -sh; v <= sh; ++v)
                for(var u = -sw; u <= sw; ++u)
                    count += tex[(j + v) * tex.width + i + u];
            var sample = count > 0.5 * (2*sw+1) * (2*sh+1) ? 1 : 0;
            out[j * tex.width + i] = sample;
        }
    }
    for(var j = sh; j + sh < tex.height; ++j)
        for(var i = sw; i + sw < tex.width; ++i)
            tex[j * tex.width + i] = out[j * tex.width + i];
    Texture.call(out, tex.width, tex.height);
    return out;
}

paintTexture(input);
document.getElementById("body").appendChild(canvas);

setTimeout(function() {
    var subsampled = subsample(input, 16);
    var eroded = erode(subsampled, 7);
    paintTexture(eroded);
}, 1000);
//]]>
```

```
<div id="body"></div>
```

# Answer
> 0 votes
Apart from using shaders, you can implement the Marching Squares algorithm to generate contours for your grid (see picture in the linked article).

A great marching squares tutorial here. It's for Unity, but the idea's still the same.

---
Tags: 2d, shaders, rendering, glsl, game-maker
---


title: Unity3D multi-threaded data importer?

text:
# Question
Title: Unity3D multi-threaded data importer?
**Goal**

I would like to be able to separate all my data file readers from the main thread and balance the load over multiple frames. The idea being that while the data is being read/parsed/filtered I can continue playing the game at a decent FPS and show a loading progress bar while the results of the file importing pop in one at a time when they are ready.

**Information**

The data files contain things like transform information for objects, points to be used in runtime mesh generation, and terrain data. They all have to be parsed, filtered, and/or modified to be ready to be used in the scene.

I already have import code for the project I just need to transplant it from blocking my main thread and being done in one frame to a multi-threaded and multi-frame approach.

**Thoughts**

I have little experience in multi-threading so this is also a learning project for me. I would appreciate all your comments, input, code samples, and pointers.

From my perspective I need to create a queue of tasks. Each task being a file to load, read, parse, and filter. Then if a CPU is open a task is taken from the queue and is given a thread to be executed on that CPU. The task completes and gives the resulting data back to Unity3D for it to handle.

**Questions**

1. Does a heavy load on other CPUs freeze the game like it would if it were on the main thread, and thus require some sort of system where you yield for one frame if execution time is taking too long?
2. How do I receive progress updates from the tasks to be used in a interface progress bar via some sort of co-routine?
3. If a user only has one CPU how would this system handle the situation? Is that even a realistic scenario?
4. What sort of C# classes (usable in Mono's subset of the .NET runtime) already exist for multi-threading and task queuing that can save me time?

# Answer
Here is some example code to expand on my comment above. A true multi threaded solution would be faster than this, but susceptible to many more problems and edge cases. Unity's model for concurrency is coroutines, and thus using them aligns your code with what is expected in the unity space. Unless you have a real need for ultra fast file processing, this solution should work.

```
using UnityEngine;
using System.IO;
using System.Collections;
using System.Collections.Generic;

public class FileImporter : MonoBehaviour
{
    public int LinesToReadPerFramePerFile = 100;

    private int _linesProcessed = 0;
    private Dictionary<string, Coroutine> _currentCoroutines = new Dictionary<string, Coroutine>();

    public int LinesProcessed {  get { return _linesProcessed; } }

    public void ProcessFile(string pathToFile)
    {
        if (_currentCoroutines.ContainsKey(pathToFile))
        {
            throw new System.Exception("Already reading file: " + pathToFile);
        }
        else
        {
            _currentCoroutines.Add(pathToFile, StartCoroutine(readFileLines(pathToFile)));
        }
    }

    private IEnumerator readFileLines(string pathToFile)
    {
        using (var data = new StreamReader(pathToFile))
        {
            int count = 0;
            var line = data.ReadLine();
            while (line != null)
            {
                count++;
                _linesProcessed++;

                /// PROCESS THE LINE HERE HELD IN "line"

                if (count == LinesToReadPerFramePerFile)
                {
                    yield return null;
                    count = 0;
                }

                line = data.ReadLine();
            }

            data.Close();
        }

        _currentCoroutines.Remove(pathToFile);
    }
}

```
> 1 votes

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


# Question
Title: Can I integrate Unity 5 with the 0.6.0 runtime for Oculus DK2?
I am a new user and I am trying to get the Oculus running on an old PC. I had a few issues with the latest SDK so I am currently using the 0.6.0.1-beta version. I would like to integrate Oculus with Unity. My question is whether I can use Unity 5 with the SDK 0.6.0.1-beta and which kind of integration should I use - or if I should download a previous release of Unity. Thank you!

# Answer
You should be able to use pre-0.7 SDKs with Unity versions before 5.2.1.

Under 'Changes' here you can see that you must use the 0.7+ SDK starting with 5.2.1.
> 0 votes

---
Tags: unity, oculus
---


# Question
Title: Java Slick2D how to draw text with a centered alingment
I've made a button class that can be drawn and clicked on. How can I write the text of that button (using the slick drawing API, g.drawString()) with a Centered alingment (so that the text is exactly centered in a rect with defined x,y,widht and height). Thanks

# Answer
> 1 votes
If I understand this question correctly you want to create a class that writes text on a button for you centered to a rect.

```
public class DrawCentered(){
    public DrawCentered(String chars, Rect r){
        TrueTypeFont font = new TrueTypeFont(new Font(...));
        int width = font.getWidth(chars);
        int height = font.getHeight(chars);

        g.drawString((r.x + r.width / 2) - (width / 2),
                     (r.y + r.height / 2) - (height / 2),
                     chars);
    }
}

```

Note **Above code is untested**

I hope this helps, and if you have any further questions, don't hesitate to ask.
JavaDocs such as:
Slick2D TrueTypeFont JavaDoc
JavaAwtFont JavaDoc are great tools to help you when you are stuck.

Cheers!

---
Tags: java, slick
---


title: Stop detecting Input in Unity?

text:
# Question
Title: Stop detecting Input in Unity?
How can I stop detecting input from the user in Unity? I want to achieve the following: "do not detect `Input.GetMouseButtonDown`" In C#?

# Answer
> 1 votes
Just do not call the input query function if you don't want any user input. Something like this:

```
class InputExample : MonoBehaviour
{
    public bool EnableInput = true;

    void Update()
    {
        if( EnableInput )
        {
            var mousedown = Input.GetMouseButtonDown(0);

            if( mousedown )
            {
                Debug.Log("Mouse button pressed");
            }
        }
    }
}

```

Now just change the `EnableInput` variable to false to disable input detection.

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


title: OpenGL shaders messed up

text:
# Question
Title: OpenGL shaders messed up
So after a long attempt at DirectX I switched back to good old OpenGL. Now I'm running into this weird problem. My code involves shaders, of course, and drawing a basic cube. But I'm getting this weird shape. I've never seen this before. I was just wondering what could possibly be causing this? Thanks very much!

Initialization:

```
lightingShader->GenerateVAO();
lightingShader->GenerateVBO();

lightingShader->SetVertices(vertices, sizeof(vertices), GL_STATIC_DRAW);

lightingShader->BindVAO();
{
    lightingShader->AddAttribute(0, 3, GL_FLOAT, GL_FALSE, 3, 0);
}
lightingShader->UnbindVAO();

```

Rendering:

```
lightingShader->Use();

GLint objectColorLoc = lightingShader->GetUniformLocation("objectColor");
GLint lightColorLoc = lightingShader->GetUniformLocation("lightColor");

glUniform3f(objectColorLoc, 1, 0.5f, 0.31f);
glUniform3f(lightColorLoc, 1, 0.5f, 1);

GLint modelLoc = lightingShader->GetUniformLocation("model");
GLint viewLoc = lightingShader->GetUniformLocation("view");
GLint projLoc = lightingShader->GetUniformLocation("projection");

glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(game_->GetCamera()->View()));
glUniformMatrix4fv(projLoc, 1, GL_FALSE, glm::value_ptr(game_->GetCamera()->Projection()));

lightingShader->BindVAO();
{
    glm::mat4 model;
    glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model));

    glDrawArrays(GL_TRIANGLES, 0, 36);
}
lightingShader->UnbindVAO();

```

Result:

As you can see, position and color is set fine, but I still get that weird shape.

# Answer
It could be that you are mixing up the multiplication (of the vertices with your matrices in your vertex shader) in the shader. Mind you, this is inverted for OpenGL, as it uses column-major matrices as opposed to DirectX. It will still compile and if I recall correctly this is because it simply decides to transpose where necessary.

Also, make sure you are using glm's functions to modify the matrices, you might be editing the matrices by hand in a row-major fashion.
> 1 votes

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


# Question
Title: Objective-C SpriteKit – How to make a circle of buttons
I have some code in a project already, but I'd like to change it up a bit. Currently, my code creates an empty node called `_buttonLayer` and then create some buttons to add to it. My buttons start from the top-left corner of the `_buttonLayer` and then get added all the way to the bottom-right corner.

```
// Set up button layer.
_buttonLayer = [SKNode node];
_buttonLayer.position = CGPointMake(_centerOfScreen.x - (_buttonSize.width * 1.5) - 5.0,
                                    self.size.height - ((self.size.height * 0.375) + (_buttonSize.height) - 50.0) + 5.0);
[self addChild:_buttonLayer];

// Set up button array.
_buttonArray = [NSMutableArray array];

// Add some buttons.
for (char row = 0; row < 4; row++) {
    for (char col = 0; col < 4; col++) {

        // Buttons.
        SKSpriteNode *button = [SKSpriteNode spriteNodeWithImageNamed:@"LightGreyButton"];
        button.name = @"LightGreyButton"; // Initially set it to grey, because they all start off that way.
        button.size = _buttonSize;
        button.position = CGPointMake(2.0 + ((button.size.width + 3.0) * col),
                                      -(2.0 + ((button.size.height + 3.0) * row)));
        [_buttonLayer addChild:button];
        [_buttonArray addObject:button];

    }
}

```

So what I need to do now is create the buttons in a circle – instead of in a square. I'd like to somehow add the buttons into an outline of a circle, and then take the whole `_buttonLayer` and rotate it. Of course, the way I have it right now, it rotates on the top-left corner of the square. I want the middle of the circle to rotate.

How would I go about doing this?

# Answer
> 0 votes
You can rotate the entire \_buttonLayer if you make it a SKSpriteNode a subclass of SKNode. You will have access to the default anchorPoint property that is already set in the middle of the SKSpriteNode object. (0.5,0.5) is the center. You will want to set its color property to clearColor so you have the same appearance as you would with using a SKNode. You will have access to the zRotation property of SKNode on your SKSpriteNode as well. That is one way of doing it.

It seems like two questions really? It might be better breaking them up. One for laying buttons out in a circle and the other for rotation. Hope that helps?

---
Tags: ios, objective-c, spritekit
---


# Question
Title: How do I make my character change his ability's when his sprite changes
I am making a platformer and am currently trying to have it so that my character will have different powers based on his emotions, and his sprite will change to match those emotions.

I have got it so that his sprite will change but I don't know how to get his powers to change as well. Note that I haven't even made his other powers yet, but even if I did I don't know how to change his ability's with his sprites as I am still very new to this whole coding thing. Can anyone please help me?

Here is my code for changing his sprites, if that would help.

```
using UnityEngine;
using System.Collections;

public class MoodManager : MonoBehaviour {

  public Sprite sprite1;// happy//
  public Sprite sprite2;// angry//
  public Sprite sprite3;//sad//
  public Sprite sprite4;//default//

  private SpriteRenderer spriteRenderer;

  void Start ()
  {
    spriteRenderer = GetComponent<SpriteRenderer>(); // we are accessing the SpriteRenderer that is attached to the Gameobject
    if (spriteRenderer.sprite == null) // if the sprite on spriteRenderer is null then
      spriteRenderer.sprite = sprite1; // set the sprite to sprite1
  }

  void Update ()
  {
    if (Input.GetKeyDown (KeyCode.Alpha1)) // If the space bar is pushed down
      ChangeMoodHappy (); // call method to change sprite

    if (Input.GetKeyDown (KeyCode.Alpha2)){
      ChangeMoodAngry ();

    if (Input.GetKeyDown (KeyCode.Alpha3)){
      ChangeMoodSad ();
  }

  void ChangeMoodHappy (){
    if (spriteRenderer.sprite == sprite1) // if the spriteRenderer sprite = sprite1 then change to sprite2
      spriteRenderer.sprite = sprite4;
    else
      spriteRenderer.sprite = sprite1; // otherwise change it back to sprite1
  }

  void ChangeMoodAngry (){
    if (spriteRenderer.sprite == sprite2) // if the spriteRenderer sprite = sprite1 then change to sprite2
      spriteRenderer.sprite = sprite4;
    else
      spriteRenderer.sprite = sprite2; // otherwise change it back to sprite1
  }

  void ChangeMoodSad (){
    if (spriteRenderer.sprite == sprite3) // if the spriteRenderer sprite = sprite1 then change to sprite2
      spriteRenderer.sprite = sprite4;
    else
      spriteRenderer.sprite = sprite3; // otherwise change it back to sprite1
    }
  }

}

```

# Answer
> 2 votes
I would have a look at Unity's animation system, Mecanim (Unity has a great set of resources available on the subject).

Essentially, for what you're trying to do, I would set up a few states in my character's animator controller, representing the character's moods. You can assign a sprite (or sequence of sprites) as the animation for a given state, and get what your code is currently doing basically for free.

Here's a preview of what your state machine might look like:

The "mood" parameter (shown on the left) is just an integer that corresponds to an enum I've defined in the `MoodManager` component, and the state transitions are simply "mood equals \[some value\]" (again, as defined in the enum). The `MoodManager` component becomes pretty simple:

```
using UnityEngine;

public class MoodManager : MonoBehaviour
{
    public enum Mood
    {
        Default = 0,
        Happy = 1,
        Sad = 2,
        Angry = 3
    }

    public Mood mood;
    Animator animator;

    void Awake ()
    {
        animator = GetComponent<Animator> ();
    }

    void Update ()
    {
        if (Input.GetKeyDown (KeyCode.Alpha1)) {
            mood = Mood.Happy;
        } else if (Input.GetKeyDown (KeyCode.Alpha2)) {
            mood = Mood.Sad;
        } else if (Input.GetKeyDown (KeyCode.Alpha3)) {
            mood = Mood.Angry;
        } else if (Input.GetKeyDown (KeyCode.Alpha0)) {
            mood = Mood.Default;
        }

        animator.SetInteger ("mood", (int)mood);
    }
}

```

You now have your character's mood available to use in driving abilities, probably from another component. The particulars are really dependent on how your game should function, but in the simplest case, you could do a switch on the character's current move whenever the mouse is clicked (or however your abilities are triggered), and execute the correct move based on that value.

# Answer
> 0 votes
you can set your sprites and powers to be Arrays instead of different public sprites and change them accordingly. you can loop thru and set them with a for loop but in this case you can easily change them 0-3 for example.

```
public Sprite[] Moods;//set mood sprites in order 0-3
public GameObject[] Powers; //set powers 0-3 these can be gameobject prefabs like fireball, ice, any power you want ..

GameObject currentPower; //set power to default in Start()

void Start(){
     spriteRenderer.sprite = Moods[3];//your default mood
     currentPower = Powers[3];//default power
}
void ChangeMoodHappy (){

     spriteRenderer.sprite = Moods[0];//will assign first sprite in Moods
     currentPower = Powers[0];//will assign first power in Powers
}

```

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


title: Wall checking not working correctly

text:
# Question
Title: Wall checking not working correctly
Basically I am working on side scrolling 2d game. For that I want to check whether player is collided with wall. I have written some code for it but can't able to decide where I have done stupid mistake. So please guide me in this. If you need any more details then I am always available.

Code for detecting wall :

```
 RaycastHit2D hit = Physics2D.Raycast (wallCheck.position, Vector2.right, wallCheckDistance);

     if (Physics2D.Raycast (wallCheck.position, Vector2.right, wallCheckDistance)) {
         Debug.Log ("collider name : " + hit.collider.name);
         isDead = true;
     }

     Debug.DrawRay (wallCheck.position, Vector3.right * wallCheckDistance, Color.red);

```

Following image gives you all idea about situation. In that I have allocated player with groundCheck and wallCheck flag. At present in wallCheck section, I am detecting ground as collider response after execution of above code. Above code I have placed in Update method for continuous checking.

For this game, I want to do game over if wallCheck object detect any object in collision.

Why wallCheck object detecting collision of ground object (stage1a)? That is big question of mine.

# Answer
> 1 votes
you can add the walls to there own Layer;

```
LayerMask wallLayer;

    if(Physics2D.Raycast(wallCheckPosition,Vector2.right, wallCheckDistance, wallLayer))
    {
        //Hit wall call GameOver()
    }

```

I prefer using Physics2D.OverlapCircle to set a radius rather than direction. ex.

```
    if (Physics2D.OverlapCircle(wallCheck.position, checkRadius, wallLayer))
    {
        //Hit wall call GameOver()
    }

```

you can also use the same method to detect other things like your barrels or ladders, ect.. or in your case you could just set any object that will end the game to a killLayer or something. then when the player touches within range of the checkRadius it will execute GameOver();

# Answer
> 0 votes
Why are you casting the ray twice? First cast the ray:

```
RaycastHit2D hit = Physics2D.Raycast (wallCheck.position, Vector2.right, wallCheckDistance);

```

Then, verify if anything is hit:

```
if (hit.collider != null)
{
    ... // Do collision reaction. Death, in your case
}

```

---
Tags: unity, collision-detection, raycasting
---


# Question
Title: When does the memory transfer from CPU to GPU happen when creating a buffer?
I just finished my first DirectX 11 program. But I have several questions on memory transfer between CPU and GPU.

In my program, I create a vertex buffer first:

```
bool InitializeGeometry() {
    VertexType vertices[] = {
        XMFLOAT3(0.0f, 0.0f, 0.5f),
        XMFLOAT3(0.5f, 0.0f, 0.5f),
        XMFLOAT3(0.0f, 0.5f, 0.5f)
    };

    D3D11_BUFFER_DESC vbDesc;
    ZeroMemory(&vbDesc, sizeof(vbDesc));
    vbDesc.Usage = D3D11_USAGE_IMMUTABLE;
    vbDesc.ByteWidth = sizeof(vertices);
    vbDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
    vbDesc.CPUAccessFlags = 0;

    D3D11_SUBRESOURCE_DATA vbData;
    ZeroMemory(&vbData, sizeof(vbData));
    vbData.pSysMem = vertices;

    if (FAILED(gDevice->CreateBuffer(&vbDesc, &vbData, &gVB)))
        return false;

    // ...
}

```

Later I will use this vertex buffer for rendering. Note that the `vertices` array is a stack variable and it will be destroyed on after the return of `InitializeGeometry`.

Does actual memory transfer from CPU to GPU happen in `CreateBuffer`? Or `CreateBuffer` just takes a reference to the `vertices` so I should give a longer lifetime to the `vertices`?

If the transfer does *starts* in `CreateBuffer`(or `Unmap` for dynamic buffers), can I expect the GPU driver save a copy of my vertices? I am afraid that the transfer takes so much time that `InitializeGeometry` function returns early, hence leaves transferring data incomplete.

# Answer
All the functions that take a lump of data like `CreateBuffer`, `CreateVertexShader` and others, they copy/interpret the data before the function returns.

As soon as it returns, you do not need to keep the data alive anymore.
> 2 votes

---
Tags: directx, directx11, memory
---


# Question
Title: Minimizing bandwidth for player movement
I am programming a multiplayer game and I am concerned about the bandwidth dedicated to player movement. Imagine a 2D top down game where players can move towards any angle using the joystick. The way I do it currently is to round directional vectors to the nearest 0.25 and send a new movement packet when the vector is different. (meaning a player moves into a different direction) Rounding to nearest 0.25 provides a fairly good approximation and the position is synchronized on every new movement packet because these packets contain the new x,y of the player.

This scheme works well for keyboard controls because this directional vector changes a lot less often than with a joystick. However, when a joystick is rotated quickly, this ups the bps up to around 500 bytes per second. Imagine 100 players packed together in a map, where everyone is quickly moving around using the joystick: 500 bps per player becomes 50000 bps because it has to be sent to every other players. Multiply this by 100 for each players, and you have about 5 megabytes of just movement packets being transferred every second.

Is there any way I can do more prediction on the client and greatly reduce bandwidth?

# Answer
Reduce the send rate of packages. I would suggest you to set a fixed rate (say, 3 times a second - actually this is a great rate of sync if you do client-side predictions correctly), rather than a rate that depends on input change rate.

But of course, this will reduce the precision of sync. So you will need to send velocity info with position too, and make extrapolation or interpolation (for a 2d top-down shooter, i would prefer interpolation) to move local representatives smoothly.

And implement an algorithm to sync data **only** when player moves or rotates.

I believe these two optimizations will dramatically reduce the amount of data being sent.
> 3 votes

---
Tags: networking, mmo, movement-prediction
---


# Question
Title: How can I save an XML file with Unity on the Android platform?
I am writing a game that has a save function which looks like this

```
    public void Save()
    {

        System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(this.GetType());
        System.IO.StreamWriter file = new System.IO.StreamWriter(("Assets/Resources/Save");
         ser.Serialize(file, this);
        file.Close();
    }
}

```

This will work fine in the editor and on Windows machines, but when we build to Android the saving no longer works. Why is that?

# Answer
> 1 votes
It's likely to do with the path you're trying to save to and/or the permissions. While I haven't done this myself, all the examples I've seen where people are writing to files in Android, they have to use `Application.persistentDataPath` and append their directory to the end. This ensures you're writing to the correct location, and a location where you have permission to do so.

# Answer
> 1 votes
It's faster to debug in the Editor, so this made my life simple:

```
#if UNITY_EDITOR
rootFolder = Application.dataPath+"/RootFolder/";
#elif UNITY_ANDROID || UNITY_IOS
rootFolder = Application.persistentDataPath;
#endif

```

And from the *rootFolder*, you build your file system structure (cross-plateform).

---
Tags: c#, android, unity, xml
---


# Question
Title: Unity and lots of objects. Can this way of designing levels bring problems?
Ok, question.

I've been fiddling for Unity for a while and now trying to make a cohesive game.

Up until now I've found the quickest way to design levels for me is to create a block of wall/floor to work as a "unit", and copy it lots of times.

The result is something like this

The blocks are basically just **a transform + a sprite renderer + a box collider**.

Now my question is: Can this approach bring problems given that it basically creates lots and lots of objects? If so what alternatives there are? Creating bigger blocks?

# Answer
Yes, creating lots of objects can create performance problems down the road. The alternative is using fewer objects. In this case, fewer objects taking up the same amount of space means larger objects.

You can, for example, create a texture that looks like 4 or 8 blocks side by side, then create one object that's 4 or 8 times longer than a regular block.
> 12 votes

# Answer
A good way to do this would be to have a game object that generates the blocks from a script, then generate a box collider for the whole thing and render it all from one game object. That would remove the need for a huge amount of game objects. All you would need to do from there is pass the map-generator some sort of block-map.

Of course, any unique blocks that could be uncommon within the game can be kept as separate units.
> 6 votes

# Answer
If it's just 1 block, then you only need 1 prefab, and you could instantiate that prefab in a script, when needed, and of course apply a transformation to fit into the right position, or destroy if you no longer need them.
> 1 votes

---
Tags: unity
---


title: Creating a content pipeline for a Unity

text:
# Question
Title: Creating a content pipeline for a Unity
I have a game with lots of assets, such as data files, images, etc. My understanding is that Unity is optimized to know about all resources at build time. i.e. binding those assets to Scene `GameObjects` or prefabs. And for performance reasons, dynamically loading files from the `/Resources` folder is discouraged.

My question is how can I set up a "content pipeline" for converting my asset files stored outside of Unity into a format that Unity expects.

With the XNA toolset you can create a separate project and "build" the content into a bundle. Is there way to achieve similar results in Unity? Or is the best I can do creating an external tool, and simply copying files into my `Unity/Textures` or `Unity/DataFiles` folder and generate the Unity metadata files myself?

If there isn't an off-the-shelf solution, do you have any experiences or recommendations with solving this problem?

# Answer
As others have said, there doesn't really seem to be any reason to believe that loading files from the `/Resources` folder is discouraged. The only other difference between `/Resources` and assets bound to GameObjects that I can think of is that assets bound to GameObjects are loaded with the scene, and assets in `/Resources` are loaded using `Resources.Load()`, so you'll have to be careful about when you call that.

But, in interest of answering your question, one thing you could try is to put your 'other' assets into another Unity project, and then package them up into one or more AssetBundles. You could then either include the bundle in the 1st project, or fetch it from a remote source, and unpackage it at runtime.
> 1 votes

# Answer
My little stone to the pyramid.

* Resources:
Already discussed in other posts.
* AssetBundle:
For big games on mobile platforms, it helps reducing the size of the build. At runtime, you can download a scene, a model, HD-textures, ... and load or instantiate. It's a nice option and the closest one(Subjective) to your XNA-toolset-bundle.
* StreamingAssets:
I use streamingAssets for files not linked to a gameObject. A little code-snippet:

```
public static string BundleFilePath(string filename) {
  string result;
  #if UNITY_EDITOR || UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX
  result = Path.Combine(string.Format("file://{0}", Application.streamingAssetsPath), filename);
  #elif UNITY_ANDROID
  result = System.IO.Path.Combine(Application.streamingAssetsPath, filename);
  #elif UNITY_IPHONE
  result = System.IO.Path.Combine(Application.dataPath, string.Format("Raw/{0}", filename));
  #elif UNITY_WEBPLAYER
  result = System.IO.Path.Combine("StreamingAssets/", filename)); // untested
  #endif
  return result;
}

```
> 0 votes

---
Tags: unity
---


# Question
Title: Want to play 1 of 3 tracks depending on current level
I want to play a gameplay music track depending on what the current level is.

E.g.

1 - Play track 1

2 - Play track 1

3 - Play track 2

4 - Play track 2

5 - Play track 3

repeat...

6 - Play track 1

7 - Play track 1

8 - Play track 2

9 - Play track 2

10 - Play track 3

This is what I have, but problem is track 2 will be used at level 6 when it should be track 1.

```
public static function playGameplayMusic(waveId:Int):Void
{
    var gamePlayTrackId:Int;

    if (waveId % 5 == 0) {
        gamePlayTrackId = 3;
    } else if (waveId % 3 == 0 || waveId % 4 == 0) {
        gamePlayTrackId = 2;
    } else {
        gamePlayTrackId = 1;
    }

    trace('playing gameplay track: ' + gamePlayTrackId);

    SoundPlayer.playMusicByName('gameplay/' + gamePlayTrackId, false);
}

```

**Update:**

Went with this. Thanks for all your contributions!

```
public static function playGameplayMusic(waveId:Int):Void
{
    var gamePlayTrackId:Int = Math.ceil(((waveId - 1) % 5 + 1) / 2);

    SoundPlayer.playMusicByName('gameplay/' + gamePlayTrackId, false);
}

```

# Answer
> 1 votes
You need to combine a modulo (for the wrap-around) and a division (for the duplication of tracks). With some testing I got to:

```
static function track(level:Int):Int
{
    return Math.ceil(((level - 1) % 5 + 1) / 2);
}

```

(live example on Try Haxe)

The idea is to divide a wrap-around, adjusting for no zeros. There might be a way to simplify this though.

# Answer
> 5 votes
This question would probably be better suited at StackOverflow.

**That being said:** You are using the wrong modulo. Pseudocode:

```
n = waveID % 5;
n == 0 => Track3
n == 1 || n == 2 => Track1
n == 3 || n == 4 => Track2

```

If you use modulo you always have to use the size of you collection/repeating pattern (in this case 5). Furthermore I would recommend enumerating the levels beginning at 0, which shifts the above code around to:

```
n = waveID % 5;
n == 0 || n == 1 => Track1
n == 2 || n == 3 => Track2
n == 4 => Track3

```

The cleanest way to do this part is probably (**Edit:** adjusted to HAXE and removed case drop, thanks to jonasmalacofilho):

```
var n = waveID % 5;
switch(n){
case 0:
  gamePlayTrackId = 1;
case 1:
  gamePlayTrackId = 1;
case 2:
  gamePlayTrackId = 2;
case 3:
  gamePlayTrackId = 2;
case 4:
  gamePlayTrackId = 3;
default:
  //throw exception
}

```

# Answer
> 4 votes
I don't know enough haxe to make this code better, but I would probably just do

```
var tracklist = [3, 1, 1, 2, 2];
gamePlayTrackId = tracklist[waveId % 5];

```

You can probably improve this by making tracklist static or any number of ways.
I'm still learning though, so look at the comments before you implement anything.

# Answer
> 1 votes
You're getting problems with higher numbers being multiples of more than one of the numbers you check. 6 is not just going to trip the last else, it will also trip the `% 3 == 0` one. I might do it this way:

```
StartGame()
{
    m_musicLevel = 1;
    m_track = playGameplayMusic(1);
}

NextLevel()
{
    m_musicLevel++;
    if(m_musicLevel > 5)
    {
        m_musicLevel = 1;
    }
    m_track = playGameplayMusic(m_musicLevel);
}

```

This means your `playGameplayMusic` function will only ever see levels 1-5. It's not super-elegant, but it's easy to understand and it will work.

# Answer
> 1 votes
If your levels are procedural / infinite, then the using the chosen method is good.

If you have a limited set of levels (i.e., only 10), then just associate the track choice with the level, hard-coded or preferably stored in the data that is loaded per level.

---
Tags: algorithm, mathematics, haxe
---


title: Change value of uniform for each VAO

text:
# Question
Title: Change value of uniform for each VAO
I've heard from several sources that it's a better approach to pass the model matrix to a shader via a uniform rather than an attribute.

I also know that the idea of a uniform is, that it has the same value for each frame.

If so, how can i change the uniforms value for each object i have in the scene?

# Answer
You can make a uniform for as many things as you want, including per object. If you want object A) to have a different uniform then object B), then create one for each item and bind it to the shader when it is time for that object to render. Any given object in a scene can have many uniform variables.

This technique applies also to any sort of post-processing effects like lighting, in which each light may have its own color/direction/position, and can set its own uniforms for when it is going to render.

```
void RenderObjectA()
{
    GLuint shaderID = getShaderProgramID();
    GLuint uniformID = glGetUniformLocation(shaderID,"<desired uniform's name>");
    glUniform<varies based on type used>(uniformID, <desired uniform>)
}

void RenderObjectB()
{
    GLuint shaderID = getShaderProgramID();
    GLuint uniformID = glGetUniformLocation(shaderID,"<desired uniform 2's name>");
    glUniform<varies based on type used>(uniformID, <desired uniform 2>)
}

```
> 3 votes

---
Tags: opengl, shaders, matrix
---


# Question
Title: How to draw a circle that is around an object and becomes smaller if the player enters it
I'm making a game in Java w/ slick and lwjgl and right now I want to do the following: draw a circle, that is drawn around an object with a radius of e.g. 75. I want the object to be IN THE MIDDLE of that circle. That is easy but I also want the circle to become smaller when the player enters it. Basically this is an example:

Players x is 100

The OBJECT'S x is 300

The circle's x is (300-75 == 225),(object's x - radius) and its width is radius\*2, so 150

When the player is inside of the circle (players x \> circles x; e.g. 230 \> 225) then I want the RADIUS of the circle to shrink to 70 (75 - (230 - 225), or, radius - (palyers x - circles x)), and after the circle shrank it should still be perfectly around the object from before. (**AND BTW** I didn't mention the y variable because it's self-explanatory after I figure out the x) Can anyone explain me the maths behind it please. Thank you

# Answer
Say, your circle is at 100, 120 and has radius 25.

Say, your object is at x, y and has radius 9.

So, the distance between the *centers* of the two is:

```
sqrt((100 - x)^2 + (120 - y)^2)

```

which means that the distance between their *boundaries* is

```
d = sqrt((100 - x)^2 + (120 - y)^2) - 25 - 9

```

Now, if this distance is less than zero, we know that objects are intersecting and we know that we should start shrinking the circle (or by how much you need to decrease your player's health). By how much you shrink the circle is your choice, but you obviously make it a function of d. Hope this was somewhat useful.
> 3 votes

---
Tags: java, mathematics
---


# Question
Title: Do I need more than one UDP socket on the server?
I'm trying to make a UDP game server using the SDL\_net library. This library offers `SocketSet`s which are, according to the documentation, an analogy to the select function. Right now I have successfuly made a simple server which has just one `UDPsocket` and dumps every message to stdout.

Can I use those `SocketSet`s somehow to make the server responsive, or am I just fine using only one `UDPsocket` for everything?

# Answer
> 2 votes
I guess the baseline you want any improvements in responsiveness of your service to be compared to is this:

You currently have a service which receives packets on a single UDP port. As each packet has been received it is processed and answers (if any) are sent. Once processing of a packet has completed, the main event loop starts over processing the next packet.

This is a quite reasonable starting point, because it will usually be the easiest way to implement the service, and in many cases it will be sufficient to serve the needs.

Assuming you already performed measurements on this implementation and found it to not be responsive enough under load, there are a few ways you can improve responsiveness. I will assume you are dealing with a large load from legitimate clients. How to protect a UDP services from DoS attacks is also an interesting question, but it does not sound like that is what you are asking.

Possible solutions include:

**Drop some requests**

This is not a great way to handle high load. But if the load goes high enough it will happen whether you want it to or not. You don't have to implement dropping of requests in your service. If your service can't keep up with incoming requests, the network layer will drop packets for you. You only need to implement dropping of requests in your service, if you feel you can do a better job at choosing which requests to drop than the network layer would do for you.

A properly implemented client will usually implement some retransmission strategy with an exponential backoff. So the dropped requests will keep coming until you are able to process them.

**Prioritize requests**

This is desirable compared to dropping requests. Prioritization means that some requests will get improved responsiveness while other requests gets worse responsiveness. You have to decide which requests are most important to get improved responsiveness for.

Using multiple ports is one way to implement prioritization, but not necessarily the best. It is not a very flexible way to prioritize, because you can only prioritize based on which of the ports packets arrive at.

A different way to prioritize is to receive all packets from the socket and use a priority queue inside your service. This can be done using a single UDP port. As long as there are packets available on the port you receive a packet from the port and put it in your service' priority queue. When there are no more packets available from the port you process the highest priority request, and send responses (if any).

There is a few caveats to this approach. First of all, you need to ensure your priority queue doesn't grow too large. You don't want the priority queue to get written to swap, so it is better to drop the lowest priority (or the oldest) requests from the queue before it grows too large.

Secondly you need to ensure that you can receive packets from the networking layer into your priority queue at line-speed. Otherwise you may end up in a situation where all the service has time to do is prioritize incoming requests to decide in which order to drop them, because it never finds the time to process any of them.

So though prioritization can be somewhat flexible, it still has to be lightweight enough to not become a bottleneck. If prioritization of requests consume as much CPU time as processing requests, it is not very useful.

If you are going down this route, then the use of more than one UDP port will make it more work for you to implement the prioritization of requests.

**Identify and drop obsolete requests**

Sometimes under load it is possible you end up processing requests which are no longer relevant. It may be the client already retransmitted the request or that a later request makes the data you are processing in an earlier request obsolete.

If a request from one client requires the service to send updated data to multiple other clients, it could be that there are multiple such requests in the queue, and it would be more efficient to process all of them and only then send updates to the clients.

By queuing requests inside your service, such optimizations become possible. But this is highly application specific, so only you know whether such optimizations apply to you.

**Optimize your processing**

If you can reduce the time needed to process each individual request, that may improve responsiveness more than any prioritization ever could. But of course there are limits to how much improvement is feasible.

**In conclusion**

Using multiple UDP ports can be useful in some situations. But if your goal is to improve responsiveness, then using multiple UDP ports is not the first approach you should consider.

Unless you already know what the difference between the packets you want send to the two ports is, there is little reason to use two UDP ports.

Using multiple UDP ports is usually done for other reasons such as the communication used on the two UDP ports is so different in nature that you are essentially using two different protocols on the two ports.

# Answer
> 0 votes
One socket should be enough, but you could split traffic between them, e.g. handling chat on a separate port, so you could later move that to its own server more easily (although I'd use TCP for that).

---
Tags: c++, sdl2, udp
---


title: Collision detection

text:
# Question
Title: Collision detection
So I've made my collision boxes visual (`Draw` method) and I saw that there were some problems with the boxes and I fixed them (x, y, length, width). They are now big enough.

This is the collision box inside my constructor for my `TileSprite` class:

```
public TileSprite(Texture2D collisionImage, Texture2D textureImage, Vector2 position, Point frameSize, Point currentFrame)
    : base (collisionImage, textureImage, position, frameSize, currentFrame)
{
    // Collision box (Rectangle)
    bCollisionRect = new Rectangle((int)position.X, (int)position.Y, frameSize.X * 2, frameSize.Y * 2);
}

```

And this is the collision box for my `PlayerMovement` class. This collision box is written in the update method so it updates when the player moves:

```
collisionRect = new Rectangle((int)position.X + 4, (int)position.Y + 14, frameSize.X + 10, frameSize.Y + 20);

```

`TileSprite` and `PlayerMovement` have an abstract class in common, named `Sprite`.I have all my virtual methods for the sprites in `Sprite` and this is my `Collision` method:

```
public virtual void Collision (GameTime gameTime)
{
    // collisionRect is from PlayerMovement and bCollisionRect from TileSprite
    if(collisionRect.Intersects(bCollisionRect))
    {
        Console.WriteLine("collision");
    }
}

```

But my problem is, that there is no console output when the two collision boxes intersect. (Yes, I call the collision method.)

# Answer
> 3 votes
Instead of updating your object's Rectangle variable each frame, you should instead create a read-only Property for it:

```
public Rectangle Rectangle
{
    get {
        return new Rectangle((int)position.X, (int)position.Y, frameSize.X * 2, frameSize.Y * 2);
    }
}

```

Your player update method should look like:

```
public void Update(TileSprite[] TilesToCheck)
{
    //Move player
    ...

    //Check for collision
    Collision(TilesToCheck);
}

```

And then your Player's Collision function:

```
public virtual void Collision (TileSprite[] TilesToCheck)
{
    for (int i = 0; i < TilesToCheck.Length; i++)
    {
        if(Rectangle.Intersects(TilesToCheck[i].Rectangle))
        {
            Console.WriteLine("collision");
        }
    }
}

```

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


# Question
Title: Slick2D How to add a method from a diffrent class to a method
I am trying to get keyboard input in a separate class so everything doesn't look as messy. I get the following error message

```
Exception in thread "main" java.lang.NullPointerException
    at com.****.****.Menu.init(Menu.java:33)
    at com.****.****.Main.initStatesList(Main.java:35)
    at org.newdawn.slick.state.StateBasedGame.init(StateBasedGame.java:164)
    at org.newdawn.slick.AppGameContainer.setup(AppGameContainer.java:393)
    at org.newdawn.slick.AppGameContainer.start(AppGameContainer.java:317)
    at com.****.****.Main.main(Main.java:27)

```

This is what I tried:

Menu Class where I load the methods

```
public class Menu extends BasicGameState{

KeyboardInput kbi;

public Menu(int state) {

}

@Override
public void init(GameContainer gc, StateBasedGame sbg) throws SlickException {

    kbi.init();

}

@Override
public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException {
    kbi.render();
}

@Override
public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException {
    kbi.update();
}

@Override
public int getID() {

    return 0;
}

}

```

KeyboardInput class

```
public class KeyboardInput {

public KeyboardInput() {

}

public void init() {

}

public void render() {

}

public void update() {

}
}

```

# Answer
> 1 votes
You need to create an instance of your keyboard class.

Change your menu constructor to this:

```
public Menu(int state) {
    kbi = new KeyboardInput();
}

```

---
Tags: java, slick
---


# Question
Title: sf::Shader not working properly on texture
I'm having trouble getting my sf::Shader to work on an sf::Texture that I've drawn myself. The vertex shader is pretty standard (I think it's just a copy of the example from SFML's page). The fragment shader is from somewhere in their forums, I'm new to glsl, but my understanding is it takes in a vec3 for the light position (I'm using the mouse position) and then figures the distance to/from the fragment (which comes from the other shader?) and then uses that to determine how light/dark things should be.

It works really well for the rectangle shape I had drawn, but when I try to use the sf::Texture, it shows up regardless of where it is. However -- it does get lighter as the light moves toward it (just not darker/disapear when the light gets farther).

Here is the texture being shown when it shouldn't: View post on imgur.com

Here is the texture being light really bright when the light gets near it: View post on imgur.com

Here is my vertex shader:

```
uniform sampler2D texture;

void main()
{
  // transform the vertex position
  gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;

  // transform the texture coordinates
  gl_TexCoord[0] = gl_TextureMatrix[0] * gl_MultiTexCoord0;

  // forward the vertex color
  gl_FrontColor = gl_Color;
}

```

And here is my fragment shader:

```
uniform sampler2D texture;
uniform vec3 light;

void main() {
     float distance = sqrt(pow(gl_FragCoord.x - light.x, 2) +
               pow(gl_FragCoord.y - light.y, 2));

     if(floor(light.x) == floor(gl_FragCoord.x) &&
        floor(light.y) == floor(gl_FragCoord.y))
       distance = 0.1;

     if(distance>light.z)
         distance = light.z;

     vec2 pos = gl_TexCoord[0].xy;

     gl_FragColor = mix(texture2D(texture,pos),
            gl_Color,
            1.0 - (distance/light.z));

}

```

As for loading/rendering, the shader loads with no error using `loadFromFile()` and then I create a `sf::RenderStates`, attaching my shader and setting the parameter "texture" to `sf::Shader::CurrentTexture`.

The cyan square is just a `sf::RectangleShape` and the poorly drawn bricks are a png file, loaded to a `sf::Texture` attached to a `sf::Sprite`.

The rendering code isn't much:

```
window.clear();
window.draw(rect, renderState);
window.draw(sprite, renderState);
window.display();

```

Any help would be much appreciated! If you need any more code / info, let me know.

Thanks!

# Answer
> 0 votes
The normal color of a pixel in an SFML fragment shader is supposed to be:

`gl_FragColor = gl_Color * texture2D(texture, gl_TexCoord[0].xy);`

In your code you're mixing color from the texture (when it's dark) to the color of the sprite (when it's lit), that's why it shows the texture when it's dark and it shows white when it's lit (white is the default sprite color).

I think mixing from black (or whatever color you want the darkness to be) to gl\_Color * texture2D(texture, pos) should do what you want:

```
 gl_FragColor = mix(vec4(0, 0, 0, 0),
        gl_Color * texture2D(texture, pos),
        1.0 - (distance/light.z));

```

---
Tags: c++, glsl, sfml
---