# Question
Title: Using coroutines to instantiate larger GameObjects in Unity/C#
We are making a scroller type game for mobile platforms and we got pretty far (Beta is already out). Now we are adding some additional content and are starting to experience a noticable lag when starting the game. I know about coroutines, but never actually used them, so I was wandering if it's possible to use them to instantiate larger GameObjects (or groups of objects). This is the code we use at the moment to create bullets (this is just an example, I have more similar methods):

```
Func<string, Pool.Poolable> bulletCreator = x => { return Instantiate(Resources.Load<Pool.Poolable>(x)) as Pool.Poolable; };

```

and then we use this method to create a certain amount of bullets:

```
Bullets = new Pool(4, () => { return bulletCreator("Bullet"); });

```

This creates 4 bullets (it fits our game desing, the player is restricted to 4 bullets and can refill them with powerups). There are different types of bullets that we create with the same function, and we create them at the start, pool them, and then use them when they are needed.

Now this is one of the "heavier" methods, and I'm trying to find a way to speed it up. I tried something like this:

```
  IEnumerator CreateBullets()
  {
     Func<string, Pool.Poolable> bulletCreator = x => { return Instantiate(Resources.Load<Pool.Poolable>(x)) as Pool.Poolable; };
     Bullets = new Pool(4, () => { return bulletCreator("Bullet"); });
     yield return Bullets;
}

```

Bullets is a global private variable of type Pool. The problem we are having is that when we try to shoot, Unity trhows the Object not set to an instance error. Is what I'm trying possible, or is it like in the regular C# that no crossthread calls are allowed. If it's not possible, what are our options? I know we could probably make a short animation and run that in the coroutine while the main thread instantiates everything. Any advice is very welcome.

Thanks in advance.

# Answer
I have faced similar problem before. I am pretty sure that co routines won't help you reduce the lag. Multi threading will be a proper solution instead of co routines.

But apparently I didn't use either of them. My game had finite predefined pool objects. So instead of instantiating them, in the editor I made a parent game object named Pool and made all the bullets as children. All I did was, on Awake()

```
Bullet [] bullets = GetComponentsInChildren<Bullet>();

```

And referenced all the poolable objects into the array without any lag :)
> 3 votes

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


# Question
Title: UNITY3D - Orthographic Camera not render SHADER (2D GAME)
I have a problem with camera render, see the video please :) (note.: sorry for the music)

http://youtu.be/BB8rXIzIWVU

In Camera "Perspective", i can see the effect of shader:

In Camera "Orthographic", i not see the effect of shader: :(

I can do my shader is rendered from my perspective camera?

\[EDITED\]: The shader script:

```
Shader "Dvornik/Distort" {
Properties {
    _Refraction ("Refraction", Range (0.00, 100.0)) = 1.0
    _DistortTex ("Base (RGB)", 2D) = "transparent" {}
}

SubShader
{
    Tags { "RenderType"="Transparent" "Queue"="Overlay" }
    LOD 100

    GrabPass
    {

    }

CGPROGRAM
#pragma exclude_renderers gles

#pragma surface surf NoLighting
#pragma vertex vert

fixed4 LightingNoLighting(SurfaceOutput s, fixed3 lightDir, fixed atten)
    {
        fixed4 c;
        c.rgb = s.Albedo;
        c.a = s.Alpha;
        return c;
    }

sampler2D _GrabTexture : register(s0);
sampler2D _DistortTex : register(s2);
float _Refraction;

float4 _GrabTexture_TexelSize;

struct Input {
    float2 uv_DistortTex;
    float3 color;
    float3 worldRefl;
    float4 screenPos;
    INTERNAL_DATA
};

void vert (inout appdata_full v, out Input o) {
  UNITY_INITIALIZE_OUTPUT(Input,o);
  o.color = v.color;
}

void surf (Input IN, inout SurfaceOutput o)
{
    float3 distort = tex2D(_DistortTex, IN.uv_DistortTex) * IN.color.rgb;
    float2 offset = distort * _Refraction * _GrabTexture_TexelSize.xy;
    IN.screenPos.xy = offset * IN.screenPos.z + IN.screenPos.xy;
    float4 refrColor = tex2Dproj(_GrabTexture, IN.screenPos);
    o.Alpha = refrColor.a;
    o.Emission = refrColor.rgb;
}
ENDCG
}
FallBack "Diffuse"
}

```

This is a 2D game... How can I fix this?

# Answer
> 1 votes
You need to tweak the shader file. Most probably there will be calculations based on the z axis. You need to take out all the z axis consideration from the calculation.

For Example:-

```
o.pos.xy += offset * o.pos.z * _Outline;

```

Change to

```
o.pos.xy += offset * _Outline;

```

As every shader is different, I don't know if it will work for you, but it definitely fixed my problem :)

Edit :- You need to edit the following line of your shader

```
 IN.screenPos.xy = offset * IN.screenPos.z + IN.screenPos.xy;

```

to

```
 IN.screenPos.xy = offset + IN.screenPos.xy;

```

Hope this works out :)

---
Tags: unity, shaders, rendering, camera
---


# Question
Title: Water4Advance far view seems stale and plain
Hi How can I remove far clipping in Water4Advance so that it matches near view like following img?

Currently far view water seems plaine with no wave n bumps at all.

# Answer
> 2 votes
This can be due to Mip Maps as it blurs out the texture farther away from the camera. In 3D computer graphics, mipmaps are pre-calculated, optimized sequences of textures, each of which is a progressively lower resolution representation of the same image. They are intended to increase rendering speed and reduce aliasing artifacts.

Try to switch off "Generte MipMaps" option for all the texture / bump maps (in the import settings) which are used by the water.

---
Tags: unity
---


title: Export normal map from unity?

text:
# Question
Title: Export normal map from unity?
In unity I can create a normal map out of a black and white image (By changing the type to normal map and select create from grayscale) Im wondering if there is a way to export the normal map like it should look so I don't need to create it from grayscale when I use it in another project?

# Answer
There is a script available to get this job done. You can follow the instructions specified in the link given below :)

## ExportNormalmap

Or else you can check this online tool to get normal maps from images

http://cpetry.github.io/NormalMap-Online/
> 1 votes

---
Tags: unity, normal-mapping, export
---


title: Best 2d AI movement system

text:
# Question
Title: Best 2d AI movement system
I'm creating a top-down rpg (no tile-based) using libgdx. Now I need to make enemies move on map with obstacles. What is the best approach to realize that? *A\**(I think, if enemy see player, he should turn to *Pursue+Raycasting*, because A\* is bad for following moving targets) or just combining steering behaviors *Seek+Raycasting*?

# Answer
There is no 'best' solution to this problem. Ultimately you're going to have to find by trial and error something that gives the best tradeoff between performance and believable intelligence.

However if you want to use any sort of path finding algorithm you're going to need to subdivide your world in some way. Whether you go with tiles, polygonal zoning or way-point nodes, your path finding algorithm needs some sort of graph to traverse. Using simple steering behaviours without any path finding will result in your AI getting stuck behind obstacles.

For seeking targets over large distances I use Jump Point Search which is considerably faster than A\*, especially if your map has open areas.

For localized searching, such as aggro detection I use a simple Dijkstra algorithm. Unlike A\*, with Dijkstra you don't ask it to search for a specific end point, you instead describe the type of end point and it will find the closest for which there is a valid path.

For example, you might have a soldier class within your game and you want it to attack any enemies that come within a certain radius of the soldier. You can simply feed the Dijkstra algorithm only the tiles that are within the radius. You then tell it that the only valid end points are tiles which contain an enemy. This will cause the soldier to always move towards an enemy if it is within aggro range.

You can couple the above approach with Steering Behaviours / Boids. Do the Dijkstra scan as described, then once an enemy target is found, stop scanning and allow your soldier to follow the path. Once your soldier is quite close switch to following by Steering Behaviours. This will work most of the time but because Steering Behaviours are not a path finding algorithm your soldier will occasionally get stuck behind objects in crowded areas. To solve this you must keep track of the distance to the enemy target. If the distance increases by X amount for Y seconds you know your soldier is likely stationary and the target is moving away from it. In this case, stop following with Steering Behaviours and perform another Dijkstra scan.
> 3 votes

# Answer
The way I have done it in the past is with A\*, but tweaked. Calculate the A\* path, but remove the last n waypoints from the path. Then when that point is reached, recalculate.

Only remove the last n waypoints if there are at lease n+m waypoints. Otherwise, send to target, and recalculate. Once there is only one way point, the calculation is minimal.

This prevents the need to constantly run the A\* algorithm. After doing this, tweak according to your specific game. A good starting point for n is 3.

An example of this approach can be seen at https://github.com/Evorlor/Outnumbered, which has 20ish entities chasing a moving target in a maze.
> 0 votes

---
Tags: java, algorithm, ai, movement, steering-behaviors
---


# Question
Title: Unity why do all gameobjects not dissapear from view when I switch cameras?
I am having trouble with camera switching. I have two cameras: "Camera1" and "Camera2". A "button script" attached to Camera1 allows a switch to Camera2. It also positions the cameras.

There is a gameobject called "Main Menu" that is meant to be a background image for the button ; it is a GUI texture background (a flat jpeg image) .

At game start, clicking the button causes "Camera" components to be enabled and disabled appropriately, and it changes the game view background. So the button works (sort of!). But my problem is that the GUI texture does not disappear from game view, and nor does the button!

When I click the button, I want a complete change of game view, i.e., I want both the button and its GUI texture background to disappear from game view. But I am not getting that.

How can I make a GUI texture visible ONLY because it is in front of Camera1? How do I make the button visible ONLY when Camera1 is active?

Here is my button script:

```
      using UnityEngine;
      using System.Collections;
 public class PageButton : MonoBehaviour
 {
 public GameObject MainMenu ;
 public Camera cam1, cam2 ;
 void Start() {
 // position the Main Menu
     MainMenu = GameObject.Find("MainMenu");
     MainMenu.transform.position = new Vector3 (0, 0, 0);
 // Setup Camera1
     cam1 = GameObject.Find("Camera1" ).GetComponent<Camera>() as Camera;
     cam1.transform.position = new Vector3 (0, 0, -10);
     cam1.orthographic = true;
     cam1.orthographicSize = 5f;
     cam1.enabled = true;
 // Setup Camera2
     cam2 = GameObject.Find("Camera2" ).GetComponent<Camera>() as Camera;
     cam2.transform.position = new Vector3 (100, 100, 10);
     cam2.enabled = false;
     cam2.transform.Rotate(0,270,0, Space.World);
     cam2.orthographic = true;
     cam2.orthographicSize = 5f;
 }
 public void OnGUI()
 {
     if(GUI.Button(new Rect(580,340,20,20), ">")) {
         Debug.Log ("Button pressed");
         cam1.enabled = false;
         cam2.enabled = true;
     }
 } // end OnGUI()

 } // end PageButton

```

# Answer
GUI is actually rendered according to the screen view port and not according to the camera. In other words it is camera independent.

You can try having a 3D text view or sprite in order to achieve the desired functionality. There are lot of other options also . Try Unity 5 GUI system or check out the NGUI plugin for unity. If you still want to use the current approach then you can switch off the GUI by checking whether a camera is active.

```
public void OnGUI()
 {
     if(cam1.activeSelf)
     {
         if(GUI.Button(new Rect(580,340,20,20), ">")) {
            Debug.Log ("Button pressed");
            cam1.enabled = false;
            cam2.enabled = true;
         }
     }
 } // end OnGUI()

```
> 1 votes

---
Tags: unity, camera, gameobject, view
---


# Question
Title: How can I generate an infinite procedural road?
I'm currently trying to make a game where the player races others along an infinite, more-or-less straight, road.

