title: Stop rendering hidden objects libgdx

text:
# Question
Title: Stop rendering hidden objects libgdx
I currently am hiding objects that are not in the frustums view. However, some objects are still being rendered that are in the frustums view, but are hidden. My goal is to not render objects that won't be seen at all rather than not render objects that are in the POV but are hidden.

Let me better explain.

There are three boxes, Box A, Box B, and Box C. They are all aligned in the x axis, However, Box C has a greater y value than the rest of the boxes. Well if I'm looking straight towards Box C, I will only see Box C. But Box A and Box B are still being rendered.

I want to know if there is a method that I can use to not render objects that are hidden behind other objects.

Thanks in advanced, Jedi.

# Answer
zOrdering can be used to prevent the sprites from being rendered on to the screen,Since LibGdx does not support zOrdering you can write your own custom zOrdering the advatage of using zOrdering is you can logically decide which sprite to be rendered on or sprites that must not be rendered on the screen

Here is an example : textureComponets class is used to draw sprite on the screen and it can setZorder for the box to decide which box to be drawn first,second or third or boxes that are never to be drawn on the screen it can also set postions width and height for boxes .We create an array list called textureComponetList to hold three boxes I have created arraylist in MyGdxGame class .

**Class textureComponents**

```
public class TextureComponets {

public TextureComponets(Texture texture,float x,float y,float width,float height)
{
this.texture=texture;
this.x=x;
this.y=y;
this.width=width;
this.height=height;
}
    public int getZorder()
    {
        return zOrder;
    }
    public void setZorder(int x)
    {
        zOrder=x;
    }
public void draw(SpriteBatch batch)
    {
        if(zOrder!=0)//This condition will avoid the boxes with zOrder value zero from rendering onto screen
        batch.draw(texture,x,y,width,height);

    }
     public static Comparator<TextureComponets> zOrderComperator = new Comparator<TextureComponets>() {

            public int compare(TextureComponets s1, TextureComponets s2) {

               int zOrder1 = s1.getZorder();
               int zOrder2 = s2.getZorder();

           }};

}

```

class **MyGdxGame**

```
public class MyGdxGame implements ApplicationListener
    {
    ArrayList<TextureComponets>textureComponetsList;
SpriteBatch batch;

@Override
public void create(){
Texture box = new Texture(Gdx.files.internal("box.png"));
batch = new SpriteBatch();
textureComponetsList=new ArrayList<TextureComponets>();

TextureComponets BoxA=new TextureComponets(box,10,10,30,30);
BoxA.setZorder(0);
//when you setZorder to zero your sprites wont be rendered on the screen
//The maximum zOrder value it will be drawn in the top most layer or that will be drawn last in the screen
textureComponetsList.add(BoxA);

TextureComponets BoxB=new TextureComponets(box,10,20,30,30);
BoxB.setZorder(0);
textureComponetsList.add(BoxB);
TextureComponets BoxC=new TextureComponets(box,10,100,30,30);
BoxC.setZorder(1);
//BoxC will be rendered on the screen since its zOrder value greater than zero
textureComponetsList.add(BoxC);

}

@Override
public void render(){
    Gdx.gl.glClearColor(1, 1, 1, 1);
    Gdx.glClear(GL20_GL_COLOR_BUFFER_BIT);
    batch.begin();

   Collections.sort(textureComponetsList, TextureComponets.zOrderComperator);

//collections.sort function will sort all the components based on the
//z order set for each box and sort them in the arraylist TextureComponetList
  // you can also logically setZorder value in program
//like if(BoxC.y>100){BoxC.setZorder(1)}  or like if(BoxC.x<100){BoxC.setZorder(0)} thus preventing BoxC from rendering on to screen

        for(TextureComponets textureComponets:textureComponetsList)
        {
//This loop draws the sorted list on to the screen
//if you look above code we have set zOrder for BoxA and BoxB as zero so they
//wont be rendered on the screen but BoxC will be rendered on screen since it have zOrder value greater than zero

            textureComponets.draw(batch);

        }
    batch.end();
}

@Override
public void dispose(){
}

//I want to zoom in to the map here
@Override
public void resize(int width, int height){
}

@Override
public void pause(){
}

@Override
public void resume(){
    }
}

```
> 0 votes

# Answer
Check whether it's possible to draw your objects or not when they are out of screen.

```
if(yourSprite.x>screenWidth || yourSprite.x+yourSprite.width<0 || yourSprite.y>screeenHeight || yourSprite.y+yourSprite.Height<0){
//Don't draw
}
else{
//Draw your sprite
}

```

And easily can find whether your sprite is behind of another object or not

```
if(boxA.x>=boxB.x && boxA.x<=boxB.x+boxB.width &&
   boxA.y>=boxB.y && boxA.y<=boxB.y+boxB.height){
//don't draw
}

```

**But** it's easy only for rectangle shapes, if you want to check this for polygons it's very expansive and better to draw your textures.
> 0 votes

---
Tags: java, libgdx, camera, frustum
---


title: How to map square texture to triangle?

text:
# Question
Title: How to map square texture to triangle?
I want to find the texture coordinates for point P. I have the vertices of the triangle and their corresponding uv coordinates.

The numbers in the little squares in the texture represent color values.

What are the steps of computing the uv coordinates of P?

# Answer
> 1 votes
You need to convert the point into barycentric coordinates and then use those points to interpolate the u, v coordinates.

Here is a previous answer that can help calculate the coordinates: What's the most efficient way to find barycentric coordinates?

With the barycentric coordinates, you then interpolate the UVs and get a weighted sum of the three vertices:

If your barycentric coordinates are defined as u,v,w then using the following equation (once for uv.X and once for uv.Y):

```
Point.UV.x = u * P0.uv.x + v * P1.uv.x + w * P2.uv.x
Point.UV.y = u * P0.uv.y + v * P1.uv.y + w * P2.uv.y

```

This works to linearly interpolate any property of each vertex across the triangle. Beware that interpolating normals linearly doesn't do what you want it to do as the normal becomes denormalized. This isn't an issue in your case.

---
Tags: textures, rendering, uv-mapping
---


# Question
Title: How do I make a box don't slide up/walk normally on a slope?
I'm trying to implement slopes in my game. When I walk up the slope and suddenly stop, here is what happens:

And when I move down, it goes like this:

I have set density to 0.5, friction to 0 on both platform and a player. I have set friction to 0 because otherwise player gets stuck on a wall if he is jumping against it. What could I do to solve this? By the way, I'm using setLinearVelocity for movement:

```
body.setLinearVelocity(new Vector2(10, body.getLinearVelocity().y));

```

# Answer
> 1 votes
I solved this problem differently, than answers sugested me.

First of all, when player isn't clicking move left/right button and doesn't jump, I made velocity Y = 0.

Next, instead of moving player in straight direction like this:

```
body.setLinearVelocity(new Vector2(-10, body.getLinearVelocity().y)); // LEFT
body.setLinearVelocity(new Vector2(10, body.getLinearVelocity().y)); // RIGHT

```

I check for a platform angle and then accordingly rotate that vector like this:

```
float tetha = platformAngle;
velocity.x = (float) (velocity.x * Math.cos(tetha) - velocity.y * Math.sin(tetha));
velocity.y = (float) (velocity.y + velocity.x * Math.sin(tetha) + velocity.y * Math.cos(tetha));

```

Also, I use this rotated vector **only**, when player is walking **downhill**. I noticed, that if he is walking uphill, then on top of the slope he jumps due to the upwards rotated velocity. So when he is walking uphill, I just use a straight vector and scale it accordingly, so that he won't slow down.

# Answer
> 0 votes
I'm not very familiar with what causes what specific effects when dealing with physics, but it doesn't appear that you are using a standard character controller, which will handle both of these problems for you most of the time.

The first one is usually a result of the slope absorbing some amount of the character movement, slowing it, even as you continue to provide an input force. Yes, even with friction 0. I am not sure how to solve it, necessarily, but the standard asset character motor should not have this problem.

However, the other problem has to do with gravity. Or rather, the lack thereof. It would appear that your gameobject scale and your gravity scalar don't line up. That is, its like having a 400 foot tall character: gravity will take a while to kick in for the character to fall half of its full height (four seconds!) whereas a correctly sized character would fall half its full height in only a fraction.

You will probably want to read over this article on common mistakes in Unity.

> **Incorrect Scale**
>
> In most games, players would assume that the scale of the world is relatable to Earth's scale. They would expect, for example, an enemy falling from a watch tower to fall at the same rate you would perceive on Earth. If the enemy falls too slowly or too quickly, it can detract from the immersion—particularly if the enemy is human-sized!

# Answer
> 0 votes
### TL;DR

Your problems will resolve themselves if you `applyForce` to the object at every frame, instead of setting the velocity.

## What's happening

When you set the velocity directly you are not allowing the physics simulation library (box2d) to enforce the normal laws of physics, and the funky behaviour you are witnessing is the result.

**Going Uphill:** When your character is walking up the hill, the velocity is being reset at every frame. This is because your `setVelocity` call causes the `y` velocity to be carried over from the previous step (There is some initial `y` velocity imparted when your character first steps onto the slope). So when you stop, the code still takes the `y` velocity from the previous step (which was greater than `0`) so your character moves upward.

**Going Downhill:** The movement pattern here is stranger, but I am still confident (from plenty of experience) that it's caused by setting the velocity based on the previous time step.

## Solution

Please, please use `applyForce` or `applyForceToCenter`, and set a non-zero friction value so that your character isn't sliding all over the place. If you try that and you are still having problems with your player getting stuck on a wall, then post another question here. This allows box2d to behave as it should, resolving velocities and positions on its own terms. If you want your character to remain upright remember to set `isFixedRotation` on the body.

I know from experience (lots of time with box2d) that if you are calling `setVelocity` on every `step` you are doing something wrong; there is always a better way.

---
Tags: physics, libgdx, box2d, angles
---


# Question
Title: OpenGL: strange thing with depth and text rendering
**TL;DR** I render a scene with M,V,P matrices as always. Than I render something (in this case - text) without any matrices and using separate shaders pair on coordinates with Z = -1. Somehow it's rendered closer to the camera than something on coordinates with Z = 0.9. I can't understand why.

Here is something I can't figure out.

Consider this vertex shader which is used for text rendering:

