# Question
Title: Timing of coroutines in Unity is never precise
I was looking an official example for coroutines in Unity here.

However, when I call WaitAndPrint the time taken is never exactly 5 seconds.

```
IEnumerator WaitAndPrint()
{
    float timeStart = Time.time;
    yield return new WaitForSeconds(5);
    Debug.Log(string.Format("Time taken = {0}", Time.time - timeStart));
}

if (Input.GetKeyDown(KeyCode.R))
    StartCoroutine(WaitAndPrint());

```

Instead, it varies around 5.003133.

This is most likely down to the frame rate, which makes me wonder how can I make sure that a coroutine takes the precise amount of time it should take despite the fluctuating frame rate?

# Answer
> 4 votes
> This is most likely down to the frame rate, which makes me wonder how can I make sure that a coroutine takes the precise amount of time it should take despite the fluctuating frame rate?

I don't think you can, honestly. Coroutines are at the mercy of Update() in the same way the rest of your code is. You can't make it end between two update loops, because that's the time Unity is spending doing other stuff instead

I am kind of wondering why you need *that* sort of precision to begin with, though. Does it really matter if the coroutine ends when the frame starts, or 3ms before that?

# Answer
> 2 votes
Coroutines aren't threads or processes or anything special like that. They're just callbacks given to the engine to call when a specific condition is met. If you yield null, the coroutine will be called every frame.