By "more-or-less straight", I mean that the road goes straight ahead (the player can't turn their vehicle to face left or right), but there are bends in the road for them to pass through, as if they were switching from one lane to another on a highway.

There will also be different "areas" to race through (all on the same road), for example, deserts, jungles and over water.

And, finally, there will be gaps in the road for the player to jump over, as well as checkpoints every so often.

Starting with a seed, how can I generate the road ahead of the player as they race? I can't generate the entire road in advance (obviously), but each player needs to see the same thing at the same places along the track.

How can I do this?

# Answer
As you know, if you want to generate the road so that both players see the same thing, then you need to start from a common seed value.

If you always start generating the road from the beginning then you can just keep calling your random number generator and the values it produces should be consistent for both players at each step. (Assuming that both players' devices are using the same pseudo random number generator (PRNG), which is not always the case. You may need to provide your own PRNG to ensure that it's consistent for all players).

If you want to be able to resume from different points along the track, then you will need to be able to reseed the PRNG from that point and keep it consistent. You would do this by calculating a new seed at each section (whether you are resuming or not) by using the original seed plus some reproducible value such as distance traveled.

Eg. (pseudo-code)

```
levelSeed = 1234 // starting seed
distanceTraveled = 100 // keep track of this every frame

// update this prior to adding a new section, obstacle, enemy, etc
// each time the distance is different
rand.setSeed(levelSeed + distanceTravelled)

// example of picking a new trackSegment, after updating the seed value
trackSegment = trackTiles[rand.getInt(numTrackTiles)]

```
> 2 votes

---
Tags: procedural-generation, terrain
---


title: My intersect detector isn't working

text:
# Question
Title: My intersect detector isn't working
I'm trying to create rooms dynamically by creating them in random places and checking if they do overlap each other. The idea is that if the new room intersects with another one, it must be recreated so it doesn't intersect with anyone.

This is the room creating loop:

```
void GenerateBasicLevel(){
    roomsList = new List<Room> ();
    int initX = 0, initY = 0;
    for (int roomsCreated = 0; roomsCreated < 10; roomsCreated ++) {
        //Room size
        height = Random.Range (minSize, maxSize);
        width = Random.Range (minSize, maxSize);
        if(roomsCreated == 0){
            initX = 1;
            initY = 1;
        }else{
            bool loopBreaker = true;
            while(loopBreaker){
                initX = Random.Range(0,mapWidth);
                initY = Random.Range(0,mapHeight);
                foreach(Room r in roomsList){
                    loopBreaker = RoomIntersects(initX - 1, initX + width +1, initY - 1,initY + height + 1,r);
                    if(loopBreaker){
                        Debug.Log ("I do intersect");
                        break;
                    }
                }
            }
        }
        roomsList.Add(new Room(initX - 1,initX + width + 1,initY - 1,initY + height + 1,floorTiles,wallTile));

    }}

```

This is the Intersect checker function:

```
bool RoomIntersects(int x1, int x2, int y1, int y2, Room cR){
        if (x1 <= cR.x2 && x1 >= cR.x1 && y1 >= cR.y1 && y1 <= cR.y2)
            return true;
        else if (x2 <= cR.x2 && x2 >= cR.x1 && y1 >= cR.y1 && y1 <= cR.y2)
            return true;
        else if (x1 <= cR.x2 && x1 >= cR.x1 && y2 >= cR.y1 && y2 <= cR.y2)
            return true;
        else if (x2 <= cR.x2 && x2 >= cR.x1 && y2 >= cR.y1 && y2 <= cR.y2)
            return true;
        else
           return false;
    }

```

Rooms are objects with just 4 parameters: x1,x2,y1,y2.

This is my final result, overlaping rooms:

# Answer
> 2 votes
The problem is with your RoomIntersects() function. If no corner of the new room is within the existing room, then your function will return false. What about when only the edge of the room overlaps and crosses completely across the existing room? In your picture. I would expect that the rooms beneath the overlapping rooms are the ones that were added after the overlapping ones.

```
bool RoomIntersects(int x1, int x2, int y1, int y2, Room cR){
    // left-top corner of room1 is within room2
    if (x1 <= cR.x2 && x1 >= cR.x1 && y1 >= cR.y1 && y1 <= cR.y2)
        return true;
    // right-top corner of room1 is within room2
    else if (x2 <= cR.x2 && x2 >= cR.x1 && y1 >= cR.y1 && y1 <= cR.y2)
        return true;
    // left-bottom corner of room1 is within room2
    else if (x1 <= cR.x2 && x1 >= cR.x1 && y2 >= cR.y1 && y2 <= cR.y2)
        return true;
    // right-bottom corner of room1 is within room2
    else if (x2 <= cR.x2 && x2 >= cR.x1 && y2 >= cR.y1 && y2 <= cR.y2)
        return true;
    else
       return false;
}

```

Here is a simpler, more efficient way (and correct way) to write your box intersection test. This is called AABB (axis aligned bounding box) collision detection. You can do it the other way also (by testing for inclusion), but this is cleaner and actually faster since there are less tests that need to be done.

```
bool RoomIntersects(int x1, int x2, int y1, int y2, Room cR) {
    // test for exclusion instead of inclusion
    if (x1 >= cR.x2) return false; // room1.left edge is greater than room2.right edge
    if (x2 <= cR.x1) return false; // room1.right edge is less than room2.left edge
    if (y1 >= cR.y2) return false; // room1.top edge is greater than room2.bottom edge
    if (y2 <= cR.y1) return false; // room1.bottom edge is less than room2.top edge
    return true; // rooms are intersecting
}

```

---
Tags: c#, intersection
---


title: OpenGL 2D Depth Perception

text:
# Question
Title: OpenGL 2D Depth Perception
I have a 2D RPG game written in Java using LWJGL. All works fine, but at the moment I'm having trouble deciding what the best way to do depth perception is. So , for example, if the player goes in front of the tree/enemy (lower than the objects y-coordinate) then show the player in front), if the player goes behind the tree/enemy (higher than the objects specific y-coordinate), then show the player behind the object.

I have tried writing a block of code to deal with this, and it works quite well for the trees, but not for the enemies yet. Is there a simpler way of doing this in LWJGL that I'm missing?

# Answer
> 4 votes
I gather you are making an isometric 2D game? You could draw the background first, then sort all sprites (player, enemies, trees) by Y-coordinate and draw them in back-to-front order.

# Answer
> 2 votes
This is very similar to Eric's answer; just elaborated a bit more.

Firstly you should draw your background (graphics that do not obscure anything) first - so as an example this would be your grass, plants, sand etc.

Next you take your foreground (graphics that do obscure) in addition to your entities (player, enemies, etc.) and draw them from the top of the screen downwards. To do this you would essentially sort them according to their Y co-ordinate and then draw them from least to biggest.

In addition I would give each tile/entity a `YRenderOffset` field (that does not participate in the sorting) that would allow you to, for example, play havoc with the 'darkness' of a door so that it seems as though your character is walking through it: in this specific case the 'darkness' sprite would be physically located above where it appears (basically behind the house) with a `YRenderOffset` that corrects it back to where it should appear when rendered. You could invert this concept entirely by instead having a field called `YSortOffset` that would participate in the sorting and not the rendering.

The above two paragraphs can be rendered by the same code entirely. This gives rise to the concept of layers: so you would have the background and foreground layers and they would be rendered exactly the same way. You would then be able to add additional layers at some point in the future (a cloud layer?).

# Answer
> 0 votes
Correct me if I'm wrong, but the gist of your drawing routine is:

```
public void draw_frame() {
  draw_world();
  draw_character();
  draw_enemies();
}

```

You will need to make it a bit more sophistocated.

Two approaches come to mind:

(1) make everything drawable in your world a subclass of some base class DrawableThing, say. Give it x, y and z accessors. use z to set the height of the thing. To draw a frame, collect all of the drawable things into a great big array, sort the array by, say, z then y, and then draw them in order. Sorting in Y ensures that (I am assuming you a are using a sort of semi-overhead look like the style of games of the SNES era) when thing A is on the same "level" (z) as thing B but is above it (y), thing B probably needs to be drawn on top of thing A as it will overlap it in the view.

This could result in a big array to sort with a lot of objects, so if you can, group some of the objects together into chunks (the flat ground is a good candidate) that can be drawn in one go.

(2) Use opengl to draw in quasi-3d and let the GL take care of the layering for you: set up an isometric perspective projection that makes your world look the way you want it to, then turn on depth testing and draw everything with a Z coordinate for how high it should be. It may need to be tweaked a bit for certain objects depending on how you model your sprites/images, but it will work.

# Answer
> 0 votes
As stated previously, layering is done in LWJGL by drawing everything in a certain order. I'd like to add a little to the responses people have given to answer your specific question:

" if the player goes in front of the tree/enemy (lower than the objects y-coordinate) then show the player in front), if the player goes behind the tree/enemy (higher than the objects specific y-coordinate), then show the player behind the object"

As stated above, you'll want to draw using a method that does things in order of bottom to top.

I've been working on this issue myself for a while.

And I think I have a solution. You'll want to create a draw order for each entity (tree, enemy, player, etc).

The draw order will be given priority using the entity's Y-Value.

So We'll draw things at a greater Y Distance BEFORE those of a Lesser.

Remember that Y Distance starts at the top left then goes down as the Y value increases.

So if we have T= tree, and x= player then

if x is behind T, T will be drawn after x (ie, ontop of x)

and if x is in front of T, T will be drawn before x (ie, behind x)

To clarify, we'll draw things sort of like this.

* World();
* For(y= 0; y \< Grid.Size(); y++)
* DrawEntitiesByRow(y);

This is mostly what I'll be doing with an Isometric game I've been doing. Of course, there's more details because I have to draw the floor before the walls, and other things. This is all situational to your needs.

---
Tags: opengl, 2d, java, lwjgl
---


# Question
Title: How do I check if pressed on a text in pygame?
How do I check if pressed on a text?

This is how I draw the text:

```
# Full code on https://github.com/Zwengel/bunny-badgers
height = pygame.display.Info().current_h
font = pygame.font.Font("freesansbold.ttf", 24)
spText = "Single Player"
sp = font.render(spText, True, (0,0,0))
spRect = sp.get_rect()
spRect.centerx = screen.get_rect().centerx
spRect.centery = height/12*5
screen.blit(sp, spRect)

```

# Answer
> 1 votes
You can use pygame.Rect.collidepoint() to get that the text was clicked on. The documentation on the function is here.

Here is an example of how you can use the function to your desired effect:

```
mpos = pygame.mouse.get_pos() # Get mouse position
if spRect.collidepoint(mpos): # Check if position is in the rect
    # Code for what you wish the click to do

```

This code will check if you clicked on the desired rect object, and execute whatever code your heart desires.

I hope this helps. (:

---
Tags: python, pygame
---


title: Unity - Water Cube (to 2D game)

text:
# Question
Title: Unity - Water Cube (to 2D game)
I wonder if you can create a cube of water within the unity!

I'm starting to use the Unity, and took a sought as to whether there was already something like this ... but have not found any tutorial

The idea is to use the 3D feature of water and turn it into a 2D scenario:

As shown below:

For this result:

The idea would be to make the cube of the material is "water".

Its possible?

# Answer
> -1 votes
This is achievable , what you need is Unity water and some script to simulate buoyancy.

You can find the script in this link:- http://forum.unity3d.com/threads/buoyancy-script.72974/

Note:- You might also need to use some particles or mesh to fill the volume of the water. As unity water is restricted only to the surface and not the entire volume :)

# Answer
> -1 votes
It's definitely achievable. Having never attempted it or anything, or really even tried all I could find was this link. I'm hoping it'll help you, as I look forward to trying it.

---
Tags: unity, shaders, water, materials, cubemap
---


# Question
Title: How do 3d engines add textures to objects?
I was wondering how 3d engines like Unity or OpenGL added textures to objects.

Example:

How would Unity add this texture to the side the arrow is pointing to?

# Answer
This deserves a very broad answer because texturing is historically THE one big job of graphics renderers.

Put shortly, this happens during rasterization. Rasterization is a process in the rendering pipeline, where the graphic card generates pixels (fragments) from geometry and then passes it on to the next stage of the pipeline, the pixel (fragment) shader, where the texture is read from memory, mixed with some color operation and put into the output for the next stage of the pipeline to treat (output merging).

So more in depth, it goes like that: the artist is first responsible in this system, he designs the texture coordinates in the modeling software, called DCCT (digital content creation tool), a widely used example is Maya (Autodesk). In the case of the cube, you can imagine the UV being (0,0)(0,1)(1,1)(1,0) for one quad.
An exporter will take the format internal to maya and write to file (.fbx for example), then the game engine will read that format, maybe using fbx library, and load in the graphics card memory, using vertex buffer locking, `memcpy`, and unlock. The texture coordinates are part of the vertex buffer. Then same for the texture in a separate piece of code, and finally at least one shader has to be uploaded in the graphics card too. this shader will probably just declare that it reads the texture by declaring a "sampler" in the uniform list.

Later when the engine runs, for one frame, it will call "draw primitive" routine which triggers the graphic card to run the pipeline.
This pipeline starts by fetching vertex data from the bound vertex stream (the one we uploaded before), then it goes into primitive assembly stage, which makes batches to create triangles. Then it undergoes transformation from 3d to 2d in the vertex shader. And this is when the rasterizer comes in. The rasterizer is a fully 2d process, which knows the resolution of the render target, and it takes the projected coordinate (given by vertex shader stage before) and puts them on their place on screen. this gives 3 points hopefully (there are details such as degenerated forms and clipping we can omit for now). The rasterizer will emit fragments by scanning the whole void between those 3 points, the hardware scheduler takes each emitted fragment by batch of 2x2 and distributes it to a free shader core. The shader core, will execute the pixel shader with some function parameter given by the rasterizer. These are the `varying` variables. They are called varying because they vary between the 3 vertices, usually linarly in 3d space, which means "perspective corrected" in 2d space. The varyings comprise the UV coordinates, therefore the pixel shader knows what texel to fetch in the texture to put at this pixel location. (the pixel pos is the `SV_screenPos` stuff determined at the time of fragment emission; one shader core executes code for a fixed screen position).

So what happens in a texturing shader is that the shader code will call `tex2d` intrinsic to require the texture unit to give a texel at the UV read from the vertex stream and interpolated by the rasterizer. The texture unit is responsible for executing filtering too, the UV are in floating point format so the actual point in the texture is usually not exactly the center of a texel, that is why it gets filtered by interpolating between neighbor pixels. There are multiple kinds of filtering, magnification, minification, and inter-mipmap.
Finally the result of the `tex2d` is the color of the texel, so the pixel shader just has to copy it to output, it can do more if it wants, like apply lighting.

At this point this is done basically, the output of the pixel shader is written to the render target by the ROPs, if some other geometry is not drawn over this later (other objects coming in front), this is what you will see at this pixel in the end, when swapping buffers (`present`).

EDIT:
additional paragraph about texture storage, a texture is a byte array, each pixel is stored in a 3x8 bits zone, or 4x8 bits for texture containing transparency. Same truth for an image file on disk. When the texture is loaded from file to memory, it is just a long flat series of bytes to which you can access one pixel using `p=width*y+x` formula. Which means the layout is "line by line, scanning horizontally to the right". In the graphic card however, the internal storage is a Z-curve (morton code), which is mandated by the need of vertical cache locality.
> 2 votes

# Answer
The procedure is called UV Mapping or Coordinates. Here's a good tutorial for OpenGL:

http://www.opengl-tutorial.org/beginners-tutorials/tutorial-5-a-textured-cube/
> 0 votes

---
Tags: 3d, textures
---


title: get back unity default interface

text:
# Question
Title: get back unity default interface
i installed unity recently .and interface of unity looks like that \[see the image\] in all tutorials i see on the internet.

but this is my one(I'm not in the game tab I'm in the scene tab)it's look like brown and i don't like it.i want default interface the interface in first pic which is black .how can i get black interface back ?

# Answer
Follow these steps

* Select the main camera
* Locate clear flag option in the inspector
* Change the value from "Skybox" to "Solid Color"

Also

* Go to Window \> lighting
* Scene tab
* Skybox \> change from "Default-Skybox" to "None"
> 1 votes

# Answer
Try enabling or disabling effects tab above the scene view.
> 0 votes

---
Tags: unity
---


title: Animation impulse system?

text:
# Question
Title: Animation impulse system?
I'm working on an animation system for an RTS game. Each unit has several animation states: Move, Idle, Engaging, etc.. Units also have a variety of "Animation Impulses" which are animations that get played on top of the animation state. They're for things like shooting or casting a spell. When the impulse finishes, the unit returns to its current animation state.

Using Unity Mecanim Animators, how can I make a system like this? Is there a way to PlayOneShot an impulse animation that reverts back to a base animation when the impulse finishes?

I.e. a unit is in the state of pointing his gun at the target. The unit fires its gun and acts out the recoil. After the recoil animation finishes, the unit returns to pointing its gun at the target.

# Answer
> 1 votes
Reverted to UnityEngine.Animation. Works like a charm and has no performance hits.

# Answer
> 1 votes
You can use Mecanim "Triggers" to start the Shoot animation state. The trigger will reset itself to false in the next frame, so the shoot animation will play only once. Then from shoot animation make transition back to idle pointing gun state and the condition should be exit time.

Example :-

---
Tags: unity, animation, mecanim
---


# Question
Title: How do I prevent raycast car wheels sliding sideways?
I've been writing a non-realistic car physics engine as a learning exercise, using this article as a reference.

I have a car that correctly collides with a terrain and applies the correct suspension forces for each wheel. My next problem is to prevent lateral movement of the wheels. For example, if I drop my car on a slope, it will slide sideways down the slope and then never stop sliding sideways (as there is no friction of any kind).

The linked article says that a "side force" must be applied, combined with the forward force, but it glosses over how that side force is calculated.

Given the collision info for each wheel (intersection normal, etc.) and the information about the car's rigid body, how can I calculate the appropriate side force to apply to the rigid body to prevent sideways motion?

# Answer
Andon's answer didn't quite give me solution, but it definitely put me on the right track!

Once I began thinking of the wheels being on their own plane (the normal of which being the vector sticking out from the centre - I'll refer to this as the wheel's "normal") I realized the side force is just the vector required to 'push' the car's velocity onto this plane. This vector is simply the wheel's "normal" multiplied by a scalar which is the dot product between the velocity and the "normal".

Here's the code that I settled on which works perfectly:

```
            // Now calculate the side force. Get the linear velocity
            auto vel = car->body()->linear_velocity();
            auto side_force = car->wheel_right_axis(i, closest_normal);

            // Find the length of the vector necessary to nullify the horizontal movement
            auto dot = kmVec3Dot(&vel, &side_force);

            // Scale the right vector to that length
            kmVec3Scale(&side_force, &side_force, -dot);

```

In the above code, "closest\_normal" is the normal of the terrain the wheel collided with which is used as an 'up' vector when calculating the wheel's "normal".
> 7 votes

# Answer
That side force is the horizontal component of the road's normal with respect to the car's forward movement. Roads are banked like you are discussing to facilitate cornering at higher speeds without flying off the track from momentum pushing them to the outside corner. The banking pushes back in a direction the tires do not freely rotate and can hopefully resist; if the banking were steep enough, center of gravity high enough or speed slow enough, the car itself would act as a wheel and simply roll over.

Tires have a limited range of steering. Forces acting perpendicular to the longitudinal axis (front to rear) are resisted in-part because tires will not rotate that way. You can compute the force acting sideways against the road from gravity and forward velocity and then calculate the remaining force after the tire scrubs some of this friction off. If the remaining force is great enough to overcome the force pushing the car into the road, the car will slide/skid.

### The following illustrates this and is discussed here *(with and without friction)*:

The force acting horizontally is of particular interest here. At rest (only force acting upon it is due to gravity), the car is not going to slide down a slope running perpendicular unless the coefficient of friction is exceptionally low (*e.g.* an icy road).
> 10 votes

---
Tags: collision-detection, physics, 3d, vehicle
---


# Question
Title: BoxCollider not blocking other object(s)
I'm really newbie , watched about 20 videos about and tried to do something. But I still have problems with collisions.

I'm working on 2D. I have a Sprite and a Cube (GameObject\>3D Object\>Cube). sprite is moving to a random position on screen and when it arrived to that position it's moving to another random position. It's going on like this forever. But when sprite hit to cube, it should change direction (when collision occured) , but instead it's passing through it.

Sprite has these components:

Cube has these components:

BallControl Script

```
public class Move : MonoBehaviour {

    public float moveSpeed = 3f;
    private Transform tf;
    Vector3 mousePosition;
    bool isMoving=false;
    void Start()
    {
        tf = GetComponent<Transform> ();
    }

    void Update ()
    {
        if(!isMoving) // Find a new position to move
            walkToRandomPosition();
        if(isMoving) // If we already found a position to move
            transform.position = Vector3.MoveTowards(transform.position, mousePosition, moveSpeed * Time.deltaTime);
        if (transform.position == mousePosition)
        { // Stop
            isMoving = false;
        }
    }

    void walkToRandomPosition()
    {
        mousePosition = Camera.main.ScreenToWorldPoint(new Vector3(Random.Range(0,Screen.width), Random.Range(0,Screen.height), Camera.main.farClipPlane/2));
        mousePosition.z = 0f; // Because we are working on 2D
        isMoving=true;
    }
}

```

Can you tell me why cube's Box Collider not blocking sprite? Should i add something like this to my BallControl script?

```
 void OnCollisionEnter2D(...)
 {
      // Change direction (find new position)
 }

```

**UPDATE 1**

Just add a new sprite and gave BoxCollider2D , now collision working as expected. But it's still not working with 3D cubes.

# Answer
If your sprite has a 2d collider you want to replace the cubes collider with a 2d as well.
> 2 votes

# Answer
Hey your ball's rigid body has isKinematic true , you need to uncheck it so that the rigidbody starts colliding with other colliders.

If isKinematic is enabled, Forces, collisions or joints will not affect the rigidbody anymore. The rigidbody will be under full control of animation or script control by changing transform.position. Kinematic bodies also affect the motion of other rigidbodies through collisions or joints. Eg. can connect a kinematic rigidbody to a normal rigidbody with a joint and the rigidbody will be constrained with the motion of the kinematic body. Kinematic rigidbodies are also particularly useful for making characters which are normally driven by an animation, but on certain events can be quickly turned into a ragdoll by setting isKinematic to false.
> 1 votes

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


title: Android TV game development

text:
# Question
Title: Android TV game development
Anybody develop games for Android TV? Especially with libGDX?

I would like to know what game controllers Android TV uses? And whether we can use libGDX to control the game controllers?

# Answer
Possible? Obviously. http://www.android.com/tv/ showcases a few games that are available. I assume that they are using the same channels that they would use to make a game for a phone or a tablet, based on the pictures and a little familiarity with the SDK.

Although I don't use libGDX that much, I assume that because it rides on the Android SDK, it shouldn't be too hard to tweak your game for TV.

Also, I assume that any game controllers you can use with Android you can use on the TV.
> 1 votes

---
Tags: android, libgdx
---


title: Movement through forces and impulses

text:
# Question
Title: Movement through forces and impulses
I'm trying to get some decent-looking movement in my game using this tutorial. In the image below... something crazy is going on. What should happen is that the NPC should start on the left side of the screen (he does), face towards the end of the black line (he does not) and then walk towards it (definitely does not).

You can't see if in the GIF, but the original angle of his body is 0 (pointing upwards), so he should smoothly rotate to the right and walk towards his target.

Here's my messy code:

```
#define DEGTORAD 0.0174532925199432957f
#define RADTODEG 57.295779513082320876f

void AiSystem::steerToNextNode(ComponentEntity *npc, QSharedPointer<Action> action) const
{
    Path *path = action->path();
    Q_ASSERT(!path->isEmpty());

    QSharedPointer<PhysicsComponent> npcPhysics = npc->component<PhysicsComponent>();
    Box2dBody *npcBody = npcPhysics->body();
    QSharedPointer<PathNode> nextNode = path->front();

    if (!isNextToTargetPos(npc, nextNode->pos())) {
        float desiredAngle = Geometry::directionTo(npcBody->getWorldCenter(), nextNode->pos());
        desiredAngle = qDegreesToRadians(desiredAngle);
        float nextAngle = npcBody->body()->GetAngle() + npcBody->body()->GetAngularVelocity() / 60.0;
        float totalRotation = desiredAngle - nextAngle;
        while ( totalRotation < -180 * DEGTORAD ) totalRotation += 360 * DEGTORAD;
        while ( totalRotation >  180 * DEGTORAD ) totalRotation -= 360 * DEGTORAD;
        float desiredAngularVelocity = totalRotation * 60;
        float change = 10 * DEGTORAD; //allow 10 degree rotation per time step
        desiredAngularVelocity = qMin( change, qMax(-change, desiredAngularVelocity));
        float impulse = npcBody->body()->GetInertia() * desiredAngularVelocity;
        npcBody->body()->ApplyAngularImpulse(impulse, true);

        qDebug() << "angle =" << npcBody->body()->GetAngle() << "desiredAngle =" << desiredAngle << "impulse =" << impulse;

        PhysicsSystem::moveForward(npcPhysics);

#ifdef VISUAL_AI_SYSTEM_DEBUG
        mFacingIndicator->setLine(QLineF(npcBody->getWorldCenter(), nextNode->pos()));
#endif
    } else {
        qCDebug(AI_MOVEMENT_DEBUG) << "We're at the next node (" << npcBody->getWorldCenter() << "," << nextNode->pos() << ")";
        // At the next node.
        path->popFront();

        if (path->isEmpty()) {
            qCDebug(AI_MOVEMENT_DEBUG) << "I've finished moving... completed requisite.";
            npc->component<AiComponent>()->primaryAction()->completeNextRequisite();
        }
    }
}

```

`AiSystem::steerToNextNode()` gets called every game step.

`PhysicsSystem::moveForward()` just applies a force in the direction the NPC should go:

```
void PhysicsSystem::moveForward(QSharedPointer<PhysicsComponent> physicsComponent)
{
    float32 force = stupidForce(physicsComponent->body()->getMass());
    float rotation = physicsComponent->body()->rotation();
    QPointF directionVector = Geometry::directionVector(rotation);
    physicsComponent->body()->applyForce(directionVector * force, physicsComponent->body()->position());
}

```

I've included some debug output as well (the first column is `seconds`:`milliseconds`):

```
38:905 angle = 0 desiredAngle = 1.5708 impulse = 0.320723
38:905 angle = 0.00268855 desiredAngle = 1.5708 impulse = 0.320723
38:905 angle = 0.00707863 desiredAngle = 1.57086 impulse = 0.320723
38:905 angle = 0.0121143 desiredAngle = 1.57108 impulse = 0.320723
38:905 angle = 0.0172392 desiredAngle = 1.57156 impulse = 0.320723
38:905 angle = 0.0225657 desiredAngle = 1.57236 impulse = 0.320723
38:905 angle = 0.0288589 desiredAngle = 1.57352 impulse = 0.320723
38:912 angle = 0.0377198 desiredAngle = 1.57504 impulse = 0.320723
38:926 angle = 0.0522711 desiredAngle = 1.57684 impulse = 0.320723
38:935 angle = 0.0778547 desiredAngle = 1.57861 impulse = 0.320723
38:945 angle = 0.115431 desiredAngle = 1.5799 impulse = 0.320723
38:956 angle = 0.150862 desiredAngle = 1.58127 impulse = 0.320723
39:029 angle = 0.191038 desiredAngle = 1.58286 impulse = 0.320723
39:029 angle = 0.240995 desiredAngle = 1.58396 impulse = 0.320723
39:029 angle = 0.287684 desiredAngle = 1.58541 impulse = 0.320723
39:029 angle = 0.34548 desiredAngle = 1.58649 impulse = 0.320723
39:030 angle = 0.398631 desiredAngle = 1.58787 impulse = 0.320723
39:030 angle = 0.462286 desiredAngle = 1.58886 impulse = 0.320723
39:030 angle = 0.521839 desiredAngle = 1.59022 impulse = 0.320723
39:043 angle = 0.588865 desiredAngle = 1.59109 impulse = 0.320723
39:050 angle = 0.657489 desiredAngle = 1.59223 impulse = 0.320723
39:055 angle = 0.722711 desiredAngle = 1.5933 impulse = 0.320723
39:069 angle = 0.797178 desiredAngle = 1.5941 impulse = 0.320723
39:079 angle = 0.868241 desiredAngle = 1.59527 impulse = 0.320723
39:090 angle = 0.938824 desiredAngle = 1.59618 impulse = 0.320723
39:099 angle = 1.01775 desiredAngle = 1.59689 impulse = 0.320723
39:109 angle = 1.09329 desiredAngle = 1.59797 impulse = 0.320723
39:124 angle = 1.16575 desiredAngle = 1.59893 impulse = 0.320723
39:134 angle = 1.24696 desiredAngle = 1.59953 impulse = 0.320723
39:145 angle = 1.32854 desiredAngle = 1.6004 impulse = 0.320723
39:154 angle = 1.40323 desiredAngle = 1.60151 impulse = 0.320723
39:170 angle = 1.4826 desiredAngle = 1.60217 impulse = -0.320723
39:180 angle = 1.55267 desiredAngle = 1.60274 impulse = -0.320723
39:189 angle = 1.60119 desiredAngle = 1.60363 impulse = -0.320723
39:199 angle = 1.64469 desiredAngle = 1.60423 impulse = -0.320723
39:209 angle = 1.67114 desiredAngle = 1.6048 impulse = -0.320723
39:226 angle = 1.68165 desiredAngle = 1.60577 impulse = -0.320723
39:231 angle = 1.68143 desiredAngle = 1.60704 impulse = -0.320723
39:244 angle = 1.67134 desiredAngle = 1.6086 impulse = -0.320723
39:254 angle = 1.6487 desiredAngle = 1.6105 impulse = -0.0510629
39:264 angle = 1.62061 desiredAngle = 1.61242 impulse = 0.320723
39:274 angle = 1.60724 desiredAngle = 1.61384 impulse = 0.320723
39:289 angle = 1.6103 desiredAngle = 1.61484 impulse = -0.0613149
39:299 angle = 1.61847 desiredAngle = 1.6154 impulse = -0.320723
39:309 angle = 1.62292 desiredAngle = 1.61552 impulse = -0.320723
39:319 angle = 1.62243 desiredAngle = 1.61524 impulse = -0.320723
39:329 angle = 1.61763 desiredAngle = 1.61458 impulse = 0.320723

```

If I change the rotation to 1 degree per time step, I get the following:

This I can understand, since he's probably not turning quickly enough to move in the correct direction. But what's going on in the first case? What am I doing wrong here?

---

**Update:** As per Hedede's advice, I've corrected the `moveForward()` function to pass radians instead of degrees:

```
void PhysicsSystem::moveForward(QSharedPointer<PhysicsComponent> physicsComponent)
{
    float32 force = stupidForce(physicsComponent->body()->getMass());
    float rotation = physicsComponent->body()->rotation();
    QPointF directionVector = Geometry::directionVector(qDegreesToRadians(rotation));
    physicsComponent->body()->applyForce(directionVector * force, physicsComponent->body()->position());
}

```

My `directionVector()` function looks like this:

```
QPointF Geometry::directionVector(qreal angle)
{
    return QPointF(qCos(angle), qSin(angle));
}

```

Thanks for spotting that. Unfortunately, it still doesn't solve the problem:

I've included the output with the direction vector before `applyForce()` is called:

```
56:586 AiSystem::steerToNextNode: angle = 0 desiredAngle = 1.5708 impulse = 0.320723
56:586 PhysicsSystem::moveForward: QPointF(1,0)
56:587 AiSystem::steerToNextNode: angle = 0.00268855 desiredAngle = 1.5708 impulse = 0.320723
56:588 PhysicsSystem::moveForward: QPointF(0.999996,-0.00268855)
56:590 AiSystem::steerToNextNode: angle = 0.00780716 desiredAngle = 1.5708 impulse = 0.320723
56:591 PhysicsSystem::moveForward: QPointF(0.99997,-0.00780709)
56:593 AiSystem::steerToNextNode: angle = 0.0151082 desiredAngle = 1.5708 impulse = 0.320723
56:594 PhysicsSystem::moveForward: QPointF(0.999886,-0.0151076)
56:595 AiSystem::steerToNextNode: angle = 0.0243554 desiredAngle = 1.57081 impulse = 0.320723
56:597 PhysicsSystem::moveForward: QPointF(0.999703,-0.024353)
56:599 AiSystem::steerToNextNode: angle = 0.0353244 desiredAngle = 1.57083 impulse = 0.320723
56:599 PhysicsSystem::moveForward: QPointF(0.999376,-0.0353171)
56:602 AiSystem::steerToNextNode: angle = 0.0478028 desiredAngle = 1.57087 impulse = 0.320723
56:604 PhysicsSystem::moveForward: QPointF(0.998858,-0.0477846)
56:605 AiSystem::steerToNextNode: angle = 0.0615907 desiredAngle = 1.57092 impulse = 0.320723
56:608 PhysicsSystem::moveForward: QPointF(0.998104,-0.0615518)
56:611 AiSystem::steerToNextNode: angle = 0.0765009 desiredAngle = 1.57099 impulse = 0.320723
56:611 PhysicsSystem::moveForward: QPointF(0.997075,-0.0764263)
56:613 AiSystem::steerToNextNode: angle = 0.0923586 desiredAngle = 1.5711 impulse = 0.320723
56:613 PhysicsSystem::moveForward: QPointF(0.995738,-0.0922273)
56:615 AiSystem::steerToNextNode: angle = 0.109002 desiredAngle = 1.57124 impulse = 0.320723
56:617 PhysicsSystem::moveForward: QPointF(0.994065,-0.108786)
56:618 AiSystem::steerToNextNode: angle = 0.126281 desiredAngle = 1.57142 impulse = 0.320723
56:619 PhysicsSystem::moveForward: QPointF(0.992037,-0.125946)
56:621 AiSystem::steerToNextNode: angle = 0.14406 desiredAngle = 1.57164 impulse = 0.320723
56:622 PhysicsSystem::moveForward: QPointF(0.989641,-0.143562)
56:624 AiSystem::steerToNextNode: angle = 0.162212 desiredAngle = 1.57192 impulse = 0.320723
56:625 PhysicsSystem::moveForward: QPointF(0.986873,-0.161501)
56:626 AiSystem::steerToNextNode: angle = 0.180624 desiredAngle = 1.57225 impulse = 0.320723
56:628 PhysicsSystem::moveForward: QPointF(0.983732,-0.179643)
56:630 AiSystem::steerToNextNode: angle = 0.199194 desiredAngle = 1.57265 impulse = 0.320723
56:630 PhysicsSystem::moveForward: QPointF(0.980226,-0.197879)
56:632 AiSystem::steerToNextNode: angle = 0.21783 desiredAngle = 1.57312 impulse = 0.320723
56:634 PhysicsSystem::moveForward: QPointF(0.976369,-0.216112)
56:634 AiSystem::steerToNextNode: angle = 0.236451 desiredAngle = 1.57367 impulse = 0.320723
56:636 PhysicsSystem::moveForward: QPointF(0.972175,-0.234254)
56:638 AiSystem::steerToNextNode: angle = 0.254986 desiredAngle = 1.5743 impulse = 0.320723
56:638 PhysicsSystem::moveForward: QPointF(0.967667,-0.252231)
56:640 AiSystem::steerToNextNode: angle = 0.27337 desiredAngle = 1.57502 impulse = 0.320723
56:642 PhysicsSystem::moveForward: QPointF(0.962867,-0.269978)
56:642 AiSystem::steerToNextNode: angle = 0.291551 desiredAngle = 1.57583 impulse = 0.320723
56:644 PhysicsSystem::moveForward: QPointF(0.957799,-0.287438)
56:646 AiSystem::steerToNextNode: angle = 0.309481 desiredAngle = 1.57674 impulse = 0.320723
56:646 PhysicsSystem::moveForward: QPointF(0.952492,-0.304564)
56:648 AiSystem::steerToNextNode: angle = 0.327121 desiredAngle = 1.57775 impulse = 0.320723
56:650 PhysicsSystem::moveForward: QPointF(0.946971,-0.321318)
56:650 AiSystem::steerToNextNode: angle = 0.344439 desiredAngle = 1.57888 impulse = 0.320723
56:652 PhysicsSystem::moveForward: QPointF(0.941265,-0.337669)
56:654 AiSystem::steerToNextNode: angle = 0.361409 desiredAngle = 1.58012 impulse = 0.320723
56:654 PhysicsSystem::moveForward: QPointF(0.9354,-0.353592)
56:656 AiSystem::steerToNextNode: angle = 0.378008 desiredAngle = 1.58148 impulse = 0.320723
56:658 PhysicsSystem::moveForward: QPointF(0.929402,-0.36907)
56:677 AiSystem::steerToNextNode: angle = 0.394222 desiredAngle = 1.58296 impulse = 0.320723
56:677 PhysicsSystem::moveForward: QPointF(0.923296,-0.38409)
56:677 AiSystem::steerToNextNode: angle = 0.410038 desiredAngle = 1.58458 impulse = 0.320723
56:679 PhysicsSystem::moveForward: QPointF(0.917106,-0.398644)
56:681 AiSystem::steerToNextNode: angle = 0.425449 desiredAngle = 1.58633 impulse = 0.320723
56:683 PhysicsSystem::moveForward: QPointF(0.910853,-0.41273)
56:685 AiSystem::steerToNextNode: angle = 0.44045 desiredAngle = 1.58821 impulse = 0.320723
56:687 PhysicsSystem::moveForward: QPointF(0.90456,-0.426347)
56:689 AiSystem::steerToNextNode: angle = 0.455041 desiredAngle = 1.59024 impulse = 0.320723
56:690 PhysicsSystem::moveForward: QPointF(0.898243,-0.439499)
56:693 AiSystem::steerToNextNode: angle = 0.469222 desiredAngle = 1.59242 impulse = 0.320723
56:694 PhysicsSystem::moveForward: QPointF(0.89192,-0.452193)
56:696 AiSystem::steerToNextNode: angle = 0.482998 desiredAngle = 1.59475 impulse = 0.320723
56:698 PhysicsSystem::moveForward: QPointF(0.885606,-0.464436)
56:700 AiSystem::steerToNextNode: angle = 0.496374 desiredAngle = 1.59724 impulse = 0.320723
56:702 PhysicsSystem::moveForward: QPointF(0.879315,-0.476241)
56:704 AiSystem::steerToNextNode: angle = 0.509358 desiredAngle = 1.59988 impulse = 0.320723
56:706 PhysicsSystem::moveForward: QPointF(0.873058,-0.487617)
56:729 AiSystem::steerToNextNode: angle = 0.521959 desiredAngle = 1.60268 impulse = 0.320723
56:729 PhysicsSystem::moveForward: QPointF(0.866844,-0.498579)
56:730 AiSystem::steerToNextNode: angle = 0.534186 desiredAngle = 1.60566 impulse = 0.320723
56:732 PhysicsSystem::moveForward: QPointF(0.860684,-0.50914)
56:734 AiSystem::steerToNextNode: angle = 0.54605 desiredAngle = 1.6088 impulse = 0.320723
56:736 PhysicsSystem::moveForward: QPointF(0.854583,-0.519316)
56:738 AiSystem::steerToNextNode: angle = 0.557563 desiredAngle = 1.61211 impulse = 0.320723
56:739 PhysicsSystem::moveForward: QPointF(0.848547,-0.52912)
56:741 AiSystem::steerToNextNode: angle = 0.568738 desiredAngle = 1.61561 impulse = 0.320723
56:742 PhysicsSystem::moveForward: QPointF(0.842582,-0.538569)
56:755 AiSystem::steerToNextNode: angle = 0.579586 desiredAngle = 1.61928 impulse = 0.320723
56:755 PhysicsSystem::moveForward: QPointF(0.83669,-0.547677)
56:755 AiSystem::steerToNextNode: angle = 0.59012 desiredAngle = 1.62313 impulse = 0.320723
56:757 PhysicsSystem::moveForward: QPointF(0.830874,-0.556461)
56:759 AiSystem::steerToNextNode: angle = 0.600354 desiredAngle = 1.62717 impulse = 0.320723
56:761 PhysicsSystem::moveForward: QPointF(0.825136,-0.564935)
56:776 AiSystem::steerToNextNode: angle = 0.6103 desiredAngle = 1.6314 impulse = 0.320723
56:776 PhysicsSystem::moveForward: QPointF(0.819476,-0.573114)
56:777 AiSystem::steerToNextNode: angle = 0.619972 desiredAngle = 1.63582 impulse = 0.320723
56:778 PhysicsSystem::moveForward: QPointF(0.813895,-0.581012)
56:793 AiSystem::steerToNextNode: angle = 0.629382 desiredAngle = 1.64044 impulse = 0.320723
56:793 PhysicsSystem::moveForward: QPointF(0.808392,-0.588645)
56:794 AiSystem::steerToNextNode: angle = 0.638542 desiredAngle = 1.64526 impulse = 0.320723
56:796 PhysicsSystem::moveForward: QPointF(0.802966,-0.596025)
56:803 AiSystem::steerToNextNode: angle = 0.647466 desiredAngle = 1.65028 impulse = 0.320723
56:803 PhysicsSystem::moveForward: QPointF(0.797615,-0.603167)
56:813 AiSystem::steerToNextNode: angle = 0.656165 desiredAngle = 1.6555 impulse = 0.320723
56:813 PhysicsSystem::moveForward: QPointF(0.792338,-0.610082)
56:828 AiSystem::steerToNextNode: angle = 0.664651 desiredAngle = 1.66093 impulse = 0.320723
56:828 PhysicsSystem::moveForward: QPointF(0.787132,-0.616784)
56:841 AiSystem::steerToNextNode: angle = 0.672936 desiredAngle = 1.66656 impulse = 0.320723
56:841 PhysicsSystem::moveForward: QPointF(0.781995,-0.623284)
56:848 AiSystem::steerToNextNode: angle = 0.68103 desiredAngle = 1.67241 impulse = 0.320723
56:848 PhysicsSystem::moveForward: QPointF(0.776925,-0.629594)
56:858 AiSystem::steerToNextNode: angle = 0.688945 desiredAngle = 1.67848 impulse = 0.320723
56:858 PhysicsSystem::moveForward: QPointF(0.771917,-0.635723)
56:873 AiSystem::steerToNextNode: angle = 0.696691 desiredAngle = 1.68476 impulse = 0.320723
56:873 PhysicsSystem::moveForward: QPointF(0.766969,-0.641684)
56:883 AiSystem::steerToNextNode: angle = 0.704279 desiredAngle = 1.69127 impulse = 0.320723
56:883 PhysicsSystem::moveForward: QPointF(0.762079,-0.647484)
56:893 AiSystem::steerToNextNode: angle = 0.711716 desiredAngle = 1.69799 impulse = 0.320723
56:893 PhysicsSystem::moveForward: QPointF(0.757242,-0.653134)
56:908 AiSystem::steerToNextNode: angle = 0.719014 desiredAngle = 1.70494 impulse = 0.320723
56:909 PhysicsSystem::moveForward: QPointF(0.752455,-0.658643)
56:913 AiSystem::steerToNextNode: angle = 0.726181 desiredAngle = 1.71212 impulse = 0.320723
56:913 PhysicsSystem::moveForward: QPointF(0.747715,-0.664019)
56:925 AiSystem::steerToNextNode: angle = 0.733226 desiredAngle = 1.71953 impulse = 0.320723
56:925 PhysicsSystem::moveForward: QPointF(0.743019,-0.66927)
56:942 AiSystem::steerToNextNode: angle = 0.740156 desiredAngle = 1.72717 impulse = 0.320723
56:942 PhysicsSystem::moveForward: QPointF(0.738363,-0.674403)
56:959 AiSystem::steerToNextNode: angle = 0.74698 desiredAngle = 1.73504 impulse = 0.320723
56:959 PhysicsSystem::moveForward: QPointF(0.733744,-0.679426)
56:959 AiSystem::steerToNextNode: angle = 0.753706 desiredAngle = 1.74315 impulse = 0.320723
56:961 PhysicsSystem::moveForward: QPointF(0.729158,-0.684345)
56:975 AiSystem::steerToNextNode: angle = 0.760339 desiredAngle = 1.7515 impulse = 0.320723
56:975 PhysicsSystem::moveForward: QPointF(0.724602,-0.689167)
56:976 AiSystem::steerToNextNode: angle = 0.766888 desiredAngle = 1.76008 impulse = 0.320723
56:978 PhysicsSystem::moveForward: QPointF(0.720073,-0.693898)
56:992 AiSystem::steerToNextNode: angle = 0.773359 desiredAngle = 1.76891 impulse = 0.320723
56:992 PhysicsSystem::moveForward: QPointF(0.715568,-0.698543)
57:009 AiSystem::steerToNextNode: angle = 0.779759 desiredAngle = 1.77797 impulse = 0.320723
57:009 PhysicsSystem::moveForward: QPointF(0.711083,-0.703108)
57:009 AiSystem::steerToNextNode: angle = 0.786093 desiredAngle = 1.78728 impulse = 0.320723
57:011 PhysicsSystem::moveForward: QPointF(0.706616,-0.707598)
57:025 AiSystem::steerToNextNode: angle = 0.792367 desiredAngle = 1.79684 impulse = 0.320723
57:025 PhysicsSystem::moveForward: QPointF(0.702162,-0.712017)
57:028 AiSystem::steerToNextNode: angle = 0.798587 desiredAngle = 1.80664 impulse = 0.320723
57:028 PhysicsSystem::moveForward: QPointF(0.69772,-0.716371)
57:042 AiSystem::steerToNextNode: angle = 0.804758 desiredAngle = 1.81668 impulse = 0.320723
57:042 PhysicsSystem::moveForward: QPointF(0.693286,-0.720663)
57:059 AiSystem::steerToNextNode: angle = 0.810886 desiredAngle = 1.82697 impulse = 0.320723
57:059 PhysicsSystem::moveForward: QPointF(0.688857,-0.724898)
57:075 AiSystem::steerToNextNode: angle = 0.816975 desiredAngle = 1.8375 impulse = 0.320723
57:075 PhysicsSystem::moveForward: QPointF(0.68443,-0.729079)
57:076 AiSystem::steerToNextNode: angle = 0.82303 desiredAngle = 1.84828 impulse = 0.320723
57:078 PhysicsSystem::moveForward: QPointF(0.680002,-0.73321)
57:092 AiSystem::steerToNextNode: angle = 0.829057 desiredAngle = 1.8593 impulse = 0.320723
57:092 PhysicsSystem::moveForward: QPointF(0.675572,-0.737294)
57:093 AiSystem::steerToNextNode: angle = 0.835058 desiredAngle = 1.87056 impulse = 0.320723
57:095 PhysicsSystem::moveForward: QPointF(0.671134,-0.741336)
57:108 AiSystem::steerToNextNode: angle = 0.84104 desiredAngle = 1.88207 impulse = 0.320723
57:109 PhysicsSystem::moveForward: QPointF(0.666688,-0.745337)
57:113 AiSystem::steerToNextNode: angle = 0.847005 desiredAngle = 1.89381 impulse = 0.320723
57:113 PhysicsSystem::moveForward: QPointF(0.66223,-0.7493)
57:125 AiSystem::steerToNextNode: angle = 0.852958 desiredAngle = 1.90579 impulse = 0.320723
57:125 PhysicsSystem::moveForward: QPointF(0.657758,-0.753229)
57:142 AiSystem::steerToNextNode: angle = 0.858903 desiredAngle = 1.918 impulse = 0.320723
57:142 PhysicsSystem::moveForward: QPointF(0.653269,-0.757126)
57:158 AiSystem::steerToNextNode: angle = 0.864843 desiredAngle = 1.93044 impulse = 0.320723
57:159 PhysicsSystem::moveForward: QPointF(0.648759,-0.760994)
57:159 AiSystem::steerToNextNode: angle = 0.870783 desiredAngle = 1.94311 impulse = 0.320723

```

# Answer
> 1 votes
It looks to me like the original rotation towards the end of the black line was working. It's just a bit slow.

What's weird is the movement. It looks like the force in the first one is in the wrong direction (accelerating backwards), and there's a weird wobble, too, like the force may be alternating forward and back between frames. I would start by trying reversing DirectionVector. It might (also?) be a rads to degrees problem, as Hedede suggested - that could cause random-looking wobble like that (i.e. if you are passing in degrees when it thinks you mean rads, that will mean instead of a few degrees you get a nearly random direction applied to the momentum).

The second one may be turning a really slow 1 degree per frame, which doesn't do much, and of course for some reason he has momentum down and to the right.

Even if you get forward force going the right direction in the original case, though, I think it's going to be quite weird because you have him turning and accelerating at the same time, even when he's facing mostly away from his target, and he doesn't turn very fast, and with the inertia he has, he's going to look like a newbie Asteroids player spiraling around out of control. People tend not to go sideways a lot, and they tend to stop and turn to face roughly where they're going before going forward. So if you want it to look good, you probably want at least two or three states with different behavior, such as:

(Don't run sideways or backwards): If your sideways component of velocity relative to your facing is greater than your forward velocity, slow down quickly. If your backwards velocity is higher than about 1/2 maximum running speed, slow down. (To slow down, you can just multiply momentum by a fraction less than 1 - start with .5 and adjust to taste.)

(If you're not facing the target, turn and slow down): If abs(angle to target off forward) is greater than about 30 degrees, turn towards target and slow down.

(If you are facing the target, speed up): If the above cases are not true, accelerate towards the target, not to exceed the desired max speed.

Edit: In comments and chat, we found that there were several issues to sort out:

1) As Hedede thought, the direction to target was passing degrees where rads were expected, resulting in unpredictable jerky motion.

2) The sprite image was 90 degrees off from intended.

3) The calculation of the direction to target was wrong - it needed -1 * on the Y component before passing into arctan2().

