# Question
Title: Access other scripts variables and classes of different directory
Im trying to learn how to access another scripts variable and classes of different direction, in Unity3D. But for some reason it keeps giving me the error.

NullReferenceException: Object reference not set to an instance of an object

```
public class Script_v2 : MonoBehaviour {

  public Vector3 size;

    public Player_Collission_Detection playerCollisionDetection;

    // Use this for initialization
    void Start () {

        playerCollisionDetection = GetComponent<Player_Collission_Detection> ();

        size = playerCollisionDetection.size;
    }

}

```

Here is the what the directory looks like.

```
Assets
     _Scripts
          _Enemy
               Script_v2.cs
          _Player
               Player_Collision_Detection.cs

```

# Answer
> 1 votes
The null reference exception basically says that there is no script of type Player\_Collision\_Detection attached on the game object. Location of the script file doesn't matter if it's placed somewhere inside the assets folder of Unity.

Just find script from the inspector and drag it on the game object you are trying run this script.

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


# Question
Title: How to detect that user has touched UI canvas in Unity 4.6?
In my 2d game I have a HUD with some buttons on it. To make it I am using new UI system, which was presented in Unity 4.6. When user is touching button, I am running method, which was declared in EventSystem. But the problem is in that I need to make difference between touch in any part of screen and touch directly on UI, because when I am touching to any part of screen my character starts fighting. And when I am touching the UI image, my character starts fighting and only after that the method that was attached to UI image EventSystem starts. So I need to check what I am touching on screen. For desktop platform everything is okay, when I am running this code:

```
if (Input.GetMouseButtonDown(0))
{
    EventSystem eventSystem = EventSystem.current;
    if (eventSystem.IsPointerOverGameObject())
    {
        return;
    }
}

```

And for mobile platforms I am using this code, but it doesn't work. The system doesn't check that user pressed on UI image.

```
public class TouchController : MonoBehaviour {
    Canvas BonusesAndPotionsCanvas;
    GameObject BonusesAndPotions;
    void Start ()
    {
        BonusesAndPotions = GameObject.FindGameObjectWithTag ("bonuses_and_potions");
        BonusesAndPotionsCanvas = BonusesAndPotions.GetComponent<Canvas> ();
    }

    void Update()
    {
        EventSystem eventSystem = EventSystem.current;
        if (eventSystem.currentSelectedGameObject != null)
            return;
        for (var i = 0; i < Input.touchCount; ++i)
        {
            if (Input.GetTouch(i).phase == TouchPhase.Began)
            {
                Vector2 worldPoint = Camera.main.ScreenToWorldPoint( Input.GetTouch(i).position );
                if (IsPointerOverUIObject(BonusesAndPotionsCanvas, worldPoint))
                    return;
            }
        }
    }

    private bool IsPointerOverUIObject(Canvas canvas, Vector2 screenPosition)
    {
        PointerEventData eventDataCurrentPosition = new PointerEventData(EventSystem.current);
        eventDataCurrentPosition.position = screenPosition;

        GraphicRaycaster uiRaycaster = canvas.gameObject.GetComponent<GraphicRaycaster>();
        List<RaycastResult> results = new List<RaycastResult>();
        uiRaycaster.Raycast(eventDataCurrentPosition, results);
        return results.Count > 0;
    }
}

```

Can anyone help me? I will be very glad for any help!

# Answer
> 3 votes
On Mobile you need to need pass Touch.fingerId as parameter into EventSystem.IsPointerOverGameObject(int pointerID), but it is still not perfect, as it fails on TouchPhase.Ended.

See this code:

```
public void Update()
{
    foreach (Touch touch in Input.touches)
    {
        int pointerID = touch.fingerId;
        if (EventSystem.current.IsPointerOverGameObject(pointerID))
        {
            // at least on touch is over a canvas UI
            return;
        }

        if (touch.phase == TouchPhase.Ended)
        {
            // here we don't know if the touch was over an canvas UI
            return;
        }
    }

    // no canvas UI is used
    // ...
}

```

---
Tags: c#, unity, touch, gui
---


# Question
Title: How to make sure that all the UI elements were the same size on all screens in new Unity 4.6 UI system
I have made a HUD for my 2d mobile game with the help of the new UI system, that was introduced in Unity 4.6. But when I am trying to play game in Unity editor, the UI elements have normal size, but when I am playing this game on mobile devices, they have more small size than in editor. Why this is happening? May be I missed something while watching Unity tutorials about new UI system. Can anyone help me please.

# Answer
The Canvas Scaler has a property called Ui Scale Mode, just select the option **Constant Physical Size**
> 1 votes

---
Tags: c#, unity, gui, ui-design
---


title: Smoother object movement in Unity?

text:
# Question
Title: Smoother object movement in Unity?
I'm using this code in my script to move a gameobject:

```
void Update () {

    // Move the object forward along its z axis 1 unit/second.
    transform.position = new Vector2(transform.position.x , transform.position.y - 0.2f);

}

```

On screen the movement is a bit jaggy and not fluent.

Is there a different approach?

Hint: Please do not suggestion to use rigidbody functions since adding rigidbody would disrupt everything I did.

Can I use FxedUpdate?

Mirza

# Answer
> 3 votes
You can use `Update` method and just multiply velocity with `Time.deltaTime`. But when you need more complex movement than "move on const velocity" better use both `Update` and `FixedUpdate`. Method `FixedUpdate` should chooses current velocity for object. For example, if you want to move object to specified position `FixedUpdate` method should calculates velocity depends on current object position and target position. Method `Update` in this case will be used for smoothing movement, it will not change real position of object but recalculates each time. Here example:

```
private Vector3 fixed_position;
private Vector3 velocity;

void FixedUpdate() {
    // apply previous velocity
    fixed_position += velocity * Time.fixedDeltaTime;

    // calculate new velocity
    velocity = new Vector3(0.0f, 0.0f, 1.0f);
}

void Update() {
    // recalculate smoothed position of object
    transform.position = fixed_position + velocity * (Time.time - Time.fixedTime);
}

```

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


# Question
Title: Unity GUIText not visible and not WYSIWYG
I have placed a Guitext in my hierarchy:

At first it was visible, now I can't see it when I run the game.

When it was visible:

When modifying the position on scene, the GUIText appears on one place, but when I run the game it's somewhere else.

Why?

# Answer
That's because you render your GUIText off-screen.

Position (x,y,z) of GUIText Object is relative to screen ration. It must be within 0..1 range. 0,0,0 means bottom left of the screen. 1,1,0 is top right.

Also, you have coordinates 0,0,0 (lower right) and anchor "upper left". This renders your GUIText just below the screen. What probably want to archive is: Position 0,0,0 and anchor "lower left"

But you shouldn't use the legacy GUI anymore. With Unity 4.6 the new uGUI System is available, more powerful and more performant.

The old GUI system is just slow, each GUI element causes a draw call and this kills performance on every mobile device. And it's very hard to work with, if the UI gets more complex than 2 buttons
> 0 votes

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


title: Mysql database reading and writing

text:
# Question
Title: Mysql database reading and writing
In my Libgdx application I would like to be able to connect to a mysql server securely and read and write data from it without other users injecting, or changing information. I've found this: http://www.helloandroid.com/tutorials/connecting-mysql-database but its only for reading what about writing data without people messing with it with other apps? I need a form of unique verification.

# Answer
> 2 votes
Don't follow the guidance of Ion Farima. This is plain wrong and not secure.

The correct way of handling this is via a webservice (REST, SOAP, protobuff, whatever suits your needs). Your app/game connects with the webservice, sending the required data (+ using salted MD5/SHA1 hash of the data with other stuff required to identify the user (i.e. unique user id you create when the app is first started)) to the webservice.

The Webservice validates the data and does the read/write operations. This way, your Database credentials are never inside your app, only in your webservice and via webservice you can controll which data is read or written, i.e. limiting a certain request to only be able certain data (of the user calling it for example).

If you use credentials in your app, this makes it vulnerable that someone will phish that credentials out and directly connect to your database, having full access of your apps user (i.e. reading/modifiing/deleting all tables that mysql user has access too).

**edit:** The only situation when an App should connect to an Database Server directly and send credentials is, when your App is an Database Client App (like HeidiSQL) and where the user enters his own credentials to manage his own Database server

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


# Question
Title: Should I use DirectX 11 for 2d games or should I stick to DirectX 9?
After two years now I wanted to continue working on my sandbox project which I actually used to learn and experiment with various C++ features and DirectX. So far I have simple elements for 2d adventures with a very basic engine, external map loading, scripts and this kind of stuff. So far the project was ported once from SDL to DirectX 9 and now I am considering to move on to DirectX 11 and the question would be: **should I consider doing the step from DX9 to DX11 even though I am no going to make any 3d content at all?**

Although often asked in various threads like this or this one which tech to use I couldn't find a suitable answer as people are referring to 3d rather than 2d.

# Answer
There's two central drawbacks to moving past Direct3D 9.0c.

1. You have a slightly higher minimum requirement when using FEATURE\_LEVEL\_9\_1 in a Direct3D version that has lower feature levels. Some of the lowest end cards that can work in Direct3D9 are not quite able to satisfy the low requirements of level 9\_1.
2. The minimum required operating system for 10 and up is Vista, and for 11 you need Vista SP2 (with platform pack). If the XP market is important to you, this may be a showstopper.

You also have more and more trouble using the DXSDK with Visual Studio versions 2012 and 2013, as those use the new Windows Kits which have conflicting headers present and require much care in picking up the right definitions and libraries.

The benefits are many, among others continued support of the SDKs involved. When the DirectX SDK was folded into the Windows Kits, you lost both D3DX and Direct3D 9. As the SDK was discontinued, there's no fixes for the bugs existing back in June 2010, and which still exist to this day. As modern DirectX is part of the platform, it's much more serviced and integrated into the IDE, and deployment is somewhat easier.

There's a bit more overhead in the amount of work you will need to do to get something equivalent running in D3D11 compared to fixed function pipeline D3D9, but it's not necessarily consuming more resources as alluded by others here.

I would go so far to suggest that a more modern DirectX version is better for doing 2D graphics, as you're less tied to the 3D-oriented semantics that Direct3D 9 used to have, and can make your shaders and data bindings in a much more true-to-the-data way.

If you're starting from scratch, I would not recommend ever starting with an essentially dying legacy technology. Go for D3D11 or modern OpenGL.
> 0 votes