```
#version 330 core

layout(location = 0) in vec2 vertexPos;
layout(location = 1) in vec2 vertexUV;

out vec2 fragmentUV;

void main() {
    fragmentUV = vertexUV;

    gl_Position.x = vertexPos.x*2 - 1;
    gl_Position.y = vertexPos.y*2 - 1;
    gl_Position.z = -1.0;
    gl_Position.w =  1.0;
}

```

When text is rendered with Z = -1 everything looks fine:

And if I change Z to 0.9 scene looks like this:

According to this tutorial perspective matrix modifies the scene so that all visible objects are in cube where -1 \<= {X,Y,Z} \<= 1. Also by default camera looks "down" towards Z axis.

So shouldn't it be conversely: larger Z - closer to the camera?

Full source code is on GitHub. Here is a code which renders text. And this code fills corresponding VBO.

# Answer
> 1 votes
Mystery solved. I was not aware of the fact that OpenGL expects vertex shader output to be left-handed. And that it *is* usually left-handed after multiplying coordinates to projection matrix (see this article). So smaller Z in vertex shader - closer to the camera.

And here is a great cheat sheet about left-handed and right-handed coordinates:

---
Tags: opengl, shaders, glsl, depth-buffer, text
---


# Question
Title: How to do directional per fragment lighting in world space?
I am attempting to create a GLSL shader for simple, per-fragment directional light. So far, after following many tutorials, I have continually ran into the issue: my light is specified in world coordinates, however, the shader treats the light's position as being in eye space, thus, the light direction changes when I move the camera. My question is, how to I transform a directional light position such as (50, 50, 50, 0) into eye space, or, would doing things this way be the incorrect approach to the problem?

# Answer
You have two options. The easiest in my opinion for a variety of reasons is to just multiply your light data by the view/camera matrix so that they're in view space.

The second option is that in your vertex shader you can generate outputs multiplied by only the model transformation matrix in addition to the usual fully projected outputs (similar to how you can generate outputs with only the model and view matrices to get outputs in view space).

Yet another option is to take the NDC-space data you have in the fragment shader and the inverse of your projection and view matrices to recalculate world-space coordinates. Just remember that you need to do the whole W divide step as NDC-space is more than just a transformation by the projection matrix.

I personally just calculate light data in view-space and add extra outputs to the vertex shader which are in eye-space, since it makes the math easier and slightly faster (you generally don't have enough lights to make the matrix multiplication on the CPU be a big deal, and with a deferred shader pipeline, you can do it on the GPU anyway).
> 4 votes

# Answer
I followed Sean Middleditch's advice to solve my directional light issue which was the same as the OP. ( I can't vote yet )

In glm i used the following code to solve my problem;

```
_view  = glm::lookAt(glm::vec3(3, 3, 3), glm::vec3(0), glm::vec3(0,1,0));
// send this to uniform location.
glm::mat3 v(_view);

```

In my shader i just did the following

```
lightDir = normalize(view * lightDir);

```
> 1 votes

---
Tags: opengl, glsl, matrix, lighting
---


# Question
Title: What does "formalism" mean in the context of video game theory?
I've come across the term "formalism" in a number of articles and discussions on the topic of video games. What does it mean?

PS: if I'm posting in the wrong place, could someone please link me a forum/site where I can ask academic game theories questions?

# Answer
Lacking any specific context, it means what the word itself means:

> the practice or the doctrine of strict adherence to prescribed or external forms (as in religion or art)

(among other similar definitions)

Within the context of the games industry, and game design or game theory in particular, "formalism" doesn't hold a specialized meaning. The concepts of philosophical, artistic and/or mathematical formalism exist and may be appropriate for a particular conversation about game design or theory, since it's a domain that has a mix of all three of those things.

But there's nothing really unique about the term as it applies to game development, in general (or at least, not in a fashion that is an established or ad hoc standard).
> 3 votes

---
Tags: terminology, game-theory
---


# Question
Title: Should I use Coroutines to change variables in inspector smoothly?
I want to change the aperture of the depth of field in the camera smoothly by using `Mathf.SmoothDamp` and a Coroutine, however, since I'm new to game development, I don't know if this is the right way to do it. Any suggestions?

Code:

```
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
using UnityStandardAssets.ImageEffects;

public class GameStartController : MonoBehaviour {
    public Button startButton;
    public GameObject cubeSpawner;

    // Use this for initialization
    private void Start() {
        startButton = startButton.GetComponent<Button>();
    }

    public void StartGame() {
        EnableCubeSpawner();
        SpawnStartingCubes();
        HideStartMenu();
        StartCoroutine("FocusCamera");
        PlayBackgroundMusic();
    }

    // Enables the cube spawner, so it can start spawning cubes
    private void EnableCubeSpawner() {
        cubeSpawner.SetActive(true);
    }

    private void SpawnStartingCubes() {
        cubeSpawner.GetComponent<CubeSpawner>().GenerateStartingCubes();
    }

    private void PlayBackgroundMusic() {
        var audio = GameObject.FindWithTag("Audio").GetComponent<AudioController>();
        audio.PlayBackgroundMusic();
    }

    private void HideStartMenu() {
        startButton.transform.parent.GetComponent<CanvasGroup>().interactable = false;
        startButton.transform.parent.GetComponent<CanvasGroup>().alpha = 0f;
    }

    private IEnumerator FocusCamera() {
        var camera = GameObject.FindWithTag("MainCamera").GetComponent<Camera>();
        var velocity = 0f;

        while (Mathf.Abs(camera.GetComponent<DepthOfField>().aperture) > 0.001f) {
            Debug.Log(Mathf.Abs(camera.GetComponent<DepthOfField>().aperture));

            camera.GetComponent<DepthOfField>().aperture = Mathf.SmoothDamp(camera.GetComponent<DepthOfField>().aperture, 0f, ref velocity, 0.3f);
            yield return null;
        }

        camera.GetComponent<DepthOfField>().aperture = 0f;
    }
}

```

# Answer
> Should I use Coroutines to change variables in inspector smoothly?

The real answer is "it depends" but to start, there's nothing wrong with your approach. While the alternative would be to just place a function call in your `Update()`, what you're doing allows you more flexibility, allows you to start and stop easily, and keeps you from needing to litter your class with flags. Arguably, utilizing the `Update()` built into `MonoBehaviour` would make debugging slightly easier.

While that hopefully answers your question, I would still clean up some parts of the coroutine you wrote. In Unity, you want to avoid calling `GetComponent<T>` during runtime so you should hold onto the reference to the `DepthOfField` component you're access 4 times each frame (unless there's the possibility that component is destroyed and recreated) :

```
private IEnumerator FocusCamera() {
    var camera = GameObject.FindWithTag("MainCamera").GetComponent<Camera>();
    var velocity = 0f;

    DepthOfField dof = camera.GetComponent<DepthOfField>();

    while (Mathf.Abs(dof.aperture) > 0.001f) {
        Debug.Log(Mathf.Abs(dof.aperture));

        dof.aperture = Mathf.SmoothDamp(dof.aperture, 0f, ref velocity, 0.3f);
        yield return null;
    }

    dof.aperture = 0f;
}

```

I also figure I'd mention using the `string` version of `StartCoroutine()` has more performance overhead that just calling the `IEnumerator` directly. The `string` version would also only allow you to pass a single parameter (which doesn't matter in this case but can make a difference down the line):

```
StartCoroutine(FocusCamera());

```

The tradeoff here is whether or not you'd like to call `StopCoroutine()` at some point. When using `string`s you can call `StopCoroutine("FocusCamera")` and it will simply kill the first coroutine with that name. This makes things simple when you're managing a single instance that starts and stops regularly but, from what I can tell, you don't have a need for `StopCouroutine()` at the moment and there's also minimal work to do for stopping with the non-string approach:

```
private IEnumerator coroutine;

...

coroutine = FocusCamera();
StartCoroutine(coroutine);

...

StopCoroutine(coroutine);

```
> 2 votes

# Answer
Using `coroutines` in this kind of situations is more convenient. It's pretty flexible, for example, you can create series of events.

```
IEnumerator Start () {
    yield FocusCamera();
    yield ShowTitleGraphic();
    yield FadeTitleGraphic();
    yield FadeInMainMenu();
    // etc.
}

```

Pretty informative discussion is here.
> 0 votes

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


# Question
Title: How can I make the player spawn at a specific location on the map?
I'm trying to make a game in Unreal Engine 4.8,

I've got a Player Start actor in the main level and a box collision that loads a new level, but when you return to the main level you obviously spawn at the Player Start, how can I make the player spawn at a specific location on the map, because I've tried with a lot of things and they didn't work.

For example I start at the tent and you walk to the house, you enter the house level, and after a few minutes you leave, what happens is that you spawn at the Player Star and I want to spawn in front of the house.

# Answer
There are lots of ways to do this kind of management for reloading a level after a transition.

One way that comes to mind is the use a global object that persists between levels during level transitions. This object could be something like a UGameInstance that tracks the position in the last level that the player was at before transitioning to the new level. When the player leaves the house level, in the "overworld" level, you check the UGameInstance for the player's last position and set the location to there. The player won't notice a thing because it will happen in the same frame.

Another way is to implement a custom level spawn manager for your "overworld" that has several IDs pertaining to the index of a PlayerStart in the level that you have placed. Then you can associate an ID when you leave a certain level (like the tent or house) and pass it as an option when you load the level. You will then set the player's start to that PlayerStart instead of the default.

Finally, you can use the save/load features of the engine when you transition through levels.

Here are several links you can use for reference:

Finally, take a look at the ShooterGame as it has code to choose spawn points. It is overkill for this, but lets you read code and get an idea of how to implement an spawn chooser class that you would just tweak to use in code based on the level you just left.
> 2 votes

---
Tags: unreal-4
---


# Question
Title: Should I implement Entity Component System in all my projects?
I'm not here to ask for any specific code implementation, I'm here just to make my ideas clearer. But let me explain the situation:

I have already developed some little and amatorial game projects (never published tho) but I recently found some interesting articles about ECS and I began to read more about it. I found the whole ECS concept every interesting and I thought I could implement it in a very tiny game I'm working on in my free time.
The problem is: should I implement this pattern on a every little project with simple game mechanics and poor gameplay ?
The 2D game I'm working on will be entirely developed by me, so I do not actually need to make the code easier to mantain by other people. This game will basically have just 2 players, some weapons and a large variety of bullets and superpowers. No IA enemies, no vehicles, static and tiny maps and.. Just that. It will have, of course, a simply physics system (just to make players fall and bullets move, for example), and a tiled but very little map which is editabile by players (destroying tiles).