4) It looks like we finally got it working for the AI, but now the resulting turn is slow in effect sometimes (right after reaching the first waypoint), even though the "impulse" from the AI is a constant full left turn.

That is, we got it to do this: animated GIF showing final motion

# Answer
> 2 votes
Your NPC seems to be turning towards the desired angle as it supposed to do, but slowly. Try increasing rotation speed.

Judging by the movement pattern, I think that you are passing degrees to a function which takes radians, or vice versa.

I think the problem is here:

```
    float rotation = physicsComponent->body()->rotation();
    QPointF directionVector = Geometry::directionVector(rotation);

```

I might be wrong about the cause, but I think the problem is with incorrectly applied force.

---
Tags: box2d, qt
---


title: Dual paraboloid shadows on GLSL

text:
# Question
Title: Dual paraboloid shadows on GLSL
I'm trying to port an XNA example to OpenTK + OpenGL, I found it here http://graphicsrunner.blogspot.com.es/2008/07/dual-paraboloid-shadow-maps.html

But I'm having a really hard time, I think my maps are generated right, but then the shadowing of the objects gets really weird, it's like some axes are inverted, when the light is under the shadow receiver plane it shows the shadows but they're also displaced.

I believe the shader code is right and the problem is setting up the matrices but I'm really lost, I've tried everything that came to my mind but with no luck.