# Answer
well, as for 2d games, dx 9 will work fine as because dx11 is for high tech 3d features such as picture smoothness and tesselation.

so if you are developing 2d games then its not a good option to make your game a resource hunter because dx11 consumes more memory :)
> -3 votes

---
Tags: 2d, directx, graphics
---


# Question
Title: Changing one prefab changes all other instances of that prefab too
I have made two prefabs of my enemies for my 2D game: normal and damaged. The I put several of these prefabs on scene. When enemies health \<=0 I need to destroy its GameObject and then instantiate a damaged prefab on its position. But when I am doing this, all other prefabs are destroying too and damaged prefabs are instantiated on their positions. After searching this site I found out that any changes with one prefab are applying to all other prefabs on scene? Is this right?

P.S. I have edited the script where I am destroying prefab and added to it a simple check, if the prefabs renderer is visible on scene, then I need to destroy it, because all other prefabs are not visible at this moment. Do I need to check to make sure that this is the instance of the prefab is that I need every time when I want to apply to it some change?

# Answer
Once a prefab has been instantiated, anything you do to that prefab should be independent of other instances of that prefab. It's more likely you have a code error that is accidentally changing all your instances. For example: How can I edit the components of an instantiated prefab? addresses editing the components of one prefab without changing any others.

You need to ensure you're referencing the specific object you're trying to change. Don't reference the prefab source, just the gameObject you want to change. If you change something that's common to all the instances, like a mesh or texture, it will affect all the instances, similar to this problem: How to make prefabs independent?
> 2 votes

---
Tags: c#, unity, 2d
---


# Question
Title: Entity Component System: Store pointer in Component to Entity
I was wondering if it is a bad idea to store a pointer in every Component to the Entity which owns the Component.

E.g. I have a Component "NPC". Each entity which owns this Component also must have a Position and Sprite Component. Sometimes i get a list of NPC Components from one of my Systems, but I also need the coresponding Position and Sprite Components. I can retrieve the entity, but it's quite some code I have to type and it is more expensive than just following the pointer.

So would it be a bad idea to store a pointer to the Entity in a Component?

# Answer
> 1 votes
One obvious solution is to store the entityId inside each component structure or class. This way when you need to obtain components or do some entity-specific logic, you already have an easy way to obtain the entityId based on a given component.

Another solution that may be a tad more complex but has some useful side affects is to assign each component a unique id that using bit-wise arithmetic you could obtain the entityId, the component type or some dense array index, and a unique version number for the component's id. This is often hinted at in situations where component pools are managed using a single sparse array based on entityId and an internal dense array that keeps components in cache friendly uniform blocks of contiguous memory.

There is nothing bad with associating an entityId with a component because how else would you plan to implement component-to-component or system-to-system communication that involves one behavior to influence another for a specific entity. :).

# Answer
> 0 votes
it will be better if your systems will return a list of entities that contain a certain component other than a list of the components themselves.

also frameworks like Ashley has a 'Family' class which is used to get all entities with a set of components.

---
Tags: java, entity-system
---


# Question
Title: Designing Diverse 2D Environment Tilesets
Is there an established methodology for designing diverse, quality 2d environment tilesets? I understand creating corners and borders and edges for different terrain types and materials, but I'm at a loss when considering how to make a terrain tileset that accomodates all types of concave edges and convex corners.

For example, the following Tilemap from Chrono Trigger:

They are able to basically create any shape they want with the surface tiles, and the rocky cliffs are perfectly matched.

How do you approach designing such a versatile tileset? Is there a specific set of required tiles that you need to design? Is there a basic terrain shape that should be designed that encompasses all these corners and types of tiles, that is later converted to a proper tileset?

Is it just a lot of artist work, or are there shortcuts?

# Answer
Here is a basic pattern that you can use.

To make the tile set look good, a basic rule needs to be followed. That is each tile must tile seamlessly with all the tiles it can connect to.

Some examples: tiles E, and J must tile with themselves in all directions. Also, the top of tile E must be seamless to the bottom of tiles B, M, and N, while the top of J must be seamless to the bottom of G, H, and I.

Tile A's top edge should be seamless to the bottom of J, G H, and I. Tile A's Right edge should be seamless to the left edge of B and C. Tile A's bottom edge should be seamless to the top of D, and G. And finally, tile A's left edge should be seamless to C, F, I, and J.

Tile B's left edge should tile with the right edge of A, B, and M. Tile B's right edge should be seamless to the left edge of B, C, and N.

Etc, etc, etc. As you can see this is a long tedious list to write out, but at this point I think you can figure the rest out.

Creating multiple sets like this you can make some intricate maps. You can have a dirt/grass, and a grass/water tile sets. If you use the same grass tile in both set, you can go from dirt to grass to water seamlessly.

This same approach can be used to construct building exteriors, fences, caverns, and mazes.
> 2 votes

# Answer
It's a technique no doubt about it. you can use templates which are basically just checkered grids for you to paint over. There is allot of artist work involved though.

Here's an example of a tileset not unlike how the chrono trigger tileset is made.

http://www.angelfire.com/rpg/nazrpg/chips/Swamp\_Village\_MacBlue.png

then it's upto the level designer to arrange them in a creative fashion.

that's the best answer i can give considering how drunk i am. (it's Christmas where i am)

Edit: Also don't forget some tiles can be drawn over other tiles so additional layers or additional tilesets for each layer may be needed.

Edit: For those who cant see the link.
> 1 votes

---
Tags: tiles
---


# Question
Title: Creating a glitch effect similar to Watch Dogs
I'm currently working on a LibGDX game. When a user does something wrong, I would like all the graphics on the screen to jitter very similar to the glitch/distort effect seen in the game Watch Dogs (See Below).

My question is this: can this effect be achieved in real time by writing a shader? If so are there any references online on how to do this? (I've had a quick Google but all I could find is how to achieve this effect in Photoshop/After Effects).

Thank you for your help.

Screen jitter: https://www.youtube.com/watch?v=EYkqC9uI8Nc

Text glitch effect: https://www.youtube.com/watch?v=Wj26Wp2AH-U

# Answer
Creating the glitchy look can be accomplished in a broad spectrum of ways. In essence, what we have been culturally accustomed to accept as a glitch is everything that is a sudden distortion of what would otherwise be coherent content. Some glitches fit well with analogue transmission (i.e white noise) and others fit well with digital displays, random ascii symbols, flickering text, artifacts (like the negative rectangles). Throwing the three layers of color out of focus (is called bleeding and) is more reminiscent of CRT displays. You can also add some high amplitude vertical waves temporarily.

To make random ascii characters appear:

1. You can copy the original text string and rapidly randomly modify some of the characters.
2. You can use a spritesheet like this and simply use randomly place sprites of characters, removing them shortly after that to make them flicker on the screen in an unpredictable manner.
3. To do the negative image thing, what you suggested would work. It is essentially a XOR between the text and the noise rectangles (if white is true and black is false).
> 6 votes

---
Tags: opengl, libgdx, shaders, graphic-effects
---


# Question
Title: how can I put an array of objects into a script?
I want to create an animation from an object sequence. I already achieved exactly what I needed with the "MeshAnimaton script" from bummzack:

```
using UnityEngine;
using System.Collections;

/**
 * Animate a mesh by cycling through different meshes.
 * @author bummzack
 */
public class MeshAnimation : MonoBehaviour {

    public Mesh[] Meshes;
    public bool Loop;
    public float FrameDuration;

    private int _index;
    private bool _playing;
    private float _accumulator;
    private MeshFilter _meshFilter;

    public void Start()
    {
        _meshFilter = GetComponent<MeshFilter>();
        _index = 0;
    }

    public void Update()
    {
        if(!_playing){
            return;
        }

        _accumulator += Time.deltaTime;

        if(_accumulator >= FrameDuration){
            _accumulator -= FrameDuration;
            _index = (_index + 1) % Meshes.Length;

            if(_index == 0 && !Loop){
                Stop();
                return;
            }

            _meshFilter.mesh = Meshes[_index];
        }
    }

    // play the animation
    public void Play()
    {
        _playing = true;
    }

    // stop the animation
    public void Stop()
    {
        _playing = false;
    }

    // restore the first frame
    public void Reset()
    {
        _index = 0;
        _accumulator = 0.0f;
        _meshFilter.mesh = Meshes[_index];
    }

    // Mouse down to toggle Stop/Play, just for testing
    public void OnMouseDown()
    {
        if(_playing){
            Stop();
            Reset();
        } else {
            Play();
        }
    }
}

```

That worked fine with an object sequence which consisted of 20 meshes. But now I have to do the same with sequences that consist of big amounts of objects. Is there a way to put an array of certain object names into the script instead of dragging each mesh file separately onto the script component? I would appreciate any kind of help.

# Answer
In the Unity Editor can select multiple files in the project view and drag them on the array in the inspector. Make sure the inspector is locked on the game object, so that it does not lose focus.
> 2 votes

# Answer
You need to use Resources.Load() in order to load objects by name. Basically, put your model in a folder called "Resources" and then they can be loaded using the Resources commands. If the models aren't in a "Resources" folder then the only way Unity would know about those assets is to link directly as an array of meshes (ie. what you're already doing and want to change).
> 1 votes

---
Tags: unity
---


# Question
Title: Odd Android touch event problem (Nexus 10)
**Overview**

When testing my game I came across a bizarre problem with my touch controls.

Note this isn't related to multi-touch as I completely removed my ACTION\_POINTER\_UP and ACTION\_POINTER\_DOWN along with my ACTION\_MOVE code. So I'm simply working with ACTION\_UP and ACTION\_DOWN now and still get the problem.

**The problem**

I have a left and right button on the left of the screen and a jump button on the right. Everything works as it should but if I touch a large area of my hand (the fleshy part at the base of the thumb for instance) onto the screen, then release it and then press one of my arrows, the sprite moves in that direction for a few seconds, and then ACTION\_UP is mysteriously triggered. The sprite stops and then if I release my finger and re-apply it to an arrow, the same thing happens. This goes on and on and eventually (randomly??) stops and everything work OK again.

**Test device & OS**

Google Nexus 10 Tablet running Jellybean 4.2.2

**Code**