Every frame, the engine calls all coroutines that are ready at that time, all together in a block (either right before or right after calling all the .Update()'s, not sure which). It will only call a WaitForSeconds routine AFTER that number of seconds has elapsed, so it will come up during the frame after that time has passed.

You can only really do things in unity in increments of frames (or physics updates), anyway. You surely can't draw something to the screen at a specific exact time, you have to wait for the next frame to happen.

Here's an in-depth article on how coroutines work, and a couple threads that I've bumped into in unity-land relating to them, which link off into other resources as well:

http://www.altdev.co/2011/07/07/unity3d-coroutines-in-detail/

http://answers.unity3d.com/questions/751178/when-using-coroutines-what-should-i-be-wary-of.html

# Answer
> 0 votes
Actually it is normal if the dvalue is under 0.01. And that 0.01ms won't bother your game. I've tested. That 5 second will be different each time you launch the game.

# Answer
> 0 votes
You can never make sure a coroutine takes a precise amount of time. As you said, it's the frame rate. You can get super close, but it'll never be spot on.

The time between frames will always differ, based on hardware. Thus you will almost always overshoot your specified time. Imagine you are at 4.89 seconds and the next frame takes 0.16 seconds to update. You'd be at 5.05 seconds on the new update. You're unable to control that.

What you can control is how you use that information given. If you had some code that needed to execute at the end of the 5 seconds. Do what you did before, get the difference in time and advance to whatever the execution would be at that time.

In your example that you would execute some code as though .003133 seconds had already passed. Now this isn't applicable in all situations - such as you wanting to just wait for an exact period of time.

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


# Question
Title: How to display a GUI Texture for a certain amount of time
Is it possible to make a gui Texture display for a certain amount of Time.

# Answer
> 1 votes
Try attaching the following class to the `GameObject` containing your `GUITexture`. The texture should have gone hidden 3 seconds after being activated.

```
[RequireComponent(typeof(GUITexture))]
public class GUITestClass : MonoBehaviour {
    GUITexture gt;

    void Awake() {
        gt = GetComponent<GUITexture>();
    }

    void Start() {
        StartCoroutine("HideGt");
    }

    IEnumerator HideGt() {
        yield return new WaitForSeconds(3);
        gt.enabled = false;
    }
}

```

# Answer
> 1 votes
You can do this with one line of code:

```
Destroy(gameObject, 3);

```

This will destroy the object after three seconds.

Put this in your script after you have sorted out your text and GUI related stuff and you're sorted.

# Answer
> 0 votes
```
using UnityEngine;
using System.Collections;

public class scene9 : MonoBehaviour {

    // Use this for initialization
    public Texture2D startWin;
    public Texture2D setupWin;

    private bool startwindow = true;
    private bool setupWindow = false;
    void Start () {
        Invoke ("startwindowFun", 2);
        Invoke ("setupwindowFun",3);
        Invoke ("loadScene11",5);
    }

    // Update is called once per frame
    void Update () {

    }
    public void startwindowFun() {
        startwindow = !setupWindow;
        }
    public void setupwindowFun() {
        startwindow = setupWindow;
        setupWindow = !setupWindow;
    }
    public void loadScene11() {
        Application.LoadLevel ("Scene11");
    }

    void OnGUI() {

                if (startwindow) {
                        GUI.Label (new Rect (270, 300, 160, 100), startWin);

                }

                if (setupWindow) {
                        GUI.Label (new Rect (270, 300, 300, 100), setupWin);

                }

        }

}

```

The above code works to load a texture one after the another at a specified time.It worked for me.

---
Tags: unity, gui, timer
---


# Question
Title: Add Objects in LWJGL without using glTranslationf function
It is possible to add an object in LWJGL without using translation function (glTranslatef) ? and if it is possible does this improve somehow performance ?

# Answer
`glTranslatef` doesn't add objects in LWJGL but translates OpenGL's built-in modelViewProjection matrix. Based on the fact that you're using `glTranslatef` I would say that you're using legacy OpenGL where this is the only way of matrix translations and these calls are not hardware accelerated.

Possibly the best way to improve your performance is to switch to modern OpenGL, bring your own math library with your own matrices (LWJGL's utility library provides you with these but you can look for other libraries if you want to) and start using shaders.
> 1 votes

# Answer
glTranslate is deprecated and slow, so you shouldn't use that function anyway and rather use the matrix operations, like `Matrix4f.translate(modelPos, modelMatrix, modelMatrix);` to transform your models. see: http://lwjgl.org/wiki/index.php?title=The\_Quad\_with\_Projection,\_View\_and\_Model\_matrices

and feed a complete Model-View-Projection matrix to the shader as described in the link above. Another way to gain a little more performance would also be to use Uniform Buffers instead, but I'm not sure if lwjgl does support that, yet.
> 0 votes

---
Tags: performance, lwjgl
---


# Question
Title: Render with multiple lights (one pass per light)
I have already a system that at the moment handle multiple lights just passing an array of light struct and loop through it. I had been told to switch to a multipass rendering approach. How should I do this in an efficient way? Can you link me to some resources about this?

I cannot switch to defferred rendering.

# Answer
I'm not exactly sure what you want to hear, but I think deferred lighting is still the best for many light sources. The way you do that is that first you gather all the geometry properties by rendering the scene without any lighting at all. You basically render the scene in 4 versions into a buffer called G-Buffer: color, normal, depth, position. You may want to have more layers in your G-Buffer, like specular maps, and other information that you might need to get more control over the material properties. With that information you're able to calculate the lighting easily as before, just this time not for every texel but only for every fragment on the screen. This saves a lot of calculations. Another way to make that more efficient is now to render the lights as spheres into another buffer, where as the sphere size is calculated by the lights power and thus the effect radius, to determine which fragments to calculate lighting for.

I think this tutorial does a great job explaining how it works: http://ogldev.atspace.co.uk/www/tutorial35/tutorial35.html
> 4 votes

# Answer
I am not super familiar with the topic but I did do a little digging for you to try and come up with some easy to understand tutorials or articles. I hope you find at least one of these useful to you. *I tried to avoid links that used deferred rendering.*

Link One

Link Two

Tutorials

Advanced Rendering in OpenGL

Random Tutorial Website
> 0 votes

---
Tags: opengl, rendering, glsl, lighting, rendertargets
---


# Question
Title: Using same buffer for vertex and index data?
Is it possible to use the same buffer for both `GL_ARRAY_BUFFER` and `GL_ELEMENT_ARRAY_BUFFER`?

I load both vertex data and index data into a big slab of memory, so it would be easier for me to just load it all into a single buffer. So naturally, I do like this

```
glBindBuffer(GL_ARRAY_BUFFER, vboId);
glBufferData(GL_ARRAY_BUFFER, dataSize, data, usage);
glBindBuffer(GL_ARRAY_BUFFER, 0);

```

Is it legal to – during rendering – simply use it as both?

```
glBindBuffer(GL_ARRAY_BUFFER, vboId);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vboId);
glVertexAttribPointer(...);
...
glDrawElements(mode, count, dataType, (void*)indexOffset);

```

I can't find anything in the spec saying it's ok to do so, but I can't find anything that says that I can't either. Googling doesn't turn up much either, but I might be looking in the wrong places.

# Answer
The GL\_ARB\_vertex\_buffer\_object specification (which all buffer objects are based on) notes:

> Note that it is expected that implementations may have different memory type requirements for efficient storage of indices and vertices. For example, some systems may prefer indices in AGP memory and vertices in video memory, or vice versa; or, on systems where DMA of index data is not supported, index data must be stored in (cacheable) system memory for acceptable performance. As a result, applications are strongly urged to put their models' vertex and index data in separate buffers, to assist drivers in choosing the most efficient locations.

In other words you certainly can, but you shouldn't because you may interfere with any optimizations the driver may make based on the initial binding-point used for the object.

A related, and slightly subtle because it may not be immediately obvious, point is that this behaviour can be expected to be different on different hardware or even different drivers from the same manufacturer. So you may test and find it's OK for you, but then get horrible performance when you ship it to a customer.
> 7 votes

# Answer
(Edited my question as I now read that your input is one big slab of data)

If your input is one big slab of data like \[vertexvertexvertex... indexindexindex\] you're better off calculating the pointers to the start of the vertex data and the start of the index data and passing those as buffers to OpenGL then to load the entire thing. OpenGL might wish to separate the data when it is uploaded to the GPU. And messing with offsets and strides for non-uniform data can only cause problems, especially when data is layed out differently than you might expect. For example if it is aligned.
> 1 votes

# Answer
For further reference, I came through the exact same problem and added the answer to this with code here:

https://stackoverflow.com/questions/24910929/use-of-gldrawelements-i-dont-understand
> 0 votes

---
Tags: opengl, index-buffer, vertex-buffer
---


title: Fire Delay Timers

text:
# Question
Title: Fire Delay Timers
I currently have a turret that can fire projectiles. I can control the delay between shots (fireDelay), and I can control the time needed to reload the magazine of the gun(reloadDelay). I do the simple solution of, when the user tries to fire, see how long has passed since he last fired, and if it has been long enough, it fires again. Same for reloadDelay.

But now I wanted to make it so clicking fire once would fire 3 bullets, with delay between, akin to the Burst Fire Mode on an M-16, like FPS genres.

A simplified overview of what happens right now:

1. User clicks mouse.
2. The program enters the fire function().
3. Fires a bullet if sufficient time has elapsed, and enough ammo remains.
4. Exits the function, and only enters again when you try and fire again.

So how do you make it fire again in the future without step 1 happening. I have a messaging system built into the engine, so my current solution would be for the gun to fire a bullet, and add 2 messages to the message list with the fire delay attached, and the message manager would send the messages to the gun to fire when the message times had expired. I didn't like this though, because I thought the gun should not be sending itself messages in the future to fire, and that's not what the messaging system was meant for initially, although it does work. I'm just wondering if there is a better solution to implement this?

# Answer
> 1 votes
The solution can be pretty simple - just add a field or flag and dont release until *n* bullets of your burst have been fired. in weapon:

```
int burst = 0;

```

when hadling event:

```
 void onFireButtonPress() {
    //previously simple fire();
    burst = burst > 0 ? BULLETS_PER_BURST : burst; //or some other behavoiur like burst += 3 etc.
}

```

in game loop:

```
if(wepon.burst > 0)
 weapon.fire();

```

in fire() method:

```
if(fired)//all conditions met (time, magazine etc.)
  burst--;

```

---
Tags: c++, 2d, timer
---


# Question
Title: map/world "decorator" algorithms/patterns
I've spent a lot of time working with perlin/simplex noise for different styles of map gen, but I'm having a hard time finding advice/resources on how to populate the map with "world decor" that have some patterns to them... not just a random flower or tree.

I can control where on the map they spawn based on the height/temp values, but what are some good ways to control "patterns" the items spawn in?

For example, I want a specific plant to always spawn in clusters, but I want it to look natural and random - a bunch all together in a cluster and some individuals further out. I don't want all spawn instances to look the same.

A good reference is the Minecraft ore spawner - they're always in random configurations with some min/max size variations. Larger veins are even more rare.

# Answer
> 2 votes
There are multiple ways to do this:

1. When you want to place such an object you instead place a cluster centre, you then place a given number (random or pre chosen) number of decorator objects around this with a distance determined by any formula (normal distribution works well). The advantage of this is it' s ease to implements and it's speed. A good example of this is the following code:

```
float offsetx=nextGaussian()*deviation+basedistance
float offsety=nextGaussian()*deviation+basedistance

if (nextRandom()>0.5)
    offsetx*-1
if (nextRandom()>0.5)
    offsety*-1
placeitem(x+offsetx,y+offsety)

```

where deviation determines the spread of the items and the basedistance how much you want to prevent items from being very close to one another (creates a bit of a circle).

An alternative is to call this function again and again from each new object (with a change of it stopping)).
2. You can create a chance map, this is a map gives the chance of each tile containing an objects. You you make each of these positions into their own object you can put them in an array and shuffle them. When you place an object you can let it affect the chance of similar items appearing (either positively or negatively). The advantage of this method is that you can decide that an object increases the chance of a similar item appearing at a medium range while reducing the chance of a small range. Because you visit each tile in a random order you could even completely remove the chance element and instead use what would otherwise be the chance affect the size, this means that such a pattern has the biggest object in the middle. The advantage of this method is it's flexibility.
3. Pre designed patterns: the most predefined method you give a set of patterns and ask the computer to try and place those instead, useful for example when dealing with mushroom circles that have to be perfectly circulair.
4. complete simulation: by running a simulation of what proces creates the patterns in nature you can put them naturally in games, for example plants have a given range in which they spread their seeds and they make it harder for other plants to grow close to them. These two together will make patches of the same plant grow together but not to close, combine with plants preferring certain climates and you will soon get a very natural spread of plants (note that this does require you to balance nature as well as the game itself or else some of these things can go extinct).

---
Tags: procedural-generation, maps
---


title: 3ds Max Biped Scale Restriction

text:
# Question
Title: 3ds Max Biped Scale Restriction
I have a 3D Model under 3ds Max and I'm trying to integrate a biped skeleton. But when I start to adjust the pelvis or any other bone I can't scale it.

I don't know why, and this is driving me crazy. If someone can help it would be much appreciated.

# Answer
> 1 votes
You need to press the figure mode in order to adjust the biped bones. It is the only way to scale the bones of the biped.

After that if you want to animate or make poses of the biped, you must be out of the figure mode, so switch if off before.

---
Tags: 3d-meshes, 3dsmax, skeletal-animation
---


# Question
Title: "CVar system" - are CVar always looked up or cached?
Many famous game such as Quake or Half-Life use **CVars** to allow easy and flexible game parameter manipulations.

You can simply open up the console and write something like

```
sv_cheats 1

```

to enable cheat codes.

CVars are used intensively during the game - if they were set or retrieved by string name lookup there would certainly be a performance hit. Therefore, I'm assuming CVars are somehow cached.

How would this kind of system be implemented? I thought about storing pointers to the *real values* in a map having the CVar names, and then use the real values in the game. Is this a viable approach? Do the AAA games have a better one?

Example:

```
struct Game
{
    std::map<std::string, int*> cVars;
    int volume, sensitivity; // Example game parameters

    Game()
    {
        cVars.emplace("volume", &volume);
        cVars.emplace("sensitivity", &sensitivity);
    }

    void setCVar(std::string mName, int mValue)
    {
        *cVars[mName] = mValue;
    }
};

```

# Answer
First, avoid premature optimization. As Matthias notes in the comments, keep your implementation simple until you actually experience a performance problem that you can attribute (via profiling) to the configuration variable system.

One of the big *potential* performance issues in an implementation like the one you have described will be the string comparisons, so you will *potentially* see a gain by removing them. A common way to remove string comparisons is to hash the strings to integers, which are generally faster to compare.

If all your variable keys are known up-front, you can do this hashing at compile time or load time (whenever the earliest you know the full set of keys is). Then you only need to hash the user input, and all subsequent comparisons to look up in the map are done via integers. In fact, if you do know everything up front you can potentially "hash" every variable to an ordered list of integers and simply use an array for lookup. If you don't know everything up-front, you can still leverage hashing, but the lack of foreknowledge means you lose out on the opportunity to achieve a perfect mapping.

Alternatively, you can store the variable data in a trie which is a tree-like structure with (in this case) up to 26 children per node; paths through the tree spell out the variable keys and the leaf nodes store the actual variable data.

In both cases you will want to build yourself an API that wraps storage of and access to those variables -- do not store a `std::map` directly in your `Game` object, as you did in your example code, because that will make it more difficult for you to tweak or replace the underlying storage and retrieval mechanism if/when you discover there are performance issues.
> 4 votes

# Answer
You are talking about string interning. It is widely used in compilers to represent identifiers. Basically, when the string is parsed from the command line or a text file, it is looked up in a global table. If it is already present, then it is assigned a number, and that number is returned. If not, then it is assigned the next available number, which is incremented.

An interned string is therefore just an integer. However, an interned string is meaningless without the global table to tell what actual string it is. This allows maps from strings to other types to just be integer key maps, which are usually particularly efficient. String comparison is just integer comparison, although sorting the strings in this way would order them by when they were first seen rather than lexicographically (obviously, on could look up the original string and compare those instead to sort lexicographically).

The critical part about this is always remembering to look up strings in the global table, and not try to send the integers over the network, for example.

**Note** it is also possible to use a pointer to the string data in place of the integer, but this doesn't serialize well. It is also really easy to confuse regular `char*` with interned strings, leading to horrendously subtle bugs.
> 1 votes

# Answer
*Setting* the CVar might lag a little, sure, but that's okay - you're already parsing the text input from a command. To optimize it if you must, hashing the name to an int for a quick lookup map is all you need. You could also make a directory structure, EG `sv` points to the sub-map containing `sv_cheats` to further minimize lookup comparison count.

It's *getting* the value of the CVar that you have to keep tightly optimized - and that's easy, just keep a pointer to the CVar, rather than looking it up by name every time. (This is how Quake and other major CVar users handle it internally).
> 0 votes

---
Tags: c++, console, configuration, settings
---


# Question
Title: Transparent texture over colored polygon?
Let's say I have a cube with each face having a different colour. I want them all to look like brick walls, but I don't want to have to recreate the same brick texture for every colour.

Is it possible to create a greyscale semi-transparent brick texture that I can overlay overtop of the polygon colour?

This scene will eventually be used in Unity, but I also have access to 3DS Max and Blender. So, whatever works.

# Answer
> 1 votes
You can combine a material's diffuse color with a diffuse map in two ways:

1. In code, by setting the GameObject's \`renderer.material.color' to a different one
2. Through the GUI by selecting the GameObject and in the inspector choosing the desired color in the *main color* field of the assigned material component

More information on Unity's materials can be found here

---
Tags: unity, blender, 3dsmax
---


title: Automatic Movement

text:
# Question
Title: Automatic Movement
I am making my very first GAME in Unity 2d. At the moment my game consists of 2 walls a floor, a ceiling, and a square which represents the character. After watching some tutorials I have created a C# character controller script which at the moment let's my player jump. Now that I can make the square jump, my next goal is to make the character move without having to press any buttons or making it think a button is being pressed.

Question:

How do I make my square move to the right automatically without any input from the user?

Current Code:

```
usingUnityEngine;
usingSystem.Collections;

public class SquareControllerScript : MonoBehaviour
{
    boolgrounded = false;
    publicTransformgroundCheck;
    floatgroundRadius = 0.2f;
    publicLayerMaskwhatIsGround;
    publicfloatjumpForce = 700f;

    void FixedUpdate()
    {
        grounded = Physics2D.OverlapCircle (groundCheck.position, groundRadius, whatIsGround);
    }

    void Update()
    {
        if (grounded && Input.GetKeyDown (KeyCode.Space))
        {
            rigidbody2D.AddForce(newVector2(0,jumpForce));
        }
    }
}

```

# Answer
> 1 votes
As you may have noticed, the `Update` function is executed every frame as long as the `MonoBehaviour` is enabled. You can assign a constant velocity to the `Rigidbody` of the square instance in the `Update` function, so it moves at a constant velocity every frame.

```
if (grounded) {
    if (Input.GetKeyDown(KeyCode.Space)) {
        rigidbody2D.AddForce(new Vector2(0, jumpForce));
    } else {
        rigidbody2D.velocity = new Vector2(2, 0);
    }
}

```

---

**UPDATE**

Savlon's comment,

* Use `FixedUpdate` when dealing with `Rigidbody`.

---
Tags: c#, unity, character, controllers
---


title: Defensive statistic mechanics

text:
# Question
Title: Defensive statistic mechanics
There are many systems where attack statistics are opposed by defense statistics:

* Strict: `HP -= (damage - defense)`
* Threshold: `HP -= (damage>defense? damage : 0)`
* Reciprocal: `HP -= (damage / defense)`

Just to name a few, and there are variations on those as well:

* Reciprocal threshold: `HP -= damage>defense ? (damage/defense) : 0`

Note that this is *by no means* an exhaustive list, since many games use multiple stats to arrive at a final "defensive" result (agility, current speed, movement relative to attacker, flanking) that's applied to any potential damage.

What drives the selection of one relationship over another?

# Answer
> 3 votes
Strict has the advantage of being easy to understand, every player can easy calculate how much damage his attack will do. Be warned through that this creates a situation in where the higher someone's defense the more they gain from a higher defense level (if you have 0 defense the other attack with 100 and you have 1000 hit points it takes 10 hits to take you down, if you have 50 defense it will take 20 hits and if you have 100 def it takes infinte hits).

A minimal damage threshold will avert the "death of a thousend cuts" where many small attack slowly wither kill of a very powerfull entity, this thus prevents zerg rush like strategies.

Reciprocal will ensure that more defense will always make you stronger, if only because you are dividing by a larger number. It also ensures more or less linair scaling in your defense and it's payoff.

There is also a percentage based system where each point of defense is fed into a formula of the type 1-C^\[defense\] which will give you a number between 0 and 1 that can be used for damage reduction in percentage after which the damage is simply the multiplication of attack and that percentage `hp-=(damage*(1-C^defense))` where C is a value between 0 and 1, which gives some really smooth damage reduction formula's but can be very hard to understand for players. This formula has slight dimishing returns for higher defense levels.

So what you need to do is decide whatever you are OK with complex formula's that most players will not understand or not. Then you need to decide whatever your sytem favours single strong players or a group, and whatever you want diminishing returns, linair returns or actual exponential returns.

# Answer
> 2 votes
Rather then simply considering the mathematical differences among these formulae, I believe the genre of the game itself plays an important role concerning this issue.

Here is something that pops up in my mind:

* Arcade fighting

+ different parts of the body may have different "on damage" modifier
    + skills/combos are the sources of the most obvious difference in damage output
* FPS

+ different parts of the body may have different "on damage" modifier
    + resulting damage depends on the weapon/armor/equipment used
* RTS/RPG

+ since there are often more entities existing in the game and these types of games usually focus on tactics/strategies used, calculations should be more intuitive and less complex
    + make use of the aforementioned "Threshold" or "Reciprocal" formulae, with the calculations of buff-related stuff applied afterwards

p.s. Watch out for "division by zero" =)