Here are the two maps, they will look dark or weird because I'm using RGBA textures and pack the depth in them, so the data is right and the position looks okay:

https://i.stack.imgur.com/PEtYV.png

https://i.stack.imgur.com/ISdMW.png

Let's start with the code.

First the light view, I set it up like this:

```
lightView =
Matrix4.LookAt(light.lightPosition, light.lightPosition - Vector3.UnitZ, Vector3.UnitY);

```

To the map creation shader I pass the object's world multiplied with the light view.

This is the vertex shader for the map creation:

```
#version 120

uniform mat4 worldView;
uniform float direction;

attribute vec3 position; //usage:position
attribute vec3 normal; //usage:normal

varying highp vec2 depth;

varying float clip;

const float near = 0.1f;
const float far = 1000.0f;

void main()
{

    highp vec4 pos4 = worldView * vec4(position, 1);

    pos4 = pos4 / pos4.w;
    pos4.z = pos4.z * direction;

    highp float L = length(pos4.xyz);
    pos4 = pos4 / L;

    clip = pos4.z;
    pos4.z = pos4.z + 1;

    pos4.x = pos4.x / pos4.z;
    pos4.y = pos4.y / pos4.z;

    pos4.z = (L - near) / (far - near);
    pos4.w = 1;

    depth = pos4.zw;

    gl_Position = pos4;

}

```