```
        //Action upon which to switch
        actionMask = event.getActionMasked();
        //Pointer Index of the currently touching pointer
        pointerIndex = event.getActionIndex();
        //Number of pointers (for multi-touch)
        pointerCount = event.getPointerCount();
        //ID of the pointer currently being processed (Multitouch)
        pointerID = event.getPointerId(pointerIndex);

        switch (actionMask){

        //Primary pointer down
        case MotionEvent.ACTION_DOWN: {

        //if pressing left button then set moving left
        if (isLeftPressed(event.getX(), event.getY())){
                    renderer.setSpriteLeft();
                }

        //if pressing right button then set moving right
        else if (isRightPressed(event.getX(), event.getY())){
                    renderer.setSpriteRight();
                }

        //if pressing jump button then set sprite jumping
        else if (isJumpPressed(event.getX(),event.getY())){
                    renderer.setSpriteState('j', true);
                }

        break;

        }//End of case

        //Primary pointer up
        case MotionEvent.ACTION_UP:{

        //When finger leaves the screen, stop sprite's horizontal movement
            renderer.setSpriteStopped();
            break;
        }

```

# Answer
Looks like this is a confirmed issue with the Nexus 10 (and 7 so it seems):

Issue 41494: Nexus 10 Multitouch Issue

**The following quote taken from the above link** (Seems this person re-produces the issue pretty much as I did).......

> Seeing on both Nexus 10 and Nexus 7.
>
> Easy to reproduce:
>
> 1. Place entire hand on the screen and remove.
> 2. Hold a single finger on the screen after, and the touch point disappears after a second or two.
>
> Kind of a pain, because I'm building a multitouch focused game.

So, just it case anyone else has this problem. There doesn't seem to be anything you can do about it unfortunately, but at least you know it's not your code.
> 0 votes

# Answer
I am not sure if I am understanding this correct, but it seems to me like you answered your own question.

> I touch a large area of my hand onto the screen, then release it

Well you touched the screen and release it there are two calls to MotionEvent one with event.ACTION\_DOWN and one with event.ACTION\_UP

> then press one of my arrows

Again a call to MotionEvent ACTION\_DOWN, and most importantly it moves your sprite the way it is intended. ACTION\_DOWN triggers your:

```
case MotionEvent.ACTION_DOWN: {
    if (isLeftPressed(event.getX(), event.getY())){
                renderer.setSpriteLeft();
            } ...

```

> if I release my finger

and then once you lift your finger that triggers the ACTION\_UP.

```
case MotionEvent.ACTION_UP:{

    //When finger leaves the screen, stop sprite's horizontal movement
        renderer.setSpriteStopped();
        break;
    }

```

> and re-apply it to an arrow, the same thing happens

... rinse and repeat

No mystery. A person cannot both be pushing on the screen and not pushing on the screen.

Why do you think this should not be happening? Could it be an error within your

```
setSpriteLeft(); or setSpriteStopped();

```

http://developer.android.com/reference/android/view/MotionEvent.html
> 1 votes

---
Tags: android, screen, touch, control, multitouch
---


# Question
Title: Out of screen position to inner screen position
I don't know how I could solve this. I'm trying to accomplish this:

So if a object is out of my screen I would like to calculate the position it would be inside of the screen. Searched already but did not found any help for this problem. You can see this in games like cod where it shows you from which direction you got hit by a bullet.

Thanks in advance.

# Answer
> 1 votes
The easiest would be to clamp the x and y to within range. That is, something like

```
apparentX = max(screenXMin, min(thingX, screenXMax));
apparentY = max(screenYMin, min(thingY, screenYMax));

```

This would let you see exactly what height or position it is if directly left, right, up, or down from the screen. Anything off in a diagonal would show up in a corner here.

Alternatively, consider a line segment from screen center to thingPosition. See if it intersects any of the four edges of your screen. (If it doesn't intersect one of them, it's already visible.)

---
Tags: 2d, screen
---


title: libgdx texture edge blending problem

text:
# Question
Title: libgdx texture edge blending problem
I have two completely white bitmaps here:

They're there, trust me.

When I put one on top of the other and scale them down with `TextureFilter.Linear` I get this:

How do I get rid of the dark pixels?

# Answer
> 0 votes
The problem was the texture packer that messed up the bitmaps. How I solved it is I premultiplied the bitmaps with white using Photoshop (Export -\> Render Video).

# Answer
> 1 votes
This is just a guess, but I notice that the edges of your image(s) are anti-aliased. When you scale the images down using Linear filtering, the semi-transparent edges might be set to black, because the filter cannot handle semi-transparent pixels. This is just an idea, but it might be worth a try to remove the semi-transparent pixels which surround the image(s).

---
Tags: textures, libgdx, opengl-es2, alpha-blending
---


title: Unity access Label in GUI?

text:
# Question
Title: Unity access Label in GUI?
There is a quick and dirty appreoch to creating text boxes:

```
void OnGUI(){
    GUILayout.Label("Text 1");
}

```

It works well. But, since the Label method returns `void`, how do I access this later on?

Let's say I want to access the text later to change the score?

```
someField = GUILayout.Label("Text 1");

```

Is not going to work.

# Answer
With a Label, the only way would be to keep your text in a string variable and manually handle all key events by changing the string variable accordingly. Clearly, this is far from ideal.

If you want a quick and dirty textbox, you should use TextField, which does all of the hard work for you.

Of course, this assumes you're sticking with the classic UI system, which your code snippet suggests. If you're using the new UI system, add an Input Field to a Text control.
> 5 votes

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


# Question
Title: Client side latency when using prediction
I've implemented Client-Side prediction into my game, where when input is received by the client, it first sends it to the server and then acts upon it just as the server will, to reduce the appearance of lag. The problem is, the server is authoritative, so when the server sends back the position of the Entity to the client, it undo's the effect of the interpolation and creates a rubber-banding effect.

For example: Client sends input to server -\> Client reacts on input -\> Server receives and reacts on input - \> Server sends back response -\> Client reaction is undone due to latency between server and client

To solve this, I've decided to store the game state and input every tick in the client, and then when I receive a packet from the server, get the game state from when the packet was sent and simulate the game up to the current point.

My questions:

Won't this cause lag? If I'm receiving 20/30 EntityPositionPackets a second, that means I have to run 20-30 simulations of the game state.

How do I sync the client and server tick? Currently, I'm sending the milli-second the packet was sent by the server, but I think it's adding too much complexity instead of just sending the tick. The problem with converting it to sending the tick is that I have no guarantee that the client and server are ticking at the same rate, for example if the client is an old-end PC.

# Answer
First of all, use tick counts instead of time. There's no good way to synchronize the client and server clocks.

You will also have to set a minimum tick rate, if a client fails to match this rate there's not much you can do. Note that this tick rate doesn't have to match the FPS rendered, it could be lower or higher. In order to make sure the client and server tick at the same rate, read this article on Fixing Your Timestep.

Getting corrections from the server will result in rubber banding if your predictions are off, you can make this less obvious by not switching positions instantaneously, but rather correct over time. The amount of states you can store and re-simulate depends on how computationally intensive your simulation is, but you can draw a line and force a re-sync of position/velocity if the client has fallen behind too much.

An alternative solution is to make your simulation deterministic and have the server respect client movement, but still remain authoritative. When the server receives input from the client on a tick that has already passed, it can rewind and simulate forward again(within a certain tick frame, otherwise correct the client). This results in clients being able to move freely without being corrected all the time. The drawback is that you'll see other clients rubber band, but this can be smoothed over time as well.
> 1 votes

---
Tags: java, networking, server, client-server, client
---


# Question
Title: Implicit Functions and extracting an isosurface
I recently discovered a paper on Dual Marching Cubes which produces a much reduced poly count to other methods like Dual Contouring and Marching Cubes, however a recurring theme when reading these papers is that they make reference to **implicit functions**.

I've been wanting to implement a form of this for procedural terrain created using a noise function (like Simplex Noise) but I don't understand how if I were to use a data structure like an Octree, or even a uniform grid, I could then use the algorithm since it wants an Implicit Function.

I think I'm going about this all wrong and not understanding something correctly, can anyone explain how it would be possible, or even if it is at all, to represent procedural terrain with an implicit function?

# Answer
> 2 votes
**Implicit Functions and Surfaces**

An implicit function is simply a function that, from any point in `N`-dimensional space gives you a real number:

```
forall x in R^N, f(x) -> R

```

In your case, what you want is a 3D function that returns some real (i.e floating point) number:

```
f(x, y, z) -> [-infinity, +infinity]

```

The *implicit* part comes in when we reinterpret this function as a series of **isosurfaces** generated by fixing the output of the function to some constant *c*.

```
surface_c = all x, y, z such that f(x, y, z) = c

```

**The Signed Distance Function**

A common implicit function used to represent real surfaces is the Signed Distance Function (SDF). The SDF represents the scene such that at every point in space, it stores the distance to the nearest surface. For points in the scene that lie *outside* of the surface, the SDF is positive. For points *inside* of the surface, the SDF is negative. Exactly on the surface, the SDF is zero. Therefore, the SDF is an implicit function that represents the surface whenever it equals zero.

As an illustrative example, consider the SDF of a sphere with radius *r* and center *c\_x, c\_y, c\_z*. At all points in space, the distance to the center of the sphere is given by:

```
f_center(x, y, z) = sqrt((x - c_x)^2 + (y - c_y)^2 + (z - c_z)^2);

```

The *signed* distance to the surface of the sphere is therefore:

```
f_sphere(x, y, z) = f_center(x, y, z) - r;

```

We can easily find the isosurface describing the sphere by simply finding all points in 3D space which are equal to zero:

```
sphere_surface = all x, y, z such that f_sphere(x, y, z) = 0

```

This surface can be extracted using marching cubes.

**Perlin Noise as a Signed Distance Function**

Perlin/Simplex noise is a function that has the same signature as the signed distance function. At every point in space, it returns a real number. The number is technically random, but the Perlin/Simplex noise function is also locally smooth. These are very nice properties for an implicit surface function!

So all we have to do is *reinterpret* the Perlin noise as a signed distance function! Then, the surfaces of the scene will be:

```
surface_perlin = all x, y, z such that Perlin(x, y, z) = 0

```

Of course, you will want to adjust the parameters of the perlin noise to give you realistic terrains. For one thing, you can ignore the *z* value, and instead create a *height map* from the perlin noise. In that case, the SDF isosurface can still be formed as:

```
surface_heightmap = all x, y, z such that (z - Perlin(x, y, 0) = 0)

```

You can read about more of this at GPU gems, where an implementation is shown.

**What Data Structure to Use?**

I strongly recommend you avoid octrees for representing implicit surfaces. They're great for memory usage, but abysmal at iterating and querying. Since you're using Marching Cubes to extract an isosurface, your time usage will be dominated by iteration. For that reason, I would recommend a fixed 3D array. If you want something that can extend over very large distances without running out of memory, I would recommend using spatially hashed 3D chunks of volumetric data like Minecraft.

# Answer
> 0 votes
You are able to use the dual marching cubes algorithm because it just operates on an array you provided.

So your code generates an area in the form of an array and the marching cubes algorithm then scans over the scene starting at some origin point you assign and finds where all the edges of your volumetric data array would be located and places bits of edging/skin.

You could use the Octree algorithm to break down the volumetric objects your putting into your world space into mini spaces and run the marching cubes algorithm only over the small space that actually contain parts of the volumetric objects to attempt to save on power.

---
Tags: mathematics, procedural-generation, perlin-noise, octree
---


title: Solving the "bullet problem"

text:
# Question
Title: Solving the "bullet problem"
I have a 3D matrix filled with "empty space" where I put some objects (objects are represented as bunch of occupied space).

The bullet is fired from coordinates (x1,y1,z1) at angles (verticalAngle,horizontalAngle).

How do I find the first coordinates in the bullet's trajectory line which is not market as "empty space"?

I suppose I'd have to loop through all the coordinates in that line till I find the not empty one (or the end of the matrix). But how do I calculate what are those coordinates that I have to go through?

---

When firing a bullet in 2D space I suppose this would be calculated as
`y = cos(angle) * x + startPosition` where I'd increment x (in a for loop) to get y and check (x,y) cell for objects or "empty". Actually I'd have to increment y in the for loop to get x instead in case the trajectory line is closer to y-axis than x-axis.

But can someone help me with doing this in 3D space?

EDIT: Well I found this formula: `(x,y,z)=(x0,y0,z0)+t(a,b,c)` where (x0,y0,z0) are starting points and (a,b,c) direction factors, so I think I could increment t in a loop to get the coordinates.

# Answer
You are looking for a grid traversal algorithm I think. I implemented mine based on this paper: http://www.cse.chalmers.se/edu/year/2011/course/TDA361/grid.pdf.

The key points are below:

"""

The traversal algorithm consists of two phases: initialization and incremental traversal. The initialization phase begins by identifying the voxel in which the ray origin, → u, is found. If the ray origin is outside the grid, we find the point in which the ray enters the grid and take the adjacent voxel. The integer variables X and Y are initialized to the starting voxel coordinates. In addition, the variables stepX and stepY are initialized to either 1 or -1 indicating whether X and Y are incremented or decremented as the ray crosses voxel boundaries (this is determined by the sign of the x and y components of →v).

Next, we determine the value of t at which the ray crosses the first vertical voxel boundary and store it in variable tMaxX. We perform a similar computation in y and store the result in tMaxY. The minimum of these two values will indicate how much we can travel along the ray and still remain in the current voxel. Finally, we compute tDeltaX and tDeltaY. TDeltaX indicates how far along the ray we must move (in units of t) for the horizontal component of such a movement to equal the width of a voxel. Similarly,we store in tDeltaY the amount of movement along the ray which has a vertical component equal to the height of a voxel. The incremental phase of the traversal algorithm is very simple. The basic loop is outlined below:

```
loop {
    if(tMaxX < tMaxY) {
        tMaxX= tMaxX + tDeltaX;
        X= X + stepX;
    } else {
        tMaxY= tMaxY + tDeltaY;
        Y= Y + stepY;
    }
    NextVoxel(X,Y);
}

```

"""

See the paper for extension to 3D.
> 1 votes

# Answer
You can check if a ray or in your case a bullet that travels in a very high speed hits a spherical target by performing this computation:

The sphere's radius is `r` and it's center is in `c = (x0,y0,z0)`. The ray's origin is `o = (x1,y1,z1)` and direction `d = (x2,y2,z2)`.

if:

```
(d * (o - c)^2) - ||o - c||^2 +r^2) >= 0

```

Then the bullet that originates from `o` with direction `d` will hit the sphere at `c` of size `r`

You may hit multiple targets and then may simply need to check which target is closest to the origin afterwards. That depends on the complexity of your game, if there is not instance where targets overlap, that will suffice.

You can use this to prune the targets.

After that you would need to check for ray to polygon intersection. You can define an axis aligned box around your target, then find the box inside it with which the ray intersects. You will probably need to check for ray / polygon intersection after that. There are many example available online.
> 1 votes

# Answer
You can contain your 3d world into a spatial hierarchy system like an octree. Then use ray casting to navigate the levels of the octree and end up only needing a handful of collision checks to narrow down the collision to the exact triangle of the object (regular or irregular shape) that gets hit by the ray first.
> 1 votes

---
Tags: 3d, projectile-physics
---


# Question
Title: NLua - How to implement Roblox like function security?
Roblox uses Normal Identities, basicly they assign a lua block/object to a certain number. They use 2 for Scripts and LocalScripts, which can only use non-secured functions, while the command bar can access everything that is LocalUserSecurity and RobloxPlaceSecurity. How can I implement this type of Lua Security into NLua?

# Answer
The best way to create a safe environment to Lua, is creating a sandbox using lua. You just need to "hide" the unsafe functions the let only the "safe" functions visible.

For exemple:

os.exit = function () {} -- after this os.exit() will be harmless.

There is more info here http://lua-users.org/wiki/SandBoxes
> 2 votes

---
Tags: lua, security, roblox
---


# Question
Title: Framerate on AIR for Android - Actionscript 3
I am currently working on making Android apps using AIR for Android.

This is a sample file and package that I am running to test the FPS and Memory usage of my application while it is not even doing anything,

it appears to hit flat at 6,975,488 FPS: 0

Which from what I can work out is 7 megabytes and a frame rate of 1/0 frames per second...

I was wondering if anyone could help me improve the way I write as3 in order to improve this and get my framerate back up to scratch.

Also I was wondering if people thought it was generally better to mix timeline and package coding or stick to just package/class coding.

Been working on this and my other file for a few days now, I am hoping to get some sleep and solve it in the morning as I know this file is a mess and that there is way too much going on in one file, but I thought after having cut everything out except the base key functions as well as leaving the memory/fps tracer there would bring the fps back up to 60 but it does not appear to have done so.

I have also noticed a blank AIR template running the mem/fps test seems to hit 60fps no problem, I guess I will just have to trace out that data 24/7 while developing so as to keep on top of it.

I apologise because I know my coding is terrible and probably very messy/poorly written.

Thank you for any help in advance.

```
package com.qr.maze{
import flash.desktop.NativeApplication
import flash.desktop.SystemIdleMode;
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.utils.getTimer;
import flash.system.System;
[SWF(width="480",height="800",frameRate="60",backgroundColor="#000000")]
public class menu extends MovieClip{

    public function menu(){
        NativeApplication.nativeApplication.systemIdleMode=SystemIdleMode.KEEP_AWAKE;
        NativeApplication.nativeApplication.addEventListener(KeyboardEvent.KEY_DOWN,keyOn);
        NativeApplication.nativeApplication.addEventListener(Event.ACTIVATE,onActivate);
        NativeApplication.nativeApplication.addEventListener(Event.DEACTIVATE,onDeactivate);
        NativeApplication.nativeApplication.addEventListener(Event.EXITING,onDeactivate);
        this.addEventListener(Event.ENTER_FRAME,performMemTest);
        this.addEventListener(Event.ENTER_FRAME,performFrameTest);
    }protected function keyOn(e:KeyboardEvent):void{
        if(e.keyCode==Keyboard.BACK){e.preventDefault();}
        else if(e.keyCode==Keyboard.HOME){onDeactivate(null);}
        else if(e.keyCode==Keyboard.MENU){e.preventDefault();}
    }protected function onActivate(e:Event):void{}
    protected function onDeactivate(e:Event):void{NativeApplication.nativeApplication.exit();}
    public function performMemTest(e:Event):void{trace(System.totalMemory);}
    public function performFrameTest(e:Event):void{
        var prevTimer:Number=0;
        var curTimer:Number=0;
        var frames:int;
        frames+=1;
        curTimer=getTimer();
        if(curTimer-prevTimer>=1000){
            trace("FPS: "); trace(Math.round(frames*1000/(curTimer-prevTimer)));
                prevTimer=curTimer;
                frames=0;
        }
    }
}
}

```

# Answer
It appears I was just being tired and overworking on the file after having got some sleep and re made the file in timeline I am maintaining a steady memory usage and steady framerate, but the framerate appears to differ heavily on the Android Device.

I will continue working on this.
> 2 votes

---
Tags: android, flash, actionscript-3
---


# Question
Title: How to calculate reflection vector from point sprite sphere?
So far I achieved building a cube map following this tutorial. Then I drew three points using glDrawArrays(GL\_POINTS,0,3) and calculate the normals based on a sphere.

To compute the incoming light direction and hence the reflection vector I need the surface position. My questions are

1. Do I need view-space or world-space coordinates for each fragment?
2. How to compute the surface position for each fragment?
3. What's the difference between computing lighting in view-space vs. world-space?

Forgot to mention that this is the way I compute the Normal for the spheres

```
vec3 N;
N.xy = gl_PointCoord * 2.0f - 1.0f;
float mag = dot(N.xy,N.xy);
if(mag > 1.0f) discard;
N.z = sqrt(1.0f - mag);
N = normalize(N);

```

# Answer
> 1 votes
The surface position is the normal itself multiplied by the size of the sphere (point sprite) plus the sphere origin.

Keep in mind a point sprite is a slice of the sphere at its center and not the surface of it so there will be some slight error due to the perspective projection not being accounted for but that's par for the course when we cheat using point sprites. (It works perfectly for parallel (ortho) projections)

If you look at it closely you'll see issues with the reflection/lighting but it falls into the \[close enough\] category and wont really be visible on tiny "spheres".

You can fix this but it roughly doubles the shader cost.

Note that this example is quite extreme with the player's nose about 10 cm (3 inches) from the sphere, the further you are the more "parallel" the view gets and the smaller the error is. If this is important then you should probably switch to a regular sphere mesh as the camera gets closer or use a shader with correction but only for those close to the camera.