So the point is: why should I actually write an ECS for such a basic game ? Do I really have any real advantage considering the game design ?
I mean, I know it is very good to make your code very flexible and easy to mantain even in the future, but I also know that this pattern was invented to avoid some limitations and the code duplication which the old hierarchical game structure provides, but this game doesn't have a wide hierarchical structure, as far as I can see.

I started coding it, but I discovered some aspects which, to be honest, scare me. Like having all the components talking to each other through a reference of their owner (the entity they are bound to), which as far as I know, is not very good to avoid cache misses.
The last thing is that I have the feeling that I won't write more than 2 components of the same type, and this would make the ECS less useful.

I know I don't have the whole ECS concept really clear in my mind, this is the first time I implement it, by the way, but I hope you got the point of my problem.

# Answer
> 13 votes
**Short version: no**, your job as an engineer is to evaluate all applicable solutions to problems before choosing a solution

Long Version:

"ECS" is an overloaded term. It had a somewhat clear definition at first but it's been overly muddled since. It doesn't matter much, though, since the answer is the same either way: every architecture has pros and cons. If the pros align with your game and the cons are minor, the architecture is good; if the pros have little utility for you and the cons are weighty, the architecture is bad.

Generally speaking, I wouldn't bother with components at all for simple games. Tetris is not improved in any conceivable way using componentization for entities. Likewise for Pong, Breakout, etc. Basically, if you have a small number of distinct object types in the game, the boilerplate of a componentized engine outweigh the benefits of breaking up the objects in the first place.

Games with a wide variety of objects but low performance needs fall into another broad category. These would be your usual bullet hell games, platformers, and even many "old school" RPGs. Since you have a large variety of objects, it's useful to be able to build them out of reusable components. However, these games generally have a small number of objects of immediate interest to the players, so you don't have to be overly clever. A naive component architecture that just has a single `GameObject` class that stores a list of `IComponent` objects works just fine.

At yet another discrete level, you run into games with a large variety of objects but are also very performance sensitive (because they have a large number of objects or because they run on very constrained platforms). In these cases, *elements* of the ECS pattern can be very useful to achieving better performance. If you're making the next Battlefield, this might be you; otherwise, it is likely not applicable.

The point is that your game determines what architecture you need; starting with an architecture without considering the needs of the game is reminiscent of the old adage "putting the cart before the horse." Architectures have cost in terms of implementation, maintenance, conceptual complexity, etc. You only want to pay a cost if what you get in return is worth more to you than the cost you paid.

As Einstein might say, you should **make your game as simple as possible, but no simpler**.

---
Tags: entity-system, component-based
---


# Question
Title: To-hit formula for turn based isometric battle RPG
I am an amateur using Unity 5 to create the aforementioned type of game. I am trying to write a function to determine whether a close quarters combat(melee) attack lands or not but am extremely terrible at math. How bad? Despite tutoring for 2-3 hours every day after class and doing my homework assignments multiple times for practice even after submitting them, I still failed business calculus 3 times and had to abandon college. Math simply does not click for me. I found a sweet sales job in the booze industry so it's all good though, but I digress. If anyone could humor me and point me in the right direction I would appreciate it. Here are the details, let me know if I'm being inarticulate.