And this is the fragment shader:

```
 #version 120

varying highp vec2 depth;
varying float clip;

vec4 mapDepthToARGB32(float value)
{
    const vec4 bitSh = vec4(256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0);
    const vec4 mask = vec4(0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0);
    highp vec4 res = fract(value * bitSh);
    res -= res.xxyz * mask;
    return res;
}

void main()
{

    if(clip < 0)
        discard;

    float finalDepth = depth.x / depth.y;
    gl_FragColor = mapDepthToARGB32(finalDepth); //vec4(depth.y, depth.y, depth.y, 1.0f);

}

```

Next, to render the shadows I pass the light view matrix and the object's world matrix to the shader unmultiplied.

Here is the vertex shader (it includes multitexturing as I'm expanding a terrain shader I already have working)

```
#version 120

uniform highp vec3 lightPosition;

uniform mat4 worldViewProjection;
uniform mat4 world;

attribute vec3 position; //usage:position
attribute vec2 uv; //usage:uv
attribute vec3 normal; //usage:normal

varying highp vec3 faceNormal;
varying highp vec3 lightNormal;
varying highp vec2 finalUv;
varying highp vec3 pos;

void main()
{

    vec4 pos4 = vec4(position, 1);
    pos = (world * pos4).xyz;

    gl_Position = worldViewProjection * pos4;

    lightNormal = lightPosition - pos;
    faceNormal = (world * vec4(normal , 0)).xyz;

    finalUv = uv;

}

```

And finally the fragment shader:

```
#version 120

uniform highp vec3 lightColor;
uniform highp vec3 ambientColor;

uniform mat4 lightView;

uniform highp float uvMultiplier;

uniform sampler2D colorTexture1;
uniform sampler2D colorTexture2;
uniform sampler2D colorTexture3;

uniform sampler2D weightTexture;

uniform sampler2D frontShadowMap;
uniform sampler2D backShadowMap;

varying highp vec3 faceNormal;
varying highp vec3 lightNormal;
varying highp vec2 finalUv;
varying highp vec3 pos;

const float SHADOW_EPSILON = 0.00005f;

float getDepthFromARGB32(vec4 value)
{
    const vec4 bitSh = vec4(1.0 / (256.0 * 256.0 * 256.0), 1.0 / (256.0 * 256.0), 1.0 / 256.0, 1.0);
    return(dot(value, bitSh));
}

const float near = 0.1f;
const float far = 1000;

void main()
{

    highp float factor = clamp(dot(normalize(lightNormal), normalize(faceNormal)), 0.0, 1.0);

    highp vec3 finalColor = vec3(0,0,0);

    lowp vec4 weights = texture2D(weightTexture, finalUv);

    finalColor += texture2D(colorTexture1, finalUv * uvMultiplier).xyz * weights.x;
    finalColor += texture2D(colorTexture2, finalUv * uvMultiplier).xyz * weights.y;
    finalColor += texture2D(colorTexture3, finalUv * uvMultiplier).xyz * weights.z;

    finalColor = (finalColor * lightColor * factor) + (finalColor * ambientColor);

    highp vec3 vPosDP = (vec4(pos, 1) * lightView).xyz;

    float fLength = length(vPosDP);

     vPosDP /= fLength;

     float fDPDepth;
     float fSceneDepth;

     if(vPosDP.z >= 0.0f)
     {
         vec2 vTexFront;
         vTexFront.x =  (vPosDP.x /  (1.0f + vPosDP.z)) * 0.5f + 0.5f;
         vTexFront.y =  1.0f - ((vPosDP.y /  (1.0f + vPosDP.z)) * 0.5f + 0.5f);

         fSceneDepth = (fLength - near) / (far - near);

         fDPDepth = getDepthFromARGB32(texture2D(frontShadowMap, vTexFront));
     }
     else
     {
         // for the back the z has to be inverted
         vec2 vTexBack;
         vTexBack.x =  (vPosDP.x /  (1.0f - vPosDP.z)) * 0.5f + 0.5f;
         vTexBack.y =  1.0f - ((vPosDP.y /  (1.0f - vPosDP.z)) * 0.5f + 0.5f);

         fSceneDepth = (fLength - near) / (far - near);

         fDPDepth = getDepthFromARGB32(texture2D(backShadowMap, vTexBack));
     }

    if((fDPDepth + SHADOW_EPSILON) < fSceneDepth)
        finalColor = finalColor * 0.3f;

    gl_FragColor = vec4(finalColor, 1);

}

```

I must say I'm packing the depth values into an RGBA texture because the devices I'm targeting don't support R32f nor R16f textures.

Any help would be really apreciated, and also, if someone knows of a working example on GLSL of the dual paraboloid shadow map I wold be really grateful, I searched for a fully working example a lot of time and the only ones I found are for DirectX.

**EDIT**:

Well, found a bug and the root of the problem.

First, the light view matrix multiplication is reversed, instead of

```
highp vec3 vPosDP = (vec4(pos, 1) * lightView).xyz;

```

it must be

```
highp vec3 vPosDP = (lightView * vec4(pos, 1)).xyz;

```

And the root of the problem, this code assumes the light is ALWAYS at 0,0,0, so, placing the light at 0,0,0 at first did not solved the problem, but as this code comes from DirectX and the operations are reversed, if instead of using pos we use -pos and place the light at 0,0,0 everything works, a nice shadows como to lofe :).