The situation is complicated further with point-sprites that are off-center:

That said, points sprites are really cool for bullet hell shooters and retro feel, as well as far-away approximations of spheres (planets, stars, boulders, bushes, pack of leaves, etc). Just don't spend too much effort trying to get them to look like perfect spheres in close-up situation the GPU will spend more time on this than with a bunch of simple triangles.

If you want Mario64 retro-feel with giant point sprites you don't need to correct them, and if you need good looking spheres then use point-sprites only for spheres smaller than 32 or even 16 pixels of radius and actual 3D meshes with different levels of details for larger and larger spheres as the camera gets closer.

The reason to use point sprites is that when polygons get smaller than 8x8 pixels a lot of GPUs start to waste huge amount of vertex and pixel shading power due to the way they work. With pixel shader units being grouped in NxM pixels (often 8x8 or 8x4) having to process the full NxM pixels for EACH triangles that might only have 1 to 4 actual pixels. A few GPUs have tricks to help fix this but not all and you're processing a huge number of vertex for a few pixels. I'll stop here on this as its almost off-topic but was worth explaining why point sprites / billboards are still useful.

---
Tags: glsl, geometry, cubemap, reflection-rendering
---


# Question
Title: How to to convert UV coordinates to texel coordinates and how to convert texel coordinates to "array coordinates"?
I am currently writing a UV texture mapper.

But i don't know how to convert UV coordinates to texel coordinates.

And i also have no idea how i should convert texel coordinates to "array coordinates".

By "array coordinates", i mean number that represents a part of an array (in this case a bitmap).

Here is my code:

```
 su =  (u0)  * (tx-1) ;
 sv =  (v0)  * (ty-1) ;

 texloc = ((sv >>16)* bytes_per_row) +((su>>16)* bytes_per_pixel);

```

Also i use fixedpoint math to interpolate between the uv coordinates.

tx and ty are the dimensions of the texturemap.

# Answer
WARNING: pointer math ahead.

`texloc` is the "array coordinate" or rather it's the byte offset:

```
uint32_t the_rgba8888_pixel = *((const uint32_t *) (((const uint8_t *)my_texture_data) + texloc));

```

Make sure you wrap u0 and v0 to (0 ... (1-epsilon)) first:

```
unsigned int su =  (u0 & 0xFFFF) * tx;
unsigned int sv =  (v0 & 0xFFFF) * ty;

texloc = ((sv >>16)* bytes_per_row) +((su>>16)* bytes_per_pixel);

uint8_t  pixel_8  = *((const uint8_t  *) (((const uint8_t *)my_texture_data) + texloc)); // 8bits
uint16_t pixel_16 = *((const uint16_t *) (((const uint8_t *)my_texture_data) + texloc)); // 16bits
uint32_t pixel_32 = *((const uint32_t *) (((const uint8_t *)my_texture_data) + texloc)); // 32bits

```

You can make this faster by pre-multiplying the UV coordinates by the texture size pre-interpolation, changing the mask to `((size-1) << 16)`, the shift amount and removing the multiplication of `bytes_per_pixels` and `bytes_per_row`.

For example 256x512 pixels, 32bpp:

```
((u0 & 0xFF0000u) >> 14) + ((v0 & 0x1FF0000u) >> 6).

```

That's

```
14 = (16 - bytes_per_pixel_as_shift_amount(4 = 1 << 2) )

```

and

```
6 = (16 - bytes_per_row_as_shift_amount(1024 = (256 x 4 bytes) = 1 << 10) )

```

This way you don't need to mask u0 and v0 first.
> 1 votes

---
Tags: c++, graphics, software-engineering, uv-mapping
---


# Question
Title: How do I make this block go back to the left with another click?
This is the script I've written so far which makes the block move from the left of the screen to the right on a mouse click. What I want to achieve is for the block to move back to the left when I click the mouse again. So I can have a back and forth movement with each mouse click. Thank you for any help it's much appreciated.

```
public class PlayerControls1 : MonoBehaviour  {

private bool hasBeenTapped = false;
private bool control = false;
public float speed = 20f;

void Update () {
    if (Input.GetMouseButtonDown (0)) {
        hasBeenTapped = true;
            }

    if (hasBeenTapped && transform.position.x < 4 && control == false){
        transform.Translate (Vector2.right * speed * Time.deltaTime);
    }

    if(transform.position.x > 4.0f) {

        control = true;

        hasBeenTapped = false;
    }

    if(hasBeenTapped && transform.position.x == 4 || transform.position.x < 4 && control == true) {
        transform.Translate (-Vector2.right * speed * Time.deltaTime);

    if(transform.position.x < -4){

            control = false;

            hasBeenTapped = false;
        }
    }
  }
}

```

# Answer
Here is a generic answer

```
public class PlayerControls1 : MonoBehaviour  {

private bool hasBeenTapped = false;
private bool shouldMoveLeft = false;
private bool control = false;
public float speed = 20f;

void Update () {
    if (Input.GetMouseButtonDown (0)) {
        hasBeenTapped = true;
            }

    if (hasBeenTapped && !shouldMoveLeft && transform.position.x < 4 && control == false){
        transform.Translate (Vector2.right * speed * Time.deltaTime);
    }

    if (hasBeenTapped && shouldMoveLeft && transform.position.x > 0 && control == false){
        transform.Translate (Vector2.left * speed * Time.deltaTime);
    }

    if(transform.position.x > 4.0f) {
        transform.position.x = 4.0f;
        control = true;
        shouldMoveLeft = true;
        hasBeenTapped = false;
    }

    if(transform.position.x <= 0.0f) {
        transform.position.x = 0.0f;
        control = true;
        shouldMoveLeft = false;
        hasBeenTapped = false;
    }

    if(hasBeenTapped && transform.position.x == 4 || transform.position.x < 4 && control == true) {
        transform.Translate (-Vector2.right * speed * Time.deltaTime);

    if(transform.position.x < -4){

            control = false;

            hasBeenTapped = false;
        }
    }
  }
}

```

You would be wise to keep a state of this object. Then decide on the behavior based on the state and the input from the user.
> 1 votes

---
Tags: c#, unity, 2d
---


# Question
Title: differences betwen game resolution in a different display resolution
my game is not supported on the other devices with a different resolutions. for example may character is 140w X 55h pixels which is ok on a 4 inch display but it goes wide when i tested my game on a device with 4.7 inch display. how can i make a correct character for 4.7 or more inch displays? i am using cocos2d-x engine. i want to see if it has a automatic synchronize tool or no. i my self must do it manually ?

# Answer
> 1 votes
What you see right now is cause by aspect ratio change (for example from 3/2 to 16/9) which causes everything to look wide. There are multiple ways that you might fix this issue:

The easiest one is to tell engine what is your design resolution, and how should engine respond to resolution changes. Should it scale everything to completely fit the screen? or place a black border in the sides, while maintaining aspect ratio? or some few other options.

Another option is to provide more than one set of resources for different devices and when the game is loading, choose one according to your device resolution.

For more information read about multiple resolution support in this link:

http://www.cocos2d-x.org/wiki/Multi\_resolution\_support

---
Tags: c++, cocos2d
---


# Question
Title: Dealing with back to front drawing with alpha blending and z buffer for a list of 2d quads
I'm using depth buffer as a layering system for my 2d render and I have to draw them from back to front to make semi-transparent quads work out. The problem is I have to sort my quads vector based on their depths whenever I add or remove one and that is time consuming. I've done this before, but I'm not sure what's the down side because in my mind I think if I sort a vector of let's say 5000 quads, then it'll really keep CPU busy if I remove one of them and sort the other 4999 items in a single frame.

I need to know if there is an alternate way for this or this is just it.

# Answer
A smart bubble/insertion sort is faster than quick sort when the array is already mostly sorted (reused on the next frame).

To speed up the copy of data rather than copying entire vertex values use an index buffer to sort the vertices.

When you remove quads you can quickly degenerate them (set all vertices to the same value) instead of removing them and copying over the following quads.

You can then gradually compact them over multiple frames or compact them only as needed. Inserting into a "swiss-cheese" vertex array with such holes lets you move data only up to the first hole and stop there rather than move the whole array.

Krom Stern's answer of using linked vectors (a list of shorter arrays) is excellent as you can fine tune the technique to a sweet spot between \[number of draw calls\] and \[sort time of individual buffers\], always put an extra bit of free space in each buffers.

And for the more adventurous:

If insertion speed is critical you can use the top-1 N bits of a positive float as an integer, skipping the sign bit, into an array of linked lists.

IEEE floating points of the same sign can be compared and sorted as integers, its part of the standard's design. They are one's-complements rather than two's-complements but this doesn't matter if we're only using positive z. If we need both positive and negative z then the negative z needs a set of reverse-sort functions due to being one's-complements.

```
#define NBITS 10    // 1024 entries
SortList *lists[1 << NBITS] = {0};
...
float z = object->z;
if(z <= 0){ // IMPORTANT this includes negative zero which is distinct from positive zero
 z = 0; // negative float number are in reverse when interpreted as integers, this would need a set of reverse functions
}
uint32_t raw_z_bits = ((uint32_t &)z);
uint32_t list_number = (raw_z_bits >> (31 - NBITS)); // 31 because we skip the sign bit
uint32_t index_within_list = raw_z_bits & ((1 << (31 - NBITS))-1);
AddToList(lists[list_number], index_within_list, object );

```

This is useful when you don't know the range you'll need to sort and/or are already using floating point depth values.

If you're using integer depth values using this float hack will limit you to 23 bits of depth values (0 to +8M) as 32bit floats only have 23 bits (+ 1bit sign) of precision (8bits used for the exponent).

All this gets complicated quickly so a good idea for debugging is to have an independant sanity-check using a per-frame sort-all-active-objects-and-verify function that will confirm everything is sorted properly and there are no bugs in the faster, gradual sorting system.
> 3 votes

# Answer
You could use a different approach for your list.

Linked list. where each item hold a pointer to the next item in list. Insertion and removal cost is O(1). This is not cache friendly though, but you can try.