* Combat is turn based, in the same vein as Ogre Battle, Heroes of Might & Magic, and Final Fantasy Tactics. Hopefully this gives you an idea of movement and engagement, if not let me know and I'll elaborate with specifics.
* Whether or not an attack lands is determined by (what I'll call for simplicity) the two combatants "Weapon Proficiency." This system is based on a 100 percentile system. For Example, if both attacker and defender have a Weapon Proficiency of 50, then the attacker has a 50 percent chance to hit the defender.

My issue is I have no idea how this mathematical function works when weapon proficiencies are of disparate values. For example, if the attacker has a weapon proficiency of 35 and the defender has a weapon proficiency of 85, what percent chance does the attacker have of scoring a hit?

Any help would be extremely appreciated, again forgive me if I'm not explaining the subject lucidly.

# Answer
There are a lot of possibilities. Here are two I can think of:

The attacker's weapon proficiency is `attack` and the defender's is `defense`. `percentage` is between 0 and 100, but it can easily be modified to be between 0 and 1.

---

```
percentage = attack/(attack + defense) *100

```

Characteristics:

* It can only get to 100% if the defense is 0. So no matter how good a weapon is it can still fail to any defense that isn't 0.
* It can only get to 0% if the attack is 0. Even if the defense is very good it can still fail.
* It depends on the ratio of attack/defense. Which means that the percentage is the same if the attack is 100 and the defense is 10, or if the attack is 1000 and the defense is 100.

---

```
percentage = 50 + (attack - defense)/ factor
if (percentage > 100)
    percentage = 100;
if (percentage < 0)
    percentage = 0;

```

Characteristics:

* The percentage can get above 100% or below 0%, so you have to check it. It also means an attack can be so much better than a defense that it is sure to hit, or a defense can be so much better that it is sure to block.
* You can tweak the result by changing *factor*, to get the results you want.
* It depends on the difference of attack-defense. Which means that the percentage is the same if the attack is 100 and the defense is 50, or if the attack is 200 and the defense is 150.

---

If they don't fit your needs, feel free to comment why to help us define what you are looking for.
> 1 votes

---
Tags: rpg, turn-based, mathematics, combat
---


# Question
Title: How can I make a peer-to-peer multiplayer game?
How can I make a p2p multiplayer game? I would like to have a server-less multiplayer game. But then, how all the clients know each other?

Why the p2p-protocol is so famous in file transfer but not in multiplayer games?

# Answer
> 37 votes
Peer to peer games generally still have a game host. Its the game host that posts the game to the master games list and accepts new connections. Whenever the game host accepts a new client to the game it notifies all existing clients about the new client so that they can ensure they connect to the new client.

The simplest way to implement p2p is with a lobby. All clients connect to the host in a lobby (or chat room). When the host is ready the player presses start and they all enter the game at the same time (commonly used in strategy games). A more complex approach is to use "drop-in drop-out" where players can join and leave mid game, however this is a lot more complex to implement in a p2p game and requires a feature called host-migration.

A good number of games use peer to peer networking, including most strategy, sports and driving titles. Just about all Xbox360 and PS3 games use p2p networking. The client-server architecture is mostly used in first person shooter or MMO games.

Client-Server is generally easier to implement as only 1 machine has not know the entire game state, the clients are basically just renderers with some prediction to make things look smooth.

When you build a p2p engine, all clients need a full state of the game world and they all are required to stay in sync.

For more details on p2p and client-server architectures I suggest you read the following article: What Every Programmer Needs To Know About Game Networking.

And if you're new to networking in general checkout the other great articles on that site. Glenn is a networking genius.

# Answer
> 14 votes
There are some interesting aspects about peer-to-peer systems and action games. I tried to post them as a comment on Glenn Fiedler's blog, but apparently he doesn't like to be proved wrong and pulled the whole article instead. It's on Internet Archive, in case you want to read it.

He didn't let the comment go online, so I'll quote it here:

> The Peer-to-Peer suggestion from the first post is actually an interesting starting point, even though it's a bit naive at times: The first possibility would be to combine the system with a standard client/server model with prediction as outlined in your post about game networking. The lower P2P ping would dramatically reduce the prediction lag between players depending on their location: The effect probably wouldn't be visible for most US gamers, but here in Europe pings of 200+ are normal on most servers and a direct connection would reduce the prediction lag to that of a European server.
>
> A true P2P approach without server is a bit more complex: A main concern with decentralized networks is ensuring consistency, especially if the simulation could suffer from butterfly effects because of slightly different timing of commands sent over the network or floating point issues. This is possible by networking the state of each object (players, NPCs, ...) at least periodically. It wouldn't even be necessary to do it for all objects at once, and each client could take possession of certain objects. Networking enough objects in a certain time should damp the difference that builds up between each synchronization of an object enough to become irrelevant even for sync-intervals of a second or more.
>
> The second problem with P2P systems is security, but that can be solved with a relatively small fix in this case: The clients can use their physics simulations to collect information about the error level on each physics object. Manipulated physics always result in a larger error, so the clients would simply "vote" to disconnect from the peer controlling a suspicious object. Additionally, control messages for non-physics objects are forwarded between clients based on their importance: Player updates can be forwarded randomly, important and infrequent updates should always be sent, but still to a random player. This way a player would have to control a large share of the connected clients to be able to cheat in any noticeable way.
>
> \[...\]

You can find the thread I'm referencing at http://www.devmaster.net/forums/showthread.php?t=14640.

I think someone mentioned the firewall problems peer-to-peer has in one of the threads from the article. A possible solution would be a NAT-Punchthrough:
\- NAT Punchthrough overview
\- Peer-to-Peer Communication Across Network Address Translators

There is no 100% success rate, so you should tell the players to open a port anyway.

# Answer
> 12 votes
There are many reasons p2p is not popular in games, mostly due to lag. Everyone is as slow as the slowest player. We're not talking about bandwidth here, but ping time.

p2p can transfer tons of data, but it does so with a quite high ping, games need to transmit very small amounts of data, with minimal ping time.

# Answer
> 9 votes
A good example of 'true peer-to-peer' gameplay would be a real-time-strategy game such as Starcraft.

In a game with hundreds of units/projectiles in motion, it's not practical to repeatedly send unit positions/states over the network to all other players, so one solution here is for all players to run the (exact same) simulation in sync.

When one player performs an action, the command/order ('move zergling to X,Y') can be sent to all other players, to be executed by all instances of the simulation a fraction of a second later.

In this situation, if any player disconnects, the game can continue - as there's no need for a server/host to be running the game, the remaining players can carry on.

However, keeping the games in sync is non-trivial, you have to use a fixed timestep for the game logic updates, and must be very careful with use and seeding of random number generators, to ensure that the simulations will not diverge!

# Answer
> 5 votes
It would be a bit disingenuous to claim that it's not famous for games when most Real Time Strategy games (Star Craft series, Command and Conquer Series) and many FPS games (Call of Duty: Modern Warfare 2) use it.

That said how one learns about the game is up to the matchmaking / lobbying service that you use or create. But even once one learns about the game, there still may be one or more peers that are more equal than others. Consider the case of 3 clients wishing to play, one behind an open nat, 2 behind strict (Closed) nats. The open nat peer can take connections from the other two. But the 2 strict can not connect directly to each other, they will require the open nat to relay the packets. If the open nat peer drops from the game, then either another relay would need to be found or the game will be disrupted.

# Answer
> 2 votes
you may also want to check out Badumna (www.badumna.com) which claims to be a peer-to-peer networking solution for online games. It seems to do the game state synchronisation in a distributed manner and according to their website there is a Flash version coming.

# Answer
> 1 votes
You probably want to run with one player(We'll call him/her the "Host") as a non authoritative server. You'll have all the other players communicate what they are doing on their end with our host, and the host will relay the messages to the other players.

You probably also want to pass a list of what computers are connected to the hosting player so that if they drop a new host can be chosen somehow and start communicating with the remaining players.

The documentation for smartfoxserver may help you out and/or you may end up wanting to use it for your game as well. You'd just embed it into your client game instead of having a separate client and server program.

# Answer
> 1 votes
I'm a little bit interested on this matter. You are saying there are a lots of problems with making a game p2p instead of a classic client-server model. But i'm pretty sure that p2p is like client-server but every peer has the chance to become a server. About the LAG if u add one more machine as a server there are more probabilities that many clients are further from the server, but using p2p there are no extra machines in the lobby u can manage the latency tests and create groups with minimal ping. About the traffic generating, as i've learned you must ask the clients to transmit lesser than less i mean the clients have to figure all the other clients are willing to mean.

# Answer
> -1 votes
If you're making a relatively simple looking mmorpg with low system requirements, I'd suggest creating an internal program that creates a "frequency" based on the contents of the game's folder and what the files consist of. This will make people with the same "frequency" play on the same channels. Modded, manipulated or normal clients will be separated. This will only work for native hacks or mods, but I'm sure this covers all of the "dumb" cheaters. Combined with the error checking method that one person mentioned means little to no moderation required. As far as ports go, just have it cover port 52225 with a background process that keeps it plugged on routers without trigger-ports.

---
Tags: networking, multiplayer, peer-to-peer
---


title: Sprite disappears on android

text:
# Question
Title: Sprite disappears on android
I am programming a game in 2D for android and pc/mac. The sprite is the same and it's visible on the pc/mac. But once I use android and move the sprite, it disappears. The code is this: what could be the reason?

This is what it looks like:

```
#if UNITY_ANDROID
  float MitteX = Screen.width - 80;
  float MitteY = 80;
  float x = Input.touches[0].position.x - MitteX;
  float y = Input.touches[0].position.y - MitteY;
  if (Input.touches[0].position.x > Screen.width/2)
  {
    float r = Mathf.Sqrt(Mathf.Pow(x, 2) + Mathf.Pow(y, 2)) / 100;
    if (r > 0.5f)
    {
      r = 1.5F;
      KameraAbstand = 50;
    }
    else
      KameraAbstand = 20;

    anim.SetFloat("Geschwindigkeit", r);
    Vector2 n = new Vector2(x, y).normalized;
    if (!anim.GetBool("istTot"))
    {
      rb.velocity = n * maxGeschwindigkeit;
      rb.transform.forward = n;
      //rb.transform.Rotate(0, 0, phi - phiv);
      neu.text = r + "\n" + n.x + " " + n.y;
      if (rb.transform.forward.x < 0)
      {
        Vector3 skalJetzt = transform.localScale;
        skalJetzt.y = -1;
        transform.localScale = skalJetzt;
      }
      else
      {
        Vector3 skalJetzt = transform.localScale;
        skalJetzt.y = 1;
        transform.localScale = skalJetzt;
      }
    }
  }
#else
  float ho = Input.GetAxis("Horizontal");
  float ve = 0;
  if (umdrehen)
    ve = -Input.GetAxis("Vertical");
  else
    ve = Input.GetAxis("Vertical");
  if (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift))
  {
    ve *= 1.5F;
    KameraAbstand = 50;
  }
  else
  {
    KameraAbstand = 20;
  }

  anim.SetFloat("Geschwindigkeit", Mathf.Abs(ve));
  if (!anim.GetBool("istTot"))
  {
    rb.velocity = new Vector2(
      ve * maxGeschwindigkeit * transform.right.x,
      ve * maxGeschwindigkeit * transform.right.y);

    rb.transform.Rotate(Vector3.back, ho);
  }
  if (transform.right.x < 0)
  {
    Vector3 skalJetzt = transform.localScale;
    skalJetzt.y = -1;
    transform.localScale = skalJetzt;
  }
  else
  {
    Vector3 skalJetzt = transform.localScale;
    skalJetzt.y = 1;
    transform.localScale = skalJetzt;
  }
#endif

```

# Answer
There are a few bugs involved with negative scaling in Unity 5 so my best bet on the issue on first sight would be this line of code:

```
Vector3 skalJetzt = transform.localScale;
skalJetzt.y = -1;
transform.localScale = skalJetzt;

```

Instead of setting the localscale to -1 you could try to use transform.rotate() to set up your sprite facing the right direction.

Had similar problems before in the past so I hope this may help you out.
> -1 votes

---
Tags: android, unity
---


title: OnTriggerEnter() without rigidbody?

text:
# Question
Title: OnTriggerEnter() without rigidbody?
I know this is an old question and it has been answered for a lot of people. Unfortunately none of the solutions apply to the problem I seem to have with rigidbodies.

I have a moving AI character and the playermodel. When the AI gets to close the player just bumps on top of it. If I unattach the rigidbody from the moving AI this does not seem to be a problem. My player is controlled by a charactercontroller and the rigidbody is set to "Is Kinematic".

Of course, when none of the agents has a rigidbody my entire combat mechanic falls apart. Does anyone have any idea on how to solve this?

For clarity, here is a short demonstration of the bug: Bump

And the code in question:

```
void FixedUpdate ()
{
    if (!controller.isGrounded)
    {
        movement.y -= gravity * Time.deltaTime;
    }
    controller.Move (movement * Time.deltaTime);
}

void CalcMovement (float h, float v)
{
    movement = new Vector3 ();

    if (v != 0 || h != 0) {
        movement = v * forward + h * right;
        movementDirection = movement.normalized;
    }
}

```

# Answer
This is not quite what I hoped for, but it did solve the problem of the bouncing. I replaced the rigidBody and the capsuleCollider with a CharacterController. I don't know if this is an efficient way of avoiding rigidBodies and still having collision and trigger detection, but it's a working way.
> 1 votes

# Answer
You can have a try to remove the `rigid body` from your player. A `Character Controller` component contains `rigid body` and `Collider`
> 0 votes

---
Tags: unity, collision-detection, physics, rigidbody
---


title: Health Bar is always 100% full

text:
# Question
Title: Health Bar is always 100% full
I have this GUI to graphically display a variable similar to the health in a game. The variable 'test' goes up and down during gameplay.

To show this I have the following onGUI ():

```
public GUISkin btnskin1;
public Texture2D emptyTex;
public Texture2D fullTex;
public Vector2 pos = new Vector2(20,40);
public Vector2 size = new Vector2(60,20);

void OnGUI()
{
    float test;

    GUI.skin = btnskin1;

    if (LoadDiagram.diagramaCarga.TryGetValue (TimeManager.gametime, out test))
    {
        GUI.BeginGroup (new Rect (pos.x, pos.y, size.x, size.y));
        GUI.Box (new Rect (0, 0, size.x, size.y), emptyTex);

        //draw the filled-in part:
        GUI.BeginGroup (new Rect (0, 0, size.x * test, size.y));
        GUI.Box (new Rect (0, 0, size.x, size.y), fullTex);
        GUI.EndGroup ();
        GUI.EndGroup ();
    }
}

```

In the game scene I attached the empty bar to the emptyTex texture, and the full bar to the fullTex texture. When I play the game, he bar is always full. I have not inserted the minimum and maximum of the variable test because I don't know where, but I guess that may be necessary.

Any hints?

# Answer
Actually your trying to use percentage but no with right way. If you want to play with values of slider like stuff then then multiply the FullValue with percentage. And you can get useable value from percentage with dividing it by 100.

For example

* 100% = 1
* 50% = 0.5
* 10% = 0.1
* 0% = 0

In this line of code you are using `GUI.BeginGroup (new Rect (0, 0, size.x * test, size.y));`

Suppose `size.x = 500` and `test = 6` then `size.x * test` will become `3000`, which is greater than `500`,greater than the actual `size.x`.

You should treat these type scenario with percentage values.

In your case you can do this by,

```
GUI.BeginGroup (new Rect (0, 0, size.x * (test/6.0f), size.y));
// Where 6 is the maximum value

// For test = 6
size.x * (test/6.0f)` will give you => `500 * 1 // this means full/maximum.

// For test = 3
size.x * (test/6.0f)` will give you => `500 * 0.5 // this means 250 (Half).

// So on...

```

Hope you got my point.
> 3 votes

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


# Question
Title: Error : No default constructor exists for "Sprite"
What i want to do is make the Player class inherit the Sprite class.

So I inherited it like this :

```
class Player: public Sprite {};

```

But when I go to my Player.cpp I get the following error :

> Error : No default constructor exists for "Sprite".

But it does have a constructor (well, 2 of them...) :

```
Sprite(int index, sf::Vector2f position);
Sprite(int index, sf::Vector2f position, float rotation);

```

---

Also, not sure if this is the right place to post this. But since it contains SFML library code I will post it here.

# Answer
> 2 votes
This is a pure c++ error and in the future it should be asked on SO, but I'll answer at the end of the post.

---

This said, with OOP, I would suggest you have your player *use* a sprite, and not *be* a sprite.

A player *is not a* sprite, a player *has a* sprite. Making this kind of architectural choice early in the development can get you in a big mess.

---

Since the parent class does not have a default constructor, your children class cannot use a default compiler-generated constructor as it will not be able to call the default constructor of the parent (because it does not have any).

To fix this issue, you have to explicitly add a constructor to your `Player` class and call the constructor for the parent class (the `Sprite`).

```
class parent
{
public:
  parent( int p1, float p2 ) {}
};

// This will not compile
class child : public parent
{
public:
};

// This will compile
class child2 : public parent
{
public:
  child2() : parent( 1, 2.9f ) {}
};

```

---
Tags: c++, sfml, inheritance
---


# Question
Title: What is the difference between PBR and SSR?
I am very new to game development and I have been trying to understand the difference between Screen Space Reflection and Physically Based Rendering.

I have read about PBR, and from what I understand, it tries to mimic how light reflects in real life, which is it usually gets split to two components, specular and diffuse depending on the type of material.

As for SSR, pls correct me if i am wrong, it is how reflections look on a surface.

If my understanding of SSR is correct, then aren't they in a way the same? I mean, isn't the way reflections look on a surface dependent on the surface roughness and etc. This will then affect how much light is specularly reflected and how much is diffusely reflected. Again, please correct me anywhere I am wrong.

# Answer
> 20 votes
## Physically-Based Rendering

You're on the right track when you say "it tries to mimic how light reflects in real life, which is it usually gets split to two components, specular and diffuse depending on the type of material."

But we've been modelling materials with specular and diffuse in games & computer graphics for a long time. The trick is that we used to handle these things as completely independent - changing the specularity didn't change the diffuse:

This is an example of Phong shading from the Blender wiki. You can see that it offers two parameters of specular intensity and specular hardness, and these parameters only change the whitish part of the reflection. The blue diffuse reflection doesn't change at all.

The way games would use this is an artist would be tasked with hand-tuning these values for each material until it "looked right." Because "specular hardness" isn't a real physical property of materials that we can measure precisely, it had to be done by eye.

This method is a bit brittle. As you change the illumination (say, a dynamic object moving through different areas, or in an environment with time of day and weather) it can look subtly wrong - too bright or too dark - as the viewing conditions aren't the same as the ones its specular parameters were tuned for.

Enter Physically-Based Rendering, which is an attempt to ground our material descriptions in more objective, measurable properties of real surfaces. One of the most apparent properties is conservation of energy - a rougher surface will scatter light diffusely, and a smoother/more metallic surface will reflect light more directly, but it's the same pool of light they're both drawing from. So other things being equal, as we make a material shinier, the diffuse component should get darker:

This example is from a Marmoset article explaining PBR originally shared by Syntac\_

There's more to physically-based rendering than energy conservation, but this is probably the most telltale sign that you're working with a physically-based system.

By keeping the reflection models similar to how materials work in real life, we reduce the need for fudge factors and artist subjectivity to get a real-world material like wood or concrete or leather to *look* real under a wide variety of lighting conditions.

Note that another answer described this in terms of indirect illumination from light bouncing off other objects in the scene. While many lighting systems that use physically-based models will also include tools to model this, it's usually known under a separate name of **Global Illumination**. This is the effect that makes one side of the diffuse head in this image appear green, illuminated by light bouncing off the green wall:

Image from this article on global illumination

## Screenspace Reflection

While PBR tries to model how the material reflects light, Screenspace Reflection tries to capture what is being reflected - specifically, for a shiny, mirror-like surface, what should I see in the reflection?

Again this is a relatively recent rendering technique that's probably clearest to understand by contrast to how games did it before:

**Flipped Rendering** \- common for water planes or flat mirrors, we literally render all the reflected geometry a second time mirrored across the plane of the reflective surface. This gives high-quality reflections (full detail, objects in contact with the surface line up with their reflections) but only works correctly for flat surfaces. The more wavy or bumpy a surface is, the less this behaves like real reflections, which should distort or blur in complex ways.

**Cube Maps** \- let us store the colour that would be seen by any view ray radiating out from their center point. By dynamically rendering cube maps from selected points in the scene, we can estimate what colour should be reflected off any arbitrarily curved surface. The trouble here is that the cube map is only completely correct at its center point - as the point where we're simulating reflection moves around the scene, it should see some parallax, which isn't present in the cube map. This means objects don't tend to line up with their reflections.

Screen Space reflection tries to address these limitations by using the rendered scene itself as the source for reflection information. It ray-marches a reflected view ray, using the scene's depth, until it would intersect something in the rendered scene.

Here's a slide from an EA DICE presentation about their approach to reflections in the Frostbite engine.

This means (with some smart algorithmic work) we can get reflections with reasonably raytracing-like accuracy off of arbitrary surfaces in games, having correct alignment of surfaces in contact, distortion and blurring, *as long as the reflected part of the surface is visible on-screen* (ie. not offscreen or occluded by something else). Where the reflection can't be accurately determined by the raymarching, it's usually approximated using nearby samples or a fallback cubemap representing the scene beside/behind the camera's view.

You can see in this example of screenspace reflection, the impression can be very convincing, although small errors are noticeable (see the reflection of the undersides of the cubes, which are not visible in the rendered frame and so simply smear & repeat adjacent pixels, or the holes in the right green curtain's reflection beside the flower pot and at the bottom of the screen, where the raymarching failed to find the right reflected pixels). It's common to use this technique for moderately shiny/slightly rough surfaces to help make the occasional error less visible.

# Answer
> 1 votes
They are not really related.

This document from Marmoset explains PBR well without invoking lots of math.

Screen space reflections on the other hand is a post-process screen-space technique used to render real-time reflections. It is generally much cheaper than rendering cube maps each frame, but can look less accurate and doesn't allow off-screen objects to be reflected.

---
Tags: lighting, terminology, pbr, specular, ssr
---


title: Fixed Time Step Flutter

text:
# Question
Title: Fixed Time Step Flutter
I've seen a lot of questions about this problem, but really no solution. Hopefully I can explain the issue well enough that I can get some sort of closure on this problem.

I'm using a Fixed Time Step based on the code found here : GAFFER ON GAMES / Fix Your Timestep! , and with that method I'm using an `accumulator` value to compensate for any slowdowns or speedups in the frame rate. Typically the time between frames is between 15.5 and 17.5 ms (with the fixed rate aiming for 1000/60 fps). What ends up happening is this:

That green chart is showing the accumulator. Which freaks out once the accumulator gets beyond 1000/60 fps. At this point you can see that because of the variance between refresh rates (15.5-17.5) sometimes the accumulator is above or below the threshold of 16.66666666... until it eventually gets to a point that the accumulator is too big to be negated by the next frame variance.

If I simply ignore the refresh rate and assume a constant 60fps the flutter never occurs, so its shouldn't be a vsync issue (right?), it's not the GC kicking in. It's an issue with this part of the code:

```
accumulator += frameTime;

while ( accumulator >= dt )
{
    update_logic();
    accumulator -= dt;
}

```

I realize the issue is when the accumulator hits ~0 it actually starts doing double updates and skipping updates for a while causing the flutter/stutter look.

It's very possible that I'm just not understanding how the accumulator is suppose to work, or perhaps the variance in screen refreshing is too much for this to work well.

Thanks in advance!

**Update**

Here is a screen cap of an output log showing how the variance in frameTime is causing the update call to double up and skip.

The items in red are when the accumulator never gets to 16.66666666...

For the time being I'm 'fixing' the issue by never letting the accumulator to get below the frameTime variance, but this doesn't feel like a real answer, just a patch.

```
if(accumulator < 1){
    accumulator = 1.5;
}

```

Perhaps this bit will help explain. If you start the accumulator at 0 and the first frame takes 15.89999ms, we don't update anything, and then if the next frame is 17.55555ms we now have (~33.44ms) so it updates twice. The more the variance in the frameTime the worse the problem.

I've noticed plenty of people with this issue, and typically the conversation ends with no posted solution, it either "goes away" or the thread dies.

# Answer
The solution provided in the Blog post you mentionned is not that good, even if you follow it to its end, that is to say if you interpolate.
Because you won't be able to escape the case when the error accumulates until there's no need for update, and then obviously there will be the need for two. It's just maths here.
The interpolation hides that issue since even with the 0+2 issue, the interpolation between two steps gives you almost the +1 status, but at the cost of duplicating all positions to be able to, well, interpolate, and you might even need to store speed or other things if your game depends on it (trail effect...). Ouch.

Now you can improve the algorithm and try to minimize the *mean* error by considering that if you the accumulated error is 'near enough' from the logic time step, you'll will step and substract the error made. So, if say you accumulated 15 ms and your step is 16, go for an update and consider you accumulated -1.

...But... more or less you have build, with this, just a complicated version of a system doing 1 fixed step update by render frame... Still it is better if you get far from your fixed logic time step ( ex : 20Hz or 120Hz).

Now there's a way that i think is most preferable : if you use an update/logic time step significantly (at least 2 times) smaller than the render time step, then it makes sense again to use the fixed time step principle. Why small time steps could be good ? stepping is a simple process, and limit the hard-to-handle cases of tunneling and 'simultaneous' collisions, i mean collisions occurring during a single step. Still the sad thing being you can't avoid to treat them, but now you might even afford to have an ugly non optimized algorithm given their unlikeliness.

For the win i did a little fiddle, you can play with it to see the various cases you want to explore.

https://jsbin.com/vadakujeme/1/edit?js,output

You can see that with the algorithm as it stands you can be lucky, but it's very unlikely, i had to hit 'run' quite a few time to get this one :

because most of the time, even in one second, you'll have 3, 4 frame drops :

Now if you use a logic step of 6, i doubt anyone will notice the 3ms average error :
> 2 votes

---
Tags: javascript, html-canvas, fixed-timestep
---


# Question
Title: 8, 16, 32 bits consoles... what does it mean?
A number of bits is often used to qualify some video game consoles: Master System and NES/Famicon are 8 bits systems, Megadrive/Genesis is a 16 bits system, etc.
What do this number actually represent for those different hardwares?

# Answer
> 10 votes
It usually refers to the CPU architecture. Grossly oversimplified the bit-size of a CPU, is the size of numbers it can perform calculations with in one operation. An 8bit CPU can work with numbers up to 256, a 16bit CPU with numbers up to 65536 and a 32bit CPU with numbers up to 4294967296. Any of these CPUs can still be used to make calculations with larger numbers, but it needs multiple operations to do so.

The third generation of home game consoles was very obviously an era of pure 8-bit systems. The market-leader of that generation was the NES, the runner-ups were the Sega Master System and the Atari 7800. All systems used 8bit architectures through and through.

The fourth generation, commonly called the 16-bit generation, is a bit fuzzy. The two dominant systems were the Sega Mega Drive (aka. Genesis for North-America) and the SNES. Both systems were marketed as 16-bit systems. But the Motorola 68000 CPU of the Sega Mega Drive was technically a 32-bit CPU, even though it communicated through a bus which was only 16bit wide. Now you could say "duh, so it's the bus size which counts". But the Ricoh 5A22 16bit CPU used by the SNES only had an 8bit data-bus. So whatever technical definition you use, either the Mega Drive is a 32bit system or the SNES is an 8bit system.

In the fifth generation, the three competing systems were the Sony Play Station (32bit CPU), the Sega Saturn (two 32bit CPUs which SEGA marketing sometimes added up to 64bit which is technically quite nonsensical) and the Nintendo 64 (64bit CPU). This is the generation where counting bits stopped making sense because not even the marketing departments of the different companies agreed anymore in which generation they were in.

Generally speaking, the number of bits of a CPU can be compared to the number of cylinders of a car. More is usually better, but it alone is not a meaningful number to compare how powerful different models are.

# Answer
> 6 votes
To give a few more details, a higher bit architecture primarily allows for more memory to be used. It also allows for higher precision data to be included. However, it's been a bit of a misnomer, it was generally accepted that higher bit systems were better (And that holds true to a degree), but it was often used when it was not the case. For instance, according to the 6th generation gaming console Wikipedia page, that generation was referred to as the "128 bit" generation. However, the major consoles actually used:

* X-box- 32 bit.
* Game Cube- 32/64 bit.
* Playstation 2- 64 bit (With a "fudge" factor, allowing for 128 bit vectors)

It is worth noting that there is a huge difference from an 8 bit to 16 bit, and 16 to 32 bit. There is a smaller difference from 32 to 64 bit. Beyond there, there isn't many practical advantages for daily application. This is mentioned in the same article listed above. Here are a few practical limits of the various bit sizes:

* 8 bit\- This severely limits the colors, to only 255. It also limits the complexity of instructions that can be done.
* 16 bit\- Allows for much more color, still not quite allowing true color, but looks more realistic. Allows for more complex instructions. Still doesn't really have enough to do true 3d processing, but is otherwise adequate for most purposes.
* 32 bit\- The only real limitation is the ram, which is limited to 4 Gb. This wasn't a significant factor until about 2010. Allows sufficient processing power to manage 3-d systems. 32 bit allows for "true" color as well, which usually uses 8 bits for each color, plus 8 bits for the alpha chanel.

# Answer
> 2 votes
The number of bits here, represent the CPU architecture.

A 32-bit gaming console, utilizes a 32-bit Central Processing Unit.

---
Tags: console
---


# Question
Title: How do you spawn a component from a class in UE4?
**Background**
I'm working on a shooter game at the moment and I'm trying to spawn an `Actor Component` for the weapon currently in use, in order to have less `Actors` to keep track of.
The problem with this is that I can't easily switch out components on the fly, without making a separate function for each weapon.

**Question**
Is there currently any way to spawn a component with blueprints from a class like you would do with an `Actor`?

# Answer
Yes, you may spawn an actor component and attach it to any given actor. The C++ version of this would be:

```
UActorComponent* SpawnedComponent = ConstructObject<UActorComponent>(UStaticMeshComponent::StaticClass(), this, TEXT("DynamicSpawnedMeshCompoent");
if(SpawnedComponent)
{
    SpawnedComponent->RegisterComponent();
    SpawnedComponent->AttachTo(GetRootComponent(), NAME_None);
}

```

this is a pointer to an Actor class (so your weapon). Now, the key code here is the ConstructObject template function. In Blueprints you would call "Construct Object from Class" using a class reference to the Component you would like to create. The outer would be a reference to the owning actor of the component (the Weapon for instance). With the return value you will cast it to the desired component.
> 2 votes

---
Tags: unreal-4
---


# Question
Title: Detecting first or second Mouse Button Release?
I want to know how to detect if the user has released the mouse button the **first time**, **or the times after that**:

Pseudo-Code:

```
 if *first* (Input.GetMouseButtonUp(0))
   {
       do something
   }

 if *second, third, fourth..etc.* (Input.GetMouseButtonUp(0))
   {
       do something else
   }

```

I really have no idea on how to accomplish this. I'm sure it's pretty simple though!

# Answer
> 1 votes
You should have private member in your class that will indicate if button was pressed for first time. You need to initialize it in starting function ( could be Awake, Start etc., read more about execution order in Unity ) as false. And then, in Update function - check it. If it is first time, the do X and set this var to true, else do Y.

```
using UnityEngine;
using System.Collections;

public class ClickerClass : MonoBehaviour {
    private bool m_clicked;

    void Awake() {
        m_clicked = false;
    }

    void Update() {
        if( Input.GetMouseButtonUp(0) )
        {
            if( m_clicked == false ) {
                m_clicked = true;
                // code for first time
            } else {
                // code for not first time
            }
        }
    }
}

```

# Answer
> 0 votes
```
int ClickCount;

void Update()
{
    if (Input.GetMouseButtonUp(0))
    {
       if (ClickCount == 0)
       {
              //First Click
              //do stuff
       }
       else
       {
             //Not first click
             //do stuff
       }

       ClickCount++;
    }
}

```

Keep in mind that the ClickCount variable will overflow once it reaches 2,147,483,648.

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


title: Hang script on the button in unity

text:
# Question
Title: Hang script on the button in unity
When you click on a hand should trigger the script. I do not understand how this script to the button.  Here's a script, even though he can not correct:

```
using UnityEngine;
using System.Collections;

public class hand : MonoBehaviour {
    public Transform player;
    public Transform mushrums;

    private Animator anim;
    private bool pick_up;

    void Start () {
        anim = GetComponent<Animator> ();
        pick_up = false;
    }

    void Update () {
        anim.SetBool ("pick_up", pick_up);

        float dist = Vector3.Distance(player.position, mushrums.position);
        Debug.Log(dist);

        if (dist <= 58.5f)
        {
            pick_up = true;
            //here the removal of the object to which came
        }
        else
        {
            pick_up= false;
        }
    }
}

```

The button should be activated only at a certain distance from the object to which came.

# Answer
> 0 votes
So, from what I've understood you want your function to be triggered on button press.

First, you can't use `Update ()` as it runs every frame. You want to rename it to something else, e.g. `triggeredFunction ()`. Then you want to declare it as public. For that, you'd add `public` in front of `void`. Then create an empty GameObject and attach the script to it. Drag the GameObject with script in the `On Click ()` frame, select the script, and function from drop down menu and you're set. Hope that helps.

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


# Question
Title: How can I implement "quality levels" for models and textures?
I'm preparing to build a 3D game without an engine and am wanting to know how I could implement graphic detail levels for my models.

To do this, are the models made in the highest quality level and then the artists remove polygons and texture detail for each model of a lower quality? Or does it work in some other way?

# Answer
The *artists* probably won't do this manually quite like you're thinking, but you're on the right track (or at least a viable track). You can generally degrade mesh and texture quality programmatically pretty easily since you probably already have the relevant data.

For geometry, you'll probably have lower level-of-detail version of a mesh you use as part of your LOD system when an object is far enough away. These may be manually generated by an artist or may be automatically generated via tools in whatever modelling software you're using (or both).

For textures, you'll probably already have lower-detail MIP levels for each texture for similar reasons.

You can thus pretty easily hook up a system where you have a few different "texture detail" quality options in your settings, with "highest" using all the available textures and with each subsequently lower setting reducing which MIP level of the texture you load and use for the top quality version. For example, if you normally generate and load five mip levels at "highest" quality, you might only load the bottom four at "high", the bottom three and "low" and the bottom two at "lowest."

The same goes for mesh geometry, which you can put on an independent control or just tie together into one simple slider.

You can make similar adjustments to other graphics features; for example if you have shadows in your game, you can reduce the size of the shadow map render targets by some factor for every lower value of the "shadow quality" slider, or simply turn them off.

Of course it's *possible* to use these sliders to swap in entirely different collections of art tailored for different performance criteria, but building all of that may be a lot more work and time than can afford, and the cost/benefit over simply degrading through automatically-generated LOD and MIP options may not be there (with the exception maybe of your main character or a handful of other high-visibility items).
> 2 votes

---
Tags: 3d, graphics
---


# Question
Title: Can Unity4 and Unity5 projects coexist in the same computer?
I've `Unity5` installed (free edition). When I started with `Unity3D` I did with 5 and never had the 4 before.

A friend has passed me legacy code of a 90% complete game he used to do with `Unity4` as he no longer wants to dedicate to videogames, for me to use that to finish it.

If I load that code into the `Unity5`, the "automatic upgrader" starts to do lots of changes. And finally the thing does not play. Says `All compiler errors have to be fixed before you can enter playmode!`

The thing is he used some third-party libraries, like the `tk2droot` among others and seems that the code of that and other dependant libreries is rather old, so I do not only need to scan over his code for the "v4 to v5 upgrade changes" but also I've to scan all his dependencies, which is rather a suicide at least for an initial contact like "let's just see if this compiles".

**Questions:**

1. Is there any way make Unity5 "behave" as Unity4 so it does not do the code-upgrade **and** it uses the old API? Ie: Compile v4-code within v5-IDE?
2. Alternatively, is is possible to freely install Unity4 parallel to Unity5 so they do not interact and I am able to compile his source un Unity4 while doing the new things in Unity5?

The easiest solution I can find is to have 2 computers, one with Unity4 and the other with Unity5 but seems a but weird to me. I'm sure I'm not the only one with this problem.

How do game developers with codebases in Unity4 and Unity5 make all the workflow?

PD: Focusing on Android now only. No need to publish for iOS, web, consoles, etc.

Thanks.

# Answer
# Yes

I happen to have...five? different versions of Unity installed myself at the moment. Two versions of 4 (4.1 and 4.6?) and three versions of 5 (5.0.1, 5.1.1, and 5.2.1).

You won't neccessarily be able to open a Unity 4 project in Unity 5 (it will upgrade it), but you can have the different versions all installed at the same time, as long as you provide separate installation directories.
> 7 votes

# Answer
Yes. I have three versions of Unity installed right now. If you don't rename the folder it will replace it, so just make sure to rename the install location.

btw "tk2d" code is referring to 2D Toolkit, and that is not an open-source library.
> 2 votes

---
Tags: unity
---


# Question
Title: How can I locate GameObjects near the player in Unity?
I'm trying to figure out how I can find GameObjects that are close to the player so that I can delete them with `Destroy()`. I know how to use `Destroy()` but I can't figure out how to get a reference to the objects I want to remove.

```
public class hand : MonoBehaviour {
public Transform player;
public Transform mushrums;
private Animator anim;

void Start () {
    anim = GetComponent<Animator> ();
}
public void HandUp () {

    float dist = Vector3.Distance(player.position, mushrums.position);
    Debug.Log(dist);
    if (dist <= 59)
    {
        anim.Play("pick_up");

            Collider[] hitColliders = Physics.OverlapSphere(this.transform.position, 20);

        while (i < hitColliders.Length) {
                 thisDist = (transform.position - hitColliders[i].transform.position).sqrMagnitude;

            if(thisDist < nearDist) {
                    nearDist = thisDist;
                    nearest = hitColliders[i].transform;

                }
            }
            if(nearest != null) {
            Destroy(nearest.gameObject);
            }

    }

}
}

```

if the radius of the 10, subject is not and `hitColliders.Length = 0` if the radius of the 20 its freezing if remove WhileLoop `while (i < hitColliders.Length) {thisDist ...` but keep `if(thisDist < nearDist) {...` everything works and get another object, not the one that is near

# Answer
There are a number of ways to get a reference to a GameObject. In your desire to locate objects near the Player, `Physics.OverlapSphere()` is likely what you are looking for.

The various Physics static methods will do similar things in terms of "find this thing" where "this thing" is a more abstract concept (e.g. "Find the object I'm looking at" would use `Physics.Raycast()` to find an object directly under the mouse cursor), and in many cases, it will return *more than one* object and you can loop through the list and do something to either one of them (using some criteria to identify it) or all of them.

For example, this code will find the nearest object to the player and delete it.

```
void Update() {
    Collider[] hitColliders = Physics.OverlapSphere(this.transform.position, 10);

    Transform nearest = null;
    float nearDist = float.PositiveInfinity;
    for (int i = 0; i < hitColliders.Length; i++) {
        Vector3 offset = transform.position - hitColliders[i].transform.position;
        float thisDist = offset.sqrMagnitude;
        if(thisDist < nearDist) {
            nearDist = thisDist;
            nearest = hitColliders[i].transform;
        }
    }
    if(nearest != null) {
        Destroy(nearest);
    }
}

```

`Destroy()` will destroy GameObjects as if you selected them in the scene hierarchy and hit \[Delete\]. For most components, it would be like right-clicking on it in the Inspector and selecting "remove." Transforms are different: Destroying a Transform will also delete the GameObject as a GameObject *requires* a Transform component, so removing one automatically removes the other. I did this on purpose to illustrate this point, but it would have been perfectly valid to do `Destroy(nearest.gameObject)` as well.
> 4 votes

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


# Question
Title: How do I check for collision between an ellipse and a rectangle?
I am working on LibGdx framework for developing a 2D isometric tower defense game.All my sprites are drawn in 2D isometric view.

I have used an array list to store 8 points at boundary in the rectangle.LibGdx has an inbuilt function (returns Boolean) ellipse.contains(x,y),by iterating through array list I can check whether any points are inside ellipse But the problem is as shown in below picture,it wont detect the enemies in some particular cases

So my question is: 1)Is this a correct approach for solving these kinds of problems 2)If not can you suggest better approach for solving this problem

Thank you.

# Answer
I'm going to tell you how to do it with a computationally cheap way in terms of CPU usage.

First, let's say that the calculation of seking if a point is "inside the ellipse or not" is not computationally cheap, while comparing just rectangles with mere "greater than" or "less than" comparisons are ultra cheap.

**Definition 1) Ellipse and its quadrants**