Now I'm struggling on how to apply the light displacement, adding it to the render shader did not work, the shadows got displaced, so I suppose I must modify also the map generation.

Any help will be welcomed. If I get it working will post an answer.

**EDIT 2**:

More advances, in my test scene had 8 shadow casters distributed equally around a center, I have changed it to be uneven and the shadows are exactly reversed.

I have checked the maps and they are exact to the ones generated by te example, so my lightView matrix and the map generation code must be OK, this leaves just a place to check and is the fragment shader.

# Answer
Finally got it working!!!

The problem indeed was in the fragment shader.

First of all, there was no need to invert the position, the error came from the UV coordinates.

Finally I remembered when I was using XNA the textures where flipped vertically respect to OpenGL, and that was the problem.

After flipping the V coordinate and correcting the reversed multiplication everything works as expected.

This is the final code for the fragment shader in case someone else needs it:

```
#version 120

uniform highp vec3 lightColor;
uniform highp vec3 ambientColor;
uniform highp mat4 lightView;
uniform highp float uvMultiplier;

uniform sampler2D colorTexture1;
uniform sampler2D colorTexture2;
uniform sampler2D colorTexture3;

uniform sampler2D weightTexture;

uniform sampler2D frontShadowMap;
uniform sampler2D backShadowMap;

varying highp vec3 faceNormal;
varying highp vec3 lightNormal;
varying highp vec2 finalUv;
varying highp vec3 pos;

const float SHADOW_EPSILON = 0.000005f;

float getDepthFromARGB32(vec4 value)
{
    const vec4 bitSh = vec4(1.0 / (256.0 * 256.0 * 256.0), 1.0 / (256.0 * 256.0), 1.0 / 256.0, 1.0);
    return(dot(value, bitSh));
}

const float near = 0.1f;
const float far = 1000;

void main()
{

    highp float factor = clamp(dot(normalize(lightNormal), normalize(faceNormal)), 0.0, 1.0);

    highp vec3 finalColor = vec3(0,0,0);

    lowp vec4 weights = texture2D(weightTexture, finalUv);

    finalColor += texture2D(colorTexture1, finalUv * uvMultiplier).xyz * weights.x;
    finalColor += texture2D(colorTexture2, finalUv * uvMultiplier).xyz * weights.y;
    finalColor += texture2D(colorTexture3, finalUv * uvMultiplier).xyz * weights.z;

    finalColor = (finalColor * lightColor * factor) + (finalColor * ambientColor);

    highp vec3 vPosDP = (lightView * vec4(pos , 1)).xyz;

    float fLength = length(vPosDP);

        vPosDP /= fLength;

        float fDPDepth;
        float fSceneDepth;

        if(vPosDP.z >= 0.0f)
        {
            vec2 vTexFront;
            vTexFront.x =  ((vPosDP.x /  (1.0f + vPosDP.z)) * 0.5f + 0.5f);
            vTexFront.y =  ((vPosDP.y /  (1.0f + vPosDP.z)) * 0.5f + 0.5f);

            fSceneDepth = (fLength - near) / (far - near);

            fDPDepth = getDepthFromARGB32(texture2D(frontShadowMap, vTexFront));
        }
        else
        {
            // for the back the z has to be inverted
            vec2 vTexBack;
            vTexBack.x =  ((vPosDP.x /  (1.0f - vPosDP.z)) * 0.5f + 0.5f);
            vTexBack.y =  ((vPosDP.y /  (1.0f - vPosDP.z)) * 0.5f + 0.5f);

            fSceneDepth = (fLength - near) / (far - near);

            fDPDepth = getDepthFromARGB32(texture2D(backShadowMap, vTexBack));
        }

    if((fDPDepth + SHADOW_EPSILON) < fSceneDepth)
        finalColor = finalColor * 0.3f;

    gl_FragColor = vec4(finalColor, 1);

}

```
> 7 votes