Better sorting methods, e.g. if you use a bubble-sort, you can pick a much better algo that suits your case better (single insertions/removals don't require to resort whole list).

You can combine and store your objects in linked vectors, where each vector is e.g. 32 items and those are linked into a list. When vector grows too big - split it. When too small - merge it to neighbour.

You can also look into spatial partitioning (Quad-trees).
> 0 votes

---
Tags: 2d, directx9, depth-buffer
---


# Question
Title: Game Programming Gems series still of value?
Former Nintendo dev Mark DeLoura wrote a series of books called "Game Programming Gems".

(http://www.satori.org/game-programming-gems/)

Do these books still contain valuable concepts, considering where games are today, the engines that are available, etc?

# Answer
> 2 votes
Yes, the concepts are valid, especially when it comes to creating an Entity Component System (which is often vaguely discussed). The last couple books are the most valuable.

---
Tags: c++
---


title: Unity 2D collision detector not working

text:
# Question
Title: Unity 2D collision detector not working
I'm making a 2D sidescrolling game in Unity where the player shoots at obstacles while running. But nothing I try seems to get the collision detection to work. This is the obstacle script:

```
void onCollisionEnter2D(Collision2D col)
{
    if (col.gameObject.tag == "circle")
                    Destroy (gameObject);
    }

```

the circle tag refers to the projectile being shot at the obstacle

# Answer
It should be void OnCollisionEnter2D(){} And if that's not the case (if you just mistyped that here) Make sure you have a rigid-body attached to one of your game objects and make sure both colliding objects have 2d colliders.

Cheers, Demetry Romanowski
> 1 votes

---
Tags: c#, unity, 2d
---


# Question
Title: Might this alternate circle-circle collision test help performance?
*Preface: I’m no gaming pro…I code business apps, but I’m experimenting with game coding this Christmas.* :-)

I want to detect collisions between 200+ circles of different sizes which are moving at different speeds.

I know I can determine if any 2 circles are actually colliding like this:

```
// are circle0 & circle1 colliding?
var dx= circle1.x-circle0.x;
var dy= circle1.y-circle0.y;
var rr= circle0.radius+circle1.radius;
var isColliding = (dx*dx + dy*dy) < rr*rr;

```

In reading about collision testing here on GameDev I understand that performance can be improved by reducing the count of circle-pairs that need to be tested during an animation cycle.

So I’m thinking I can skip the above collision test for any circle-pair that is too far apart to possibly be colliding.

To calculate how many times I can safely skip the collision test I can calculate the separation distance between a circle-pair and divide that distance by the combined speeds of the circles.

```
// no collision is possible for `var safe` animation cycles
var safe = Math.sqrt(dx*dx+dy*dy)/(circle0.speed+circle1.speed);

```

**Question#1:** In general, is it worthwhile to do the “expensive” `Math.sqrt` once to gain skipping multiple “cheap” arithmetic `isColliding` tests?

**Question#2:** What collision testing pattern would you gaming pro’s use to detect collisions between different sized circles moving at different speeds?

BTW, I ask the first question out of inexperience, so I understand the answer may well be: You just have to compare both methods yourself and see which works best for you. 

# Answer
Math.sqrt() is indeed very expensive but you can always use fast sqrt instead. I generally would avoid this altogether.

Spatial indexing works for circles of all sizes. Start with a simple grid which has been proven to be the most efficient anyhow in many tests. Use a 2d array of circle lists to conceptually divide the space to 2d-grid of squares.

The grid should be spacious enough so that each circle can be in four squares at the same time at most.

Each frame, you can:

1. Check the grid squares for correctness (circles are actually in their respective squares).
2. Update with changes if necessary (i.e. remove a circle from where it no longer is, add it to where it actually is).
3. Check for collisions only with circles that occupy the same grid squares.
4. Check first if collision is possible across both x & y, i.e. check that distance in x & y is less than `r1 + r2` on both axes (addition is simpler than multiplication).
5. Do the actual check.

Remember to avoid checking the same pair twice. There are several ways to do that, you don't have to, this will still speed up things considerably.

Here is the pseudo code for the technique I use:

```
class Grid {
    const int SQUARE_SIZE = 100;
    array<array<int>> grid; //An array that represents a 2d grid with circles ids
                            //The squares are ordered by rows and then by columns
    /* lets say the grid is 8 x 8 and has 64 squares inside */
    const int SQUARE_COUNT_X = 8;
    const int SQUARE_COUNT_Y = 8;
}

```

The grid class is used to store data about circle positions.

```
class Circle {
    static int counter;

    int cx; //center x position
    int cy; //center y position
    int cr  //radius

    int id; // A static counter assigns a unique serial id to each circle
    int squareIndex // the index of the square the center is in,
                    // a circle can only overlap with four squares
}

```

The circle class stores the basic needed data for the circle as well as it's collision square index to keep things simple. This could have been stored in some collision class as hash from circleId to collision square.

```
// Somewhere in the collision code //
grabSquareIndex(_x, _y)
{
  squareX = _x / SQUARE_SIZE;
  squareY = _y / SQUARE_SIZE;
  index = squareX + squareY * SQUARE_COUNT_X;
}

```

Keeping the grid up to date.

```
foreach (circle in circleList)
{
  tmpSquareIndex = grabSquareIndex(circle.cx, circl.cy);
  if (circle.squareIndex != tmpSquareIndex)
  {
    // remove circle id from old square
    grid[circle.squareIndex].remove(circle.id); // Won't work (implement in real code)
    // add it to new square
    grid[circle.tmpSquareIndex].add(circle.id); // Normally we use push() to do this
    circle.squareIndex = tmpSquareIndex;
  }
}

```

Checking for collisions between circles

```
foreach (circle in circleList)
{
  foreach (circleId in grid[circle.squareIndex])
  {
    if (circleId > circle.id) //cehck for collision
  }
  // check if circle may be overlapping a tile to the top left
  topLeft = grabSquareIndex(circle.cx - circle.cr, circle.cy - circle.cr);
  if (topLeft != circle.squareIndex)
  {
    foreach (circleId in grid[topLeft])
    {
      if (circleId > circle.id) //cehck for collision
    }
  }
  // Do the same for topRight and Bottom
  topRight = grabSquareIndex(circle.cx + circle.cr, circle.cy - circle.cr);
  if (topRight != topLeft && topRight != circle.squareIndex ...)
   //... do the same
  // Same idea for bottom
}

```
> 3 votes

---
Tags: collision-detection
---


# Question
Title: Seeking Advice: Collision with JBox2d for Top-Down or Isometric Maps
I Hope I can make this as clear as possible!

Currently working on an action RPG game, very early stages, more just the basic ideas down and written in. So i'll start on with my setup:

Using Java with LibGDX Map creation is done with TILEd Style of map: Isometric

Collision Engine? ... well this is where I need a bit of guidance and advice.

LibGdx is linked in with Box2d which makes it . I'd personally love to use Box2D, more because I've played around with it on a platform level and I liked how it operated with force and impulses etc, however, it seems to be created for only platform style games. So I guess one questions is: Can Box2d's properties be easily changed to support a Top-Down collision system or an Isometric collision system?

I have tried to implement Box2d into a top down game before by setting the gravity to zero, but with no gravity, the other entities on the map just float. (You bump into them and they just start... floating!)

What I was originally thinking was once I have my map created in TILEd, I would start adding a collision layer (Or modify the tiles individually) to mark what is passable and what is not. I have seen examples for box2d (again Platform only however) ways to create an Object in TILEd to mark the collidable wall or floor and when loaded it would create the shapes. Box2d would be perfect if it wasn't for the whole floating entity due to zero gravity.

So what I am looking for...

**1)** Is there a way to create Box2D work on a Top-Down set up without entities floating?

**2)** If not, what other solutions do I have for collision?

If there is any other information needed for a better response Please let me know!

Thank you!

# Answer
it's quite easy to detect collusion in `Box2d` but you have to know that collusion depend on your Game object or characters which are created with box2d properties ( the BodyDef , FixtureDef..) so all your objects needs to be inside the `box2d` then in your `Main Class` you just have to add `implements ContactListener` if you are using eclipse the compiler will suggest you to override 4 methods `beginContact(Contact contact)` `ndContact(Contact contact)` theses two methods will detect all collusion happens in your physical world so if for exemple you try `System.out.println(contact);` in the `beginContact` overridden method it will display the address of every object when starts to be in contact with another , and if you want to detect the collusion between a specific object and the world you do like so :

```
public void beginContact(Contact contact) {

        String result = (String) contact.getFixtureA().getBody().getFixtureList().getUserData();
        if (result == "Playron")
            hud.tick();

    }

```

-

```
getBody().getFixtureList().getUserData()

```

this code will look for body fixture which start being in contact with other objects in the word and I'm using `getUserData` to figure out which of my game characters is the listener and then if the game character is the Playron `hub.tick` which will decrease the health of the player

here is the `Player Class`

```
public Player(World world)
    {

        BodyDef bodyDef = new BodyDef();
        bodyDef.type = BodyType.DYNAMIC;
        bodyDef.fixedRotation = true;
        bodyDef.position.set(20.0f/RATE, 375.0f/RATE);
        characBody = world.createBody(bodyDef);

        PolygonShape box = new PolygonShape();
        box.setAsBox(10.0f/RATE, 25.0f/RATE);

        FixtureDef fixtureDef = new FixtureDef();
        fixtureDef.shape = box;
        fixtureDef.density = 2.0f;
        fixtureDef.friction = 0.3f;
        characBody.createFixture(fixtureDef);
        characBody.getFixtureList().setUserData("Playron");

    }

```

i hope this clarifies your concern
> 0 votes

---
Tags: collision-detection, libgdx, box2d, jbox2d
---


# Question
Title: How can I estimate the perfomance of graphics cards I don't have?
I'm developing a voxel game with OpenGL and want to optimize the number of rendered faces. How can I estimate how many faces at most a modern graphics card of a certain brand is able to compute, while still managing to render at 60fps?

# Answer
> 3 votes
There's only one sure way - You need to test it yourself.

Estimation result largely depends on your actual code (how efficient is it) and shaders (how complicated are they).

Also, there's number of parameters you need to take into account, each can dramatically change the estimation:

* Antialiasing (ranged from Off to 16x ?)
* Display resolution (0.5k to 4k)
* Anisotropic filtering (ranged from Off to 32x ?)
* other GPU settings (performance vs. quality slider)
* slow CPU can also be a bottleneck

**EDIT:** Generally you need a bunch of testers, who will play your Alpha/Beta and from whom you collect performance data and decide if you need to reduce polycount or not. Also it is generally a good idea to add Options slider to allow players to tradeoff picture quality for speed. Some prefer higher FPS, some prefer picture quality.