If the perspective is isometric I'm going to assume that the axes of the ellipse `E` are always horizontal and vertical.

The axes define 4 quadrants `Q` around the center of the ellipse `E` as seen in the following picture. Let's name them like this:

* `QTL` = Quadrant Top Left
* `QTR` = Quadrant Top Right
* `QBL` = Quadrant Bottom Left
* `QBR` = Quadrant Bottom Right

Note that the quadrant is all the area defined by the axes, like for example, the blue area for QBR, which comprises the area inside the ellipse and the area outside it, despite of where the labels are set in the image.

**Definition 2) Ellipse and its bounding box**

Now let's define a bounding box `B` around the ellipse `E`, like in this image:

Now let's focus in the areas of the quadrants that belong to the inside of the bounding box. Let me give the `Exx` names for the areas inside the ellipse and the `Dxx` names for the "diff" of the bounding box less the ellipse (so the bounding box area that is not inside the ellipse).

Those are the names for the areas inside the ellipse:

* `ETL` = Ellipse Top Left
* `ETR` = Ellipse Top Right
* `EBL` = Ellipse Bottom Left
* `EBR` = Ellipse Bottom Right

And these for the "diff areas" (the ones inside `B` but outside `E`):

* `DTL` = Diff Top Left
* `DTR` = Diff Top Right
* `DBL` = Diff Bottom Left
* `DBR` = Diff Bottom Right