---
Tags: opengl, glsl, shadows, opentk
---


# Question
Title: How to correctly draw a 2D polygon in Unity
I'm trying to draw a 2D polygon using GL.Line; however I'm not getting a polygon but separated lines instead. In the example below, I would expect a rectangle formed by the spheres:

My code is the following:

```
void OnPostRender( )
 {
     GL.PushMatrix ( );
     mat.SetPass ( 0 );
     GL.LoadOrtho( );

     GL.Begin( GL.LINES );
     GL.Color( Color.white );

     for ( int i = 0; i < spheres.Length; i++ )
     {
         currentVector = Camera.main.WorldToViewportPoint ( spheres[i].transform.position );
         GL.Vertex3 ( currentVector.x, currentVector.y , 0  );
     }

     GL.End();
     GL.PopMatrix();
 }

```

Also, I found this tutorial/example but is not exactly what i'm looking for, since in the example, all have the same origin point.

I'm asumming that the correct way of achieving what I want, would be to call the Gl.Vertex3 method once for each of the 2 points that form each line:

* From A to B (GL.Vertex3 call 2 times)
* From B to C (GL.Vertex3 call 2 times)
* From C to D (GL.Vertex3 call 2 times)
* From D to A (GL.Vertex3 call 2 times)

**Is this the right way of doing this?**

Thanks in advance.

# Answer
The GL\_LINES primitive type draws a line for each pair of vertices. The lines are not connected, so your assumption of drawing 2 vertices per line segment would be correct.

Unfortunately, Unity only supports the GL\_LINES primitive type for line drawing, otherwise the GL\_LINE\_LOOP primitive would be better suited and your code would already be correct.

Refer to the GL documentation here for a desrcription of the different primitive types.

> GL\_LINES Treats each pair of vertices as an independent line segment. Vertices 2n-1 and 2n define line n. N/2 lines are drawn.

A better way might be to use GL\_QUADS. If you just want the outline with no fill, then set GL.wireframe before calling GL.Begin(). The benefit of using a quad would be that you could turn wireframe on or off to show a filled poly if you want. Also, it only needs 4 vertices instead of 8, so it should map to your existing code with no changes.

You could also use GL\_TRIANGLE\_STRIP but if you want to display it in wireframe, it will have a diagonal line through the rectangle.

Keep in mind that when using the polygon primitives, the order of the vertices matters. You must specify them in clockwise order in Unity or your shape will not render properly. This doesn't matter if you are using GL\_LINES.
> 0 votes

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


# Question
Title: Can't move character at all in unity basic platformer guide
so, I followed below tutorial.

https://unity3d.com/learn/tutorials/modules/beginner/live-training-archive/creating-a-basic-platformer-game

Going well until 18:50 (video time in tutorial), when the tutor compiles and able to move and jump the character. And then, when I try it, mine was not moving or jumping at all.

So, how to move the character?

I've also tried some solutions on the video's youtube comments, but nothing works.

P.S. I'm not new to C# at all, but new to Unity development. I'm using Unity 5.

Thanks.

Update : Here are the props screenshots and Controller c# code :

**Cube**

**Hero**

**SimplePlatformController**

```
using UnityEngine;
using System.Collections;

public class SimplePlatformController : MonoBehaviour {

[HideInInspector] public bool facingRight = true;
[HideInInspector] public bool jump = false;

public float moveForce = 365f;
public float maxSpeed = 5f;
public float jumpForce = 1000f;
public Transform groundCheck;

private bool grounded = false;
private Animator anim;
private Rigidbody2D rb2d;

// Use this for initialization
void Awake ()
{
    anim = GetComponent<Animator> ();
    rb2d = GetComponent<Rigidbody2D> ();
}

// Update is called once per frame
void Update ()
{
    grounded = Physics2D.Linecast(
        transform.position,
        groundCheck.position,
        1 << LayerMask.NameToLayer("Ground"));

    if (Input.GetButtonDown ("Jump") && grounded)
    {
        jump = true;
    }

}

void fixedUpdate()
{
    float h = Input.GetAxis ("Horizontal");

    anim.SetFloat ("Speed", Mathf.Abs (h));

    if (h * rb2d.velocity.x < maxSpeed)
        rb2d.AddForce (Vector2.right * h * moveForce);

    if (Mathf.Abs (rb2d.velocity.x) > maxSpeed)
        rb2d.velocity = new Vector2 (
            Mathf.Sign (rb2d.velocity.x) * maxSpeed,
            rb2d.velocity.y);

    if ((h > 0 && facingRight) || (h < 0 && !facingRight))
        Flip ();

    if (jump)
    {
        anim.SetTrigger ("Jump");
        rb2d.AddForce (new Vector2 (0f, jumpForce));
        jump = false;
    }
}

void Flip()
{
    facingRight = !facingRight;
    Vector3 theScale = transform.localScale;
    theScale.x *= -1;
    transform.localScale = theScale;
}

```

}

# Answer
Make sure the ground layer is set to ground on the cubes layer.

Drag the groundCheck object to the new slot on the platform controller script that is visible when selecting the hero object.

Also make sure the hero has his rigidbody2d not set to kinematic.

And that the ground cube does not have a normal collider and is replaced with a 2d collider

edit - or fix a typo from `void fixedUpdate()` to

```
void FixedUpdate()

```
> 1 votes

---
Tags: 2d, platformer, unity
---


title: Space of Tangent and Bitangent Vectors

text:
# Question
Title: Space of Tangent and Bitangent Vectors
I have a really simple question I cannot be sure about the answer.

What is the space of tangent (T), and bitangent (B) vectors when we calculate them using vertex positions, and texture coordinates?

# Answer
> 1 votes
Assuming your vertices haven't been multiplied by any matrices the tangent and bitangent will be in object space.

Edit:

Your vertices are in object space. A normal is a vector perpendicular to a face (usually a triangle made from 3 vertices). Because the vertices used to calculate the normal are in object space, the normal will be also. The same follows for the tangent and bitangent.

---
Tags: vector, spaces
---


# Question
Title: Update DirectX 11 Texture Created in Unity Asynchronously in the Native (c++) Plugin
**tl;dr version :)** Is it possible to update DirectX 11 textures created in Unity asynchronously in a native plugin (C++)?

I've written a plugin that retrieves data from Kinect. Currently, color stream data is written to a texture created by Unity in a separate thread in the plugin using DirectX 9 as shown in the example below.

```
D3DLOCKED_RECT lockedRectangle;
colorFrameTextureDX9->LockRect(0, &lockedRectangle, NULL, 0);
memcpy(lockedRectangle.pBits, colorFrameMat.data, colorFrameMat.total() * colorFrameMat.channels());
colorFrameTextureDX9->UnlockRect(0);

```

With DX9 this works beautifully. As far as I know calling *LockRect* on a DX9 texture locks the texture data and *memcpy* after that is thread safe.

---

Using this code sample from Unity I've added support for DX11 textures.

```
ID3D11DeviceContext *ctx = NULL;
device->GetImmediateContext(&ctx); // Device is sent from Unity

D3D11_TEXTURE2D_DESC desc;
colorFrameTextureDX11->GetDesc(&desc);
ctx->UpdateSubresource(colorFrameTextureDX11, 0, NULL, colorFrameMat.data, colorFrameMat.cols * colorFrameMat.channels(), 0);
ctx->Release();

```

When Unity is run in DX11 mode, this runs perfectly for a few second after which it crashes without error report. I believe the problem is in using **UpdateSubresource** method which doesn't lock the texture causing simultaneous access from Unity's rendering pipeline and plugin thread.

In DX11 documentation I came across the Map/Unmap methods for updating textures which work similarly to **LockRect/UnlockRect** methods from DX9. However these methods can only be used with DX11 textures created as D3D11\_USAGE\_DYNAMIC and the texture from Unity is created as D3D11\_USAGE\_DEFAULT.

Is it possible to change or recreate the texture created in Unity with different usage flags?

Thanks in advance to anyone who even read it all :D

# Answer
Yes, you can use that code to update a Unity RenderTexture (not simply a Texture2D). You need to make sure that code executes on the render thread. To do that, make sure you only call it in response to the GL.IssuePluginEvent (which will translate to the C++ function UnityRenderEvent).
> 3 votes

---
Tags: c++, unity, textures, directx11
---


title: invaliduriexception with photon unity

text:
# Question
Title: invaliduriexception with photon unity
I am using photon unity networking right now to make a multiplayer game. When I publish to windows the build works fine, but when I change unitys build settings from windows to webgl it gives my a invaliduriexception. It also does not work when I publish it to webgl. I tried looking for a answer on google but it does not seem like anyone else has had this problem.

# Answer
So here I go figuring it out all by myself. It basically will not work because the photon server sdk v3.x does not have support for it. Once photon releases photon server sdk v4 it will work.
> 1 votes

---
Tags: unity, networking, photon
---


# Question
Title: What's the best way to handle slopes for a platfomer game using Box2D
I would like to know if there is any known solution for handling the player's movement on slopes using Box2D engine.

I tried to do it using a circle as the player. Everything was fine until I tried to walk on slopes, the main problem is that due to gravity, the circle does not stop on the slope.

Please if somebody has tried this before I'll appreciate it. If you have a better solution without the physics engine would be fine for me too.

Thank you.

# Answer
Behind boxboy by Robert Dodd describes a very sensible method for making a character in box2d that plays like a more traditional platformer character.

The main components is the anglejoint as well as a fixed speed motor joint. With enough friction your character will not slide down slopes, and as long as the motor is active it would keep it from rolling downhill. I'm uncertain exactly how, but you should be able to keep the motor engaged even when its not rotating, to prevent the circle from rolling freely.
> 2 votes

# Answer
You could raycast to judge whether the character is standing on a slope and modify their velocity accordingly.
> -1 votes

---
Tags: box2d, physics, platformer
---


# Question
Title: Generating hidden box collider between two game objects in unity
I'm trying to implement flappy bird clone using unity. I'm creating two obstacles at random y position. I would like to create a hidden box collider game object between them, but I'm struggling with the math. I want the box collider to be generated between both game objects so that I use it to detect if the bird has passed the two obstacles.

Here is how I generate the obstacles

// function called by InvokeRepeating function

```
void CreateObstacle(){
        // generating random upper pipe position
        float randomPos = 4f-(4f-0.8f-pipeHole)*Random.value;
        // adding upper pipe to stage
        GameObject upperPipe = (GameObject)Instantiate(pipeObject);
        // setting upper pipe position
        upperPipe.transform.position = new Vector2(4f,randomPos);
        // adding lower pipe to stage
        GameObject lowerPipe = (GameObject)Instantiate(pipeObject);
        // setting lower pipe position
        lowerPipe.transform.position = new Vector2(4f,randomPos-pipeHole-4.8f);
    }

```

# Answer
why not make a prefab with 3 gameobjects with a trigger in the middle and you spawn the complete prefab should be much easier
> 1 votes

# Answer
You need to create emtpy gameobject and add colliders to it. Also, check the istrigger? checkbox. because, a normal collider will not allow the bird to pass through
> 0 votes

---
Tags: unity, mathematics
---


title: Update Based Animation Position Values?

text:
# Question
Title: Update Based Animation Position Values?
Is it possible to control the key-frame/sample value or the time based position in the animator? I’ve set a global float that identifies the rotation of an object on its Y axis and I would like the rotation value to equal/manipulate the time or key-frame in an animation – I’ve converted 360 degrees to a float of 10.00. So.. if I rotate this object to ‘5.00 (180 degrees), it would update to the 300th key-frame/sample or 5.00 seconds into the animation and update every frame from the value changes.