---
Tags: game-design, game-mechanics
---


title: 2D Rectangle Collision

text:
# Question
Title: 2D Rectangle Collision
I want to make a small 2D game. In the game you can go in all directions(with the bird's-eye view) and can shoot. (A little bit like BoxHead http://de.y8.com/games/box\_head\_2play) My problem there is the collision detection and especially the response, in which the detection of a collision is not really the problem(I use for that a quad tree). The real problem is the response to the collision. For simplifying it, all objects in the game are rectangles that cannot rotate, no shapes or circles. The rectangles are represented by a vector for the left bottom corner and a vector for the right top corner. The origin of the coordinate system is in the left bottom corner(I know in games its often on the left top corner but I prefer the bottom corner). So now a object in the world is composite with a rectangle and a velocity vector. The algorithm for now is, change the velocity(For example if the user press a key) from a object(In this case the player), add the velocity on the object and at last check for collision(I leave fro now the acceleration alone).

**The real question now:** How I response to the collision now ? What should I do, if the quad tree detect a collision ? Is the basic algorithm right ?

Still a small question: How I can detect collision in a **endless** world with a quad tree(Quad trees was always limited to a specify size) ?

You see I have a lot of questions. I don't know where to start and handle/detect the collision. I hope you can help me to get started.

**EDIT:** I don't need/want advanced collisions/physics. I only want that a player cant go through walls and detect if a bullet hits something.

# Answer
Well, Mike C already gave you a simple answer, I am going a bit deeper:

First you need to a way to filter the results by proximity (this is to prevent lag when looping throught the objects) I advise using some sort of hashmap to sort the objects. Calculate them on a grid with their X and Y coordinates and then just Iterate between the near objects, if they are not near they wont collide.

But before that, make this question how many objects will there be in your world at a current time? 100? If they are rects this is relatively fast to process.

If thats not the case and you have Thousands of objects that gets complicate quite fast.

A few optimizations: Reduce the number of comparisons by doing something like this:

```
for(int i = 0; i < MyObjectsCount;i++)
  for(int j = i+1; j < MyObjectsCount;j++)
    //Do Collision

```

This will cut some unecessary computations, for example if A checks collision with B, the re is no point in B checking collision with A again.

If that still not enough, well you will need to start doing the screen partition, or chunks like they described above. Divide your world in areas, and each object can be in at most 4 of those areas (like a quad tree) but without the subdivision.

If you really want a quadtree, you can make your quadtree increase in size to accommodate the new objects boundaries. But if your world is infinite, you will need a way to Load/unload the objects you need at runtime, You can't load infinite data in the Ram.

So my advice is when you load Data, make your quadtree accommodate the new objects, and reposition the old ones, if this is done correctly, the overhead of doing this wouldn't be a issue. Take this example, if the map scrolls in positive X, you just copy the TopRight and BottomRight to the left Side of the quadtree (should be just changing references)

Hope this can give you a insight on how to do it. If you need further help, or if you describe your case more in depth, I will glady throw some pieces of code for you to mess arround.
> 1 votes

# Answer
It depends on how advanced you want it to be. The simplest solution I'm aware of given your setup is merely "push back" anyone who collides. As in, if the player collides with an enemy during this frame, put the player against the edge of the enemies hit box.

```
// An example of when the player is walking to the left
if (rect.x < enemy.rect.x + enemy.rect.width) {
    rect.x = enemy.rect.x + enemy.rect.width + 1; // A little buffer to avoid
                                                  // constant collisions
}

```

As for bullets, I would suggest this GameDev question.
> 0 votes

---
Tags: 2d, collision-detection
---


# Question
Title: Can I directly pass a Boost ptr_vector list to glBufferData?
I have a data structure like this:

```
typedef struct vertex_ {
float x;
float y;
float z;
float s;
float t;
}vertex;

```

Then I add to a list called: `boost::ptr_vector<vector> vertices;`

Is there a way to use vertices to provide the parameters for `glBufferData`?

# Answer
> 3 votes
`boost::ptr_vector` is, underneath the hood, a `std::vector<void *>`.

Not only is it not possible to use the `ptr_vector` to directly supply an input to `glBufferData` (et cetera), but it is a *phenomenally bad* way to store vertex data in general because of the extremely poor cache locality of the data

If you were to use `std::vector<vertex> vertices;` instead, you could pass the address of the first element of the vector to functions like `glBufferData` easily.

---
Tags: opengl, c
---


title: Rearranging array for memory efficiency

text:
# Question
Title: Rearranging array for memory efficiency
This is a question about a passage from this article on component based engine design.

> I suggest having every game object exist within a single giant array. This keeps game objects together in memory, and even though deletion of a game object is of O(n) complexity, that O(n) operation traverses an array, and usually will turn out to be unnoticeable. A custom vector or array class can be created that avoids the O(n) operation entirely **by taking the element at the end, and placing it into the deleted slot**.

I'm trying to understand what kind of operation the author is talking about. If I'm getting the overall point correctly, it's that accessing elements that are closer together in memory is faster, so therefor it's desirable to reorder the array such that there aren't any holes left when a game object is deleted.

If that is what the author means, then how is it possible to implement? This is what I'm imagining:

```
void Factory::addObject(const std::string name) {
    objects.push_back(new GameObject(name));

void Facrory::removeObject(const std::string name) {
    for(auto itr = objects.begin(); itr != objects.end()) {
        GameObject* obj = *itr;
        if(obj->name == name) {
            delete obj;
            // grab GameObject from end
            GameObject* endObj = objects.back();
            objects.erase(--m_objects.end());
            itr = objects.insert(itr, endObj);
        // else increment itr and continue

```

But that can't be right because just rearranging the pointers doesn't change how the memory is organized. So the author must be talking about something I don't understand about memory management.

My question is:
Have I misunderstood what the author meant? If not, then please explain how the author is suggesting the rearrangement is supposed to be done.

# Answer
This is a good question. I was trying to express that instead of holding an array of pointers to game objects, you can hold an array of game objects themselves, as pointed out by API-Beast in the comments of your question.

You can implement this swap operation like this, assuming the array holds structs with simple data (structs with ints, floats, etc., no free, no delete, no malloc, no new, no deep copies):

```
void Array::Release( index i )
{
    m_array[ i ] = m_array[ --m_size ];
}

```

Please note that it is important to be able to refer to an object by its index. In your question you are looking up an object by string, which means there's not a clear mapping from string to memory location. If you use an integer index you can understand exactly where in memory (in the array) the object is located. This lets you grow the array by allocating a bigger array, copying the old elements over, and freeing the new array. Old indices into the old array will still work with the new array memory.

This is just how the swap operation works. You'll need to somehow update the `index` of the moved object, which is where the idea of a `handle` becomes useful. Implementing handles is another different topic, but will probably be necessary for being able to move objects around in memory without any dangling pointers. The idea of utilizing the cache properly, handles, simple structs and copying the last element is talked about in detail in the next article on cache aware components.
> 2 votes

---
Tags: c++, optimization, memory-efficiency
---


title: Move a sphere along the swipe?

text:
# Question
Title: Move a sphere along the swipe?
I am trying to get a sphere curl based on the swipe. I know this has been asked many times, but still it's yearning to be answered. I have managed to add force on the direction of the swipe and it works near perfect. I also have all the swipe positions stored in a list. Now I would like to know how can the curl be achieved. I believe the the curve in the swipe can be calculated by the Vector dot product

If theta is 0, then there is no need to add the swipe. If it is not, then add the curl. Maybe this condition is redundant if I managed to find how to curl the sphere along the swipe position

The code that adds the force to sphere based on the swipe direction is as below:

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

public class SwipeControl : MonoBehaviour
{
//First establish some variables
private Vector3 fp; //First finger position
private Vector3 lp; //Last finger position
private Vector3 ip; //some intermediate finger position

private float dragDistance;  //Distance needed for a swipe to register
public float power;
private Vector3 footballPos;
private bool canShoot = true;
private float factor = 40f;

private List<Vector3> touchPositions = new List<Vector3>();

void Start(){

    dragDistance = Screen.height*20/100;
    Physics.gravity = new Vector3(0, -20, 0);
    footballPos = transform.position;
}

// Update is called once per frame
void Update()
{
    //Examine the touch inputs
    foreach (Touch touch in Input.touches)
    {
        /*if (touch.phase == TouchPhase.Began)
        {
            fp = touch.position;
            lp = touch.position;

        }*/

        if (touch.phase == TouchPhase.Moved)
        {
            touchPositions.Add(touch.position);
        }

        if (touch.phase == TouchPhase.Ended)
        {

            fp = touchPositions[0];
            lp = touchPositions[touchPositions.Count-1];
            ip = touchPositions[touchPositions.Count/2];

            //First check if it's actually a drag
            if (Mathf.Abs(lp.x - fp.x) > dragDistance || Mathf.Abs(lp.y - fp.y) > dragDistance)
            {   //It's a drag

                //Now check what direction the drag was
                //First check which axis
                if (Mathf.Abs(lp.x - fp.x) > Mathf.Abs(lp.y - fp.y))
                {   //If the horizontal movement is greater than the vertical movement...
                    if ((lp.x>fp.x) && canShoot)  //If the movement was to the right)
                    {   //Right move
                        float x = (lp.x - fp.x) / Screen.height * factor;
                        rigidbody.AddForce((new Vector3(x,10,16))*power);
                        Debug.Log("right "+(lp.x-fp.x));//MOVE RIGHT CODE HERE
                        canShoot = false;
                        //rigidbody.AddForce((new Vector3((lp.x-fp.x)/30,10,16))*power);
                        StartCoroutine(ReturnBall());

                    }
                    else
                    {   //Left move
                        float x = (lp.x - fp.x) / Screen.height * factor;
                        rigidbody.AddForce((new Vector3(x,10,16))*power);
                        Debug.Log("left "+(lp.x-fp.x));//MOVE LEFT CODE HERE
                        canShoot = false;
                        //rigidbody.AddForce(new Vector3((lp.x-fp.x)/30,10,16)*power);
                        StartCoroutine(ReturnBall());
                    }
                }
                else
                {   //the vertical movement is greater than the horizontal movement
                    if (lp.y>fp.y)  //If the movement was up
                    {   //Up move
                        float y = (lp.y-fp.y)/Screen.height*factor;
                        float x = (lp.x - fp.x) / Screen.height * factor;
                        rigidbody.AddForce((new Vector3(x,y,16))*power);
                        Debug.Log("up "+(lp.x-fp.x));//MOVE UP CODE HERE
                        canShoot = false;
                        //rigidbody.AddForce(new Vector3((lp.x-fp.x)/30,10,16)*power);
                        StartCoroutine(ReturnBall());
                    }
                    else
                    {   //Down move
                        Debug.Log("down "+lp+" "+fp);//MOVE DOWN CODE HERE
                    }
                }

            }
            else
            {   //It's a tap
                Debug.Log("none");//TAP CODE HERE
            }

        }
    }

}

IEnumerator ReturnBall() {

    yield return new WaitForSeconds(5.0f);
    rigidbody.velocity = Vector3.zero;
    rigidbody.angularVelocity = Vector3.zero;
    transform.position = footballPos;
    canShoot =true;
    isKicked  = false;
}

```

}

# Answer
> 1 votes
I have written a utility class in a game before for handling Bezier Curve. You may try to use the points along the swiping path as control points. Though I did not make use of any physics stuff for calculations, the outcome should satisfy your need.

```
using UnityEngine;
using System;
using System.Collections;

public class BezierCurve {
    public static Vector3 Lerp(Vector3 start, Vector3 end, Vector3[] controlPoints, float time) {
        Vector3[] points = new Vector3[controlPoints.Length + 2];
        points[0] = start;
        points[points.Length - 1] = end;
        Array.Copy(controlPoints, 0, points, 1, controlPoints.Length);
        return Lerp(points, time);
    }

    public static Vector3 Lerp(Vector3[] points, float time) {
        Vector3 ret = Vector3.zero;

        if (points != null && points.Length > 0) {
            int n = points.Length;
            for (int i = 0; i < n; i++) {
                Vector3 cp = points[i];
                cp *= BinomialCoefficient(n - 1, i);
                cp *= Mathf.Pow(1 - time, n - i - 1);
                cp *= Mathf.Pow(time, i);
                ret += cp;
            }
        }

        return ret;
    }

    static int BinomialCoefficient(int n, int k) {
        int nCk = 1;

        if (k >= 1 && k <= n - 1) {
            int numerator = 1;
            int denominator = 1;

            for (int i = 0; i < k; i++) {
                numerator *= (n - i);
                denominator *= (k - i);
            }

            nCk = (int)(numerator / denominator);
        }

        return nCk;
    }
}

```

---
Tags: unity, touch, curves
---


# Question
Title: How big should my tiles be for tilemaps?
I'm creating my first tilemaps.

Tutorials usually do 32x32px (example), but this tutorial did 128x128px, which made it easier for me to see without zooming in so much.

In tiled, I did a 40 x 40 tile map at 128 x 128 px, and the map was 5120 x 5120 px big, versus the same 40 x 40 tile map at 32 x 32 px giving me 1280 x 1280 px in resolution. I'm making a web game from the typical HTML 5 (with canvas), JS, CSS3, and melonJS engine.

Does it matter if I make 32 x 32 px tiles vs 128 x 128 px? Will it affect performance?

# Answer
That's purely a matter of personal preference. Unless you are going to extremes of some sort (too small or too large), that aspect alone won't affect performance. Of course if you have same count of tiles, larger images will naturally consume more memory and, generally, perform slower.

As a side note, assuming you are beginner in a gamedev, most performance aspects should be absolutely ignored, unless you immediately see serious perfomance degradation. I'm not saying they are not important, but often they are overestimated.
> 2 votes

# Answer
Its really a matter of how much definition you want in your map... If you choose 32x32 px you'll mostly end up with Pixel Art. If that is not what you are looking for, just pick a bigger size. As long as it is a power of 2 and its not an absurd HD size just for one tile, it wont really affect performance.
> 2 votes

---
Tags: tiles, tilemap, pixel
---


# Question
Title: How can I increase text using scale and keep the text smooth in libgdx?
I found that I can use DistanceFieldShader from here and found an example but I couldn't make it work. First my whole screen becomes white, all the other actors that I have on screen disappears. second, the text that supposed to be smooth becomes to be black squares. whats wrong with my code? Or maybe someone can give me an example that suits my needs.

This class represents score in the game. (Maybe this should be actor and needs to be Label)

```
public class Score extends Actor {
    private int scoreInt;
    private BitmapFont scoreBitmapFont;
    private int x, y;
    private DistanceFieldShader distanceFieldShader;

    private Texture distanceFieldTexture;
    private BitmapFont distanceFieldFont;

    float scale = 1.5f;
    float smoothing;

    public Score(int x, int y) {
        this.x = x;
        this.y = y;
        scoreInt = 0;
        scoreBitmapFont = new BitmapFont();
        scoreBitmapFont.setColor(Color.BLACK);
        scoreBitmapFont.scale(scale);

        distanceFieldTexture = new Texture(Gdx.files.internal("default.png"), true);
        distanceFieldFont = new BitmapFont(Gdx.files.internal("default.fnt"), new TextureRegion(
                distanceFieldTexture), true);
        distanceFieldFont.setColor(Color.BLACK);

        distanceFieldShader = new DistanceFieldShader();

        // set filters for each page
        Texture.TextureFilter minFilter = Texture.TextureFilter.MipMapLinearNearest;
        Texture.TextureFilter magFilter = Texture.TextureFilter.Linear;

       scoreBitmapFont.getRegion().getTexture().setFilter(Texture.TextureFilter.MipMapLinearNearest, Texture.TextureFilter.Linear);
    }

    public void inc(int inc) {
        scoreInt = scoreInt + inc;
        if (scoreInt < 0) scoreInt = 0;
    }

    @Override
    public void draw(Batch batch, float alpha) {
        String scoreStr = String.format("Score: %d", scoreInt);
        smoothing = scoreBitmapFont.getBounds(scoreStr).width;
        batch.setShader(distanceFieldShader);
        scoreBitmapFont.draw(batch, scoreStr, x, y/* + scale * getBaselineShift(scoreBitmapFont)*/);
        distanceFieldShader.setSmoothing(smoothing / scale);

//        y += scoreBitmapFont.getLineHeight();
    }

    public int getScoreValue() {
        return scoreInt;
    }

    private float getBaselineShift(BitmapFont font) {
        if (font == distanceFieldFont) {
            // We set -8 paddingAdvanceY in Hiero to compensate for 4 padding on each side.
            // Unfortunately the padding affects the baseline inside the font description.
            return -8;
        } else {
            return 0;
        }
    }
}

```

# Answer
I found the solution and now it works:

```
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.TextureRegion;

public class BitmapFontShader extends BitmapFont {

private final Texture.TextureFilter minFilter = Texture.TextureFilter.MipMapLinearNearest;
private final Texture.TextureFilter magFilter = Texture.TextureFilter.Linear;

private DistanceFieldShader distanceFieldShader;
private float smoothing;

public BitmapFontShader(FileHandle fontFile, TextureRegion textureRegion, Boolean flip, float shaderSmooth) {
    super(fontFile, textureRegion, flip);
    this.smoothing = shaderSmooth;
    distanceFieldShader = new DistanceFieldShader();
    getRegion().getTexture().setFilter(minFilter, magFilter);
}

@Override
public BitmapFont.TextBounds draw(Batch batch, java.lang.CharSequence str, float x, float y) {
    smoothing = this.getBounds(str).width;
    if(this.getScaleX() != 0) {
        batch.setShader(distanceFieldShader);
        distanceFieldShader.setSmoothing(smoothing / this.getScaleX());
    }
    TextBounds textBounds = super.draw(batch, str, x, y + this.getScaleY() * getBaselineShift(this));
    batch.setShader(null);
    return textBounds;
}

private float getBaselineShift(BitmapFont font) {
    if (font == this) {
        // We set -8 paddingAdvanceY in Hiero to compensate for 4 padding on each side.
        // Unfortunately the padding affects the baseline inside the font description.
        return -8;
    } else {
        return 0;
    }
}

```

}
> 1 votes

---
Tags: libgdx
---


# Question
Title: Which game logic should run when doing prediction for PNP state updates
We are writing a multiplayer game, where each game client (player) is responsible for sending state updates regarding its "owned" objects to other players.

Each message that arrives to other (remote) clients is processed as such:

1. Figure out when the message was sent.
2. Create a diff between NOW and that time.
3. Run game specific logic to bring the received state to "current" time.

I am wondering which sort of logic should execute as part of step #3 ?

Our game is composed of a physical update (position, speed, acceleration, etc) and many other components that can update an object's state and occur regularly (locally).

There's a trade off here - Getting the new state quickly or remaining "faithful" to the true state representation and executing the whole thing to predict the "true" state when receiving state updates from remote clients.

Which one is recommended to be used? and why?

# Answer
> 1 votes
I think what you are asking here is whether to use authoritative servers or non-authoritative servers. Unity network documentation has a nice discussion about each mode. Also if I'm not wrong, some people call semi-authoritative to a mixed approach where some state is handled by the server and some by the client.

I think Unity discussion should give you a good grip of the pros and cons of each alternative. Regarding the implementation, the two alternatives are: calculating state deltas, sending them and reconciling the state, or either sending the whole state. What method is better depends on the state, so you will need to define it in an individual basis.

# Answer
> 0 votes
I suggest to have a compromise on frames delivered(fps), anyways without a strong server to handle and maintainance cost building up, you would consider switching to provide players with full functionality of game resources and less(relatively) attention to getting the state quickly.\`

> \[I suggest to compromise(slightly) and remain faithful to players\]

\`

Now for the developing part, you could keep two times (zones),

1.Depicting user time(this depends on user & may vary by location/zone)

2.Depicting **server time** to club all game related events (Universal time)

For this , you need to send state ,that is recently configured, just before the end of your update method() and set frames afterwards, or you may end up in loop. In main method, try to use dynamic variables and "store state and previous states in array.", alongwith updates for player position speed, accl, as mentioned by you.

Whenever a player acquires a object, only a variale boolean corresponding to it should be active, and sent to other clients whenever next update is called

*You will have to figure out a rate that suits your game best, although both are important* refrence: http://www.mmorpg.com/blogs/FaceOfMankind/052013/25185\_A-Journey-Into-MMO-Server-Architecture

http://www.leebrimelow.com/actionscript-3-quicktip-4-dynamic-frame-rates/

And studying from open source MMO examples also...How should chat be transmitted and stored in an MMO? for an approach to store times for objects instead of messages in your case.

HOPE this answers your question, feel free to ask me for socket side settings for sending updates to other clients...

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


# Question
Title: Changing the color of some fragment of a texture using shaders
Declarative programming language QML allows to connect the elements, their properties with universal variables in shader programs description. For these purposes there is such elements as ShaderEffectItem, for instance. Here, for example, we define a certain image `image.jpg`. And in the `source` property we set just that this image any will change in the image and further this property is set already in the fragment shader program description fragmentShader as uniform sampler2D source. `qt_TexCoord0` defines initial coordinate a texture. We receive there gray color on all texture scalar product lowp float gray = dot (textureColor, vec4 (0.299, 0.587, 0.114, 0.0)); also we install color of a fragment in an output variable gl\_FragColor.

```
....
Item {
    id: main
    Image {
         id: img
         source: "images/image.jpg"
      }

    ShaderEffectItem {
       id: effect
       property real ratio: 1.0
        property variant source: ShaderEffectSource {
             sourceItem: img;
             hideSource: true
        }

        fragmentShader:
          "
          varying highp vec2 qt_TexCoord0;
          uniform sampler2D source;
          uniform highp float ratio;
          void main(void)
          {
            lowp vec4 textureColor = texture2D(source, qt_TexCoord0.st);
            lowp float gray = dot(textureColor, vec4(0.299, 0.587, 0.114, 0.0));
            gl_FragColor = vec4(gray * ratio + textureColor.r * (1.0 - ratio), gray * ratio + textureColor.g * (1.0 - ratio), gray * ratio + textureColor.b * (1.0 - ratio), textureColor.a);
         }
         "
    }

        SequentialAnimation on ratio {
            id: ratioAnimation
            running: true
            loops: Animation.Infinite
            NumberAnimation {
                easing.type: Easing.Linear
                to: 0.0
                duration: 500
            }
            PauseAnimation {
                duration: 500
            }
            NumberAnimation {
                easing.type: Easing.Linear
                to: 1.0
                duration: 500
            }
            PauseAnimation {
                duration: 500
            }
        }
    }

```

After performance color of a texture (picture) gradually completely passes in gray, and all is then reverse also it is fulfilled in an infinite loop. Now:

A question actually here in what: and I can change somehow color of any definiteness of a part of a texture (my picture images/image.jpg), i.e. any certain sections. For example I will define in QML two variables xColor, yColor, we transfer it similarly ratio the shader description and then for example the texture will change only in a square with coordinates the left top corner \[xColor - 10, yColor - 10\] and \[xColor + 10, yColor + 10\] - bottom right corner. I want:

I know that it can be implemented. How it more optimally to make? In what direction to me to think? Whether there are any similar examples? It would be nice to add blending color (red to gray in this section).

# Answer
> 3 votes
I hope I understand the question correctly. What you want is tell the fragment shader to only apply your effect to a neighbourhood of `(xColor,yColor)`.

First of all, you should learn about the GLSL `mix()` function (called `lerp()` in HLSL). This heavy calculation:

```
gl_FragColor = vec4(gray * ratio + textureColor.r * (1.0 - ratio),
                    gray * ratio + textureColor.g * (1.0 - ratio),
                    gray * ratio + textureColor.b * (1.0 - ratio),
                    textureColor.a);

```

Can be rewritten as:

```
gl_FragColor = mix(textureColor, gray, vec4(vec3(ratio), 0.0));

```

There is also the `step()` command, which tests whether a value is higher than another. This should work:

```
      varying highp vec2 qt_TexCoord0;
      uniform sampler2D source;
      uniform highp float ratio;
      uniform highp vec2 pa, pb;
      void main(void)
      {
        lowp vec4 textureColor = texture2D(source, qt_TexCoord0.st);
        lowp float gray = dot(textureColor, vec4(0.299, 0.587, 0.114, 0.0));
        lowp vec4 test = step(vec4(pa.xy, qt_TexCoord0.st),
                              vec4(qt_TexCoord0.st, pb.xy));
        ratio *= (test[0] * test[1]) * (test[2] * test[3]);
        gl_FragColor = mix(textureColor, gray, vec4(vec3(ratio), 0.0));
     }

```

Finally, you just need to pass `((xColor - 10) / xTextureSize, (yColor - 10) / yTextureSize)` in `pa`, and the same (with `+ 10`) in `pb`. Merging `pa` and `pb` in one single `vec4` uniform would be a lot better but maybe less readable.

# Answer
> 0 votes
You can create a mask using a new texture:

And use the colour at each point as the ratio to GLSL mix() with your textureColor from your original image in your shader and your grey value.

You can also multiply the ratio by a blend ammount.

Something like

```
varying vec blend_ammount; // 0.0 to 1.0
lowp vec4 textureColor = texture2D(source, qt_TexCoord0.st);
lowp vec4 maskcolor = texture2D(mask, qt_TexCoord0.st);
lowp float gray = dot(textureColor, vec4(0.299, 0.587, 0.114, 0.0));
vec4 color = mix(textureColor, gray, maskcolor * blend_ammount);

```

---
Tags: opengl, textures, shaders, opengl-es
---


title: Grow first, Ads later for mobile games?

text:
# Question
Title: Grow first, Ads later for mobile games?
Facebook's strategy has been to Grow First, include Ads Later. For mobile games, is there any evidence that ads hinder popularity, or that people are more likely to share games without ads? Or as mentioned by angarg12, is there evidence that introducing ads part-way through a game's life cycle affects how people feel toward your game?

# Answer
A user keeps a game on his mobile phone on average 20 days. So for the most part, adding ads is not going to be noticed much after launch. However, it is going to affect your biggest fan the most, which is the segment you don't really want to piss off.

There are ways to mitigate the effect however. #1 is to only show ads to people who downloaded the game after version X, so old player won't see any ads. Also, do not show ads to players who purchased something (so no ads in premium games and no ads to a user who dropped $5 on virtual goods).

I have retroactively added ads into a popular game. The effect was some bad reviews, but for the most part people expect ads - as long as they are not over the top annoying. The rating didn't really drop when I added the ads. Maybe 0.1 points, but that's it.

Also you can let the users know that you need the money to make another game... lots of people are quite understanding of the plea of the indie developer.
> 5 votes

# Answer
Facebook is not at all analogous to games. Once you and all your friends are there (let's say 50 people), you are all not going to get up and leave at the same time because of ads. Just one person won't leave because his network of people won't be at the new place.

Facebook as a system has huge momentum because of the social capital thing. An individual game doesn't, unless it's something involving tons of players like WoW. Even then, the networks of involved players in WoW aren't as big as the networks on FB.
> 6 votes

# Answer
I think the question you should ask is "what is the impact of transition from ad-free to include ads in players?"

All examples I personally know from mobile game developers, they either included ads or didn't, but never switched from one to the other. Just think, if somebody gets hooked to you game with ads, he is OK. But if he gets hooked without ads, and you add them, is he going to react negatively?.

After a quick search I was unable to find advice on the matter, but think that while people is quite tolerant to changes in large platforms like Facebook, I usually picture users of mobile games as much more volatile (after all, they have thousands of alternatives to choose from).
> 5 votes

# Answer
The following article is from the dev(s) of clash of clans where they point out one of their "Keys to success" is not having ads. Its just a small reason but its something that's brought up.

http://www.gamasutra.com/view/news/185406/Clash\_of\_Clans\_5\_keys\_to\_success.php
> 4 votes

# Answer
Changing the rules of the game mid-way is usually a bad idea. People acquire a product for a number of reasons which vary from person to person. One of those reasons might be not being bothered by annoying ads popping up from everywhere. In therms of mobile games, I always enjoyed the idea of creating a free version with ads and an ad-less comercial version. That way users always feel like they have the power of choice.
> 1 votes

# Answer
Good question. Let us assume some simple things:

1. A game without ads is more likable to a user.
2. User understands that ads are 'necessary evil' to make 'free' games possible.

Given that, *For mobile games, is there any evidence that ads hinder popularity, or that people are more likely to share games without ads?* I would say 'No'. People are more likely to share games that they like, and such games are not necessarily ads free.

*Or as mentioned by angarg12, is there evidence that introducing ads part-way through a game's life cycle affects how people feel toward your game?* I think most important aspect here is that people don't like being fooled. Changing rules is some sort of cheating, they would not like it. However given p.2 most users will understand that this is normal -- it was free, but it can't be free forever (unless you told them so). You could also mention specifically that game won't be ads free forever. It also can be reasonable to add, at the same time, ability to buy ads-free option, so you won't lose people that are zero-tolerant to ads, but like your game.

As a personal experience, I think major problem with ads is then there is excessive amounts of it and then it's placed deliberately so you can accidentally hit it. It doesn't matter if it was added from the start, or after some time. If there is no option to buy game, most will stop using it.

As a conclusion I think that adding ads midway would not affect users significally unless you add it too much. But I also think that adding it from the start would NOT make it more or less popular -- as already mentioned Facebook analogy can't be really applied here.
> 1 votes

# Answer
I'd say waiting at least a little bit is best.

When you put ads is less about how your users will respond to ads. If you put ads immediately (like Microsoft Studios Windows 8 game apps) people will come if it's not intrusive. If you put ads later (like Facebook, YouTube, Twitter, ...) your following will moan but stay.

The real advantage to waiting on ads is focus. First your decisions cater to users. When ads come in, you now have another audience to give time, screen space and production effort to, the advertisers. Developing a strong, loyal community can be easier if in the beginning you are giving your all (screen space, design thought effort, programming time, game time, etc) to the users. Once things are stable and your users are happy, then you can slowly start to tackle that second audience of advertisers.

Also, looking at a more complete and stable sense of your app makes it easier to see where ads would work. After the UI is made, it might become clearer whether text, graphic or inter-level video ads would be best. You can use in-app analytics to figure out expendable screen real estate, what kinds of screen sizes you have to work with, what places a user tends to just be waiting while things load, etc. This can all help you make a better design for putting in ads.

...Lastly, if you do have a big following before ads, that might help you have some say in picking out sponsors if you wanted.
> 0 votes

# Answer
Im a beginning android developer, and been thinking on this subject.

Obvious is that, that an unpopular game doesnt need ads, because theres noone to see them. Our main goal being monetization, we need to have a popular game and for it to have ads.

One of the hints to make a popular game is to make lots of games. So, by not implementing ads in all of them, you save time, so you can make more games. Then, when you see one game gaining popularity, you implement ads.

Also, as other mentioned, a game that doesnt have ads is a little bit more attractive to users.

So yes, grow first, ads later makes sense for me.
> 0 votes

# Answer
**General INTRO/Context:**

It is a general misconception that people think, while playing,how can inclusion of ads in the mid way affect gameplay, but reality dives deep into it.

A lot of thinking goes into marketting department for each game, what possible dates should be planned to make the update of a game more successful, how adding a simple patch, at right time causes deep crests and troughs in game sales

**Answering the question:**

A good game usually starts off on its root, and i am not completely against displaying ads, cause that is the game earning source for the developers, and it should be used with care, and the reasons for this statement are few of experiences listed in google hangouts and game review sites:

1. Adding a ad in the midway of game development,reflects 2 things , firstly that game has strong roots(& or strong marketting resources), and secondly that developers also want a fair share of users to understand their credit in achieving the gameplay level.
2. Premium items: Inclusion of premium items(gold/gem)or high order currency in which users can dominate other freeloaders by the resources, these techniques, really spoil the gaming environment, but introducing them, so that both freebies and richies remain at content is a skill,
3. Placement of an ad url link that occurs just after you press an "OK" button that arrives at the same location, an you get frustrated to get back to play
4. Demo versions: Now these demos are good to play for some games, but not even letting the players to complete one level in the game and redirecting to buy the game page, shows the greed and desperate attempt from developers side, and from game's point of view it is considerred to be a money-milking strategy.
5. Ads That appear afterwards the game hits a success tier should be more careful to look at all aspects regarding content of ads, and also place all the items relating to game-related queries only
6. Preloader ads: These are most frustrating, and every time the user thinks, that waste all your energy in loading the game not the ad, and game may fail in later stage.
7. Adding a patch :**that deletes your local save and restarts, enabling you to go from a series of ads**, this is the most dangerous type, users get frustrated and angry instantly and game is burried into bad reviews section everywhere. 8.

> Coming back to just ADS

Those ADS that are inserted in some patch, From developers point of view its a fortune and game can grow even more, and this enables high values of rich context in relation to game to reach out to market for even more success.

* Another factor is HONESTY: \[from the developers side\], giving a free game, and later giving out a paid sequel to awesome game can truly reflect ads matter and game content also drives users. we see a lot of versions of Angry Birds in the market, take a close look at its marketing case study, and how it evolved. I think it is the perfect example.

Also This answer is more from the point of how players perceive the game and how ADS/patch/updates change their behaviour reflecting it on game, From developers side , a developer should consider this point of view and also avoid accidental-click money, if they drive on game content.

Hope the answer explains and stands true from both sides...

**Referrences:** http://www.cnet.com/news/bioshock-studio-irrational-games-closing-its-doors/

http://www.mmaglobal.com/files/casestudies/Mobile\_Ad\_Formats\_Explained\_20131119.pdf

and normal experience of playing and developing mobile games(dumb games included), google hangout seesions on game development and game chatrooms

http://www.gamefaqs.com/wii-u/631516-wii-u/answers?qid=363046 this is the game that works for wii, but for mobile platforms as in question, there are many (Im not naming) games that appear in bad reviews that have instant loss due to new patches deleting saved data.

angrybirds case study
> 0 votes

# Answer
From my experience, it is not so much if there are ads or not, but more of how they are being used. If you have an ad on the main screen that the player will be on for the majority of their time, then they are exposed to the ad more. If it's on a menu screen, that the player will always use, but not for a long period of time, then it is not as heavy of an exposure.

Another idea is if the player can get rid of the ad in some way, mainly navigation of the game. If the ad is on the main game screen, then when playing your game, they will always be exposed to it for as long as they play, which gives a kind of trapped sense to the player. If the ad is on a menu screen or something, the player can navigate away, and avoid seeing it. You are giving the player actions to prevent exposure to the ad, but exposure is the only way to prompt the action.
> 0 votes

---
Tags: marketing, monetization, social, advertisements
---


title: Pure OpenGL software rendering

text:
# Question
Title: Pure OpenGL software rendering
For training a machine learning algorithm, we need to render some geometry in OpenGL without any hardware rendering support (no graphics card). So we were thinking of rendering in pure software, and we have looked at Mesa already. It seems like it is capable of rendering in pure software, but so far, we only get OpenGL 2.x, whereas we need OpenGL 3.3 .

Does anyone know if that is possible? and if so, how? We seem to run into stumbling blocks all the time.

(Background, why we want to do that: for training the learning algorithm, we need to perform a lot of runs of our software on a PC cluster, which do not allow rendering in hardware.)

Any hints, ideas, and pointer will be appreciated.

# Answer
I am confused at your requirements. Are you running the code on a PC or an embedded system? If you are running on anything that remotely looks like a PC the "any hardware rendering support" is basically simply not true. At the bare minimum you have some Intel integrated stuff. I have yet to see a headless system that physically did not have a video chip.

On a headless system you can render without a window, how to do this with GLX you can see details in Windowless OpenGL. In any case even the most crappy hardware will be more efficient than a software renderer.

If you really are in a pinch and absolutely have no graphic hardware, you can use something like VirtualGL.

But if you are synthesizing pictures in software using OpenGL is sort of backwards. OpenGL is designed around the severe restrictions of graphic hardware. The result is that there are significant build in restrictions that can willfully be ignored when rendering in software. In addition the raster algorithm is not very efficient when using current hardware. A first order ray tracing can be more efficient and easily paralyzes over multiple cores. Maybe you can look into something like PovRay.
> 6 votes

# Answer
It would seem only OpenGL 2.x is fully supported by the software renderer in Mesa.

However, this answer suggests, that most of the functionality of OpenGL 3.x is supported via extensions. So, you might want to give it a try.
> 3 votes

---
Tags: software-rendering
---


title: Assimp skeletal animation matrices

text:
# Question
Title: Assimp skeletal animation matrices
I startded to make an assimp only opengl skeletal animation demo. For that I used this: http://sourceforge.net/p/assimp/discussion/817654/thread/5462cbf5 And something is not correct in bone matrices.

and my standerd bob\_with\_lamp model(.md5) looks like this. its moving its parts but not in correct way.This is the code:

```
    for( size_t a = 0; a < anim->mNumChannels; ++a)
{
  const aiNodeAnim* channel = anim->mChannels[a];
  aiVector3D curPosition(0,0,0);
  aiQuaternion curRotation(1,0,0,0);
  aiNode* targetNode = scene->mRootNode->FindNode(channel->mNodeName);
  while((int)time >channel->mNumPositionKeys) time-=channel->mNumPositionKeys;
  curPosition = channel->mPositionKeys[(int)time].mValue;
  curRotation = channel->mRotationKeys[(int)time].mValue;
  aiMatrix4x4 trafo = aiMatrix4x4(curRotation.GetMatrix());
  trafo.a4 = curPosition.x; trafo.b4 = curPosition.y; trafo.c4 = curPosition.z;
  targetNode->mTransformation = trafo;
}
for (unsigned int n = 0; n < scene->mNumMeshes; ++n)
{
    const aiMesh* mesh = scene->mMeshes[n];
    std::vector<aiMatrix4x4> boneMatrices( mesh->mNumBones);
    for( size_t a = 0; a < mesh->mNumBones; a++)
    {
      const aiBone* bone = mesh->mBones[a];
      aiNode* node = scene->mRootNode->FindNode( bone->mName);
      boneMatrices[a] = bone->mOffsetMatrix;
      const aiNode* tempNode = node;
      while( tempNode)
      {
          aiMatrix4x4 m = tempNode->mTransformation;
          boneMatrices[a] *= tempNode->mTransformation;
          tempNode = tempNode->mParent;
      }
    }

```

and my render:

```
    std::vector<aiVector3D> resultPos( mesh->mNumVertices);
    std::vector<aiVector3D> resultNorm( mesh->mNumVertices);

    for( size_t a = 0; a < mesh->mNumBones; ++a)
    {
      const aiBone* bone = mesh->mBones[a];
      const aiMatrix4x4& posTrafo = boneMatrices[a];
      aiMatrix3x3 normTrafo = aiMatrix3x3( posTrafo);
      for( size_t b = 0; b < bone->mNumWeights; ++b)
      {
        const aiVertexWeight& weight = bone->mWeights[b];
        size_t vertexId = weight.mVertexId;
        const aiVector3D& srcPos = mesh->mVertices[vertexId];
        const aiVector3D& srcNorm = mesh->mNormals[vertexId];
        resultPos[vertexId] += weight.mWeight * (posTrafo *srcPos);
        resultNorm[vertexId] += weight.mWeight * (normTrafo * srcNorm);
      }
    }
    //And rendering the vertices from the pos vector

```

what should I change to made this to get correct positions?

# Answer
I have founded the solution: https://www.youtube.com/watch?v=xf0VD4ba4ns In this video's desc link shows a file that I used to the new code wich is working
> 3 votes

---
Tags: opengl, c++, skeletal-animation, assimp
---


# Question
Title: How can I make an soundsystem with Slick?
My question would be, how can I develop an easy-to-use sound system under slick-util? Under the function

`a.playAsSoundEffect(1, 1, true, x, y, z);`

it already works to create a static position for the source. But if I adjust my CameraPosition in-game. So how can I change the position of the listener in Slick?

Answers would be awesome :) Thanks, Mineorbit!

# Answer
Looking at the slick-util documentation, it doesn't look like there's a way to just change the x, y, and z positions while a sound is playing. The following is a work-around I could think of off the top of my head, but I don't know how efficient this would be

So, every time the camera position changes (or maybe only when the camera position has changed significantly,) store `a.getPosition()` in some variable (like `lastPosition`) to save where the sound was playing from. Then call `a.stop()`, `a.playAsSoundEffect(1, 1, true, new_x, new_y, new_z)`, and then `a.setPosition(lastPosition)`.

Again, not sure how efficient that would be, but it's an idea.
> 1 votes

---
Tags: java, lwjgl, slick
---


# Question
Title: GUI Label shows on screen when object is out of view?
I have GUI Labels over NPCs in my game, and the labels display their name above their head. But when I walk away and go somewhere else, their names stay on screen like it's mirrored or something?

Here's what I'm talking about:

This is how it looks normally

This is what happens when I walk out of view.

**The Code:**

```
using UnityEngine;
using System.Collections;

public class NPC : MonoBehaviour {

private float left;
private float top;
public float leftModifier;
public float topModifier;

private Vector3 NPCScreenPosition;

//FIX THE MIRRORING ISSUE

void Start () {

}

void Update () {
    Vector3 NPCNameWorldPosition = (transform.position + new Vector3(0.0f, transform.lossyScale.y, 0.0f));
    NPCScreenPosition = Camera.main.WorldToScreenPoint(NPCNameWorldPosition);
    left = NPCScreenPosition.x + leftModifier;
    top = Screen.height - (NPCScreenPosition.y + topModifier);
}

void OnGUI() {
    GUI.Label(new Rect(left, top, 150, 25), gameObject.name.ToString());
  }
}

```

# Answer
> 2 votes
i recently resolved a similar issue by doing as bummzack suggested in his comment. the gui element is going to try and draw the nameplate on a 2d plane in front of the camera regardless of the direction its facing. you need to stop it manually

```
void Update () {

    Vector2 temp = cam.WorldToViewportPoint( target.position + offset );

    // check if camera is facing the target
    float angle = 60;  // my cameras view angle

    if ( Vector3.Angle( cam.transform.forward, transform.position - cam.transform.position) < angle ){

        transform.position = temp;
        guiText.text = "WORKING";
        guiText.color = Color.green;

    }

}

```

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


# Question
Title: Nearest neighbor search in 2D to find circles that interacts with point
I need to store big number of object that every object have range, then I need to find objects that the point are in their range. So basically I need to store circles and then check who interacts with some point.

`R*-tree` is very slow at the insert (again I need huge number of objects). `kd-tree` and `quadtree` doesn't allow to store shapes. another problem with `quadtree` is that there are no bounds.

There is another algorithms that meet the requirements?

# Answer
If all of your objects have the same range (say r), then the problem is to find all object centers which lie inside a given circle. In other words you can think of your original point (let's call this the target) as a circle of radius r centered at the target and your original circles (let's call them objects) as points, at their centers.

In this case you can build e.g. a kd-tree from the object centers. To find the set of object centers which lie inside the circle of radius r centered at the target (the query circle), you can traverse the kd-tree, and prune the subtrees which completely lie outside the query circle.

If you have different object ranges, I would suggest defining range buckets (e.g. close range, mid range, far range), and building different kd-trees for those buckets. The range search should be pessimistic, i.e. it should use the largest r in the bucket. You have to perform the search on the kd-trees of each bucket and consider the union of the results.
> 1 votes

# Answer
sweepline, you sort the objects by the X or Y coordinate of the center and then check the objects in the range `point.x-maxRange, point.x+maxRange`
> 0 votes

# Answer
DBVH (dynamic bounding volume hierarchy) is a common approach to solving this need.

A BVH is just a tree of nodes containing one or more bounding volumes (e.g., circles/spheres) that are grouped together into a large bounding volume encompassing the children.

There are several ways to construct a BVH. Some are intended to produce optimal trees from a known set of objects while others can dynamically construct the BVH as objects are added, removed, moved, or resized (and this kind of dynamic BVH is probably what you need).

The classic resource that will cover this algorithm in detail (and many others) is \[url=http://www.amazon.com/Real-Time-Collision-Detection-Interactive-Technology/dp/1558607323\]Real-Time Collision Detection by Christer Ericson\[/url\]. Every game programmer should have a copy of this nearby for reference, IMO.

You can also consider a grid-based approach. For each circle, add an entry to all the grid locations that the circle overlaps with pointing to the detector object. When an object is added or moves, determine which grid locations it interacts with, find the set of all detector circles registered with those grid locations, and signal them. If your world is particularly large, you can consider a hash-based sparse grid rather than a 2D array.
> 0 votes

---
Tags: c++
---


# Question
Title: Unity3d : Make prefab follow raycast hit
I've been trying to make a weapon script which fires a projectile (prefab) straight forward.I added to the bullet the first script shown here.And the second one to the main camera.The problem is that the gun doesn't shoot straight forward.I mean it shoots straight but in small distances it looks...crap.How can I make it so it follows the hit point of the raycast.I placed my attempt below.

**Script 1:**

```
var bulletSpeed : float = 20;

function Update ()
{
    transform.Translate(Vector3.forward * bulletSpeed * Time.deltaTime);
}

```

**Script 2 :**

```
var hit : RaycastHit;
    var forward = transform.TransformDirection(Vector3.forward);

    if(Physics.Raycast(transform.position, forward, hit, rayLength))
    {

    if(Input.GetButtonDown("Fire1") && canShoot==true && clip > 0)
    {
        var rocketInstance : Transform;
        rocketInstance = Instantiate(rocketPrefab, barrelEnd.position, transform.rotation);
        rocketPrefab.LookAt(hit.point);
        w();
        gun.animation.Play("Shoot");
        audio.PlayOneShot(soundEffect);
        clip -= 1;
    }
}

```

Thank you for your time,please help me!

# Answer
> 1 votes
I fixed this problem by doing this :

```
rocketInstance.LookAt(hit.point);

```

instead of this :

```
rocketPrefab.LookAt(hit.point);

```

---
Tags: unity, raycasting, unityscript
---


# Question
Title: Optimizing Draw calls in MonoGame Android platformer
I am working on a 2D platformer that is in the final stages of optimization. I have a few different devices for testing, and I am trying to get the best possible framerate on the weaker ones.

* On a Nexus 5 I get a constant 60fps, with an occasional hiccup.
* On a Galaxy S4 I also get a good 55-60fps
* On an original Galaxy S (Vibrant) The frames drop to about 20-25

My question is, **given the tile system described below, what can I do to increase the FPS on low-end devices?** And granted the Galaxy S came out years ago, should I even worry about it?

My background consists of 3 scrolling parallax layers.

The world I am drawing in a viewport of 25x15 tiles, at a size of 32x32px per tile, with 3 layers each (32x32x3px). The camera already culls tiles that are out of view. All tiles are found in one texture, and this is done in a single SpriteBatch call that locates the correct texture location for the tile layer. Code is below:

```
public void Draw(SpriteBatch spriteBatch, bool upsideDown)
{
    int startX = GetCellAtPixelX( (int)Camera.Position.X );
    int startY = GetCellAtPixelY( (int)Camera.Position.Y );

    int endX = GetCellAtPixelX( (int)Camera.Position.X +
        Camera.ViewportWidth );
    int endY = GetCellAtPixelY( (int)Camera.Position.Y +
        Camera.ViewportHeight );

    for (int x = startX; x <= endX; x++)
    {
        for (int y = startY; y <= endY; y++)
        {
            for (int z = 0; z < MapLayers; z++)
            {
                if ((x >= 0) && (y >= 0) &&
                    (x < MapWidth) && (y < MapHeight))
                {
                    // ...

                    /// The very last parameter in this draw call is
                    /// the draw depth. This draw format will arrange
                    /// layers from front to back (0 = front, 1 = back)
                    /// so we subtract 1 from the z-index as a decimal
                    /// to get the appropriate location:
                    ///     Background      -> 0.7
                    ///     Middleground    -> 0.6
                    ///     Foreground      -> 0.5
                    spriteBatch.Draw(
                        tileSheet,
                        CellScreenRectangle(x, y),
                        TileSourceRectangle(mapCells[x,y].
                            GetLayerIndex((TileLayers)z)),
                        Color.White,
                        0.0f,
                        Vector2.Zero,
                        effect,
                        0.7f - ((float)z * 0.1f)
                    );
                }
            }
        } /// End y loop
    } /// End x loop
}

```

As you can see, it's not very complex code. I have checked if my Update calls are slowing the game down, but it's very clearly in the Draw function. When I leave out my call to world.Draw(), fps shoot up to about 50 on the Galaxy S. Also, if I draw only a single layer, I get better performance around 42-45 fps.

I can discard one layer if necessary, but I need at least 2 tile layers. **How else can I speed up the draw calls?**

I am using MonoGame for Android (XNA)

# Answer
> 1 votes
What I would try to do is get rid of the draw depth calculation by drawing your tiles in the correct order to start with.

What this means is, you'll be drawing your back layer first, then the middle layer, then the top layer. If your tile sprites overlap (e.g. isometric view) you may also need to draw the back row first, then the next and so on and depending on the angle, maybe reverse the loops. I'd have to see a screenshot looks like to get a better idea.

You should also do as many calculations as possible outside the loops. For example, rather than checking if X and Y are inside the bounds of the map in the inner most loop, you can do it before the loops even begin.

Lastly, it concerns me that some of the methods inside the loop may be taking longer than an index lookup. For example, you need X, Y and Z to get the layer index so you can get the tile source rectangle. These seems excessive, but without knowing more about your implementation I can't provide any suggestions.

Here's a partial re-factoring based on the above suggestions.

```
    public void Draw(SpriteBatch spriteBatch, bool upsideDown)
    {
        int startX = GetCellAtPixelX((int)Camera.Position.X);
        int startY = GetCellAtPixelY((int)Camera.Position.Y);

        int endX = GetCellAtPixelX((int)Camera.Position.X + Camera.ViewportWidth);
        int endY = GetCellAtPixelY((int)Camera.Position.Y + Camera.ViewportHeight);

        if (startX < 0) startX = 0;
        if (endX > MapWidth - 1) endX = MapWidth - 1;
        if (startY < 0) startY = 0;
        if (endY > MapHeight - 1) endY = MapHeight - 1;

        for (int z = 0; z < MapLayers; z++)
        {
            for (int y = startY; y <= endY; y++)
            {
                for (int x = startX; x <= endX; x++)
                {
                    var cellScreenRectangle = CellScreenRectangle(x, y);
                    var mapCell = mapCells[x, y];
                    var layerIndex = mapCell.GetLayerIndex((TileLayers) z);
                    var tileSourceRectangle = TileSourceRectangle(layerIndex);

                    spriteBatch.Draw(
                        tileSheet,
                        cellScreenRectangle,
                        tileSourceRectangle,
                        Color.White,
                        0.0f,
                        Vector2.Zero,
                        effect,
                        0);
                } // End y loop
            } // End x loop
        } // End z loop
    }

```

If you can provide a screenshot and some more information about the CellScreenRectangle, GetLayerIndex and TileSourceRectangle methods I'm sure there are more things that can be improved.

---
Tags: android, monogame, optimization
---


title: XNA Masking Mayhem

text:
# Question
Title: XNA Masking Mayhem
I'd like to start by mentioning that I'm just an amateur programmer of the past 2 years with no formal training and know very little about maximizing the potential of graphics hardware. I can write shaders and manipulate a multi-layered drawing environment, but I've basically stuck to minimalist pixel shaders.

I'm working on putting dynamic point light shadows in my 2d sidescroller, and have had it working to a reasonable degree. Just chucking it in without working on serious optimizations outside of basic culling, I can get 50 lights or so onscreen at once and still hover around 100 fps.

The only issue is that I'm on a very high end machine and would like to target the game at as many platforms I can, low and high end. The way I'm doing shadows involves a lot of masking before I can finally draw the light to my light layer.

Basically, my technique to achieveing such shadows is as follows.

See pics in this album

https://i.stack.imgur.com/yONK5.jpg

1. The dark gray represents the background tiles, the light gray represents the foreground tiles, and the yellow represents the shadow-emitting foreground tile.
2. I'll draw the light using a radial gradient and a color of choice
3. I'll then exclude light from the mask by drawing some geometry extending through the tile from my point light. I actually don't mask the light yet at this point, but I'm just illustrating the technique in this image
4. Finally, I'll re-include the foreground layer in my mask, as I only want shadows to collect on the background layer and finally multiply the light with it's mask to the light layer

My question is simple - How can I go about reducing the amount of render target switches I need to do to achieve the following:

a. Draw mask to exclude shadows from the foreground to it's own target once per frame

b. For each light that emits shadows,

-Begin light mask as full white

-Render shadow geometry as transparent with an opaque blendmode to eliminate shadowed areas from the mask

-Render foreground mask back over the light mask to reintroduce light to the foreground

c. Multiply light texture with it's individual mask to the main light layer.

# Answer
> 1 votes
You can create a polygon that captures everywhere the light can reach. Drawing a light (with shadows) then only requires one draw call and no render target switches.

The basic set-up is:

* Draw everything than can be lit
* For each light
* + Compute the polygon of where the light can reach
* + Draw the polygon using additive blending

I've wrote a small article, with a video, about how I implemented it which you can read here

The most important resource I used was this beautiful tutorial with interactive examples.

With this approach I was able to draw hundreds of lights (and smooth hem) at interactive rates.

Another (more sophisticated) example you can look at is this tutorial by one of the XNA MVPs

*Disclosure: first article is on my personal blog*

---
Tags: xna, hlsl, shadows
---


# Question
Title: OpenGL render to texture causing edge artifacts
This is my first post here so any help would be massively appreciated :)

I'm using C++ with SDL and OpenGL 3.3

When rendering directly to screen I get the following result

And when I render to texture I this happens

Anti-aliasing is turned off for both. I'm guessing this has something to do with depth buffer accuracy but I've tried a lot of different methods to improve the result but, no success :( I'm currently using the following code to set up my FBO:

```
GLuint frameBufferID;
glGenFramebuffers(1, &frameBufferID);
glBindFramebuffer(GL_FRAMEBUFFER, frameBufferID);

glGenTextures(1, &coloursTextureID);

glBindTexture(GL_TEXTURE_2D, coloursTextureID);
glTexImage2D(GL_TEXTURE_2D,0,GL_RGB,SCREEN_WIDTH,SCREEN_HEIGHT,0,GL_RGB,GL_UNSIGNED_BYTE,NULL);

glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

//Depth buffer setup

GLuint depthrenderbuffer;
glGenRenderbuffers(1, &depthrenderbuffer);
glBindRenderbuffer(GL_RENDERBUFFER, depthrenderbuffer);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, SCREEN_WIDTH,SCREEN_HEIGHT);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depthrenderbuffer);

glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, coloursTextureID, 0);

GLenum DrawBuffers[1] = {GL_COLOR_ATTACHMENT0};
glDrawBuffers(1, DrawBuffers); //

if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
        return false;

```

Thank you so much for any help :)

# Answer
> 1 votes
I fixed it!!!!! Finally!!!!!

Turns out all that was required was a tiny change in the line:

```
    glTexImage2D(GL_TEXTURE_2D,0,GL_RGB,SCREEN_WIDTH,SCREEN_HEIGHT,0,GL_RGB,GL_UNSIGNED_BYTE,0);

```

to

```
    glTexImage2D(GL_TEXTURE_2D,0,GL_RGB32F,SCREEN_WIDTH,SCREEN_HEIGHT,0,GL_RGB,GL_UNSIGNED_BYTE,0);

```

This tutorial saved the day! Any help understanding why changing GL\_RGB to GL\_RGB32F solved the problem would still be greatly appreciated! Thanks to Heckel for helping reformat my question :)

---
Tags: opengl
---