---
Tags: performance, gpu, profiling
---


title: 2D Tile Movement in Java

text:
# Question
Title: 2D Tile Movement in Java
I have this tilemap and a player in my game, and I got the player to move by adding the velocity to the position. However, it is very hard to control the player exact this way of the tilemap. So, I began trying to do something like the old final fantasy games did (and a heap of other games too): moving tile by tile, but making it look smooth.

However, I failed. So, if anyone have any idea of what the best way to make the player move tile by tile is, then shout out. If you have played final fantasy V for example, then that's the kind of movement I want to try to implement in my game.

To explain it a bit further; each tile in my game is 16x16, so is the player. I don't want the player to "jump" between the tiles, but I want it so that say, if you press "A", then move the player to the tile to the left in a smooth way.

I tried something like this:

```
    private Vector posA;
private Vector posB;
private double time = 0.6 / 60;
private void move(Direction dir) {
    if (!moving) {
        //Initialize Movement
        posA = new Vector(position);
        posB = new Vector(position);

        switch (dir) {
        case UP:
            posB.subtract(0, 16);
            break;
        case DOWN:
            posB.add(0, 16);
            break;
        case LEFT:
            posB.subtract(16, 0);
            break;
        case RIGHT:
            posB.add(16, 0);
            break;
        }

        moving = true;
    }

    //Update Position
    if (moving) {
        Vector v = new Vector();
        v.set((posA.x + (posB.x - posA.x) * time), (posA.y + (posB.y - posA.y) * time));

        //Set  Position
        position.add(v);

        if (position.x >= posB.x && position.y >= posB.y) {
            position.set(posB);
            moving = false;
            System.out.println("DONE MOVING!!!");
            posB = null;
            posA = null;
        }
    }

}

```

# Answer
The problem is here:

```
if (position.x >= posB.x && position.y >= posB.y) {

```

This will only work if moving in positive X and/or positive Y. When moving the other way posB will be smaller than position and the character will stop right away.

Also, you keep adding the new position to position when you should be adding the delta

`v.set((`posA.x + `(posB.x - posA.x) * time), (`posA.y + `(posB.y - posA.y) * time))`

Try changing it to something like

```
int time;
int steps;

...

if (!moving) {

  ...

  time = 0;
  steps = 16;
}

...

if (moving) {

  ++time;

  position.set((posA.x + (posB.x - posA.x) * ((float)time / (float)steps))), (posA.y + (posB.y - posA.y) * ((float)time / (float)steps)));

  if(time >= steps){
   // stop
   moving = false;
  }
}

```

Using an integer variable for N number of steps is the correct way to interpolate as floats accumulate errors, especially when you want to hit an exact target like the next 2D tile. Otherwise your characters can become more and more misaligned.

I'm incrementing time before calculating the positions so that we hit 16/16 and don't need to force the position to posB at the end.
> 0 votes

---
Tags: java, 2d, movement
---


# Question
Title: Capping framerate independently of logic updates in single-threaded Android Gameloop
My game is currently using the below game loop (this is an OpenGL ES 2.0 game, therefore the loop-work takes place on the rendering thread in the provided onDrawFrame method).

Currently my loop provides (and will need to continue providing) the following:

* The loop allows me to cap logic updates to an arbitary value (which I have set to 60) - so 60 updates per second. This allows my game to run at the same speed (ie, not too fast) on all devices I've tested so far. (I'm not concerned with a device not being able to handle 60 ticks per second as I'm yet to find one that can't and I've tested this on some *very* old devices, they all run perfectly fine).
* If a device can't handle the rendering demands (much more likely), the loop will allow it to drop frames so it can catch up. All the while, allowing the logic/physics tics to carry on running at a smooth 60 ticks per second.

The only remaining problem with the loop is that it renders 'flat out' - so, out of the 20+ devices on which I've tested this, there are 3 main groups:

VSYNC'd at 60 FPS - (for example Google Nexus 10)

VSYNC'd at 30 FPS - (eg, generic Android tablet)

No VSYNC - (Samsung Galaxy Ace Mk1)

So, when running on say, a VSYNC 60FPS device, I generally get 60 logic updates per second and 60FPS.

On a VSYNC 30FPS device, I get 60 Logic updates and 30FPS

On a No VSYNC device, I get 60 Logic updates and 'The Sky is the limit' FPS (on my Ace, it can get up to 90-100 FPS).

What I really want my loop to do, is *limit the rendering*. In my case I want to run my physics at 60 ticks per second and render at 30FPS.

I want to do this because rendering flat out is eating battery and heating up devices unnecessarily. If my rendering is capped at 30FPS I would think it would help a lot in this case no? I need my physics to keep running at 60 ticks, reducing that isn't really an option (I've tried it and it causes a few glitches with collision and sprites that move *very* fast over tiny distances) but I digress....

I've been trying all day to figure out how to do this so that:

On *all* devices (that can handle at least 30FPS or greater) it will always run at 30FPS. (so even if VSYNC'd to 60FPS).

**The loop**

```
@Override
public void onDrawFrame(GL10 gl) {

    //Grab time
    newTime = System.currentTimeMillis()*0.001;
    frameTime = newTime - currentTime; //Amount of time this entire frame took
            if ( frameTime > (dt*25))
                frameTime = (dt*25);
            currentTime = newTime;

            accumulator += frameTime;

            //Update logic while
            while (accumulator >= dt){
                saveGameState();
                updateLogic(dt);
                t += dt;
                accumulator -= dt;
            }

            interpolation = (float) (accumulator / dt);

            render(interpolation);

}

```

**Sleep time?**

As the loop renders whenever it's not updating, I'm thinking I need a way to 'sleep' once it's called and finished render(interpolation) until it's ready to go again.

I tried putting this following code in after render(interpolation) (within onDrawFrame - where newTimeMillis is System.currentTimeMillis() grabbed at the start of onDrawFrame) but I'm not really sure how this would work when onDrawFrame is called every 16.66666666666667MS on devices that have VSYNC capped at 60FPS. I've getting really confused over this and would appreciate if someone could give me a clue as to what kind of code I need to inject into my loop to achieve that which I'm trying to achieve.....(something I incorrectly assumed would a simple thing to do!!)

```
            render(interpolation);

            long sleepTime = (System.currentTimeMillis()-(newTimeMillis));
            if (sleepTime<33.33333333333333){
            try {
                Thread.sleep((long) (33.33333333333333-(sleepTime)));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
}

```

# Answer
> 1 votes
Only render when you've done at least 1 logic update.

If you have not done any logic update (too fast) sleep for about 1ms and check again.

I found that on some OSes calculating the sleep time caused the timing to always be off by a good margin. It's not an issue on Android or iOS but I got into the habit of using 1ms sleep for action games and calculating sleep time only for animated applications (audio visualizers, etc) or slow-pace games where high consistent fps isn't critical.

---
Tags: android, rendering, game-loop, frame-rate
---


# Question
Title: Handling creation of entities on level creation
I'm currently working on a 2d physics based plat former, kinda in the style of super meat boy. In super meat boy, you have multiple levels and I want a similar sort of thing but is there a general way of handling creating entities at the start of a level. Since I'm using an entity-component design and using tiled editor to load levels (and even lua script do to some more config/level related logic), how would I handle creating entities?

Currently, I parse my tiled xml map and do something like

```
if("MovingPlatform"){
   createMovingPlatform(mapObject)
}elseif("SomeOtherEntity"){

} //... so on so forth

```

But this will soon become a really long branch of if statements just to load my entities. Is there a cleaner design pattern or way of doing this. I was thinking to use a map or strings to classes that create that entity like so:

```
 //in constructor of level loader
 entityCreatorMap["MovingPlatform"] = MovingPlatformEntityLoader()

//somewhere later creating my entities by parsing xml
entityCreatorMap[mapObject.getName()].create(mapObject)

```

But that will be lots of lines initialising these kind of objects. Any ideas?

# Answer
You can make a singleton which will store relationships between name and loader instance and register loaders to it in loader's constructor. You'll have same operations like in your example, but it would be distributed. Here is an example:

```
MovingPlatformEntityLoader::MovingPlatformEntityLoader()
{
    EntityLoaderRegistry::registerEntity( "MovingPlatform", this );
}

static MovingPlatformEntityLoader loader;

```

When `MovingPlatformEntityLoader`'s constructor will be called loader would be registered in registry and other classes could use it. To call constructor you can create instance of `MovingPlatformEntityLoader` just in this `.cpp` file with static modifier like in the example.

Pluses of this technique:

* You don't need hard-modifiable registration method.
* You can add new loaders even if you have no access to all code of a game (useful for plugins).

Minuses:

* If you have multiple modules and use dynamic linkage (for examples for plugins) you will have problems with linkage's "bad habbit" to forget unused `.cpp` files (you must link this files manually to dll's entry point).
* You can't predict order of creating loaders. That's why singleton should be accessed by a static method like in the example.
> 1 votes

---
Tags: c++, entity-system, design-patterns, lua, tiled
---


# Question
Title: Anchoring HingeJoint2D to clicked upon spot
I'm creating a 2D game where the user can click and drag objects around. This is done by connecting a 'Hand' object to the object the user is current clicking on with a HingeJoint2D. Right now it simply connects the HingeJoint2D to the center of the clicked upon object.

I want to anchor the Hingejoint2D to the exact spot on the rigidbody (not the center) that the user is clicking on. This must involve transforming the clicked upon point to coordinates relative to the clicked upon rigidbody, but I've had no success using methods like transform's TransformPoint.

Any help would be appreciated.

This is the code I have attached to the object that the user will be dragging around:

```
void OnMouseDown() {
     // Create a hinge joint between the hand and this object so object will slowly rotate
     // around the hinge point
     this.gameObject.AddComponent("HingeJoint2D");
     connectingHinge = this.GetComponent<HingeJoint2D>();
     connectingHinge.connectedBody = handRigidbody;

     // Set anchor to offset of current hand position relative to the object.
     //connectingHinge.anchor = new Vector2(offset.x, offset.y);
 }
```

Image of gameplay:

The gray box is the 'hand', which is the mouse cursor. The gun is an object that the user is dragging about while it is connected to the gray box with a HingeJoint2D.

I want to anchor the HingeJoint2D to the exact spot the user is clicking on, and not just the center of the rigidbody.