It’s basically scrolling though the position of a cross fade by manually changing the value.

# Answer
> 1 votes
You can use normalised time to jump to a particular frame.

```
 Animator.Play(state, layer, normalizedTime);

```

The range of normlaized time is 0 to 1.

For example if your total animation has a rotation of 360 and you rotate the object manually to 180 and want the animation to be played from middle frame. Then you need to give normalised time as 0.5 (i.e. 180/360)

---
Tags: unity, animation
---


# Question
Title: How to create axes for a console controller
What should I change in the input manager to enable me to use a joystick? I have a usb cable to connect the joystick to the computer but how do I set up the controls?

# Answer
You can set up new axes for joysticks in the input manager by using "Joystick Axis" for the Type. The left stick would need two entries in the input manager, one horizontal (using the X axis), and one vertical (using the Y axis). The right joystick , using the 3rd and 4th axes. To use this in scripting, you need to get through Input.GetAxis("Joystick Left"), where "Joystick Left" is the name of the axis created in the input manager.

Unity already has some predefined joystick settings , you can try if those work for you, else you can make new axes as per your need.
> 2 votes

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


# Question
Title: Could someone help me understand this game loop logic?
I'm learning Java game development and trying to dissect this game loop:

```
// Game loop
    final int TICKS_PER_SECOND = 60;
    final int SKIP_TICKS = 1000 / TICKS_PER_SECOND;
    final int MAX_FRAMESKIP = 5;

    long nextGameTick = System.currentTimeMillis();
    int loops;
    float interpolation;

    boolean running = true;
    while(running) {
        loops = 0;

        while(System.currentTimeMillis() > nextGameTick && loops < MAX_FRAMESKIP) {
            System.out.println(System.currentTimeMillis() + " > " + nextGameTick);
            update();
            ticks++;

            nextGameTick += SKIP_TICKS;
            loops++;
        }

        interpolation = (float) (System.currentTimeMillis() + SKIP_TICKS - nextGameTick)
                        / (float) SKIP_TICKS;
        render(interpolation);

        if(System.currentTimeMillis() - timeAtLastFPSCheck >= 1000) {
            System.out.println("FPS: " + ticks);
            gameWindow.setTitle(gameName + " - FPS: " + ticks);
            ticks = 0;
            timeAtLastFPSCheck = System.currentTimeMillis();
        }
    }

```

So far, here's what I understand:

* TICKS\_PER\_SECOND is the amount of times we want the game to update per second
* SKIP\_TICKS is the max time that a game tick should take if we want to keep to our TICKS\_PER\_SECOND value
* MAX\_FRAMESKIP is the max amount of updates per render

Here's where I'm confused: the 'nextGameTick' variable takes the current time and then we go into the loop. The first logic that we come across is that while the current time is GREATER THAN 'nextGameTick' AND the loops of this logic is LESS THAN the MAX\_FRAMESKIP (the max updates per render). I *cannot* get my head around why we are comparing if the current time is greater than the 'nextGameTick' - as far as I can see from the code the 'nextGameTick' is basically the time value if the update took the maximum amount of time allowed. But surely then we should be comparing if the current time is LESS THAN the maximum time allowed for the update - i.e. if the update is taking too long we break from the loop immediately and go to render. However if I change the GREATER THAN to a LESS THAN then update is never called.

I think what this logic is trying to do/doing (but I don't know how) is basically allowing the game to update more times than it renders - because a lot of people's computers will be fast enough to do so. So it allows us to update 5 times per render (while loops \< MAX\_FRAMESKIP). HOWEVER we also have the comparison to check if these updates are taking longer than expected in which case we should stop being greedy with the updates and go ahead and render **(at least, this is what I think it's trying to do, please correct me if I'm wrong)**. But surely the current time being LESS THAN the time expected to take is the condition on which we want to continue updating?

As for the next part of the logic, the interpolation, I know we receive a value that we can use within rendering logic to draw game objects "in-between" updates so the movement doesn't seem jerky. Could someone expand on this though? And possibly even break down the actual code and how it arrives at the value we get.

So, to clarify, my overall question about this is: \- **Why do we check if the current time is greater than the time it was expected to take (this would surely mean it took longer than expected?? which is a BAD thing)** \- **How does the interpolation value work, and how to we obtain it?**

Thanks to anyone who can help me. Please just ask if you need more information from me.

# Answer
The game loop looks to see if the current time is after (greater than) the time the next update should have happened. A basic example with easier to understand timings (SKIP\_TICKS is set to 2 seconds):

0 Seconds - Set nextGameTick to 2 seconds and Update Game (takes 3 seconds)

3 Seconds - If current time (3 seconds) \> nextGameTick (2 seconds) update again.

As you can see the update process fell behind its expected time of next update so the logic decided to update again instantly. This would be done a maximum number of times based on the MAX\_FRAMESKIP variable.

The interpolation basically looks at how long has passed between now and the last update and calculates how far each object should have moved without any changes since that update:

```
(System.currentTimeMillis() + SKIP_TICKS - nextGameTick)
                    / (float) SKIP_TICKS

```

The first section in brackets is the length of time between the render and the next planned update, by dividing that time passed by the length of a single tick we get the percentage of an update that has passed, using the above example but updating the SKIP\_TICKS to the actual length of update (SKIP\_TICKS is set to 3 seconds):

0 Seconds - Set nextGameTick to 3 seconds and update Game (takes 3 seconds)

3 Seconds - If current time (3 seconds) \> nextGameTick (3 seconds) update again, it isn't so we can render. Set next nextGameTick to 6 Seconds

4 Seconds - current time (4 seconds) + SKIP\_TICKS (3 seconds) - nextGameTick (6 seconds) = 1 Second. Then \>\> 1 Second / SKIP\_TICKS (3 seconds) = 0.33

The interpolate would then draw things as if they continued moving for 0.33 seconds, this would not take into account collision detection or any other changes but simple continue all movement as if nothing changed in those 0.33 seconds. This helps to smooth out movement by ensuring what is drawn on screen **at the time of render** actually shows the correct position of object.

In reality the interpolation is much shorter than 0.33 seconds so there are rarely issue such as things passing through each other as the next tick happens so soon the error is corrected before anyone can notice. However an example is when on an online shooter and you see blood from a hit but don't get a kill. This is because your computer has interpolated that the bullet hit, however the server shows the player moved out of the way of the bullet. (NOTE: this example is due to network lag rather than slow updates but the interpolation is similar.)
> 2 votes

# Answer
Each time the loop executes, nextGameTick is incremented by `1000 / TICKS_PER_SECOND`. This puts an upper limit on the framerate.

In this case, it caps the framerate at a maximum of 60fps, because if a frame takes less than 16.67ms (1000 / 60) to execute, it waits until 16.67ms has passed from when the last frame started.

By combining it with the `loops` check, it allows the game to skip the **rendering** process if the **update** process is taking too long.

If the **update** process is taking less than a single frame to process, the game goes ahead and renders it, otherwise it goes "crap, I've gotta catch up, I'll just interpolate the rendering later!"

The `MAX_FRAMESKIP` variable then limits the amount of frames that the game can skip the **rendering** process.

*UPDATE:* Don't forget, System.currentTimeMillis() keeps incrementing. Each time it's called, it's a different value. So if the frame took 2ms to execute, then `System.currentTimeMillis() > nextGameTick` will evaluate to false, and the frame will render.
> 4 votes

---
Tags: java, game-loop
---


# Question
Title: How do I go from world coordinates (X/Y) to tile coordinates?
So, I've got this game rendered in fake isometric view with the following code for generating the mesh:

```
_x = x + ( y & 1 > 0 ? 0 : 0.5 );
_y = y * 0.25;

ADD_VERTICES( [
        _x-0.5,  _y,      0,  _uv[0], _uv[3], //B
        _x,      _y+0.25, 0,  _uv[0], _uv[1], //A
        _x+0.5,  _y,      0,  _uv[2], _uv[1], //C

        _x+0.5,  _y,      0,  _uv[2], _uv[1], //C
        _x,      _y-0.25, 0,  _uv[0], _uv[1], //D
        _x-0.5,  _y,      0,  _uv[0], _uv[3], //B
] );

```

Which creates quads (2 triangles really) with the following corners:

```
0 0 [0.5, -0.5  -   0, 0,       -   0.5, 0.5    - 1, 0]
1 0 [1.5, -0.5  -   1, 0,       -   1.5, 0.5    - 2, 0]
0 1 [0, 0       -   -0.5, 0.5   -   0, 1        - 0.5, 0.5]
1 1 [1, 0       -   0.5, 0.5    -   1, 1        - 1.5, 0.5]

```

I can get the world coordinates from the mouse position, how ever, I can't for the life of me figure out how to get from world coordinates back to tile coordinates. What is the algorithm for that? (Or, how can I change the vertices around so that that is easier)

# Answer
> 4 votes
First You need to re-organize numbering your tiles in an Isometric map it is much easier to defined the isometric axis along to tiles lats.

*Like This*

Take a look at the following tutorial which is the best one that I found on the Internet, there is alot of isometric map math tutorial on the web but this guy is a prophet!

http://clintbellanger.net/articles/isometric\_math/

as the tutorial says you may transform map coordinate to isometric coordinate via the following equations

```
screen.x = (Isomap.x - Isomap.y) * TILE_WIDTH_HALF;
screen.y = (Isomap.x + ISomap.y) * TILE_HEIGHT_HALF;

```

since your tiles have equal width and height its a bit easier but I used this tile size : (36,24) which has a better look, but still camera location is high enough so all the elements on the map can be viewed without much overlap

However the above formula may need to be changed a little bit since the origin of tiles coordinate system is the above point of the first tile from top, But you may use the center of the top tile as a your origin, I personally used lower left vertex of MBB of the top tile as origin So I had to translate (move) the coordinate halfwidth,halfHeight so this was mine :

```
func project(Cartesian screen : CGPoint) -> CGPoint {
    let TILE_WIDTH_HALF = (tileWidth / 2)
    let TILE_HEIGHT_HALF = (tileHeight / 2)
    let movedScreen = CGPointMake(-1, -1) * (screen - CGPointMake(tileWidth,tileHeight))
    let mapx = ((movedScreen.x / TILE_WIDTH_HALF) + (movedScreen.y / TILE_HEIGHT_HALF)) / 2;
    let mapy = ((movedScreen.y / TILE_HEIGHT_HALF) - (movedScreen.x / TILE_WIDTH_HALF)) / 2;
    return CGPointMake(mapx+0.5, mapy+1.5)
}

```

if you look deeper you see that I am inversing Y before and after of Tile 2 Map transformations formula since in iOs y ascends by going up on screen but in tutorial y descends by going up.

So if you are write your game for a mobile device you need to do it too

At the end of my function I have added 0.5,1.5 to what is suppose to be my tiles coordinate system.

As you see, it is a little bit confusing and depending on how you have drawn your tiles and y positive direction is up or down, you need to change the basic formula in the tutorial slightly. Sorry that I can not provide you the exact equation but I can show you how to do it. (find your own equations)

write down the basic formula but add an Tx and Ty to both equations, you need to find what is Tx and Ty is in your case. To find out what they are just write the equations for two different tiles (eg. Tile 0,1 and tile 1,1) as you did in your question above. afterwards you will have a complete equation.

```
    screen.x = (Isomap.x - Isomap.y) * TILE_WIDTH_HALF + Tx;
    screen.y = (Isomap.x + ISomap.y) * TILE_HEIGHT_HALF+ Ty;

```

And here it is my reverse code, if you compare it with the tutorial you will see that it has slightly changed too. and you have to find your own by the skill you just gained above.

```
func unproject (tileIndex tileIdx : CGPoint) -> CGPoint
{
    let TILE_WIDTH_HALF = (tileWidth / 2) // 16
    let TILE_HEIGHT_HALF = (tileHeight / 2) // 12

    let screenX = TILE_WIDTH_HALF * (tileIdx.y - tileIdx.x + 1)
    let screenY = 24 - TILE_HEIGHT_HALF * (tileIdx.x + tileIdx.y)
    return CGPointMake(screenX, screenY)

}

```

---
Tags: mathematics
---