**Definition 3) Enemy rectangles**

Additionally, watching your images, I'm going to imagine that the enemies are always bound with a rectangle `R` whose sides are exactly horizontal and vertical.

Also, I am going to use only the 4 vertexes `V` of the rectagle and forget about the intermediate points you used.

**Algorithm**

**Step 1. Check the bounding box**

If the enemy rectangle `R` is outside the bounding box `B` then for sure it is outside the ellipse `E`.

Checking this first saves a lot of calculation as you forget expensive calculations to discard a lot of rectangles (and most of the time enemies shall be far).

You can check if `R` is outside `B` by checking each 4 sides:

`R` is outside `B` if and only if:

* The bottom side of `R` is higher than the top side of `B` **OR**
* The top side of `R` is lower than the bottom side of `B` **OR**
* The left side of `R` is more to the right than the right side of `B` **OR**
* The right side of `R` is more to the left than the left side of `B`.

In other words: If **any** of those conditions are met, then the enemy `R` is outside the bounding box `B`. This is the same than saying than if **all** those conditions are false, then `R` shares some area with `B`.

If the enemy `R` is outside the bounding box `B` set collision to false and end the algorithm here.

Note that checking the bounding box is a cheap operation.

**Step 2. Quadrant check**

If you are here, it means that your enemy `R` shares at least one small area with the bounding box `B`, and we require further analysis to see if the enemy collides or not with the ellipse `E`.