# Answer
> 1 votes
The anchor in HingeJoint2d is the coordinate in local space where the end point of the joint is attached. In order to transform the coordinates to the gun's local space, you should first subtract the center point of the gun from the world position of the mouse, then inversely rotate it by the gun's rotation, and finally inversely scale this by the gun's scale. This all can be done in one line by calling transform.InverseTransformPoint. ConnectedAnchor works the same way as anchor, but the coordinate has to be given in global space.

```
public class AddHingeOnClick : MonoBehaviour {
    HingeJoint2D hingeJoint2D;

    void Start () {
        hingeJoint2D = gameObject.AddComponent<HingeJoint2D>();
        hingeJoint2D.enabled = false;
    }

    void OnMouseDown() {
        Vector3 mouseWorldPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);

        //Vector3 scale = transform.localScale;
        //Vector3 inverseScale = new Vector3(1 / scale.x, 1 / scale.y, 1 / scale.z);
        //Quaternion inverseRotation = Quaternion.Inverse(transform.rotation);
        //Vector3 offset = mouseWorldPosition - transform.position;
        //Vector3 mouseLocalPosition = Vector3.Scale(inverseScale, inverseRotation * offset);

        Vector3 mouseLocalPosition = transform.InverseTransformPoint(mouseWorldPosition)
        hingeJoint2D.enabled = true;
        hingeJoint2D.connectedAnchor = mouseWorldPosition;
        hingeJoint2D.anchor = mouseLocalPosition;
    }
}

```

I advise against creating the HingeJoint2D in the OnMouseDown() function, there seems to be a bug in Unity 4.6 which prevents it from working.

---
Tags: unity, 2d, physics, mouse
---


title: How to make a Wii game with SDL?

text:
# Question
Title: How to make a Wii game with SDL?
I am trying to find a way to create a Wii game using SDL2, but I can't find any tutorials on how to do it. How can I use SDL2 to build and privately distribute a Wii game without hacking/modding the Wii?

# Answer
You cannot, the Wii does not have a supported environment for developing software, except by licensing with Nintendo and probably renting hardware.

Any private development done is generally on a hacked Wii, there is a SDL port for the Wii if you want to go that route: http://wiibrew.org/wiki/SDL\_Wii but it is an incomplete port.
> 0 votes

---
Tags: sdl2, wii
---


title: render with const depth value

text:
# Question
Title: render with const depth value
This is a question that may have an answer that differs for vanilla desktop GL and GL ES 2.0 (and wishful thinking is that ES 3.0 would have the same answer as vanilla GL).

What I'm doing is rendering a cubemap with a FS quad and I'd like to know if there's a way to specify a constant depth value for an entire render call rather than to get involved at the fragment shader level, in hopes of chasing a little bit of performance as well as flexibility in that I can use the same shader for drawing to different const depth values.

As for why it might benefit performance, the note at the bottom here offers some ideas, such as early-z testing... I suppose realistically if I emit a constant distant fragment depth, then early-z can still happen while maintaining the flexibility of pixel-programmable depth in general (necessary for proper impostors as shown). In this case I may be splitting hairs unnecessarily at this point. However that note does mention that if I can avoid specifying gl\_FragDepth, I should, but it'd be up to the driver whether it will do something smart if I e.g. set gl\_FragDepth to a constant.

As an example I could render my 3D scene, then set depth draw value to maximum, keep depth test on, and then render a fullscreen quad for my cubemap skybox, and it would just do the right thing.

Otherwise, choices include:

* render skybox first with depth testing switched off, then render scene
* use a fragment shader for the skybox that specifies the requisite depth value (this may very well just be the answer)

# Answer
Tile based GPUs usually prefers you to call `glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT)` with depth at 1.0 in order to do a fast tile clear. Then render your skybox as an opaque quad with depth test "less" and no blending like any other opaque geometry.

The driver usually uses the `glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT)` call to know it can start over with a completely fresh frame buffer, throwing away all previous data.

If you do not clear the color buffer it will need to reload the old color data from the previous frame buffer and it wont be able to pre-clear the internal tile rendering memory to a preset value (`glClearColor`, `glClearDepth`, `glClearStencil`) using specialized hardware.

If you need to render a primitive at a fixed depth force the z & w values in the **vertex** shader, do not do it in the pixel shader.

Setting the depth in the pixel shader, even to a constant value, forces pixel shader code to be run to calculate the depth rather than use the interpolator's special hardware/routine that is already optimized.

Even if a few drivers optimize for the very unique and extremely rare case of a forced const depth most drivers wont. For all the other devices you'll have to switch back to setting the depth in the vertex shader anyway which means a lot of wasted work just to save an insignificant fraction of gpu time on the skybox if anything at all.

Cheers,
> 2 votes

---
Tags: opengl, opengl-es, opengl-es2, opengl-es3
---


# Question
Title: Should we always prefer OpenGL ES version 2 over version 1.x
OpengGL ES version 2 goes a long way into changing the development paradigm that was established with OpenGL ES 1.x. You have shaders which you can chain together to apply varios effects/transforms to your elements, the projection and transformation matrices work completly different etc. I've seen a lot of online tutorials and blogs that simply say "ditch version 1.x, use version 2, that's the way to go". Even on Android's documentation it sais to "use version 2 as it may prove faster than 1.x".

Now, I've also read a book on OpenGL ES (which was rather good, but I'm not gonna mention here because I don't want to give the impression that I'm trying to make hidden publicity). The guy there treated only OpenGL ES 1.x for 80% of the book, and then at the end only listed the differences in version 2 and said something like "if OpenGL ES 1 does what you need, there's no need to switch to version 2, as it's only gonna over complicate your code. Version 2 was changed a lot to facillitate newer, fancier stuff, but if you don't need it, version 1.x is fine".

My question is then, is the last statement right? Should I always use Open GL ES version 1.x if I don't need version 2 only stuff? I'd sure like to do that, because I find coding in version 1.x A LOT simpler than version 2 but I'm afraid that my apps might get obsolete faster for using an older version.

# Answer
Yes, also this is a common scenario for both desktop and mobile users, with OpenGL the fixed pipeline approach is just deprecated and when using old code on modern devices you are just guessing, because any GPU maker that wants to stick with a modern OpenGL approach is not forced to support old functions and the old approach for the pipeline.

These days you get OpenGL ES 2 capable devices from the low end market up to the high end, and the OpenGL ES 3 will come soon, adopting OpenGL ES 1.x is just an old and deprecated approach for the market of today.

OpenGL ES 2 introduces the programmable pipeline on mobile devices discarding the old fixed-pipeline approach; probably for this reason you find it more difficult to use, but just a change of mindset and some hours passed on coding will make you change your idea about this.
> 3 votes

# Answer
I disagree with user827992's answer. If you don't want or need the added complexity of OpenGL ES 2, stick with GL 1.1. When checking the **facts** you will see that **all** phones in today's market support OpenGL ES 1.1, and about 90 % support OpenGL ES 2.

Here's what Google has to say about choosing OpenGL version:
<sub>(I removed a point about compatibility as I linked to it above)</sub>

> OpenGL ES API version 1.0 (and the 1.1 extensions) and version 2.0 both provide high performance graphics interfaces for creating 3D games, visualizations and user interfaces. Graphics programming for the OpenGL ES 1.0/1.1 API versus ES 2.0 differs significantly, and so developers should carefully consider the following factors before starting development with either API:
>
> * **Performance** \- In general, OpenGL ES 2.0 provides faster graphics performance than the ES 1.0/1.1 APIs. However, the performance difference can vary depending on the Android device your OpenGL application is running on, due to differences in the implementation of the OpenGL graphics pipeline.
> * **Coding Convenience** \- The OpenGL ES 1.0/1.1 API provides a fixed function pipeline and convenience functions which are not available
> in the ES 2.0 API. Developers who are new to OpenGL may find coding
> for OpenGL ES 1.0/1.1 faster and more convenient.
> * **Graphics Control** \- The OpenGL ES 2.0 API provides a higher degree of control by providing a fully programmable pipeline through the use of shaders. With more direct control of the graphics processing pipeline, developers can create effects that would be very difficult to generate using the 1.0/1.1 API.
>
> While performance, compatibility, convenience, control and other factors may influence your decision, you should pick an OpenGL API version based on what you think provides the best experience for your users.

So while I agree that ES 2+ is the future, there's nothing wrong about still using ES 1.1 if it fits your needs.
> 4 votes

# Answer
If a device supports both OpenGL ES 1.x and 2.x, it is very unlikely that there's any actual ES 1.x hardware. Which means that your ES 1.x code generates ES 2.x calls, shaders included - and the shaders most likely do stuff you don't actually need.

On the other hand, if what you're doing doesn't require a lot of performance, using ES 1.x may let you write your applications faster.

In the long term, I'd recommend using ES 2.x though.
> 2 votes

# Answer
Actually, the right question is: Which OpenGL ES best fits for my application needs ?

If your application just needs nice 3D graphics, without fancy and expensive effects, then OpenGL 1.1 is just enough for you. No shaders to bother! In other hand, If you need lots of special, and sometimes expensive, effects, only available through shaders, then you must go for OpenGL ES 2.0.

One drawback often omitted on the use of OpenGL ES 2.0 / 3.0 is that the lack of FFP (see below) requires the programmer to rewrite some fixed functions on shaders, as well some plain code for management. This way, developing using OpenGL ES 2.0 put a lot of pressure about developing good shaders, alongside application's 3D graphic engine. In a nutshell, to have the same visual effect, you have double work. Nevertheless, GLES 2.0 still is cool and fun.

\*Fixed Function Pipeline - a set of functions used to create and manage transformations, lighting and material. Available on OpenGL ES 1.x and on desktop OpenGL 1.0 through 3.1 (today). FFP is not available on OpenGL ES 2.0 and higher.
> 1 votes

# Answer
Ha hah. I know the book you are referring to. Yes. He blabs about ES 1.1 for 80% of the book, then tries to pass off ES 2.0 as a lesser version. Sorry, but 1.1 is dead, Jim. He's wasted your time. I reckon he wrote it as a 1.1 book and when 2.0 came out he tacked it on the end. 1.1 is lower performance is depreciated. You should not be writing new code with it. If you are a new coder use 2.0.
> 0 votes

---
Tags: opengl-es, opengl-es2
---