# Question
Title: Random black screen when changing states
I'm making a game with LibGDX but I ran into a really odd problem.

When I was working on the loading screen I delayed the loading process with an image of ~87MB. When the loading is finished, it should continue to the next state with the main menu.

The odd thing is that when the big-image isn't loaded the screen blacks out after displaying the main menu state for less than a second. When I let it load the big-image it doesn't black out.

Main game loop:

```
public class MGame extends ApplicationAdapter {
    private SpriteBatch batch;
    private AssetManager assetmanager;

    @Override
    public void create() {
        batch = new SpriteBatch();
        assetmanager = new AssetManager();

        assetmanager.load("logo.png", Texture.class);
        assetmanager.load("loading.png", Texture.class);
        assetmanager.load("loading.mp3", Music.class);
        assetmanager.finishLoading();
        assetmanager.load("title_bg.jpg", Texture.class);
        assetmanager.load("menu.mp3", Music.class);
        //assetmanager.load("bigfile.png", Texture.class); //so now it blacks out

        GameStateManager.pushOnTop(new StateLoadingScreen());
    }

    @Override
    public void dispose() {
        batch.dispose();
        assetmanager.dispose();
    }

    @Override
    public void render() {
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        batch.begin();
        GameStateManager.updateCurrent(assetmanager, batch);
        batch.end();
    }
}

```

StateLoadingScreen:

```
public class StateLoadingScreen extends AState {
    public enum ANI_STATE {
        LOGO_INC, LOGO_OPAQUE__LOADING_INC, LOGO_OPAQUE__LOADING_DEC, DONE_DECREASE_ALL, DONE_NEXT_STATE
    }

    private float alphaLogo = 0, alphaLoading = 0;
    /** 0 = logo increasing alpha; 1 = logo opaque, loading increasing; 2 = logo opaque, loading decreasing; 3 = done->decreasing; 4 = done->next state */
    private ANI_STATE state = ANI_STATE.LOGO_INC;

    @Override
    public void update(float dt, AssetManager assetmanager) {
        if (!assetmanager.get("loading.mp3", Music.class).isLooping()) {
            assetmanager.get("loading.mp3", Music.class).setLooping(true);
            assetmanager.get("loading.mp3", Music.class).play();
        }

        if (assetmanager.update()) if (state != ANI_STATE.LOGO_INC && state != ANI_STATE.DONE_NEXT_STATE) state = ANI_STATE.DONE_DECREASE_ALL;
        switch (state) {
            case LOGO_INC:
                if (alphaLogo > 100) state = ANI_STATE.LOGO_OPAQUE__LOADING_INC;
                else alphaLogo += dt*100;
                break;
            case LOGO_OPAQUE__LOADING_INC:
                if (alphaLoading > 100) state = ANI_STATE.LOGO_OPAQUE__LOADING_DEC;
                else alphaLoading += dt*100;
                break;
            case LOGO_OPAQUE__LOADING_DEC:
                if (alphaLoading < 0) state = ANI_STATE.LOGO_OPAQUE__LOADING_INC;
                else alphaLoading -= dt*100;
                break;
            case DONE_DECREASE_ALL:
                if (alphaLogo > 0) alphaLogo -= dt*100;
                if (alphaLoading > 0) alphaLoading -= dt*100;
                if (alphaLogo <= 0 && alphaLoading <= 0) state = ANI_STATE.DONE_NEXT_STATE;
                break;
            case DONE_NEXT_STATE:
                GameStateManager.set(new StateMenu(assetmanager), assetmanager);
                break;
            default:
                throw new EnumUpdateException();
        }
    }

    @Override
    public void render(SpriteBatch sb, AssetManager assetmanager) {
        Color c = sb.getColor();
        sb.setColor(new Color(c.r, c.g, c.b, alphaLogo/100));
        Texture texLogo = assetmanager.get("logo.png", Texture.class);
        sb.draw(texLogo, (Ref.WIDTH/2)-(texLogo.getWidth()/2), (Ref.HEIGHT/2)-(texLogo.getHeight()/2));
        if (assetmanager.isLoaded("loading.png")) {
            sb.setColor(new Color(c.r, c.g, c.b, alphaLoading/100));
            Texture texLoading = assetmanager.get("loading.png", Texture.class);
            sb.draw(texLoading, (Ref.WIDTH/2)-(texLoading.getWidth()/2), (Ref.HEIGHT/2)-(texLoading.getHeight()/2)-(texLogo.getHeight()/2));
        }
    }

    @Override
    public void dispose(AssetManager assetmanager) {
        assetmanager.unload("loading.png");
        assetmanager.unload("loading.mp3");
        assetmanager.unload("logo.png");
        //if (assetmanager.isLoaded("bigfile.png")) assetmanager.unload("bigfile.png");
    }
}

```

StateMainMenu:

```
public class StateMenu extends AState {
    private boolean fadeFinished = false;
    private float a = 0;

    public StateMenu(AssetManager assetmanager) {

    }

    @Override
    public void update(float dt, AssetManager assetmanager) {
        if (!assetmanager.get("menu.mp3", Music.class).isLooping()) {
            assetmanager.get("menu.mp3", Music.class).setLooping(true);
            assetmanager.get("menu.mp3", Music.class).play();
        }

        if (a > 100) fadeFinished = true;
        if (!fadeFinished) a += 100*dt;
    }

    @Override
    public void render(SpriteBatch sb, AssetManager assetmanager) {
        sb.setColor(sb.getColor().r, sb.getColor().g, sb.getColor().b, a/100);
        sb.draw(assetmanager.get("title_bg.jpg", Texture.class), 0, 0, Ref.WIDTH, Ref.HEIGHT);
    }

    @Override
    public void dispose(AssetManager assetmanager) {
        assetmanager.unload("title_bg.jpg");
        assetmanager.unload("menu.mp3");
    }

}

```

# Answer
So I found the solution and I find it rather odd.

Basicly I increase the overal alpha-value with 100\*delta. Sometimes the result is \>1, and appearently libGDX can't handle an alpha of 1.1, blacking out the screen (drawing at alpha 0.1 propably?)
> 0 votes

---
Tags: java, libgdx
---


title: Unity 5/C#/Scripting Switching Cameras

text:
# Question
Title: Unity 5/C#/Scripting Switching Cameras
How can I switch cameras from First Person to Third person or from thrid person to first person. Like at GTA V you can switch the cameras. How to do this?

Tnx for your time.

# Answer
> 2 votes
Simple method: Add two cameras to your scene, the first-person camera and the third-person camera. Attach both to the player-character. Move one on eye-height, the other further behind. Deactivate one of them. To switch between them, deactivate one and activate the other. This results in an immediate switch between the two perspectives.

Fancier method: Have one camera, but switch by moving its `localPosition` between the 1st person position and the 3rd person position. This results in a smooth transition.

---
Tags: unity, c#, camera, scripting
---


# Question
Title: Loop in coroutine stops after going halfway
I have a very weird problem with a particular loop in a coroutine:

```
    public IEnumerator DestroyCubesGameOver() {
    var startingCubeHolder = GameObject.FindWithTag("StartingCubeHolder");
    DestroyOutOfCameraCubes();

    Debug.Log(cubeGroup.transform.childCount);

    for (int i = 0; i < cubeGroup.transform.childCount; i++) {
        Debug.Log(i);
        Destroy(cubeGroup.transform.GetChild(i).gameObject);
        yield return new WaitForSeconds(0.001f);
    }

    Destroy(startingCubeHolder);
}

```

The loop starts doing its thing and it needs to do it 100 times for example. However it stops after going about halfway and after destroying about half of the objects. Even if I increase the delay for each repeat it still does the same exact thing - needs to repeat itself and destroy 100 objects, ends after destroying just 50. What is causing this?

Edit: If I make it just a `void` method it destroys all of the objects.

Edit 2: This loop was initially a `foreach` but I rewrote it to try the other way - same thing.

# Answer
> 1 votes
On each loop you destroy one object so your childcount goes down, at the half your i and childcount meet and the loop stops.

---
Tags: unity, game-loop, coroutines
---


# Question
Title: Implementing my own UI sprite class in Unity using shaders: where and how to position the sprites
For learning purposes, I am trying to implement my own UI classes in Unity "from scratch", in the GPU using shaders. I mean, I am trying to use simple 2D sprites either positioned via shaders or created within the geometry shaders. These sprites should be, of course, displayed above all else.

I know how to create or translate the sprites within the shader. However, I am struggling with a couple of conceptual issues:

1) where exactly, relative to the camera (or to the near frustum plane), should the UI sprites be positioned? I man, thinking of the Z axis as being the camera.forward, what is the correct default distance to display the sprites at (assuming that at that location, the sprite texture would be the closes to its correct 100% zoom scale).

2) for the correct positioning+rotation, would it just be the case of, every frame, calculating in the shader such correct world position of the sprite in relation to the camera/near frustum plane, and then making the sprite rotate towards the camera? Or is there a better way of doing that, i.e. disregarding world position at all and going directly for the screen position of the sprites within the shaders, since the final step of shaders is to paint the pixels in screen-space?

Thanks for your suggestions!

# Answer
1. Don't use worldspace, use screenspace
2. See 1

See, if you use World Space, what happens when an object gets closer to the camera than your arbitrary sprite distance? Why, it renders in front of the UI. This is bad.

Secondly, if you're using GL calls, GL natively works in Screen Space, you actually have to perform counteracting translates in order to position your sprites.
> 1 votes

---
Tags: unity, shaders, gui, transformation, ui-design
---


title: TiledMap render uses 15% of my cpu

text:
# Question
Title: TiledMap render uses 15% of my cpu
I am a beginner in Slick2D. I used TiledMap render in my game,but I do not know why it use 15%cpu and how to fix it. I used map is 1024\*768. This is a part of my code. Thanks for any help

```
 public class Map{
        public static Image[][] solids;
        public static int WIDTH;
        public static int HEIGHT;
        private static TiledMap map;
        private static int objectLayer;
        private static int mapEndX;
        private static int mapEndY;
        private static int  startX=0,realX=0;
        private static int  startY=0,realY=0;
        public static void render(){

            map.render(startX, startY);
        //  map.render(startX, startY, startX+60, startY+60, 80, 80);
        }

        public static void update(){

            map.getTileId(0, 0, objectLayer);
        }

        public static void load(String name){

            map=Resources.getMap(name);
            objectLayer = map.getLayerIndex("solids");
        }

        public static void setStartXY(int tileX,int tileY){
            startX = (-1 * tileX * Tile.SMALL_SIZE);
            realX = ( -1 * startX);
            startY = (-1 * tileY * Tile.SMALL_SIZE);
            realY = ( -1 * startY);
            mapEndX = (startX + map.getWidth() * Tile.SMALL_SIZE);
            mapEndY = (startY + map.getWidth() * Tile.SMALL_SIZE);

        }

        public static boolean hitTest(int x,int y){

        /*  if((map.getTileId((x+startX)/4-1, (y+startY)/4-1,objectLayer) ==0)){
                return true;
            }*/
            return false;
        }

    }

```