Look at this image:

I have painted rectangles of 3 types here. The green and yellow rectangles share a common characteristic: All the 4 vertexes of the rectangle `R` fall in the very same quadrant. And this does not ensure if the enemy `R` collides with the ellipse `E` or not.

Instead, all the red rectangles also share not only one characteristic, but two:

* Feature 1: All the red rectangles have vertexes that do not fall in the same quadrant.
* Feature 2: All the red rectangles collide with the ellipse.

Why this happens? Because the red rectangles all cross, at least, one axis. And the axis points that are crossed are necessary inside the ellipse, as if `R` crossed an axis outside the ellipse we would have catched that `R` while checking the bounding box, as the bounding box is precisely the limit where the axes change from "inside the ellipse" to the "outside of it".

So if one rectangle not catched in step 1, then, in step 2, has vertexes in different quadrants, then necessarily it happens that **some** points of **some** axis that are **also** contained in the ellipse `E` are **shared** with the rectangle `R`. This means that the rectangle `R` for sure collides with `E` **at least** on those axis points and for sure all non-axis points surrounding the points mentioned before, to the extent of the limit of `R` or `E` whichever comes first.

So... if a rectangle has vertexes in any different quadrant than the other vertexes of itself, just mark `collision = true` and exit the algorithm.

Note that checking if all vertexes fall in the same quadrant is merely checking coordinates with "greater than" or "less than" comparisons, so it's a cheap operation.

**Step 3. Ellipse check.**

So, finally, we enter step 3 only with green and yellow rectangles. Ie: it's a pre-requisite we may assume. Enemies `R` here shall match that:

* They collide with the bounding box.
* All the vertexes of `R` fall in a single quadrant.

We can then conclude that:

* 'At least one vertex' shall lie in the part of the area of the quadrant that is within the bounding box.
* Which is the same to say that 'at least one vertex' shall lie either in the `Exx` area or the `Dxx` area.
* And which is that vertex? This happens at least to the 'nearest vertex to the center of the ellipse'.

So we can reformualte the conclussion as:

* The vertex `V` of the rectangle `R` which is nearest to the center of the ellipse `E` must fall necessarily in the ellipse area `Exx` or the diff area `Dxx`.

But it also happens that, by *Reductio ad absurdum* we can say that:

* If the nearest vertex defined above falls in in the diff area `Dxx` (ie: does not fall inside the ellipse) then no other point `P` in the enemy `R` can be touching the ellipse. The demonstration is that if with this hypotheses we could find another point `P` that was touching the ellipse `E` then the tested vertex `V` could not be the nearest to the center of the ellipse which contradicts the hypotheses.

We don't care if "the other vertexes" are inside or outside the box. And you don't have to do complex maths to select the nearest vertex... just it is straight forward:

* For the Top Left quadrant, choose the Bottom Right vertex of `R`.
* For the Top Right quadrant, choose the Bottom Left vertex of `R`.
* For the Bottom Left quadrant, choose the Top Right vertex of `R`.
* For the Bottom Right quadrant, choose the Top Left vertex of `R`.

Those vertexes are highlighted in the green and yellow rectangles of the picture.

Just then test one single selected vertex with the expensive maths. Test that vertex against the ellipse.

Set the `collision` flag if the selected vertex is in the ellipse area `Exx`, otherwise the vertex shall lie in `Dxx` and leave `collision` clear.

Computationally the cost of this 3rd step is just one single complex calculation at most. Never more than 1 vertex per rectangle.

End of the algorithm.

I hope I have helped! Cheers.
> 7 votes

---
Tags: android, collision-detection, libgdx, mathematics
---


# Question
Title: Strange artifacts when using gl_FragCoord to access texels
I ran into a problem with using `gl_FragCoord` variable to access texels. The problem can be illustrated by following example:

First I render a textured quad into texture of size `(W, H)` where `W` and `H` are viewport width and height correspondingly. Then I draw another quad with lower left corner in `(0, 0)` and upper right corner in `(W, H)` (so that it effectively takes whole viewport) which is textured with this texture. Let's call it quad **A**. Then I draw another quad (let's call it quad **B**) on top of it, with lower left corner in `(0, H1)` and upper right in `(W, H)` and also use the same texture for it. The whole scene can be illustrated by this picture:

As you can see, the bottom part of the first quad lays in quad **A** and a top part in quad **B**. Thus when I experiment with fragment shader for quad **B** I can see whether the top part of the quad matches the bottom part.

Now to the problem:

When in fragment shader for quad **B** I use

```
gl_FragColor = texture2D(u_backgroundTexture, v_texCoord);

```

*(`v_texCoord` is (0, 0) for lower left corner and (1, 1) for upper right)*

to determine fragment color, everything is fine. Top and bottom parts of the first quad perfectly match each other:

However, when I change this line to:

```
gl_FragColor = texture2D(u_backgroundTexture, gl_FragCoord.xy / u_resolution);

```

*(where u\_resolution is a `vec2(W, H)`)*

the top and bottom parts of the quad doesn't match anymore. If I render that quad close to right edge of the screen I get following artifacts:

and if I draw it close to the left side artifacts looks like this:

Could anyone please explain what are the possible causes for such artifacts? Apparently I am missing some fundamental understanding of how texturing works, since in my mind `texture2D(u_backgroundTexture, v_texCoord)` should be completely equivalent to `texture2D(u_backgroundTexture, gl_FragCoord.xy / u_resolution);` in my case.

*P.S. Obviously, for quad **A** I always use `gl_FragColor = texture2D(u_backgroundTexture, v_texCoord)` in fragment shader.*

# Answer
> 0 votes
I finally found the root-cause of this weird discrepancy.

I use Cocos2d framework which builds projection matrix from the current camera settings. As it turned out, projection matrix built by Cocos2d has some precision loss. Thus, after vertices of quads **A** and **B** multiplied by projection matrix, the result vertices don't hit exact points `(-1, -1), (-1, 1), (1, 1), (1, -1)` in NDC as I would expect. The actual NDC of the points look more like `(-1.00164..., -1.00164...)` etc. This causes texture on quad **A** to be just a little bit stretched which is why it doesn't match texture on quad **B**.

To "fix" for this issue I changed coordinates of quads **A** and **B** to NDC and removed multiplication by Cocos2d's projection matrix from vertex shader.

---
Tags: opengl, textures, glsl
---


title: FRAMEBUFFER_UNSUPORTED (0x8cdd)

text:
# Question
Title: FRAMEBUFFER_UNSUPORTED (0x8cdd)
I've tried to implement bloom following this tutorial. But everytime I get the framebuffer object error 0x8cdd, which I believe means FRAMEBUFFER\_UNSUPORTED. I'm pretty sure the problem occures because of the GL\_RGB16F format. But for HDR I need more precision than GL\_RGB. Does somebody know how to fix this issue?

```
    glGenFramebuffers(1, &hdrFBO);
    glBindFramebuffer(GL_FRAMEBUFFER, hdrFBO);

    glGenTextures(2, hdrColorBuffers);
    for (GLuint i = 0; i < 2; i++)
    {
        glBindTexture(GL_TEXTURE_2D, hdrColorBuffers[i]);
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16F, WINDOW_WIDTH, WINDOW_HEIGHT, 0, GL_RGB, GL_FLOAT, 0);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);  // We clamp to the edge as the blur filter would otherwise sample repeated texture values!
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
        // attach texture to framebuffer
        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i, GL_TEXTURE_2D, hdrColorBuffers[i], 0);
    }

    glGenRenderbuffers(1, &rboDepth);
    glBindRenderbuffer(GL_RENDERBUFFER, rboDepth);
    glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, WINDOW_WIDTH, WINDOW_HEIGHT);
    glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rboDepth);
    // - Tell OpenGL which color attachments we'll use (of this framebuffer) for rendering
    GLuint attachments[2] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 };
    glDrawBuffers(2, attachments);
    // - Finally check if framebuffer is complete
    GLenum  status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
    if (status != GL_FRAMEBUFFER_COMPLETE){
        printf("Framebuffer hdr fail: 0x%x\n", status);
    }

    glBindFramebuffer(GL_FRAMEBUFFER, 0);

    // bloom framebuffer

    glGenFramebuffers(2, bloomFBO);
    glGenTextures(2, bloomColorBuffers);
    for(GLuint i = 0; i < 2; i++){
        glBindFramebuffer(GL_FRAMEBUFFER, bloomFBO[i]);
        glBindTexture(GL_TEXTURE_2D, bloomColorBuffers[i]);
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16F, WINDOW_WIDTH, WINDOW_HEIGHT, 0, GL_RGB, GL_FLOAT, NULL);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, bloomColorBuffers[i], 0);

        GLenum  status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
        if (status != GL_FRAMEBUFFER_COMPLETE){
            printf("Framebuffer bloom fail: 0x%x\n", status);
        }
    }

```

# Answer
> 1 votes
Try with **GL\_RGBA16F** instead of **GL\_RGB16F**.

It's likely the GPU can't render to 48bit buffers.

---
Tags: opengl, frame-buffer
---


# Question
Title: Problem with transparent textures in SFML
I have been told that this is kind of a common problem with transparent textures, but didn't get any further information on how to solve it.

In my code, I'm trying to render this texture (a square with rounded corners, where rounded corners have some alpha)

What I get instead is this

Notice those greyish places on the corners of the textures - where rounded corners are supposed to be.

What could be causing this? I have a pure-white texture, so I don't expect a single pixel to get any darker than the background. All pixels should have at least the color of background, but as you can see, there is something darker.

Zoomed even more:

Any help would be highly appreciated.

# Answer
> 1 votes
It looks like the color values are premultiplied with the alpha but are rendered with the non premultiplied blending factors.

This makes the color of any texels with alpha \< 1 darker than they should be.

For premultiplied alpha textures blending factors should be:

```
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);

```

You can test this by making your white rounded rectangle texture 50% opaque (the actual texture, not the vertex colors) and see if it makes a white/light background darker.

The usual factors (`glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);`) will cause this darkening on premultiplied textures. A similar issue happens with linear interpolation of color when textures are not premultiplied.

---
Tags: textures, graphics, rendering, image, transparency
---


# Question
Title: Adjacency in procedural generation of dungeon
I wanted to make a procedural dungeon experimenting a new approach, it works nice for random-meaningless content (in example a procedural background to a level), however when I want it to be not-so-random I incur in some conceptual problem: basically I end up with a grid of numeric sector IDs in 2D.

Grid example:

```
27 |  56  | 74
---+------+----
35 |  31  | 115
---+------+----
14 |  52  | 12

```

The main problem is how to fix adjacency so that content is generated in a deterministic way:

* Content of sector "31" should be generated as a function of adjacent sectors (this works)
* However when I generate content for sector "35", I end up with a different link between sector "35" and "31".

So basically according from which direction I cross a sector I see a different passage each time (while the content of the sector is always the same).

As you see in the following image:

The passage between 35-31 is different according to which sector is used to start content generation, which is not what I want. I want the same passage arise.

To answer comments:

```
sector[id].content = generateContent( sector[id].neighboursIds());

```

# Answer
What you can do is seed the passage according to the two sector ids being linked in numeric order.

```
function CalculateConnectionSeed ( sectorA, sectorB )
  if sectorA < sectorB
    return sectorA + sectorB * 16384
  else
    return sectorB + sectorA * 16384
endfunction

```

So no matter which way the connection is made the same seed will be used (16384 is just a number I picked to make sure sector 2+3 wont be the same as sectors 1+4 provided there are less than 16384 sector ids).

Or always generate the connection in the same direction: left-to-right or up-to-down.
> 1 votes

---
Tags: mathematics, procedural-generation
---


title: Player fatigue for tablets?

text:
# Question
Title: Player fatigue for tablets?
I'm thinking about making games for tablets. Coming from a PC/console background, I'm keenly aware of the huge differences in the user interfaces, and that I need to design it with the target platform in mind.

One aspect I'm worried about is **player fatigue**. The input devices used on PCs and consoles - *keyboards* and *game controllers* \- are optimized for extended play and have mature, ergonomic designs. Most seasoned players can easily use them for an hour, clocking in thousands of key/button presses, without suffering from fatigue. Designers can depend on this when designing the user experience, with consequences ranging from *size/length of levels*, *steps required to execute commands*, *pace of the game* and many more.

What about touch-screen tablets? Do players become fatigued faster, or are unable to execute as many taps/swipes per unit of time? If so, are there any resources or guidelines about this matter?

# Answer
Yes this is a real consideration (or rather something similar along these lines) but no I'm not aware of any specific resources that provide guidelines.

> Do players become fatigued faster

I've never thought about mobile UI in terms of fatigue. Now that I am, this is possibly true, but fatigue is far from the most important UI problem.

> or are unable to execute as many taps/swipes per unit of time?

This is closer to the real problem. Again, I've never thought about it in terms of "X swipes per unit time" and more in terms of "swipes are a lot less accurate than a joystick".

> If so, are there any resources or guidelines about this matter?

None that I'm aware of. The general guideline however is that a touchscreen is a very different (and overall less accurate) way of controlling a game than a controller. This has a huge impact on how you design your game: design towards the strengths of mobile input devices, and away from the weaknesses. In general that means games that are less twitchy and more based on players tapping different parts of the screen.
> 1 votes

# Answer
The only thing remotely similar to what you ask that I have found is the paper Examining User Preferences in Interacting with Touchscreen Devices (which, sadly, seems to be offline). Personally I am surprised for the lack of research on the topic, which seems quite important for this big industry.

Beyond that, my anecdotal evidence from personal experience: taps cause much less fatigue than swipes. Try to reduce swipes to a minimum, ideally only use them for special movements.

If you are really really concerned about this and want to walk an extra mile, you could prepare a few mock-ups of user interfaces for your game, and ask a few persons to use them for a while. It won't give you scientifically accurate answer, but will probably better than working on a void. And if you do, please share your findings with the rest of the community!.
> 1 votes

# Answer
I've never seen physical fatigue be an issue for tablets (unlike the Wii and especially Kinect).

I think many other considerations will kick in much sooner than physical fatigue, including attention span (which for mobile players seems to be way shorter than console), battery life (games tend to burn through the battery very quickly) and even how hot the device gets, making it uncomfortable.
> 1 votes

# Answer
As a player of games on my iPad, I can say that taps DO cause fatigue. Too many taps and your fingers and hands start to ache. It IS a real problem and one that most gaming devs don't consider. Repetitive actions should be kept to a minimum or automated whenever possible.
> -2 votes

---
Tags: game-design, input, touch, user-experience
---