//----------------------------------------------

```
 public class  Play extends BasicGameState{
         int x=0,i=100,j=50;
         int y=0;
         private ArrayList<Entity> entities;
         private TiledMap map;
         Image image;
        public Play(int play) {

        }

        @Override
        public void init(GameContainer gc, StateBasedGame arg1) throws SlickException {
            try {
                    Map.load("test");
                    Map.setStartXY(0, 0);
                } catch (Exception e) {

                    e.printStackTrace();
                }

            entities = new ArrayList<Entity>();
            entities.add(new Player());
            System.out.println("1");

        }

        @Override
        public void render(GameContainer gc, StateBasedGame arg1, Graphics g) throws SlickException {

            g.setBackground(Color.black);
        //  g.scale(4f, 4f);
            Map.render();

            for(int i=0;i < entities.size();i++){

                entities.get(i).render(gc, g);
            }
        }

        @Override
        public void update(GameContainer gc, StateBasedGame sbd, int delta) throws SlickException {
            for(int i=0;i < entities.size();i++)
            {
                try {
                    entities.get(i).update(gc, delta);
                } catch (Exception e) {

                    e.printStackTrace();
                }
            }
            Map.update();

        }

        @Override
        public int getID() {

            return state.Play;
        }

     }

```

# Answer
The reason why your game takes up 15% CPU is because of your map size, which is 1024\*768, and the game constantly has to run this map several times each second in the render() method, which of course would take up memory. I would suggest following this tutorial on TiledMap rendering (https://www.youtube.com/watch?v=0BivL6Carh4), start watching at around 6 minutes into the video, this individual will teach you how to render the map efficiently and this will of course take up less memory for your game. Hope this helps.
> -2 votes

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


# Question
Title: Online Tower Defense : Problem in protecting user's data
Sorry about the question heading

I am creating an **online tower defense game** with SQL Server 2008 as my database.

SQL user used to send data to server is **restricted to only execute existing storeprocedures** which means to do anything like building or destroying a tower a storeprocedure has to be used. Now in the case of destroying of towers a storeprocedure named "**sp\_remove\_tower**" is fired with just 1 parameter "UserId" which will tell the database from which account the tower has to be removed.

## Problem

is that if a person has SQL Server 2008 management studio installed and gets the SQL Server Name, SQL User ID, SQL User Password from lets say through inspect element in google chrome or by hacking the game itself. Then he can randomly pass any UserId in the storeprocedure which will cause to delete towers from other innocent players account.

How do i stop such a thing from happening?

Thanks in advance

# Answer
> 5 votes
2 things:

1. Never, EVER, should you give the client the password to anything.
2. Never, EVER, should the client be executing queries themselves.

So a solution is put a service between it, let the user have a session from whatever your service is written in and store the user id in there, don't let the client pass along an arbitrary user id.

---
Tags: tower-defense, sql
---


# Question
Title: Coroutine doesn't continue after checking for bool
I have the following coroutine:

```
    public IEnumerator EndGame() {
    //StopAllCoroutines();
    GamePauseController.instance.UnfreezeTime();
    DisintegratorModalController.instance.ignoreBorderDisin = false;
    ignoreBorderEndGame = true;
    StartCoroutine(CubeBehavior.instance.DestroyCubesGameOver());
    StopBackgroundMusic();
    DisableCubeSpawner();
    CubeBehavior.instance.ClearSelectedCubes();
    ScoreManager.instance.StopCountingScore();
    GameDataManager.instance.SaveHighScoreAndDisintegrators();
    ScoreManager.instance.SaveScoreToLeaderboard();
    LightColorManager.instance.WhiteFadeToHeartbeat();

    while (!CubeBehavior.instance.allCubesDestroyed) { // Wait for all the cubes to be destroyed before continuing
        yield return null;
    }

    Debug.Log("Working");
    StartCoroutine(HUDController.instance.HideHUD());
    StartCoroutine(GameResultsController.instance.ShowResultsMenu());
    MenuParticles.instance.Show();
}

```

After the bool check the code below it doesn't execute when it should. What is the issue here?

# Answer
1. `CubeBehavior.instance.allCubesDestroyed` remains `false`.
2. You're calling `StopAllCoroutines` somewhere else in the code, before this one can complete
3. There's some other error that your code here and explanation haven't revealed.

Attach the debugger, break on execution of the `yield`, check your variables at runtime to ensure they're doing what you expect. Step through your code visually to ensure it's doing what you want. And other basic troubleshooting debugging steps.
> 0 votes

---
Tags: unity, coroutines
---


# Question
Title: Unity sprite renderer uses standard 2D sprite instead of custom loaded one
I have loaded a 2D sprite from the filesystem and created a sprite from it, which I then attach to a SpriteRenderer. The game object appears in the scene but for some reason it doesn't seem to be using the sprite I loaded, and is instead using the Standard Assets/2D/Materials/SpriteLift sprite. I have attached my sprite creation code and some screenshots:

```
public static Sprite LoadSprite(string relPath) {
    var fileUrl = "file://D:/Unity Projects/2D-Game/mod/base/textures/" + relPath + ".png";

    // Download texture from file location and resize it
    var www = new WWW (fileUrl);
    var texture = www.texture;
    texture.Resize (textureSize, textureSize);
    texture.name = relPath;
    Debug.Log (texture);

    // Make the sprite
    var sprite = Sprite.Create (texture, spriteRect, spritePivot, textureSize);
    sprite.name = relPath;
    return sprite;
}

```

The Unity scene with the incorrect sprite:

The desired texture:

The code that creates the game object and attaches the loaded sprite to the SpriteRenderer:

```
GameObject go = new GameObject ();
go.name = "Tile_ " + tile.location.ToString();
go.transform.position = tile.location.ToVector3 ();
go.transform.SetParent (this.transform, true);
SpriteRenderer sr = go.AddComponent<SpriteRenderer> ();
sr.sprite = tile.Type.sprite;
sr.enabled = true;

```

Note that the screenshot contains many game objects all with the same sprite, that's why it looks big in the scene.

**EDIT:** The problem may be due to materials.

**EDIT 2:** Screenshot of a selected tile:

# Answer
My apologies, I should have picked up on this quicker. Instead I made you get a screenshot that wasn't needed.

Your not waiting for your WWW to complete before creating the sprite. So basically the www.texture is empty at the time you use it. Check www.isDone before working with the texture to see what I mean.

If you do not want to do this in a Coroutine (yield return www;), you can block until it is done, but this is not recommended. By blocking I mean something like "while(!www.isDone){ // Do nothing }".

See the WWW documention for more information, looking at the example.
> 1 votes

---
Tags: sprites, unity
---


# Question
Title: LookAt different object smoothly in unity3d
As picture depicted my camera moving on path i want to lookAt bath different object smoothly. Currently have tried

```
trasnform.LooAt(activePath.gameObject.transform);

```

but it producing jerky result. object suddenly lookAt to next object how to avoid it. I searched and found this sloution but it also not working

```
var targetRotation = Quaternion.LookRotation(activePath.gameObject.transform.position - transform.position);
        transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Time.deltaTime);

```

# Answer
Slerp is an interpolation. The final parameter T must be a ratio of TimeSinceLookingAtLastTarget/TotalTimeDesiredToLookAtNextTarget.

0 \<= T \<= 1

If you expect it to take 2 seconds to turn from target A to target B, and it's been .25 seconds, the interpolation ratio should be 0.125.

Time.DeltaTime is just the number of seconds in took to process the last frame. It should always be consistently low and won't change much. At 60FPS, that code would leave you looking 1/60th of the way between two targets.

So you will need to know the actual time and how long it should take. When you start the turn, capture

`float SecondsToTurn = 2; //adjust this`

`float TurnStartTime = Time.Time;`

Each frame calculate your slerpT as

`float slerpT = (Time.Time - TurnStartTime) / SecondsToTurn`

Use slerpT instead of Time.deltaTime in your Quaternion.Slerp
> 2 votes

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


# Question
Title: Efficiently separating Read/Compute/Write steps for concurrent processing of entities in Entity/Component systems
## Setup

I have an entity-component architecture where Entities can have a set of attributes (which are pure data with no behavior) and there exist systems that run the entity logic which act on that data. Essentially, in somewhat pseudo-code:

```
Entity
{
    id;
    map<id_type, Attribute> attributes;
}

System
{
    update();
    vector<Entity> entities;
}

```

A system that just moves along all entities at a constant rate might be

```
MovementSystem extends System
{
   update()
   {
      for each entity in entities
        position = entity.attributes["position"];
        position += vec3(1,1,1);
   }
}

```

Essentially, I'm trying to parallelise update() as efficiently as possible. This can be done by running entire systems in parallel, or by giving each update() of one system a couple of components so different threads can execute the update of the same system, but for a different subset of entities registered with that system.

## Problem

In the case of the shown MovementSystem, parallelization is trivial. Since entities don't depend on each other, and don't modify shared data, we could just move all entities in parallel.

However, these systems sometimes require that entities interact with (read/write data from/to) each other, sometimes within the same system, but often between different systems that depend on each other.

For example, in a physics system sometimes entities may interact with each other. Two objects collide, their positions, velocities and other attributes are read from them, are updated, and then the updated attributes are written back to both entities.

And before the rendering system in the engine can start rendering entities, it has to wait for other systems to complete execution to ensure that all relevant attributes are what they need to be.

If we try to blindly parallelize this, it will lead to classical race conditions where different systems may read and modify data at the same time.

Ideally, there would exist a solution where all systems may read data from any entities it wishes to, without having to worry about other systems modifying that same data at the same time, and without having the programmer care about properly ordering the execution and parallelization of these systems manually (which may sometimes not even be possible).

In a basic implementation, this could be achieved by just putting all data reads and writes in critical sections (guarding them with mutexes). But this induces a large amount of runtime overhead and is probably not suitable for performance sensitive applications.

## Solution?

In my thinking, a possible solution would be a system where reading/updating and writing of data is separated, so that in one expensive phase, systems only read data and compute what they need to compute, somehow cache the results, and then write all the changed data back to the target entities in a separate writing pass. All systems would act on the data in the state that it was in at the beginning of the frame, and then before the end of the frame, when all systems have finished updating, a serialized writing pass happens where the cached results from all the different systems are iterated through and written back to the target entities.

This is based on the (maybe wrong?) idea that the easy parallelization win could be big enough to outdo the cost (both in terms of runtime performance as well a code overhead) of the result caching and the writing pass.

## The Question

How might such a system be implemented to achieve optimal performance? What are the implementation details of such a system and what are the prerequisites for an Entity-Component system that wants to use this solution?

# Answer
> 1 votes
----- (based on the revised question)

First point: since you don't mention having profiled your release build runtime and found a specific need I suggest you do that ASAP. What does your profile look like, are you thrashing the caches with bad memory layout, is one core pegged at 100%, how much relative time is spent processing your ECS versus the rest of your engine, etc...

Read from an entity and compute something... and hold onto the results somewhere in an intermediate storage area until later? I don't think that you can separate read+compute+store in the way you think and expect this intermediate store to be anything but pure overhead.

Plus, since you're doing continuous processing the main rule you want to follow is to have one thread per CPU core. I think that you are **looking at this at the wrong layer**, try looking at entire systems and not individual entities.

Create a dependency graph between your systems, a tree of what system needs results from an earlier system's work. Once you have that dependency tree then you can easily send **entire systems full of entities off to process** on a thread.

So let's say that your dependency tree is morass of brambles and bear traps, a design issue but we have to work with what we have. The best case here is that inside each system each entity does not depend on any other result inside that system. Here you easily subdivide the processing across threads, 0-99 and 100-199 on two threads for an example with two cores and 200 entities that this system owns.

In either case, at each stage you have to wait for results that the next stage depends on. But this is OK because waiting for the results of ten large blocks of data being processed in bulk is far superior to synchronizing a thousand times for small blocks.

The idea behind building a dependency graph was to trivialize the seemingly impossible task of "Finding and assembling other systems to run in parallel" by automating it. If such a graph shows signs of being blocked by constant waiting for previous results then creating a read+modify and delayed write only moves the blockage and does not remove the serial nature of the processing.

And serial processing can only be turned parallel between each sequence point, but not overall. But you realize this because it is the core of your problem. Even if you cache reads from data that haven't been written yet you still need to wait on that cache to become available.

If creating parallel architectures were easy or even possible with these kinds of constraints then computer science wouldn't have been struggling with the problem since Bletchley Park.

The only real solution would be to **minimize all these dependencies** to make the sequence points as rarely needed as possible. This may involve **subdividing systems into sequential processing steps** where, inside each subsystem, going parallel with threads becomes trivial.

Best I got for this problem and it's really nothing more than recommending that if hitting your head on a brick wall hurts then break it into smaller brick walls so you're only hitting your shins.

# Answer
> 0 votes
I've heard of an interesting solution to this problem: The idea is that there would be 2 copies of the entity data (wasteful, I know). One copy would be the present copy, and the other would be the past copy. The present copy is strictly write only, and the past copy is strictly read only. I'm assuming that systems don't want to write to the same data elements, but if that's not the case, those systems should be on the same thread. Each thread would have write-access to the present copies of mutually exclusive sections of the data, and every thread has read-access to the all past copies of the data, and thus can update the present copies using data from the past copies with no locking. Between each frame, the present copy becomes the past copy, however you want to handle the swapping of roles.

This method also removes race conditions because all systems will be working with a stale state that will not change before/after the system has processed it.

# Answer
> 0 votes
I know 3 software designs handling parallel processing of data:

1. Process the data **sequentially**: This may sound wierd since we want to process the data using multiple threads. However, most scenarios require multiple threads just in order for work to be completed while other threads wait or do long running operations. Most common usage are UI threads that update the user interface in a single thread, while other threads may run in the background, but are not allowed to directly access the UI elements. In order to pass results from the background threads, **job queues** are used that will be processed by the single thread at the next reasonable opportunity.
2. **Synchronize** the data access: this is the most common way to handle multiple threads accessing the same data. Most programming languages have build in classes and tools in order to **lock** sections where data is read and/or written by multiple threads concurrently. However, caution should be taken to not block operations. On the other hand, this approach costs a lot overhead in real-time applications.
3. Handle **concurrent modifications** only when they happen: this optimistic approach can be done if collisions occur rarely. The data will be read and modified if there was no multiple access at all, but there is a mechanism that detects when the data was updated concurrently. If that happens, the single computation will just be executed again until success.

Here some examples for each approach that may be used in an entity system:

1. Lets think of a `CollisionSystem` that reads `Position` and `RigidBody` components and should update a `Velocity`. Instead of manipulating the `Velocity` directly, the `CollisionSystem` will instead put a `CollisionEvent` in the work queue of an `EventSystem`. This event will be then processed sequentially with other updates to the `Velocity`.
2. An `EntitySystem` defines a set of components that it needs to read and write. For each `Entity` it will aquire a *read lock* for each component that it wishes to read, and a *write lock* for each component that it wishes to update. Like this, every `EntitySystem` will be able to concurrently read components while update operations are synchronized.
3. Taking the example of the `MovementSystem`, the `Position` component is *immutable* and contains a *revision* number. The `MovementSystem` savely reads the `Position` and `Velocity` component and computes the new `Position`, incrementing the read *revision* number and tries updating the `Position` component. In case of a concurrent modification, the framework indicates this on the update and the `Entity` will be put back in the list of entities that have to be updated by the `MovementSystem`.

Depending on the systems, entities and update intervals, each approach might be good or bad. An entity system framework might allow the user to choose between those options to tweak the performance.

I hope I could add some ideas to the discussion and please let me know if there are some news about it.

---
Tags: entity-system, multithreading
---


# Question
Title: How can I select a object (canvas) with tag using Physics.Raycast?
I made this C# script, becase I want select a Button of the menu(canvas) for choice the dificulty of the game, but I don't want select with mouse I just want select with Aim, and I made this script for make this happen, but don't it works. What am I doing wrong ?

**My C# Script:**

```
using UnityEngine;
using System.Collections;

public class AimManager : MonoBehaviour {

    float TimeInterval = 2f;
    float time = 0;
    public UI_cozinha uiCozinha;

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {
        RaycastHit hit;

        if (Physics.Raycast(transform.position, transform.forward, out hit))
        {
            if(time >= TimeInterval)
            {
                if((hit.transform.tag == "ButtonE"))
                {
                    uiCozinha.setDiff(5);
                }if((hit.transform.tag == "ButtonM"))
                {
                    uiCozinha.setDiff(7);
                }
                if ((hit.transform.tag == "ButtonH"))
                {
                    uiCozinha.setDiff(10);
                }
                time = 0;
            }
            else
            {
                time += Time.deltaTime;
            }
        }

    }
}

```

**CardBoard View:**

**Normal GameView:**

> **Image of Menu(canvas):** i.stack.imgur.com/MRIbl.png

# Answer
**I Finaly find my Solution.**

When I do **`Debug.Log(hit.transform.name)`**, I can see that only hit in my Aim, so **`Physics.Raycast()`** works in the wrong way, I just change my Layer Type to **Ignore Raycast**, as it is in the picture:

When I changed the Layer Type, I could see that my Script was right, and works. So I can select a object tag (in my case a button\[canvas\]) with **`Physics.Raycast()`**.
> 0 votes

# Answer
Ok here is my guess. you are using `Physics.Raycast` that works with 3d object. but I'm guessing you have put 2DBoxColliders on your buttons. Use this instead.

```
RaycastHit2D hit = Physics2D.Raycast(mousePos, Vector2.up);
 if (hit.collider)
 {
  if(hit.collider.gameObject.tag == "someTag")
  {
    //do stuff here
  }
 }

```

Dont forget to add a Physics 2D RayCaster component to your camera.
> 0 votes

---
Tags: c#, unity, unityscript, virtual-reality
---


# Question
Title: Have an object rotate on its Y axis towards mouse position
I've been looking at some other answers to similar cases but not every one used different methods, and a lot of them were not what i needed, so here's my question :

What's the best/standard way to get the X and Z positions of the mouse onto a plane, so that object can rotate to look at that position?

I'm trying to get it in a similar setting to, for example "Angry Bots" where the Player is always facing mouse position.

Also, would that be camera independent? i mean, if my camera changes its angle, it would still work because it usually is a projection of the "screen" plane onto the "player" plane, right?

I'm sorry, i'm a bit overwhelmed with the many options `Camera.main.` has, and i'm not really sure which one should i use.

# Answer
I'm not currently at my computer to show a valid demonstration, however, I've used "Camera.main.ScreenPointToRay(Input.mousePosition)" casting that ray and referencing the point that it hits. You could set that point to be the position that your character looks at via Vector3.lookToward(). Also,you are correct, this would work regardless of camera angle as long say the raycast returns true.
> 1 votes

---
Tags: unity, 3d
---


# Question
Title: Configuring Implicit Multi-GPU Rendering Driver Settings Programmatically
What is available to game developers to take advantage of implicit multi-GPU rendering technologies as of 2016? For this question I will only be asking about Nvidia's SLI and AMD's Crossfire technologies as they apply to rendering in OpenGL and Direct3D, specifically non-ancient versions of these APIs like OpenGL core 3.3+ and Direct3D 10.0+.

What tools do developers have access to, to programmatically detect and alter the state of implicit multi-GPU rendering for their game?

A key component of this question is what is openly available to independent developers, SLI and Crossfire aren't problems to AAA developers who get GameReady drivers tweaked to enhance the performance of their game and have SLI profiles included within the driver. What is available for smaller developers to take advantage of multiple GPUs?

At the very least, is there anything that developers can do to reduce the negative effects that these technologies can cause? Is there a way to avoid a FPS drop or artifacts that come with SLI/Crossfire bugs, can a developer programmatically disable SLI or Crossfire?

With all of this, how is the cross-platform support? Is there a solution for these issues that will work across Windows, Linux, and OSX? Will it work with OpenGL and Direct3D? Can it run out of the box or packaged with your game?

# Answer
With all the research I've done on this topic looking for modern solutions, this is as much I could find available to independent developers available as of early 2016 for SLI and CrossFire:

**Windows + CrossFire + AGS for Direct3D (Allows for some explicit control)**

I was really impressed with what AMD had done for Windows with their AMD GPU Services API which allows for explicit control over CrossFire configuration on GCN-based (HD 7000+) GPUs when using Direc3D 11. They have good documentation, a getting started guide, and samples.

**Windows + CrossFire for OpenGL and Direct3D**

You don't get any explicit control, but there are things you can do to make your game more friendly for CrossFire Alternate Frame Rendering, even for OpenGL. They have a couple guides on optimizing your game for AMD GPUs and CrossFire. You may be able to increase the performance of your game just by requesting that the AMD drivers try to use CrossFire AFR on your game be renaming the executable to `AFR-FriendlyOGL.exe` or `AFR-FriendlyD3D.exe`.

**Windows + SLI + NVAPI for Direct3D**

The Nvidia NVAPI allows developers the ability to query some information about the current SLI configuration and use that information to better configure their rendering engine. Functions like NvAPI\_D3D\_GetCurrentSLIState allow you to query some information about the SLI AFR configuration if you are using Direct3D 10+.

**Windows + SLI for OpenGL and Direct3D**

Nvidia provides a best practices guide for SLI AFR (Alternate Frame Rendering) and SFR (Split Frame Rendering). Which appears you can influence the Nvidia drivers in a similar way as the AMD drivers by renaming your executable to `AFR-FriendlyD3D.exe`. There is also, the Nvidia GPU programming guide which will help you optimize your game for Nvidia GPUs which will naturally help your SLI compatibility and performance as well.

**Linux + SLI or Crossfire for OpenGL**

Nvidia and AMD are on a fairly equal playing field here. SLI and CrossFire are practically impossible to get working even for AAA titles, it takes a lot of user configuration to get SLI or CrossFire working slightly. In most cases performance goes down or introduces terrible graphics issues when SLI or CrossFire are enabled. Implicit multi-GPU support just doesn't work here yet, at least not consistently enough for you to depend on it for your game. This is an issue that I hope to see change soon in the future as many enthusiasts and VR users are making a move to Linux and SteamOS to tinker in a more open space.

**Mac OSX + SLI or Crossfire for OpenGL**

Support for this is worse than on Linux for the most part, but it doesn't seem like it will be a necessity. The cheapest computer running OSX with two GPUs starts at $3,000 USD and ships with two workstation GPUs (FirePro) realistically anyone looking to spend that much money on a computer for games isn't going to buy a mac in the first place.

In closing, multi-GPU support for games today isn't great but it's getting easier to build games for enthusiast grade hardware, and if you really care about getting that much more performance APIs like Vulkan and Direct3D 12 look like they will provide some great explicit multi-GPU support.
> 2 votes

---
Tags: optimization, cross-platform, nvidia, amd
---


# Question
Title: How to export slick2d game into a jar with the res and native folder
I am a beginner in Slick2D.

I use jarspliceJarSplice to output Slick2D game.

But, but it is export all thingexports everything into one jar.

I want to export one jar with the res andand native folder ....

Soso I can easily modify the game resources in the design process.

Thanks for any help.

# Answer
From my own personal experiences, you can't really add the res folder into the jar file unless you use InputStreams (this is so that the game can read the res files inside the jar file and not in the same folder), however, you can add the native files into the jar.

With JarSplice, there is a tab called "Add Natives," you use that tab to locate the natives you want to add to your game (i.e. windows, mac, linux native files):

Under 'Add Natives', add your native files for the specified Operating System, in this case I'm adding window natives.

RES: For adding res files, I would recommend to have them in the same folder as the game, but if you use InputStreams to fetch the resource files, than the following will most likely work:

Under the tab "Add Jars," add the jar of your game and for your assets, add them as a .zip file (I used WinRar to create the .zip), here's an example:

This way the game fetches the resource files within the jar file and not within the folder it is in.

Hopefully this will help you.
> 1 votes

---
Tags: java, slick, lwjgl3, jarsplice
---


title: Where does the roughness map go?

text:
# Question
Title: Where does the roughness map go?
So I used Quixel, and created a great item. I want to view it in Unity with all the maps the problem however is I have 5 maps but only know how to insert 4.

Diffuse Normal AO Specular Roughness

I don't see a slot for roughness (AKA gloss).

# Answer
> 2 votes
Okay it took some researching but apparently my software I was using don't do all the heavy lifting. You copy & paste the roughness into the alpha channel of the specular/metalness texture which will do the trick (the RGB channels must be off though).

I discovered the reason for this is.

* White = Solid
* Black = Transparent

This technique must be used in lets say games where you shoot at the wall, and you see all the little bullet hole textures.

Doing more research I discovered this great guide. Which helped me further understand the decision to use an alpha.

https://www.gametextures.com/putting-your-texture-in-an-alpha-channel-using-photoshop/

---
Tags: textures, unity
---


# Question
Title: Poor performance wth custom particle system in LibGDX
I'm using a custom particle system for my LibGDX / Java based game project (because I used Slick2D earlier on, need more parameters so I made my own and then ported). The system is fairly standard as far as I'm concerned, uses particle pooling (each emitter has its own fixed size particle pool) and renders each particle in a batch and uses one single (2048x1028) packed texture with all particle textures on it. Here is how I render the particles in semi-pseudo-code (because the entire code isn't relevant):

```
//ParticleSystem class
//Note: ExtendedBatch is my custom sprite batch implementation, largely just the normal SpriteBatch with two additional vertices for grayscale factor and additive tinting
void renderEmitter(ParticleEmitter emitter, ExtendedBatch batch)
{
    ParticlePool pool = particlePools.get(emitter);

    if (emitter.shouldScissor)
        Renderer.pushScissor(emitter.scissor);

    for (Particle particle : pool.particles)
    {
        if (particle.inUse)
              particle.render(batch);
    }

    if (emitter.shouldScissor)
        Renderer.popScissor();
}

//Particle class
void render(ExtendedBatch batch)
{
      relativeX = getRelativeX();
      relativeY = getRelativeY();

      if (isInScreenBounds(relativeX, relativeY))
      {
            batch.setColor(myColor);
            batch.draw(myTexture, position, origin, size, scale, rotation);
      }
}

```

Now for some reason with only around 300 particles (split up into 10 emitters with varying sizes) the performance drops to awful ~30FPS on my notebook's integrated GPU (Intel HD 4400) when I need / want 60FPS at all times. I know iGPUs aren't great, but that one is one of the better ones out there and games like Ori or Braid which have thousands of similar particles run without any problems at 60FPS on that very chip. I also doubt (and hope) that it's not just Java vs C++ which is causing this huge performance drop here.

Looking at in-game profiling data:

The in-game profiling data however shows a few things: Particles aren't really taking that long to render and there is a *lot* of idle time. To me, that doesn't really make much sense. It looks like there would be enough resources to easily render everything at 200FPS or more, but it is stuck at a horrible 30FPS.

There are a lot of things I already tried that didn't help:

* Packing all particle textures into one (which is 2048x1024)
* Batching all particle draw calls
* Profiling to find out the cause (see above)
* VisualVM to find potential memory issues, didn't help
* Disabling vSync and FPS locks doesn't help

For the record, here's a VisualVM CPU sample over a timespan of 2 minutes:

There must be something I'm doing wrong and I also want / need more particles than just 300 so I definitely have to fix this - but I don't know how.

Update: Using the default SpriteBatch implementation and default shaders doesn't improve performance either.

**Update - Solution:**

I forgot to turn off MSAA. I had it running at 2x sampling rate for smoother antialising, I completely forgot to check for that. In the meantime I improved performance in a lot of other parts, but that's what finally did it.

# Answer
> 2 votes
I would take a look at glDraw\*Instances (Instancing) Also, reducing vertex count for a large amount of small particles is extremely important. I don't know if your using a model or a single 2D texture or what, but some general tips:

Use as few verticies as possible.

If using transparency in your textures, use glAlphaFunc to reduce blending needed.

If using textures, keep batching them, and definitely use VAO's if your not already.

A nice approach I've seen is to have a single 2D texture for particles, and have it face the camera. Minecraft uses this for some particles.

I could say more, but I don't see your rendering code above.

# Answer
> 1 votes
Dont know how your particle system is written but it is very possible that your bottle neck is the communication time between CPU and GPU. Not going to go into too much detail but just know that this operation can be very slow because it causes stalling. Perhaps the idle time you see in profiling is due to that.

What a good particle system do is to move all the particle movement calculation to the GPU so that CPU only need to communicate with GPU when a particle is spawned and when a particle needs to be destroyed.

This can be accomplished by passing some additional attribute to the GPU, such as the spawntime, start\_position, velocity and acceleration of each particle. Then on the GPU, calculate the position of each particle as start\_position + vel * dt + accel * dt * dt; (dt = current\_time-spawntime;) in the vertex shader.

---
Tags: opengl, java, libgdx, particles
---


# Question
Title: My background stopped looping and is mushy and weird looking
My looping bacground texture looped perfectly, but maybe after building the project as an android project broke it? How can I fix it?

```
using UnityEngine;
using System.Collections;

public class ScrollScript : MonoBehaviour {

public float speed = 0.01f;

void Start () {

}

void Update () {
    Vector2 offset = new Vector2 (Time.time * speed, 0);

    GetComponent<Renderer>().material.mainTextureOffset = offset;
}
}

```

# Answer
Perhaps switching the platform messed up the texture setting. Check the compression point filters, mip maps and so on. As suggested I moved my comment to be a answer.
> 2 votes

# Answer
GetComponent calls are way to expensive to use in Update like that, especially on mobile, because Update is called once per frame. A main rule of thumb is repeat actions as little as possible, so do things like GetComponent once and store it in a variable.

```
using UnityEngine;
using System.Collections;

public class ScrollScript : MonoBehaviour {

public float speed = 0.01f;

private Material _material;

void Start () {
_material = GetComponent<Renderer>().material;
}

void Update () {
    _material.mainTextureOffset = new Vector2 (Time.time * speed, 0);
}
}

```

For performance on mobile, even using material isn't the best way, but it should work for you until your ready to dive a bit deeper. You may never need to do anything different, but I personally like to use a few sprites and scroll them past in a loop. Think of it like holding up three pictures. Take the last picture and put it in front of the first, while the player can only see the middle one. Continue this as long as needed.

Good luck with your project!
> 1 votes

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


# Question
Title: How do I allow my player object to continue rotating once it's met a clamped boundary?
I have a spaceship I'm moving around on the screen, when the player moves the ship, it rotates on its axis. However, when the ship meets a clamped boundary(on the x-axis) it abruptly stops. How do I make it so that the ship will still rotate when it hits the clamped boundary?

```
void Controls(){
     Rotate();
     MoveShip();
 }
 void Rotate(){
     player.rotation = Quaternion.Euler((player.velocity.y * -pitchAngle), 0f, (player.velocity.x * -bankRotation));
 }
 void MoveShip(){
     float moveVertical = Input.GetAxis("Vertical");
     float moveHorizontal = Input.GetAxis("Horizontal");
     Vector3 bank = new Vector3(moveHorizontal, 0f, 0f);
     Vector3 pitch = new Vector3(0f, moveVertical, 0f);
     player.AddForce(bank * bankSpeed);
     player.AddForce(pitch * pitchSpeed);
     player.position = new Vector3(Mathf.Clamp(player.position.x, xMin, xMax), Mathf.Clamp(player.position.y, yMin, yMax), 0f);
     if((player.position.x == xMin) || (player.position.x == xMax) || (player.position.y == yMin) || (player.position.y == yMax)){
         player.velocity = new Vector3(0f, 0f, 0f);
         player.angularVelocity = new Vector3(0f, 0f, 0f);
     }
 }

```

The question that this one has been marked a duplicate of, the question I asked, does not address what this question is asking. That question asked "Why was the player object continuing to move passed the clamped boundaries?". This question is asking "How do I keep the player object rotating once it hist those clamped boundaries?" Two completely different questions asking two completely different things.

# Answer
> 1 votes
My guess: At the bottom of MoveShip() you are setting the velocity to zero, if the player is at the boundary. As your code in Rotate() depends on the x and y components of the velocity (which is set to zero in the previous update, when at the boundary), the rotation will be set to Quaternion.Euler(0,0,0) in these occasions

One way to solve this could be to use a Vector3 that holds some sort of "desired velocity" which is not clamped at the boundary. When you read from the desired velocity instead of the real velocity in order to rotate the ship, it should work

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


# Question
Title: What is the proper way to get input from the motion controllers touch pads?
I've been trying to figure out how to get the inputs from the touch pads on the motion controllers but have yet to find out how to do so. Initially I tried doing the following (as it was how I accessed the triggers and the side buttons)...

```
private Valve.VR.EVRButtonId gripButton = Valve.VR.EVRButtonId.k_EButton_Grip; //Essentially this is accessing
                                                                               //SteamVR_TrackedObject.cs and telling our script
                                                                               //and defining it here.

private Valve.VR.EVRButtonId triggerButton = Valve.VR.EVRButtonId.k_EButton_SteamVR_Trigger;
private Valve.VR.EVRButtonId Axis0 = Valve.VR.EVRButtonId.k_EButton_Axis0;
private Valve.VR.EVRButtonId Axis1 = Valve.VR.EVRButtonId.k_EButton_Axis1;
private Valve.VR.EVRButtonId Axis2 = Valve.VR.EVRButtonId.k_EButton_Axis2;
private Valve.VR.EVRButtonId Axis3 = Valve.VR.EVRButtonId.k_EButton_Axis3;
private Valve.VR.EVRButtonId Axis4 = Valve.VR.EVRButtonId.k_EButton_Axis4;

```

I know I got the buttons right but I'm not sure if I'm getting the touch pad inputs properly. Also the other issue I'm having is how do I differentiate between controllers?

For context here is my script in full (which is based upon this video)...

```
public class WandController : MonoBehaviour {
    private Valve.VR.EVRButtonId gripButton = Valve.VR.EVRButtonId.k_EButton_Grip; //Essentially this is accessing
                                                                                //SteamVR_TrackedObject.cs and telling our script
                                                                                //and defining it here.

    private Valve.VR.EVRButtonId triggerButton = Valve.VR.EVRButtonId.k_EButton_SteamVR_Trigger;
    private Valve.VR.EVRButtonId Axis0 = Valve.VR.EVRButtonId.k_EButton_Axis0;
    private Valve.VR.EVRButtonId Axis1 = Valve.VR.EVRButtonId.k_EButton_Axis1;
    private Valve.VR.EVRButtonId Axis2 = Valve.VR.EVRButtonId.k_EButton_Axis2;
    private Valve.VR.EVRButtonId Axis3 = Valve.VR.EVRButtonId.k_EButton_Axis3;
    private Valve.VR.EVRButtonId Axis4 = Valve.VR.EVRButtonId.k_EButton_Axis4;

    private SteamVR_Controller.Device controller { get { return SteamVR_Controller.Input((int)trackedObj.index); } }
    private SteamVR_TrackedObject trackedObj;

    private GameObject pickup;

    // Use this for initialization
    void Start ()
    {
        trackedObj = GetComponent<SteamVR_TrackedObject>();
    }

    // Update is called once per frame
    void Update ()
    {
        if (controller == null)
        {
            Debug.Log("Controller not initalized");
            return;
        }

        if (controller.GetPressDown(gripButton) && pickup != null)
        {
            pickup.transform.parent = this.transform;
        }
        if (controller.GetPressUp(gripButton) && pickup != null)
        {
            Debug.Log("Grip button was unpressed");
        }

        if (controller.GetAxis(Axis0).x >= 1)
        {
            Debug.Log("Axis0 detected");
        }
        if (controller.GetAxis(Axis1).x >= 1)
        {
            Debug.Log("Axis1 detected");
        }
        if (controller.GetAxis(Axis2).x >= 1)
        {
            Debug.Log("Axis2 detected");
        }
        if (controller.GetAxis(Axis3).x >= 1)
        {
            Debug.Log("Axis3 detected");
        }
        if (controller.GetAxis(Axis4).x >= 1)
        {
            Debug.Log("Axis4 detected");
        }
    }

    private void OnTriggerEnter(Collider collider)
    {
        pickup = collider.gameObject;
    }
    private void OnTriggerExit(Collider collider)
    {
        pickup = collider.gameObject;
    }
}

```

Also here is the script where I retrieved all the inputs...

```
//========= Copyright 2015, Valve Corporation, All rights reserved. ===========
//
// Purpose: Wrapper for working with SteamVR controller input
//
// Example usage:
//
//  var deviceIndex = SteamVR_Controller.GetDeviceIndex(SteamVR_Controller.DeviceRelation.Leftmost);
//  if (deviceIndex != -1 && SteamVR_Controller.Input(deviceIndex).GetPressDown(SteamVR_Controller.ButtonMask.Trigger))
//      SteamVR_Controller.Input(deviceIndex).TriggerHapticPulse(1000);
//
//=============================================================================

using UnityEngine;
using Valve.VR;

public class SteamVR_Controller
{
    public class ButtonMask
    {
        public const ulong System           = (1ul << (int)EVRButtonId.k_EButton_System); // reserved
        public const ulong ApplicationMenu  = (1ul << (int)EVRButtonId.k_EButton_ApplicationMenu);
        public const ulong Grip             = (1ul << (int)EVRButtonId.k_EButton_Grip);
        public const ulong Axis0            = (1ul << (int)EVRButtonId.k_EButton_Axis0);
        public const ulong Axis1            = (1ul << (int)EVRButtonId.k_EButton_Axis1);
        public const ulong Axis2            = (1ul << (int)EVRButtonId.k_EButton_Axis2);
        public const ulong Axis3            = (1ul << (int)EVRButtonId.k_EButton_Axis3);
        public const ulong Axis4            = (1ul << (int)EVRButtonId.k_EButton_Axis4);
        public const ulong Touchpad         = (1ul << (int)EVRButtonId.k_EButton_SteamVR_Touchpad);
        public const ulong Trigger          = (1ul << (int)EVRButtonId.k_EButton_SteamVR_Trigger);
    }

    public class Device
    {
        public Device(uint i) { index = i; }
        public uint index { get; private set; }

        public bool valid { get; private set; }
        public bool connected { get { Update(); return pose.bDeviceIsConnected; } }
        public bool hasTracking { get { Update(); return pose.bPoseIsValid; } }

        public bool outOfRange { get { Update(); return pose.eTrackingResult == ETrackingResult.Running_OutOfRange || pose.eTrackingResult == ETrackingResult.Calibrating_OutOfRange; } }
        public bool calibrating { get { Update(); return pose.eTrackingResult == ETrackingResult.Calibrating_InProgress || pose.eTrackingResult == ETrackingResult.Calibrating_OutOfRange; } }
        public bool uninitialized { get { Update(); return pose.eTrackingResult == ETrackingResult.Uninitialized; } }

        // These values are only accurate for the last controller state change (e.g. trigger release), and by definition, will always lag behind
        // the predicted visual poses that drive SteamVR_TrackedObjects since they are sync'd to the input timestamp that caused them to update.
        public SteamVR_Utils.RigidTransform transform { get { Update(); return new SteamVR_Utils.RigidTransform(pose.mDeviceToAbsoluteTracking); } }
        public Vector3 velocity { get { Update(); return new Vector3(pose.vVelocity.v0, pose.vVelocity.v1, -pose.vVelocity.v2); } }
        public Vector3 angularVelocity { get { Update(); return new Vector3(-pose.vAngularVelocity.v0, -pose.vAngularVelocity.v1, pose.vAngularVelocity.v2); } }

        public VRControllerState_t GetState() { Update(); return state; }
        public VRControllerState_t GetPrevState() { Update(); return prevState; }
        public TrackedDevicePose_t GetPose() { Update(); return pose; }

        VRControllerState_t state, prevState;
        TrackedDevicePose_t pose;
        int prevFrameCount = -1;
        public void Update()
        {
            if (Time.frameCount != prevFrameCount)
            {
                prevFrameCount = Time.frameCount;
                prevState = state;

                var system = OpenVR.System;
                if (system != null)
                {
                    valid = system.GetControllerStateWithPose(SteamVR_Render.instance.trackingSpace, index, ref state, ref pose);
                    UpdateHairTrigger();
                }
            }
        }

        public bool GetPress(ulong buttonMask) { Update(); return (state.ulButtonPressed & buttonMask) != 0; }
        public bool GetPressDown(ulong buttonMask) { Update(); return (state.ulButtonPressed & buttonMask) != 0 && (prevState.ulButtonPressed & buttonMask) == 0; }
        public bool GetPressUp(ulong buttonMask) { Update(); return (state.ulButtonPressed & buttonMask) == 0 && (prevState.ulButtonPressed & buttonMask) != 0; }

        public bool GetPress(EVRButtonId buttonId) { return GetPress(1ul << (int)buttonId); }
        public bool GetPressDown(EVRButtonId buttonId) { return GetPressDown(1ul << (int)buttonId); }
        public bool GetPressUp(EVRButtonId buttonId) { return GetPressUp(1ul << (int)buttonId); }

        public bool GetTouch(ulong buttonMask) { Update(); return (state.ulButtonTouched & buttonMask) != 0; }
        public bool GetTouchDown(ulong buttonMask) { Update(); return (state.ulButtonTouched & buttonMask) != 0 && (prevState.ulButtonTouched & buttonMask) == 0; }
        public bool GetTouchUp(ulong buttonMask) { Update(); return (state.ulButtonTouched & buttonMask) == 0 && (prevState.ulButtonTouched & buttonMask) != 0; }

        public bool GetTouch(EVRButtonId buttonId) { return GetTouch(1ul << (int)buttonId); }
        public bool GetTouchDown(EVRButtonId buttonId) { return GetTouchDown(1ul << (int)buttonId); }
        public bool GetTouchUp(EVRButtonId buttonId) { return GetTouchUp(1ul << (int)buttonId); }

        public Vector2 GetAxis(EVRButtonId buttonId = EVRButtonId.k_EButton_SteamVR_Touchpad)
        {
            Update();
            var axisId = (uint)buttonId - (uint)EVRButtonId.k_EButton_Axis0;
            switch (axisId)
            {
                case 0: return new Vector2(state.rAxis0.x, state.rAxis0.y);
                case 1: return new Vector2(state.rAxis1.x, state.rAxis1.y);
                case 2: return new Vector2(state.rAxis2.x, state.rAxis2.y);
                case 3: return new Vector2(state.rAxis3.x, state.rAxis3.y);
                case 4: return new Vector2(state.rAxis4.x, state.rAxis4.y);
            }
            return Vector2.zero;
        }

        public void TriggerHapticPulse(ushort durationMicroSec = 500, EVRButtonId buttonId = EVRButtonId.k_EButton_SteamVR_Touchpad)
        {
            var system = OpenVR.System;
            if (system != null)
            {
                var axisId = (uint)buttonId - (uint)EVRButtonId.k_EButton_Axis0;
                system.TriggerHapticPulse(index, axisId, (char)durationMicroSec);
            }
        }

        public float hairTriggerDelta = 0.1f; // amount trigger must be pulled or released to change state
        float hairTriggerLimit;
        bool hairTriggerState, hairTriggerPrevState;
        void UpdateHairTrigger()
        {
            hairTriggerPrevState = hairTriggerState;
            var value = state.rAxis1.x; // trigger
            if (hairTriggerState)
            {
                if (value < hairTriggerLimit - hairTriggerDelta || value <= 0.0f)
                    hairTriggerState = false;
            }
            else
            {
                if (value > hairTriggerLimit + hairTriggerDelta || value >= 1.0f)
                    hairTriggerState = true;
            }
            hairTriggerLimit = hairTriggerState ? Mathf.Max(hairTriggerLimit, value) : Mathf.Min(hairTriggerLimit, value);
        }

        public bool GetHairTrigger() { Update(); return hairTriggerState; }
        public bool GetHairTriggerDown() { Update(); return hairTriggerState && !hairTriggerPrevState; }
        public bool GetHairTriggerUp() { Update(); return !hairTriggerState && hairTriggerPrevState; }
    }

    private static Device[] devices;

    public static Device Input(int deviceIndex)
    {
        if (devices == null)
        {
            devices = new Device[OpenVR.k_unMaxTrackedDeviceCount];
            for (uint i = 0; i < devices.Length; i++)
                devices[i] = new Device(i);
        }

        return devices[deviceIndex];
    }

    public static void Update()
    {
        for (int i = 0; i < OpenVR.k_unMaxTrackedDeviceCount; i++)
            Input(i).Update();
    }

    // This helper can be used in a variety of ways.  Beware that indices may change
    // as new devices are dynamically added or removed, controllers are physically
    // swapped between hands, arms crossed, etc.
    public enum DeviceRelation
    {
        First,
        // radially
        Leftmost,
        Rightmost,
        // distance - also see vr.hmd.GetSortedTrackedDeviceIndicesOfClass
        FarthestLeft,
        FarthestRight,
    }
    public static int GetDeviceIndex(DeviceRelation relation,
        ETrackedDeviceClass deviceClass = ETrackedDeviceClass.Controller,
        int relativeTo = (int)OpenVR.k_unTrackedDeviceIndex_Hmd) // use -1 for absolute tracking space
    {
        var result = -1;

        var invXform = ((uint)relativeTo < OpenVR.k_unMaxTrackedDeviceCount) ?
            Input(relativeTo).transform.GetInverse() : SteamVR_Utils.RigidTransform.identity;

        var system = OpenVR.System;
        if (system == null)
            return result;

        var best = -float.MaxValue;
        for (int i = 0; i < OpenVR.k_unMaxTrackedDeviceCount; i++)
        {
            if (i == relativeTo || system.GetTrackedDeviceClass((uint)i) != deviceClass)
                continue;

            var device = Input(i);
            if (!device.connected)
                continue;

            if (relation == DeviceRelation.First)
                return i;

            float score;

            var pos = invXform * device.transform.pos;
            if (relation == DeviceRelation.FarthestRight)
            {
                score = pos.x;
            }
            else if (relation == DeviceRelation.FarthestLeft)
            {
                score = -pos.x;
            }
            else
            {
                var dir = new Vector3(pos.x, 0.0f, pos.z).normalized;
                var dot = Vector3.Dot(dir, Vector3.forward);
                var cross = Vector3.Cross(dir, Vector3.forward);
                if (relation == DeviceRelation.Leftmost)
                {
                    score = (cross.y > 0.0f) ? 2.0f - dot : dot;
                }
                else
                {
                    score = (cross.y < 0.0f) ? 2.0f - dot : dot;
                }
            }

            if (score > best)
            {
                result = i;
                best = score;
            }
        }

        return result;
    }
}

```

So anyone know what I am missing here?

# Answer
> 1 votes
Stumbled upon this looking for something else.

`SteamVR_Controller.Device` has a method `GetAxis()` (as you have already tried using) and the default parameter is the touchpad so you don't want to pass any value. That will return the `Vector2` position on the touchpad that you are touching.

`controller.GetAxis()` should be all you need. The returned `Vector2` goes from `(-1, -1)` to `(1,1)` so just check the value isn't `(0,0)`:

```
Vector2 value = controller.GetAxis();
if(value != Vector2.zero)
    DoSomething(value);

```

---
Tags: unity, c#, htc-vive
---


# Question
Title: Is there a way to use the UnityEngine.UI with SteamVR and the Vive?
I recently got into developing VR games using the Vive as my standard platform. Now I would like to design some UnityEngine.UI elements that would be interactable via the built in pointer scripts that come with the SteamVR module from the Unity Asset Store. However, I can't seem to find any kind of built in method for allowing interaction between the pointers and buttons, scroll bars, etc. I have also been unable to write anything myself that would do the trick, it's almost as if the Unity UI is just not designed to interact in a VR environment at all. Does anyone have a method for using the UnityEngine.UI in a VR environment? If so, can you please point me in the right direction?

# Answer
> 1 votes
You can try this: https://github.com/VREALITY/ViveUGUIModule

It is doable without this. I'm pretty sure I've just used a default UI Button though (can't check right now).

---
Tags: unity, ui-design, steam, virtual-reality
---


# Question
Title: Texture atlas vs. array-texture: how differently are they handled by CPU and GPU and how that impacts performance?
Unity 5.4 (currently in beta), will bring a much awaited feature (since 2013) that is array-textures - in the same vain as OpenGL's ArrayTexture. However, after doing some reading about arrays-textures and texture atlases, I still can't quite understand the technical differences on their usage by CPUs and GPUs.

So, to be more specific, I would like to ask for an explanation on the main differences between how texture atlas and texture arrays are dealt with by CPU and GPU and, most importantly, how such differences can impact on performance and memory handling (e.g. how texture arrays can be more performance than texture atlases, etc).

If technical details on Unity's implementation are lacking due to its unfortunate closed-sourceness, I would be happy enough with an answer regarding OpenGL.s ArrayTexture.

# Answer
As noted in the comments above, performance is going to depend on implementation, your particular hardware, and what you're trying to do with the textures, so the only reliable answer there is to profile each alternative.

There are a few differences in terms of how you use each option though, which will apply consistently:

One big difference is that, for array textures, each texture is treated separately for purposes like wrapping texture coordinates or mipmapping.

This avoids common problems with texture atlases where we need to add padding between adjacent texture swatches to keep samples at their edges from bleeding together, especially in deeper mip levels.

This also means if you want your textures to tile, you can use the texture sampling hardware to do it just like with a vanilla texture. With atlases, we usually have to do the tiling math in our fragment shader, since the sampler only wraps/mirrors/clamps/borders texture coordinates over the whole atlas, not individual tiles inside it.

The main restriction with array textures is that they require all their constituent textures to have the same resolution and number of mip levels. If you're trying to batch-together textures with very different resolution needs (say, storing terrain tiles whose LoD falls off with distance in a virtual texture) then you may want the flexibility of an atlas instead.
> 16 votes

---
Tags: textures, rendering, texture-atlas
---


# Question
Title: Coroutine wrong Behavior when scene is loaded.
Ok so I have this coroutine :

```
 IEnumerator ShowCharTraits()
    {

        while(!hasPlayerChosen)
        {
            yield return null;
            traitPanel.SetActive(true);
        }
        hasPlayerChosen = false;
        traitPanel.SetActive(false);
    //    Debug.Log("Got called! job done");

    }

```

It's being called like this from the awake method in my `GameManager`:

```
players = GameObject.FindGameObjectsWithTag("Player");
                foreach (GameObject g in players)
                {
                    ui_Controller.StartShowCharTraits();
                    g.GetComponent<PlayerToken>().isTurn = false;
                }

```

StartShowCharTraits() is a simple method that does this :

```
  public void StartShowCharTraits()
    {
        StartCoroutine("ShowCharTraits");
    }

```

Now, I have checked the tags, no null reference exception, actually no errors or warnings are being thrown. If i load the scene in the editor and then play it everything works fine. `traitPanel.SetActive(true);` get called and my panel shows up. However when I load my scene from another scene using `SceneManager.LoadScene(1);` the above mentioned line is never reached. Any ideas why this is happening ?

# Answer
> 0 votes
Ok how do I explain this. I have a singleton that acts as a data holder. While developing the scene with the game manager I had attached the singleton to the gamemanger object that hold a bunch of scripts. Now when I made the main menu I ofc added my singleton to it so I can carry info to the game scene and because of this my whole game manger object was being deleted. This is the culprit from the DataHolder :

```
 void Awake()
    {
        if (instance == null)
            instance = this;
        else if (instance != this)
            Destroy(gameObject);//This right here.

        DontDestroyOnLoad(gameObject);
    }

```

So I changed that line to `Destroy(gameObject.GetComponent(instance.GetType()));`

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


# Question
Title: How to spawn enemies within a minimum distance of each other randomly? 2D
So I'm making an 2D infinite runner. So I try to spawn obstacles randomly in x-coordinate, but these just spawn most of the time in the same position and too frequently. generationPoint is just a small Empty a medium distance from the camera that's where the obstacles spawn. Even if I make them spawn at a small random rate It's still impossible to play.

```
{

public GameObject thePlatform;
public Transform generationPoint;
public float distanceBetween;

private float platformWidth;

public ObjectPooler theObjectPool;

public float randomEnemyThreshold;
public ObjectPooler enemyPool;

public float randomReindeerThreshold;
public ObjectPooler ReindeerPool;

void Start () {
    platformWidth = thePlatform.GetComponent<BoxCollider2D>().size.x;

}

void Update () {

    if (transform.position.x < generationPoint.position.x)
    {
        transform.position = new Vector3 (transform.position.x + platformWidth + distanceBetween, transform.position.y, transform.position.z);

        GameObject newPlatform = theObjectPool.GetPooledObject();

        newPlatform.transform.position = transform.position;
        newPlatform.transform.rotation = transform.rotation;
        newPlatform.SetActive (true);

        if (Random.Range (0f, 100f) < randomEnemyThreshold)
        {
            GameObject newEnemy = enemyPool.GetPooledObject();

            Vector3 enemyPosition = new Vector3 (-10f, 0.5f, 0f);

            newEnemy.transform.position = transform.position + enemyPosition;
            newEnemy.transform.rotation = transform.rotation;
            newEnemy.SetActive(true);

        }

        if (Random.Range (0f, 100f) < randomReindeerThreshold)
        {

            GameObject newDeer = ReindeerPool.GetPooledObject ();

            Vector3 reindeerPosition = new Vector3 (5f, 0.5f, 0f);

            newDeer.transform.position = transform.position + reindeerPosition;
            newDeer.transform.rotation = transform.rotation;
            newDeer.SetActive(true);
        }
    }

}

}

```

# Answer
> 4 votes
Poisson disc sampling places the samples (in your case spawn points) randomly, but does so in a way that ensures no two points are not too close & yields a uniform distribution.

Robert Bridson's algorithm is the most efficient way I know, with a performance of O(n). Basically, you divide your space with a grid & when placing a random point, you find its grid cell & check it & the nearby cells for previously placed points. This allows you to discard random placements that would be too close without needing to test all of the points generated so far.

This question/answer on Random enemy placement on a 2d grid has more details & links to tutorials.

---

Edit with 1D specific details, assuming that you're building things a screen width at a time:

```
double r;     // minimium distance between points
double width; // screen width
// set r & width
double sqrt2 = 1.41421356237;
double cellSize = r / sqrt2;
int dim = (int) Math.ceil(width / cellSize);
float[] array = new float[dim]

```

Now, when you generate a new potential point x, find the corresponding index for the cell of that point in the array as follows:

```
int baseIndex = (int)(x/cellSize);

```

Then loop & check for previously generated points from `array[index-2]` to `array[index+2]` (obviously, be careful not to go past the bounds of the array). If you don't have any points saved in that region, nothing is too close, so add the new point. If you do find something, check the distance between it & the new potential point. If anything is too close, you'll need to discard the new point & generate a new random point. If you find prior points, but none are too close, add the point.

I'm certain there are some ways you could optimize things by taking advantage of the fact that this is a 1D version of the problem, (E.G. tracking empty cells & only attempting to generate points for them).

# Answer
> 1 votes
Here's a way to control the spacing of spawn points, but it requires you to build them in one direction; in this case I'll restrict them to only add new points of increasing value:

```
// lastX - holds the last X value you generated
// distanceMin - the minimum distance to allow between points
// distanceMax - the maximum distance to allow between points
public double getNextPointX(double lastX, double distanceMin, double distanceMax){
    double diff = distanceMax - distanceMin;
    return nextX = (Random.NextDouble() * diff) + distanceMin + lastX;
}

```

So, if you give the method the last x value generated, a min distance & a max distance, it will generate a new random x value that is at least distanceMin away & not more than distanceMax away from the last value.

# Answer
> 0 votes
The easiest way to solve this would be to generate more than new points instead of 1, and pick the one with the highest distance from the other points, and spawn an enemy at it.

This results in a random look, but with the enemies more uniformly spread across the game field.

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


# Question
Title: How can I use an HLSL pixel shader to peek at other pixels?
I think this is like a pixilation shader but I had a hard time trying to find one online, and one that I could manipulate specifically.

I want to create a pixel shader for my monogame project that splits the texture up into blocks. The width and height of the block may or may not match. Then on each block, I want to average out the color of all pixels in the block, and fill it in.

I'm not sure how I would do this in a pixel shader. I can do something like this in code pretty easily but that is because the code scans the entire image at once. A pixel shader though seems to run on each pixel, so I'm not sure how to do that.

I currently have a simple pixel shader where I can plug in code to test. It doesn't do anything right now but return the same color.

```
#if OPENGL
    #define SV_POSITION POSITION
    #define VS_SHADERMODEL vs_3_0
    #define PS_SHADERMODEL ps_3_0
#else
    #define VS_SHADERMODEL vs_4_0_level_9_1
    #define PS_SHADERMODEL ps_4_0_level_9_1
#endif

// Our texture sampler
texture Texture;
sampler TextureSampler = sampler_state
{
    Texture = <Texture>;
};

// This data comes from the SpriteBatch Vertex Shader
struct VertexShaderOutput
{
    float4 Position : POSITION;
    float4 Color : COLOR0;
    float2 TextureCordinate : TEXCOORD0;
};

// Our Pixel Shader
float4 PixelShaderFunction(VertexShaderOutput input) : COLOR0
{
    float4 color = tex2D(TextureSampler, input.TextureCordinate);
    return color;
}

technique Technique1
{
    pass Pass1
    {
        PixelShader = compile PS_SHADERMODEL PixelShaderFunction();
    }
}

```

# Answer
> 1 votes
You could render your image to a lower resolution rendertarget with point sampling to achieve a pixelation effect. This way you could use a simple pass-through pixels shader but the sampling of the texture alone would make it pixelated.

An other way would be a compute shader. You could dispatch it with the number of desired blocks, and for each block average imageresolution/blockCount number of pixels in a sqare.

# Answer
> 1 votes
I would abandon the though of perfectly averaging all pixels in a block. Instead, sample the color from say 3x3 underlying (but not neighbouring) pixels, while using biliear filtering. This is only 9 texture lookups per final painted pixel - not at all a big job for the GPU. As opposite to per-painted-pixel sampling all pixels in a block and averaging. Say a block is 30x30 pixels. If the fullscreen picture is 2 million pixels, that would be 2mil x 30 x 30 = 1.8 billion lookups per painted frame. Too much.

Sampling 9 pixels 2 million times is only 18 million lookups. Feasible, and the final color of a block wouln't be too far away from the average.

You achieve this by "snapping UV-addresses onto grid". If your current U-address (for the pixel currently being painted) is 0.701, you'd first snap that into 0.7. Same with 0.699, 0.702, 0.703, etc., up to the snap-to-grid resolution.

Then you add (-0.01, 0, 0.01) to 0.7, do the lookup, calculate the average. Hence you always have a fixed place for the lookup, for all pixels in the current block -\> all pixels in the block get the same color. The next block then does the lookup on 9 different pixcels, etc.

You round 0.709 to 0.7 by: x = 0.1 * floor(0.5 + x * 10)

You round 0.709 to 0.71 by: x = 0.01 * floor(0.5 + x * 100)

If you want to make the pixelation a bit "restless", you can do a small lookup adjustment from the color of the center pixel in the lookup. Dark = i bit to left, light = a bit to right. Or something similar.

If not using this technique, you need another help surface for storing the averages, and then looking up colors for the blocks from that surface. That surface would be 1px high and \[number of blocks\] wide. But that means much more work.

The 0.01, 0.701 etc are just sample values. You'd have to use 1/\[number of blocks horizontally, vertically\] to get the suitable snap resolution.

Maybe even a 2x2 px lookup would do. You must try.

If you want to pixelate only a specific area, you need a control texture, for example grayscale, preferrably with soft edged shapes. Then, in the pixelate shader, you do a lookup of the exact pixel from the source image, and separately calculate the average from the source, as mentioned above. Then you lookup the control texture, and lerp between to two earlier, by the control textures brightness, or some other element of it that controls the end result. Ie. using texture splattering.

---
Tags: xna, monogame, hlsl, fragment-shader
---


# Question
Title: In Unity3D, what is the relation between inertiaTensor and inertiaTensorRotation?
In there are two properties on rigidbody that correspond to the moment of inertia tensor.

One of them is: `rigidbody.inertiaTensor`, which I know is the diagonal of the inertia tensor,
The other is `rigidody.inertiaTensorRotation`, which I don't quite understand. I have, though, created a rigidbody in such a way that I get it to be other number than `Quatenion.identity`, but I still don't see the connection.

Can I describe the products of inertia tensor with the rotation or ... what is the relation between them and where would I require them?

# Answer
> 1 votes
`inertiaTensor` is a `Vector3`, `inertiaTensorRotation` is a `Quaternion`. And from the docs for `inertiaTensor`:

> The inertia tensor is rotated by the inertiaTensorRotation.

Essentially, `inertiaTensor` is the moment of inertia (defined as a tensor) and the `inertiaTensorRotation` is how that tensor is rotated.

If you'd like them to be calculated automatically, you don't set them. Or you can call `Rigidbody.ResetInertiaTensor` which:

> After calling this function, the inertia tensor and tensor rotation will be updated automatically after any modification of the rigidbody.

---
Tags: unity, physics, rigid-body-dynamics
---


# Question
Title: How can I implement a "disable ads" purchase in my game?
I would like to add a "no ads" service to my game such that ads can be removed with a single payment. How can I implement this correctly?

If I just save the fact that the service was paid for locally on the device, the user would have to pay again if they somehow erase the application's data.

# Answer
> 28 votes
If you use Google Play's in-app purchase APIs to implement your 'disable ads' purchase, this is basically handled for you. You'll want to create a non-consumable product that users can purchase. Non-consumable products represent, essentially, a permanent benefit or unlock. Such purchases can be restored to wiped/clean/new phones by the user, so they'll never need to re-purchase the ad disable.

This page contains detailed instructions on integrating the IAP API with your game. The steps are, essentially:

* Add the library to your project and update your manifest files.
* Bind to `IInAppBillingService` via a service connection.
* Send and receive the appropriate data to the service via that interface (`getSkuDetails` to get the list of available products, `getBuyIntent` to begin the purchase transaction, et cetera).

You'll also need to test, via `getPurchases`, to see if a user has purchased the 'disable ads' item (and if so, actually disable the ads).

You create the actual 'disable ads' purchasable item from your Google Play developer console.

# Answer
> 9 votes
If you're not using Google Play's tools as in Josh's answer (although, I recommend you do use those tools). You'd have to manage this information yourself.

You would want to avoid storing something locally on the user's device. Users don't want to have to pay to remove ads per device or per install.

You need to maintain a database with users who have paid. Upon launch (every time, in case they purchase the ad removal on a different device), your application checks the database, if the user account is found, you'd disable the ads permanently for that installation. The user account information should be unique to the user, ideally the Google account they used to purchase the ad removal.

When a user purchases the ad removal, you'd add their account information to the database and disable their ads.

---
Tags: android, monetization
---


# Question
Title: How i can make better jump to my game? - C++ SFML
So, I ask question about my 2D game, actually it is not game, but it is something like poor game. Well i made moving system and now is time to make jump. I made some kind of gravity with tutorial but I don't like it. It is simple and nice but there is problems in that gravity example: 1. You can hold up arrow and "fly" with jump. I tried to fix that and make some kind of limit to jump but it was bad try. Second problem is that when you jump and you release up arrow (jumping key) then my sprite fall very fast and I can't really control that sprite in air.

This is my first game and I want spend time to do that, but now i have problem that i can't solve with my self so if you can help, please do it. I use C++ with CodeBlocks and SFML multimedia library.

So there is little parts of my code.

First there is velocity and gravity configuration:

```
     //gravity & velocity
     const float gravity = 1;
     int ground = 600; //height of ground
     Vector2f velocity(Vector2f(0,0));
     float movingSpeed = 0.5f, jumpingSpeed = 2.0f;

```

Then there is simple when you press button you jump:

```
if(Keyboard::isKeyPressed(Keyboard::Up)){
            skeleton.move(0,velocity.y = -jumpingSpeed);
            source.y = Up;
            isWalking = true;
        }

```

And there is system what recognize if you jump and this make you fall:

```
if(skeleton.getPosition().y + skeleton.getScale().y < ground || velocity.y < 0){
             velocity.y += gravity;
        }else{
            skeleton.setPosition(skeleton.getPosition().x, ground - skeleton.getScale().y);
        }

```

So my sprite name is "skeleton". And yeah this is first time with game physics. I'm not very good game programmer so these code can be poor and yeah... if you invent a solution share it.

# Answer
Here's one of my go-to jump functions. It's similar to a Mario jump - fast at first, slowing down until reaching the top.

Please excuse the syntax. I haven't used C++ in ages, and never SFML.

```
const float GRAVITY = 9.0f;
const float MAX_VELOCITY = -10.0f;
const float MAX_AIR_TIME = 1.2f;

float timeInAir = 0.0f;
float jumpImpulseTime = 0.2f;
float jumpImpulseVel = -10.0f;
float jumpAccel = -1.0f;

void doJump () {
    Vector2f accel = new Vector2f(0.0, 0.0);
    Vector2f vel = new Vector2f(0.0, 0.0);

    // Allow player to jump
    if (isTouchingGround) {
        timeInAir = 0.0f;
        accel.y = 0.0;
        vel.y = 0.0;
    }

    // Handle vertical velocity and acceleration
    if (Keyboard::isKeyPressed(Keyboard::Up)) {
        // First, jump up quickly..
        if (timeInAir < jumpImpulseTime) {
            vel.y = jumpImpulseVel;
        }
        // Then slowly go higher..
        else if (timeInAir < MAX_AIR_TIME) {
            acc.y = jumpAccel;
        }
        // Until finally falling
        else {
            acc.y = GRAVITY;
        }
    }
    else {
        // Prevent double jumps
        timeInAir = MAX_AIR_TIME;
        acc.y = GRAVITY;
    }

    player.velocity.y = vel.y;
    player.acceleration.y = accel.y;
}

void update(float deltaTime) {
    doMove();
    doJump();

    player.velocity = player.velocity + (player.acceleration * deltaTime);

    // Clamp to maximum velocity
    player.velocity.x = math.min(MAX_VELOCITY, math.max(player.velocity.x, -MAX_VELOCITY));
    player.velocity.y = math.min(MAX_VELOCITY, math.max(player.velocity.y, -MAX_VELOCITY));
}

```
> 2 votes

---
Tags: c++, 2d, physics, sfml
---


title: LibGDX Gravity and Jumping

text:
# Question
Title: LibGDX Gravity and Jumping
I'm trying to implement gravity and the ability for the player to jump in my 2D LibGDX game. At the moment, I have two handlers: One for gravity and one for keyboard input

```
@Override
public boolean keyDown(int keycode) {
    // Jumping
    if (keycode == Input.Keys.SPACE) {
        player.getVelocity().add(0, 32);
    }
    return false;
}

@Override
public void update(float deltaTime) { // Update is called every frame
    // Gravity handling
    player.getVelocity().add(0, -50 * deltaTime);

    // Update the position of the player
    player.getPosition().add(player.getVelocity().scl(deltaTime));
}

```

I thought this would work well, however the jumping is very jittery and abrupt. I would like to make it more smooth.

# Answer
My guess to why it is choppy is because `scl()` is permanently scaling your velocity by `deltaTime` each update call. Since `deltaTime` varies a little from frame to frame, this causes the choppiness. Change the position update to

```
float velocityX = player.getVelocity().x;
float velocityY = player.getVelocity().y;
player.getPosition().add(velocityX * deltaTime,velocityY * deltaTime);

```

The only reason that `scl()` returns a `Vector2` is for chaining. It is still the original `Vector2` that was scaled.
> 1 votes

# Answer
I've solved the problem after a bit more analysis. In addition to the suggestion by spectacularbob, I forgot about a line of code that applies damping to the players velocity to make him slide less. This worked well for movement on the x-axis, but resulted in the jittery jumping on the y-axis. I simply changed the following:

```
player.getVelocity().scl(player.dampingSpeed);

```

to only apply the damping on the x velocity:

```
player.getVelocity().x *= player.dampingSpeed;

```
> 0 votes

---
Tags: 2d, libgdx
---


# Question
Title: Game-App deep linking is working in all android phone, but it is not working in tablets . Do i need to add any manifest code to work it in Android?
This is my manifest, which is used for App indexing auto complete and deep linking.

# Answer
> 1 votes
https://developer.android.com/guide/topics/manifest/supports-screens-element.html

we have to add the Screen support in Manifest file..

---
Tags: unity, android, plugin
---


title: Monogame movement Handling

text:
# Question
Title: Monogame movement Handling
I was curious if anyone could explain how I would be able to create simple movement handling in monogame. So far I have a red block which I tried to move by using a loop but that didn't take any effect.

```
protected override void Initialize()
        {
            // TODO: Add your initialization logic here
            position = new Vector2(0, 0);
            texture = new Texture2D(this.GraphicsDevice, 100, 100);
            Color[] colorData = new Color[150 * 150];
            for(int i = 0; i < 10000; i++)
                colorData[i] = Color.Red;
            texture.SetData<Color>(colorData);
            base.Initialize();
        }

```

I also have created this handler but I don't exactly know what I have to do next.

```
/*protected override void HandleInput(KeyboardState keyState)
        {
            if (keyState.IsKeyDown(Keys.W))
            {
                // Look Up
            }
            if (keyState.IsKeyDown(Keys.S))
            {
                // Look Down
            }
            if (keyState.IsKeyDown(Keys.A))
            {
                // Move Left
            }
            if (keyState.IsKeyDown(Keys.D))
            {
                // Move Right
            }
        }*/

```

# Answer
From your code it is not clear if you use GameComponents or not, so I answer for both. I assume you do, since I think you are able to draw the Red Block and not update it. Which leads me to assume you haven't seen the `Update` and `Draw` methods in the main class.

Behavior and player input is handled in the *gameloop*. The gameloop is basically the "update the gameworld state"- "draw the gameworld state" cycle.

The *update* (like the *draw*) is handled in your main game class. Since you seem to be able to show the Red Block, you found the draw method. In the main game class (`Game1`, if you follow the project template) you'll also find a pregenerated `Update` method:

```
 protected override void Update(GameTime gameTime)
        {
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
                Exit();
        }

```

From that method call your RedBlock object to do things. For example:

```
 protected override void Update(GameTime gameTime)
        {
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
                Exit();

           KeyboardState kbstate = Keyboard.GetState();
           _myRedBlock.HandleInput(kbstate);
        }

```

This tells your Red Block code to execute the HandleInput every update frame. From this you can update the `position.X` or `position.Y` based on the input.

You might have used a GameComponent. When registered via `Game.Components.Add(_myRedBlock);`, the component automatically is updated and drawn in the gameloop. Use the `Update` in the GameComponent to have it updated each frame (see GameComponent.Update). From this Update, check the state of the keyboard and move the block accordingly.

Personally I don't use the GameComponent/DrawableGameComponent classes, but write my own game objects. There have been debates on what architecture works best. Both ways work and each have their advantages.
> 0 votes

---
Tags: movement, monogame
---


# Question
Title: Moving object orientation toward its movement in unity3d
I have a gameObject (camera) which is moving on the spline. I want to set it orientation towards it movement. Means, object should need to see where it is moving. I some thing tried this but this is not looking rightly! any advice?

```
 transform.rotation = Quaternion.LookRotation(transform.position);

```

I have also tried this

```
 transform.rotation = Quaternion.LookRotation(transform.forward);

```

# Answer
> 1 votes
I wiped up a script that does what you want I think. Check it out.

```
public class OrientTowardsDirection : MonoBehaviour {

    Vector3 prevLoc = Vector3.zero;
    Vector3 moveDirection = Vector3.zero;
    public Transform cube;
    private float MaxTurnSpeed = 100;
 void Start()
    {
     //code for simply moving the camera was here but was removed as per requested from Op.
    }
    void Update () {

        Orient();
    }
    void Orient()
    {
         moveDirection = transform.TransformDirection(moveDirection);// Turns the direction from local to world space
         moveDirection = (transform.position - prevLoc);// calculate direction vector;
         Quaternion wanted_rotation = Quaternion.LookRotation(moveDirection);//create the rotation
         transform.rotation = Quaternion.RotateTowards(transform.rotation, wanted_rotation,MaxTurnSpeed* Time.deltaTime);// apply the rotation with a max turn speed so its smooth
         prevLoc = transform.position;// change our prev pos.
    }
}

```

Explanations are comments in the code.

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


# Question
Title: Problem with Quaternions and Unity's Euler Angle Convention
So I want to rotate an UI-Element according to my magneticHeading, I just want to apply the magnetic heading to the z rotation in EulerAngles. So I tried to do so, which brought me to some weird rotations, then I tried this :

`transform.rotation = Quaternion.Euler(transform.rotation.z, transform.rotation.x, transform.rotation.y);`

Which also lead to some weird rotation, but I don't understand why, since in my understanding this should actually do nothing to the rotation...

This:

`transform.rotation = transform.rotation;`

is working again, like I expected it and does nothing to the rotation.

Can someone explain me why the `Quaternion.Euler` stuff is not working and how I can fix my problem?

Solution :

```
    transform.Rotate(0, 0, -temp.z);
    transform.Rotate(0,0,Input.compass.magneticHeading);
    temp = transform.rotation.eulerAngles;

```

So I'm reseting the `Rotation` first and then set the z value to the `magneticHeading`, the reset with `Quaternion.identity` did not work for me, so I just subtracted the last value.

# Answer
Converting between a Quaternion (`transform.rotation`) and an Euler angle triplet is not possible the way you wrote it.

See the API http://docs.unity3d.com/ScriptReference/Transform-rotation.html for the meaning of the `transform.rotation` property.

If you want to double check or verify that your Euler angles are correct, you can convert them to a quaternion and then set them. Refer to https://en.wikipedia.org/wiki/Conversion\_between\_quaternions\_and\_Euler\_angles.
> 1 votes

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