title: Help Needed with Shaders

text:
# Question
Title: Help Needed with Shaders
Ok, bear with me, I am a beginner with Google Cardboard programming.
What I have been doing is looking at the TreasureHunter sample app from Google's page and (with the help of documentation and other sources) have been trying to create a simple cube floating in space.
I have also been trying to avoid making everything as bare bones as the sample, so I have been trying to object orient things such as lights and the meshes.

I am pretty sure that my matrices and methods are correct, but I think there could be something wrong with my shaders.

When I compile the app and install it, no errors are thrown, but I am given just my white screen (set with `glClearColor`) with the Cardboard binocular UI/view; no cube is rendered, tilting/looking around has no effect.

I am using the colors, verticies, and normals from the Treasure Hunter sample, so those should be correct.

Full source code (Java) is here.

```
uniform mat4 u_Model; // model position in world space
uniform mat4 u_MVP;  // model in projection space
uniform mat4 u_MVMatrix; // model in view space
uniform vec3 u_LightPos; // Light position in eye/camera space (projection space)

attribute vec4 a_Position; // vertex in local space
attribute vec4 a_Color; //Vertex colors
attribute vec3 a_Normal; //vertex normal

varying vec4 v_Color; // color
varying vec3 v_Grid;
varying vec3 v_Normal;
varying vec3 v_Position;

void main() {
   v_Grid = vec3(u_Model * a_Position);
   v_Normal = vec3(u_MVMatrix * vec4(a_Normal, 0.0));
   v_Position = vec3(u_MVMatrix * a_Position);
   vec3 modelViewVertex = vec3(u_MVMatrix * a_Position); //Vertex position in view space
   vec3 modelViewNormal = vec3(u_MVMatrix * vec4(a_Normal, 0.0)); //Normal in view space

   float distance = distance(u_LightPos, modelViewVertex);
   vec3 lightVector = normalize(u_LightPos - modelViewVertex);
   float diffuse = max(dot(modelViewNormal, lightVector), 0.5);

   diffuse = diffuse * 1.0/(distance * distance);
   v_Color = a_Color * diffuse;
   gl_Position = u_MVP * a_Position;
}

```

My vertex shader:

My fragment shader:

```
precision mediump float;

varying vec4 v_Color;

void main()
{
    gl_FragColor = v_Color;
}

```

# Answer
> 0 votes
Turns out I was calculating my "u\_MVP" (Model View Projection) matrix wrong. I used a vector instead of a matrix for the model position. That along with many other bugs. Now it's fixed.

---
Tags: android, opengl-es2, google-cardboard
---


title: Reading from a txt file (C++)?

text:
# Question
Title: Reading from a txt file (C++)?
When use ifstream to read from a txt file into 2d array i get some extra chars.

Txt file:

I get:

**My code:**

```
ifstream read;
read.open(resourcePath() + "res/txt/menu.txt");
if (read.fail()) {
    read.close();
    cout << "File does not exist!" << endl;
    exit(1);
}

for (int i = 0; i < HEIGHT/BLOCK_HEIGHT; i++) {
    for (int j = 0; j < WIDTH/BLOCK_WIDTH; j++) {
        read >> board[i][j];
    }
}

read.close();

```

Could someone point out the mistake?

# Answer
> 0 votes
```
read >> board[i][j];

```

looks wrong. Try to read only one char or use string manipulation afterwards to extract the Boolean type.

---
Tags: c++, filestream
---


# Question
Title: Rotating Object parallel to other object
I try to rotate objects in the same direction as a reference object.

Normaly this would be easy:

```
object1.rotation = reference.rotation

```

But the same rotation can be expressed with different vectors:

```
(0, 45, 270) is the same as (0, 225, 90)
(0, 0, 270) is the same as (0, 180, 90)

```

In my case the final rotation should account for this.

```
The reference object has a rotation of: (0, 45, 270)

Object1 Should Rotate from (0, 45, 270) to (0, 0, 270)

Object2 Should Rotate from (0, 225, 90) to (0, 180, 90)

```

How can i calculate this? Im using unity if this is any help.

# Answer
> 0 votes
I found the solution with help from @tyjkenn

```
Quaternion newRot = Quaternion.FromToRotation(
    object.transform.forward,
    reference.transform.forward
);

object.transform.rotation = neRot * reference.transform.rotation;

```

A few important things with this:

* Both object and reference need to be aligned with unity's forward and up axis. (forward is the blue Z axis, up is the green Y axis). You can change this in your modeling software or within a parent gameObject.
* The order of quaternion multiplication matters. Its the same as changing the order of rotation matrices

# Answer
> 1 votes
If you know one start and end rotation, in this example, from (0, 45, 270) to (0, 0, 270), first calculate the rotation between the two. You can do that like this:

```
Quaternion startRot = Quaternion.EulerAngles(0, 45, 270);
Quaternion endRot = Quaternion.EulerAngles(0, 0, 270);
Quaternion betweenRot = endRot * Quaternion.Inverse(startRot)

```

Now, you can simply rotate anything by multiplying by betweenRot:

```
Quaternion startRot2 = Quaternion.Euler(0, 225, 90);
Quaternion endRot2 = startRot2 * betweenRot;

```

`endRot2` should be equivalent to `Quaternion.Euler(0, 180, 90)`.

---
Tags: rotation, vector, linear-algebra
---


# Question
Title: Unity3D position of 2D objects with size of Object
I'm making a 2D project in Unity3D. I want to place an image in the right upper corner. I've got this working, but ofcourse the image is falling of the screen for a part (and completely when I change the screenrotation).

This is the code I've got for it;

```
posImage = new Vector2(Screen.width - imgGear.transform.localScale.x, Screen.height - imgGear.transform.lossyScale.y );

```

As you can see in the code I've tried to adapt the position with the size of the object, using localScale 1.0f and lossyscale 0.9...f doesn't really do much as it will be changed with 1 unit. Is their a way to get the real width and height of the objects?

# Answer
I got same problem for atleast 2 week until i figured myself how to handle object in different resolution which **preventing object falling apart** or place object based with the screen resolution .

***If you want to keep the object right in the position following camera , don't forget to put the object inside camera object .***

this is my script to control the resolution :

**calculateresolution.cs**

```
using UnityEngine;
using System.Collections;

public class calculateresolution : MonoBehaviour {

    // change this to resolution size when you create the game

 float desiredscreenheights = 768;
 float desiredscreenwidths = 1366;

void CalculateResolution(string theobjectm) {
 GameObject objecttocalculate = GameObject.Find(theobjectm);
 float desiredscreenheight = desiredscreenheights;
 float desiredscreenwidth = desiredscreenwidths;
 float desiredaspectratiowidth = desiredscreenwidth / desiredscreenheight;
 float desiredaspectratioheight = desiredscreenheight / desiredscreenwidth ;
 float screenheight = Screen.height;
 float screenwidth = Screen.width;
 float aspectratioheight = screenheight / screenwidth;
 float aspectratiowidth = screenwidth / screenheight;
 Debug.Log (screenheight + " " + screenwidth + " " + aspectratioheight + " " + aspectratiowidth);
 float objectsizex = objecttocalculate.transform.localScale.x;
 float objectsizey = objecttocalculate.transform.localScale.y;
 float objectsizez = objecttocalculate.transform.localScale.z;
 float objectcoordx = objecttocalculate.transform.localPosition.x;
 float objectcoordy = objecttocalculate.transform.localPosition.y;
 float objectcoordz = objecttocalculate.transform.localPosition.z;
 Debug.Log (objectsizex + " " + objectsizey + " " + objectsizez + " " + objectcoordx + " " + objectcoordy + " " + objectcoordz);
 float newobjectsizex = aspectratiowidth / desiredaspectratiowidth * objectsizex;
 float newobjectsizey = objectsizey;
 float newobjectsizez = objectsizez;
 float newobjectcoordx = aspectratiowidth / desiredaspectratiowidth * objectcoordx;
 float newobjectcoordy = aspectratiowidth / desiredaspectratiowidth * objectcoordy;
 float newobjectcoordz = objectcoordz;
 Debug.Log (newobjectsizex + " " + newobjectsizey + " " + newobjectsizez);
 Debug.Log (newobjectcoordx + " " + newobjectcoordy + " " + newobjectcoordz);
 objecttocalculate.transform.localScale = new Vector3 (newobjectsizex, newobjectsizey, newobjectsizez);
 objecttocalculate.transform.localPosition = new Vector3 (newobjectcoordx, newobjectcoordy, newobjectcoordz);
 Debug.Log ("Calculate Finish For Now");

}
void Start () {

}

// Update is called once per frame
void Update () {
// your gameobject name

CalculateResolution ("yourobjectname ");
}

}
```

To calculate the object , just call CalculateResolution("**yourgameobjectname**") , change **yourgameobjectname** with the **object name** .

Change "**float desiredscreenwidths**" and "**float desiredscreenheights**" value to resolution size you use to build the game .

***But unfortunally this script does not support screen rotation because i did not know how to :I sorry , or maybe you tell me how ;) .***
> 0 votes

# Answer
When I putted the positioning script in the update part instead of the start function, it changed position perfectly when rotating screen. For the "real size" of the object I might have to puzzle a bit.

I know that repositioning on every update can be causing some lag in the application but since it is a menu screen, it doesn't cause mayor delays in the application (menu's and popups still open instantly).

this is how i got it now :)
> 1 votes

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


# Question
Title: What gamepad functionality can be assumed?
When I offer gamepad support, the simplest solution seems to be to assume XBox controllers and use a library that maps the most frequent gamepads to a similar layout.

Now if I want to minimize customer complaints, can I just use all the buttons (in a sensible way), or are there some I should avoid because they are missing on some common controllers?

The question is primarily about PCs (Linux/Windows/Mac), but does the answer change if we consider gamepads for mobile devices?

---

The one thing I know about is that we cannot use any input scheme that requires the user to press LT and RT at the same time, but that limitation affects XBox controllers as well.

# Answer
> 16 votes
The standard which you will find on most platforms is:

* Analog directional input left thumb
* Digital directional input left thumb
* Analog directional input right thumb
* 4 buttons right thumb
* 2 shoulder buttons left hand
* 2 shoulder buttons right hand
* 2 buttons in the center of the gamepad which are awkward to reach and should be used for special actions like pausing the game.

You find this at least on:

* current and previous generation Xbox
* current and previous generation Play Station
* Wii U
* Nintendo Switch (with both joy-cons attached or with external controller)
* Nintendo 3DS series
* most PC gamepads, including Steam Controller

These are some exceptions which are more limited which you might or might not consider relevant to support:

* PlayStation Vita which has only one shoulder-button per hand
* Nintendo Switch when using only one joy-con which is limited to:
    + Analog stick left thumb
    + 4 buttons right thumb
    + 1 shoulder button left hand
    + 1 shoulder button right hand
* Nintendo Wii which is limited to:
    + Digital d-pad for left thumb
    + 2 buttons for right thumb
    + Gyroscope which might or might not be an adequate substitute for an analog directional input
    + (With Nunchuck Extension) analog stick for the right thumb

Also keep in mind that **not all PC gamers own a gamepad**. The standard controls for a PC are still keyboard and mouse. So you can expect to lose a considerable market segment if you do not provide proper support for this setup.

# Answer
> 1 votes
Tl;dr: There are about 4 categories. If you want to support many gamepads simply target the XBox layout. If you want to support all gamepads make sure your game can be controlled with the SNES layout (which is a subset of XBox), and allow the user to remap the controls, and also allow them to map any additional buttons and axes their gamepad may have. Of course this requires you to use one of the many libraries that correctly map a ton of gamepads based on their layout,.

**XBox compatible** \- 2 shoulder buttons & 2 triggers. D-pad (direction), 2 thumbsticks that can be clicked. Front: 4 buttons in diamond shape, "back" and "start". If you support these, you support most gamepads out there.

Warning:

* Users are sometimes unaware that thumb sticks can be clicked, so consider avoiding these buttons.
* Left and Right Triggers are implemented as a single axis instead of 2 independent axes in some drivers, so never allow the player to press both at the same time.
* None of the directional inputs (thumbsticks and D-Pad) may allow precise/fine control by the user, even tough thumbsticks are supposed to do that. Allow users to turn thumbstick half-left to turn at half speed, but don't assume the user has the ability to move a thumbstick half-left .
* Some gamepads don't use A, B, X, Y labels for the diamond buttons. Consider using images instead of letters to let user know which button to press in tutorial and setup.
* "back" and "start" aren't always labeled, are usually hard to reach, and "back" is sometimes labeled "select".

**SNES compatible** \- 2 shoulder buttons. D-Pad (direction), 4 buttons in diamond shape, "select" and "start". If you support these you support pretty much all gamepads out there.

Warning:

* "select" vs "back" button label.
* Uses same A, B, X, Y labels as XBox for 4 diamond buttons, but uses them in different order. Consider using images instead of letters to let user know which button to press in tutorial and setup.

**XBox extended** \- They can do everything the XBox controller does and some more. They are mostly irrelevant for this question, except for the fact that is nice to allow players to use these extra buttons and touchpads. So best allow players to bind extra buttons to useful game functions. And please never disrupt gamepad input just because a gamepad's touchpad is accidentally touched.

**SNES extended** Some controllers fall in between SNES and XBox, by offering only some extra functionality. They may have quite unusual button arrangements so allowing users to customize the input scheme is important. Same advice applies as in XBox extended above. There is also a significant subset of these controllers that are essentially SNES compatible plus 2 thumbsticks, resp. XBox compatible minus both triggers.

**NES** \- Not in use anymore. Tell customer to buy a newer gamepad.

---
Tags: mobile, pc, gamepad
---


title: Protecting/Handling game data

text:
# Question
Title: Protecting/Handling game data
I have been working on a web based game, in which involves a lot of javascript/PHP. My question is what is the most secure way to handle any data being passed between the two languages?

At this moment I am currently using javascript to preform any required functions such as making objects appear for you to click and then awarding points for clicking that object.

I know javascript isn't the best way to handle the data due to how accessible it is on the client-side. I currently use ajax to pass the points gained from a click, to PHP where it can then assess whether the points were gained fairly or by an exploit.

This works, however when it comes to making sure that the user doesn't abuse a function in the console such as "Spawning an object" I run into some issues, as I can't seem to think/find of a way to achieve this. At the moment I have it so when the game starts an interval begins which displays an object based on a random value and then when the user clicks that object it gets destroyed and their score is sent to a PHP file to check the action was legit.

Is there some sort of way I can make a checker in the PHP file to make sure that an object can only be spawned if the browser calls it and not the client. I know you can't stop a user from using the console, its more of thinking of a system to judge/evaluate whether an action is allowed by a user.

# Answer
There are a few ways to secure your data depending on your needs. I'm listing the ones I've found the most use of over the years.

---

**Javascript** ( client side )

My suggestion is: Don't spend too much time on the client-side Javascript. Everything you do increases the time it takes to crack it and usually by not that much.

Do the basic stuff - minify your javascript and maybe obfuscate it ( UglifyJS2 does both and more - I do recommend using it ).

*This will surely get rid of most of the people trying to hack - after all the majority are just programmers who might do it because it's fun but won't waste their time digging through obfuscated code for the purpose.*

---

**PHP** ( Server side )

Here you can make magic happen. The rule of thumb is - if you want something to be reliable - do it yourself ( on the server, don't let the arbitrary clients handle it ). As your example with the points - this work rather well.

The main ways you can implement that are:

**Server Only Logic**

The server does what it does - the client posts a request and waits for the appropriate response.

> **Example**: Final Action of Quest -\> The Server finishes the quests and gives the reward -\> The client displays the provided rewards to the user

**Shared Game Logic**

Both the client and the server do everything. The client mimics it to provide instant feedback for user actions, but anything happening on the server can override the client state.

> **Example**: Movement. ( Usually the overriding of the state here is gradual and some minor differences are tolerated to improve the overall smoothness of the game )

**Sanity Checks**

The client executes the logic. The server has a pseudo algorithm to check if certain elements of the game behave 'normally'.

> **Example**: Spawning objects can be a client-side operation, but acquiring points from them would be on the server. So the server would check whether or not the points acquired are from an unusually high amount of objects - after a certain threshold - they'll stop giving points or the points will be capped. You can also set up monitoring (plus notifications to you/admins) or even automatic bans for players that get a substantially higher amount of points.
> 0 votes

# Answer
Usually, obfuscating (minifying) the JavaScript code is enough to deter all but the most fervent of exploiters from abusing the script through the developer console. But without knowing how the PHP and JavaScript sides communicate, that might not be an option.

One idea does come to mind, however. You could have the server explicitly request the client to perform a specific job, and only care about the received result that relates to the requested task.

For example, your server determines it needs to spawn two objects. It tells the client to spawn two objects and keep track of what happens to them.

Now, the client might spawn more than the requested two by illegal means. It might even tell the server about all of the objects that have been spawned. But that doesn't matter - the server will *only* care about *two* objects and disregard the rest.

To summarise, have your server always make requests expecting a certain result. That way you'd deal with predictable data, and will be able to easily detect spoofing and other trickery from users looking to exploit the game.
> 0 votes

# Answer
If you want security, do the important jobs on the server. Nearly all operations that are being done on the client are easily accesible, editable and *cheatable*.

*Note that, this may reduce the performance a bit depending on the connection speed of client.*
> 0 votes

---
Tags: javascript, game-mechanics, php
---


# Question
Title: Debug Unity apps on Xbox One without ID@XBOX?
I have developer mode setup on my Xbox One, and can debug Windows Universal apps on it without issue from Visual Studio.

I am playing around with Unity, and would like to be able to debug on my Xbox one in the same way. When I look under Build Settings I see the following:

Clicking Open Download Page takes me to this blog post from 2014.

I have heard from other sources that I should be able to debug Unity games on the Xbox without an ID account, is this the case?

At this link, it says:

> You don't need help from ID@Xbox to begin experimenting with Dev Mode – just download the Dev Mode Activation app on your Xbox One to get started!

Cheers

# Answer
There is the new Xbox One developer mode but is is only made for testing Universal Windows Platform Apps as it limits usable RAM/CPU power/GPU power, so it is pretty limited. But you can do it if you enable dev mode (how to: https://msdn.microsoft.com/en-us/windows/uwp/xbox-apps/devkit-activation). Then, Set the Unity Build Target to Windows Store. After that, set the SDK to "Universal 10" and set the UWP Build Type to either "D3D" or "XAML". This creates a Visual Studio Project that you can then deploy with the instructions at the MSDN link: https://msdn.microsoft.com/en-us/windows/uwp/xbox-apps/getting-started.
> 2 votes

---
Tags: unity, xbox
---


# Question
Title: Why does the player jump every time it touches the ground in my JavaScript game?
I am making a javascript game where the player jumps over oncoming cars, but after the first jump every time the player hits the ground they jump again automatically. I believe the problem is because I am resetting the jumping variable to false when it hits the ground yet it is still going through the initial jump() function so it sees it as false and makes it jump again. Is there any way to fix this?

```
this.isJumping = function(){
  var y=player.y;
  var jumping;

  if (y=area.canvas.height - 200){
    player.image.src="man.png";
  }
  else{
    jumping=true;
    player.image.src="man2.png";
  }
  return jumping;
}

```

(And later in the code)

```
function jump() {
  if (!player.isJumping() && area.frameNo>0) {
    player.speedY = -20;
    jumping=true;
  }
}

```

# Answer
## Update - Nov 28, 2016

One solution to your issue is to switch to mousedown and mouseup with the following event handler, as shared before:

```
function jumpHandler() {
    if (!player.isJumping() && area.frameNo > 0) {
        player.speedY = -20;
        jumping = true;
    } else {
        jumping = false;
    }
}

```

Another solution would be to switch over to Phaser input events, which make a bit more contextual sense, but might require some work depending on your implementation.

Phaser also has mouseDown and mouseUp detection which would then be passed to the same handler as before.

All of the above should work, but requires some testing for triage and addressing the issue.

## Initial Answer

A quick and easy solution, one that would still depend on your other implementation details, is to have the else block for your jump method set jumping to false.

```
function jump() {
    if (!player.isJumping() && area.frameNo > 0) {
        player.speedY = -20;
        jumping = true;
    } else {
        jumping = false;
    }
}

```

Looking at your code makes me think that there may be some scoping issues that would need to be shared to be able to nail down a more accurate and maintainable solution.
> 1 votes

# Answer
You are not setting `jumping` to `false` anywhere so it will be `true` forever, change this:

```
if (y=area.canvas.height - 200)
{
    player.image.src="man.png";
}

```

to this

```
if (y=area.canvas.height - 200)
{
    player.image.src="man.png";
    jumping = false;
}

```

Also, it is not a good idea to use `y = area.canvas.height - 200`, i would do `<=` instead, what if the `area.canvas.height` is odd?
> -1 votes

---
Tags: javascript, jumping
---


title: get Actor hit() from array of Nodes

text:
# Question
Title: get Actor hit() from array of Nodes
I have an array of nodes, i need to get a specific `Node` from this array in the `InputListener` event using Actor hit()..

I have multiple menu items (Buttons, Levels) but the touch event not working. This is what i tried so far:

```
 public Actor hit(final float x, final float y, final boolean b) {
    ...
        for (int i = this.nodesList.size() - 1; i >= 0; --i) {
            final Node node = this.nodesList.get(i);
            if (node instanceof SpriteNode) {
                SpriteNode newNode = (SpriteNode) node;
                if  (newNode.anchornsform.det() != 0.0f) {
                    final Affine2 inv = newNode.anchoreansform.inv();
                  ...
                }
            }
        }
    }
    return myactor;
}

```

Please help, if you have a better solution I'm open to any suggestions.

Thank you

# Answer
As you wrote in the comment, your `hit()` is returning `null`

This part:

```
} else {
        for (int i = nodesList.size() - 1; i >= 0; --i) {
            final Node node = nodesList.get(i);
            if (node instanceof SpriteNode) {
                if (node != null && ((SpriteNode)node).anchoredAffineWorldTransform.det() != 0.0f) {
                    final Affine2 inv = ((SpriteNode)node).anchoredAffineWorldTransform.inv();
                    if (((SpriteNode)node).hit(inv.m00 * x + inv.m01 * y + inv.m02, inv.m10 * x + inv.m11 * y + inv.m12, b) != null) {
                        myactor= node;
                        return myactor;
                    }
                }
            }
        }
    }

```

can't return `null` \- cause it just can't.

So either `myactor = super.hit(x, y, b);` is causing null or `else` isn't fired at all and you have `null` cause nothing was assigned to `myactor`.
> 1 votes

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


# Question
Title: 3D prospective with geometry shader objects
I am wanting to be able to render objects with a geometry shader and allow them to rotate with the camera perspective...this is what I have so far, as a example

Vertex shader

```
#version 400 core

uniform mat4 transformationMatrix;
uniform mat4 projectionMatrix;
uniform mat4 viewMatrix;

void main()
{
    vec4 worldPosition = transformationMatrix * vec4(0,0,0, 1.0);
    vec4 positionRelitiveToCam = viewMatrix * worldPosition;
    gl_Position = projectionMatrix * positionRelitiveToCam;
}

```

Geometry Shader

```
#version 400 core
layout(points) in;
layout(triangle_strip, max_vertices = 3) out;

void main() {
    gl_Position = gl_in[0].gl_Position + vec4(-1.0, 0.0, 0.0, 0.0);
    EmitVertex();

    gl_Position = gl_in[0].gl_Position + vec4(1.0, 0.0, 0.0, 0.0);
    EmitVertex();

    gl_Position = gl_in[0].gl_Position + vec4(0.0, 2.0, 0.0, 0.0);
    EmitVertex();

    EndPrimitive();
}

```

As you can see, I am able to draw a triangle with POV working but as I rotate around it, the triangle does not rotate. Ideas?

# Answer
You are applying transformation to the point and not to the vertices of the triangle.

Transformation should be applied to EACH vertex of the output triangle if you want the triangle to rotate.

Vertex shader

```
#version 400 core

void main()
{
    gl_Position = vec4(0,0,0, 1.0);
}

```

Geometry Shader

```
#version 400 core

layout(points) in;
layout(triangle_strip, max_vertices = 3) out;

uniform mat4 transformationMatrix;
uniform mat4 projectionMatrix;
uniform mat4 viewMatrix;

void main() {
    gl_Position = projectionMatrix * (viewMatrix * (transformationMatrix * (gl_in[0].gl_Position + vec4(-1.0, 0.0, 0.0, 0.0))));
    EmitVertex();

    gl_Position = projectionMatrix * (viewMatrix * (transformationMatrix * (gl_in[0].gl_Position + vec4(1.0, 0.0, 0.0, 0.0))));
    EmitVertex();

    gl_Position = projectionMatrix * (viewMatrix * (transformationMatrix * (gl_in[0].gl_Position + vec4(0.0, 2.0, 0.0, 0.0))));
    EmitVertex();

    EndPrimitive();
}

```
> 1 votes

---
Tags: opengl, c++, geometry-shader
---


# Question
Title: In Unity - Move a GameObject at Animator State
I want to move one of my GameObject to a different vector 3 position, when animator transit to a new state. How do I do it? Also there shouldn't be any delay.

# Answer
This is the solution I came up with, In my Animator state I added a behaviour script, that moves the object before the animation starts,

Script is a very simple C# script:

```
using UnityEngine;
using System.Collections;

public class BehaviorMoveGameObject : StateMachineBehaviour {

    public float Position_X;
    public float Position_Y;
    public float Position_Z;

// OnStateEnter is called when a transition starts and the state machine  starts to evaluate this state
    override public void OnStateEnter (Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
    {

        animator.gameObject.transform.position = new Vector3 (Position_X, Position_Y, Position_Z);

    }

}

```
> 0 votes

# Answer
You Don't need to moving via animating. You can simply make a method that first change the animation state and then move object using Translate method( for instant transition) and MoveTowards or some other methods. Something like this :

```
Public myMethod (){
animator.set...();
transform.translate...
}

```

And whenever you call myMethod you have two behaviors together.
> 1 votes

---
Tags: unity, unityscript
---


title: Query for users machine hardware

text:
# Question
Title: Query for users machine hardware
When writing a game, you can do many things in many ways. But not all the machines the code will be ran on support all the ways of doing it.

How can you query for the capabilities of the machine hardware programmatically?

For example, there are ways in openGL to detect if certain openGL methods are supported by the GPU, you can also see if certain extensions are supported, query the openGL version, ect, but that still doesn't give you all the data (I'm pretty sure you cannot query the amount of VRAM the machine has).

Can you do a hardware query system-wide? To ask for the number of cores, CPU frequencies, L2 cache size, amount of ram/vram, sound card capabilities and any other system specifics so you could instruct your code how to behave (for example, to not try to play sound on 64 channels if sound card supports only 32, if vram is limited use smaller textures, etc)?

It would be nice to query for such data on startup to see if machine supports minimum requirements and then have the data globally available to the code so certain feature can be turned on or off or substituted by maybe less efficient but supported code for that machine.

I remember GTA IV had a gfx menu where it showed the amount of VRAM available and the amount required for the selected setup.

Anyway, is there a way to do what I ask?

# Answer
> 2 votes
You're asking a lot of unrelated questions, but here goes...

* Check supported OpenGL version.

```
glGetString(GL_VERSION);

```
* Check supported extensions.

```
glGetIntegerv(GL_NUM_EXETENSIONS, *);
glGetStringi(GL_EXTENSIONS, n); // n == the result of GL_NUM_EXTENSIONS

```
* Identify vendor. This will return something like "ATI Technologies" or "NVIDIA Corporation."

```
glGetString(GL_VENDOR);

```
* Identify renderer. This can return the ASIC name or the software renderer.

```
glGetString(GL_RENDERER);

```
* Check for specific capabilities. For example, check for the max number of supported texture units, which is implementation-specific:

```
glGetIntegerv(GL_MAX_TEXTURE_UNITS, *);

```
* Check for GPU capabilities with vendor-specific extensions and libraries. I'm not allowed to have more than two links in my post, so just copy-pasta:

+ GL\_NVX\_gpu\_memory\_info

`http://developer.download.nvidia.com/opengl/specs/GL_NVX_gpu_memory_info.txt`

+ GL\_ATI\_meminfo

`https://www.opengl.org/registry/specs/ATI/meminfo.txt`

+ WGL\_AMD\_gpu\_association

`https://www.opengl.org/registry/specs/AMD/wgl_gpu_association.txt`

+ AMD GPU Services library (for DirectX)

`https://github.com/GPUOpen-LibrariesAndSDKs/AGS_SDK`

Additional hardware information such as CPU and VRAM details are platform-specific and fall outside of OpenGL's scope. For that answer, I need to know what platform you care about. Since you didn't tell us, I'll tell you how do it on the one I (and most of us) care about.

```
#include <Windows.h> // Must be included FIRST
#include <Psapi.h>

#include <thread>
#include <string>
#include <vector>

#include <iostream>

#define COUTPUT(str, num) std::cout << str << ": " << num << '\n';

int main()
{
    /***** CPU Stuff *****/
    // Get number of CPU cores
    // https://msdn.microsoft.com/en-us/library/windows/desktop/ms724958(v=vs.85).aspx
    // https://msdn.microsoft.com/en-us/library/windows/desktop/ms724381(v=vs.85).aspx
    COUTPUT("Number of processor cores", std::thread::hardware_concurrency()); // C++11
    SYSTEM_INFO sysInfo;
    GetSystemInfo(&sysInfo);
    COUTPUT("Number of processor cores", sysInfo.dwNumberOfProcessors); // Pre-C++11

    // Get CPU frequency
    // https://msdn.microsoft.com/en-us/library/windows/desktop/aa383713(v=vs.85).aspx
    // https://msdn.microsoft.com/en-us/library/windows/desktop/ms644905(v=vs.85).aspx
    // https://msdn.microsoft.com/en-us/library/windows/desktop/ms644904(v=vs.85).aspx
    LARGE_INTEGER freq;
    QueryPerformanceFrequency(&freq);
    std::string arr[] { "KB", "MB", "GB" };
    int i = 0;
    double speed = 0;

    for (i = 3; i > 0; --i)
    {
        double power = pow(1024, i);
        if (power <= freq.QuadPart)
        {
            speed = freq.QuadPart / power;
            break;
        }
    }
    std::string formatted = std::to_string(speed) + ' ' + arr[i];
    COUTPUT("CPU frequency", formatted);

    // Get CPU cache sizes
    // https://msdn.microsoft.com/en-us/library/windows/desktop/ms686694(v=vs.85).aspx
    // https://msdn.microsoft.com/en-us/library/windows/desktop/ms683194(v=vs.85).aspx
    DWORD bufSize = 0;
    GetLogicalProcessorInformation(0, &bufSize);
    std::vector<SYSTEM_LOGICAL_PROCESSOR_INFORMATION> buffer(bufSize/sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION));
    GetLogicalProcessorInformation(buffer.data(), &bufSize);

    // Note: Multicore processors will have multiple L1 caches, one for each
    // core, so extra work here is needed if you want to report each one.
    // For this example, I just read one. L2/L3 cache is usually shared, so
    // the extra checks for those shouldn't be needed, but I did them anyway.
    for (int i = 0; i != buffer.size(); ++i)
    {
        if (buffer[i].Relationship == RelationCache)
        {
            static bool bAlreadyReadL1 = false, bAlreadyReadL2 = false, bAlreadyReadL3 = false;
            if (bAlreadyReadL1 && bAlreadyReadL2 && bAlreadyReadL3)
                break;

            if (!bAlreadyReadL1 && buffer[i].Cache.Level == 1)
            {
                COUTPUT("CPU L1 cache size", buffer[i].Cache.Size);
                COUTPUT("CPU L1 cache line size", buffer[i].Cache.LineSize);
                bAlreadyReadL1 = true;
            }
            else if (!bAlreadyReadL2 && buffer[i].Cache.Level == 2)
            {
                COUTPUT("CPU L2 cache size", buffer[i].Cache.Size);
                COUTPUT("CPU L2 cache line size", buffer[i].Cache.LineSize);
                bAlreadyReadL2 = true;
            }
            else if (!bAlreadyReadL3 && buffer[i].Cache.Level == 3)
            {
                COUTPUT("CPU L3 cache size", buffer[i].Cache.Size);
                COUTPUT("CPU L3 cache line size", buffer[i].Cache.LineSize);
                bAlreadyReadL3 = true;
            }
        }
    }

    /***** Memory Stuff *****/
    // Physical memory
    // https://msdn.microsoft.com/en-us/library/windows/desktop/aa366770(v=vs.85).aspx
    // https://msdn.microsoft.com/en-us/library/windows/desktop/aa366589(v=vs.85).aspx
    MEMORYSTATUSEX memStatus;
    memStatus.dwLength = sizeof(memStatus);
    GlobalMemoryStatusEx(&memStatus);

    COUTPUT("Approximate percentage of physical memory that is in use", memStatus.dwMemoryLoad);
    COUTPUT("Amount of actual physical memory, in bytes", memStatus.ullTotalPhys);
    COUTPUT("Amount of physical memory currently available, in bytes", memStatus.ullAvailPhys);
    COUTPUT("Current committed memory limit for the system or the current process, whichever is smaller, in bytes", memStatus.ullTotalPageFile);
    COUTPUT("Maximum amount of memory the current process can commit, in bytes", memStatus.ullAvailPageFile);
    COUTPUT("Size of the user-mode portion of the virtual address space of the calling process, in bytes", memStatus.ullTotalVirtual);
    COUTPUT("Amount of unreserved and uncommitted memory currently in the user-mode portion of the virtual address space of the calling process, in bytes", memStatus.ullAvailVirtual);

    // Virtual memory
    // https://msdn.microsoft.com/en-us/library/windows/desktop/ms684874(v=vs.85).aspx
    // https://msdn.microsoft.com/en-us/library/windows/desktop/ms683219(v=vs.85).aspx
    PROCESS_MEMORY_COUNTERS_EX memCounters;
    memCounters.cb = sizeof(memCounters);
    GetProcessMemoryInfo(GetCurrentProcess(), reinterpret_cast<PROCESS_MEMORY_COUNTERS*>(&memCounters), memCounters.cb);

    COUTPUT("Number of page faults", memCounters.PageFaultCount);
    COUTPUT("Peak working set size, in bytes", memCounters.PeakWorkingSetSize);
    COUTPUT("Working set size, in bytes", memCounters.WorkingSetSize);
    COUTPUT("Peak paged pool usage, in bytes", memCounters.QuotaPeakPagedPoolUsage);
    COUTPUT("Current paged pool usage, in bytes", memCounters.QuotaPagedPoolUsage);
    COUTPUT("Peak nonpaged pool usage, in bytes", memCounters.QuotaPeakNonPagedPoolUsage);
    COUTPUT("Current nonpaged pool usage, in bytes", memCounters.QuotaNonPagedPoolUsage);
    COUTPUT("Total amount of memory that the memory manager has committed for this running process", memCounters.PagefileUsage); // Win8+
    COUTPUT("Total amount of memory that the memory manager has committed for this running process", memCounters.PrivateUsage);  // Win7 and below
    COUTPUT("Peak value in bytes of the Commit Charge during the lifetime of this process", memCounters.PeakPagefileUsage);

    return 0;
}

```

# Answer
> 1 votes
Windows specific: you can use the Microsoft DirectX Diagnostics API to query the information gathered by the DirectX Diagnostics Tool (DxDiag).

Alternatively, you can call DxDiag via ShellExecute or the like, dump the results to file & then parse them.

---
Tags: c++
---


title: DirectX 12 and Feature levels

text:
# Question
Title: DirectX 12 and Feature levels
As far as I know the DirectX12 SDK that comes with the Windows 10 SDK can only be used on a Windows 10 machine. Although I'm not entirely sure about the runtime and the use of future levels (which came with `DX11`). Considering the radical API changes in `DX12`, is it possible to initiate a `level 11_0` device that will operate on the `DX11` runtime on Windows 7 for instance? Or am I getting the feature levels idea wrong?

# Answer
> 2 votes
You are confusing the "Runtime version" with the Direct3D Hardware Feature level. They are not the same thing.

The DirectX 12 API is only supported by the Windows 10 operating system. There is no update for older versions of Windows that would install the DirectX 12 API.

> If you need to support Windows 7, either use Direct3D 11 only or provide an alternative codepath that uses Direct3D 11.

The DirectX 12 API supports Feature Level 11.0, 11.1, 12.0, and 12.1 hardware. This also requires WDDM 2.0 drivers. Technically it would be possible for a video card manufacturer to make a driver for DirectX 12 that supported older Direct3D hardware feature levels, but there isn't one or likely to be one.

> If you need to support a broad range of video hardware, you should stick with Direct3D 11 which supports 9.1, 9.2, 9.3, 10.0, 10.1, 11.0, or later. Windows 8 or later is required to support Direct3D hardware feature level 11.1, and Windows 10 is required to support Direct3D hardware feature level 12.0 or 12.1.

See Direct3D Feature Levels and Direct3D 11 Deployment for Game Developers.

# Answer
> -2 votes
Any machine that can run DirectX 12 can run your program.

---
Tags: directx12
---


title: 2D Camera in LWJGL 3

text:
# Question
Title: 2D Camera in LWJGL 3
I am trying to implement a simple 2D camera in LWJGL3.

The camera has an orthographic projection and can move in 2D space.

This is run once at game start-up:

```
GL11.glMatrixMode(GL11.GL_PROJECTION);
GL11.glLoadIdentity();
GL11.glOrtho(0, graphics.window().width(), graphics.window().height(), 0, 1, -1);
GL11.glMatrixMode(GL11.GL_MODELVIEW);
GL11.glLoadIdentity();

```

This is run as part of the draw loop:

```
GL11.glMatrixMode(GL11.GL_PROJECTION);
GL11.glPushMatrix();
GL11.glTranslatef(-position.x(), -position.y(), 0f);

// Draw stuff

GL11.glPopMatrix();

```

Everything looks fine until I move the view, after which everything seems to be closer to the top left (0, 0) than it should be. It seems to be off by a scalar of the window size - the factor is greater in x than y.

How have I misunderstood the OpenGL commands?

# Answer
You put the translation data in the projection matrix. Don't do this, that matrix is strictly for converting 3d to 2d, put the camera stuff in the modelview matrix.
> 2 votes

# Answer
The OpenGL fixed pipeline has two different matrices for the camera.
* ModelView where you transform it (position, rotation, scale - Note that you have you should apply them in this order!)
* Projection where you apply the view matrix (orthographic, frustum, perspective)

My advise would be to use shaders for this, but you can stick to the fixed pipeline.

As Bálint already stated, the projection matrix is not for transformation.

However, if you want to load the identity matrix for the ModelView every call, you could transform it in the Projection matrix.
Do note that you shouldn't call the Push and Pop matrix in the Projection matrix.
> -1 votes

---
Tags: opengl, 2d, camera, lwjgl, lwjgl3
---


title: SFML: Optimizing sf::Text?

text:
# Question
Title: SFML: Optimizing sf::Text?
I've been noticing that using multiple sf::Text objects has a huge impact on performance.

The difference between using 1 or 4 sf::Text objects can result in almost a 40FPS drop (From 120 to 80).

```
ExampleText = new sf::Text();
ExampleText->setFont(*ResourceManager::GetInstance()->GetAceFont());
ExampleText->setColor(sf::Color::White);
ExampleText->setCharacterSize(36);

```

Am I not making them right? If somebody could even explain why this happens as the docs tell me sf::Text is really lightweight.

Any help would be appreciated.

# Answer
The problem was that the x and/or y position wasn't rounded, and apparently that causes the text to blur.

Also, it is possible the font has fixed sizes where it's sharp, and might not render good at different sizes. Example of this was one font that was only sharp at 16px and 24px, so keep that in mind as well.
> 0 votes

# Answer
I don't think your issue is necessarily with sf::Text -- I wrote up a small program to draw multiple sf::Texts and record the frames per second for 40 seconds, and got these results:

Drawing 1 sf::Text: Average 738.7 FPS
Drawing 4 sf::Texts: Average 735 FPS

That's a slight difference, but nowhere near your 40 FPS drop; you may want to double-check that nothing was changed other than the number of Text items drawn.

My program doesn't do anything special with the text items -- other than FPS counting, all it does is draw either 1 or all 4 of the sf::Text objects declared outside of the program loop (I could show the code if you want) -- which leads me to believe that the issue likely has something to do with how your program handles drawing & manipulating the Text objects.

I don't see anything particularly suspicious in the extract of code your post shows (assuming there's a reason you're creating the Text with new). It might help to be able to see where you actually draw them.

So, without knowledge of your code, there are a couple of potential causes that I can think of:

* For some reason, your text objects are being recreated each frame, or perhaps are resetting some of their data which needs to be drawn. The former could cause slight performance loss on its own, but both would require new vertex data to be sent to the GPU each frame, which can (potentially) be a performance loss more noticeable with more things to be drawn.
* Your draw code alternates between drawing various different textures (drawing text between drawing other objects?). Changing the active texture when drawing is not a cheap OpenGL operation. SFML uses OpenGL, and thus is partially vulnerable to this.
* Using multiple sf::Fonts alongside multiple sf::Texts. The sf::Font class is more computationally expensive than sf::Texts to use.
* Your program is simple enough that quadrupling the number of drawn texts is actually a pretty large increase in computational load.

Edit: How many frames per second do you get if you don't draw *any* of the sf::Text objects?
> 1 votes

---
Tags: rendering, optimization, sfml, text
---


title: Move relative to screen

text:
# Question
Title: Move relative to screen
I use top down 60 degree tilted camera and want move always visually straight directions relative to screen (up, down, left, right). When object is near screen edges it starts moving diagonally (visually) probably because of camera tilt.

I tried with `WorldToViewportPoint` / `ViewportPointToRay` but it doesnt work exactly because even when there is no input, conversion to viewport and back to world same value sometimes gives slighltly offset from start position.

```
float delta = Time.deltaTime;

float h = Input.GetAxisRaw("Horizontal");
float v = Input.GetAxisRaw("Vertical");

Vector3 view = MainCamera.WorldToViewportPoint(transform.position);

view.x = (h > 0) ? 1 : (h < 0) ? 0 : view.x;
view.y = (v > 0) ? 1 : (v < 0) ? 0 : view.y;

Ray ray = MainCamera.ViewportPointToRay(view);

RaycastHit hit;

Physics.Raycast(ray, out hit, Mathf.Infinity, 1 << 15); // 15 - ground plane layer

Vector3 world = new Vector3(hit.point.x, transform.position.y, hit.point.z);

Vector3 dir = (world - transform.position).normalized;

transform.position += dir * Speed * delta;

```

# Answer
> 1 votes
You are currently trying to **transform** a camera-space vector to a world-space vector, that's one of the best use case for **matrices**! ( I may get a bit too hyped about math-related questions)

I'll be honest, if I'd say I know Unity I would lie, but I know it has a `Matrix4x4` class, and that you can create a transformation matrix with the `TRS(Vector3 position, Quaternion rotation, Vector3 scale)` function. Because we don't want to move or scale the vector, we can pass a `(0; 0; 0)` and a `(1; 1; 1)` vector to position and scale respectively.

`rotation` is what we care the most about. For this you'll need the angles of your camera im a `Quaternion`, which if you don't have already, you can get like the following:

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

```

And you're almost done! Now you only need to pass these as an argument to the TRS function, then use the resulting matrix to get the world-space vector.

```
Matrix4x4 rotation = Matrix4x4.TRS(new Vector3(0, 0, 0), rotation, new Vector3(1, 1, 1));
// Here I assume your camera-space vector is a 2d vector named "move"
Vector4 worldSpaceMove = rotation * new Vector4(move.x, move.y, 0, 0);

```

And worldPosMove is your world-space vector. It's a 4d vector, because you can't multiply a 4x4 matrix with a 3d vector.

Edit:

Second approach:

The current solution moves the object on a plane. Because of this, the object gets actually farther from the camera at some points. To solve this problem, you need to move it around the camera.

This is also very simple: You need to get the vector between the camera and the object, rotate it around, then you can get the new position of the object by adding the vector to the camera's position:

```
Vector3 toObject = objectPosition - camera.transform.position;
Vector4 tempVector = new Vector4(toObject.x, toObject.y, toObject.z, 0);
// Note the order of the coordinates when creating the quaternion
Matrix4x4 rotation = Matrix4x4.TRS(new Vector3(0, 0, 0), Quaternion.Euler(move.y, move.x, 0), new Vector3(1, 1, 1));
tempVector *= rotation;
Vector3 newPosition = camera.transform.position + new Vector3(tempVector.x, tempVector.y, tempVector.z);

```

Now set the position of the object to newPosition.

# Answer
> 0 votes
Thanks for help. I made workaround to make it look move pretty straight. If anyone has more reliable and correct solution I will accept answer. Plane / box collider at layer 8.

```
float delta = Time.deltaTime;

float h = Input.GetAxisRaw("Horizontal");
float v = Input.GetAxisRaw("Vertical");

Vector3 screen = MainCamera.WorldToScreenPoint(transform.position);

Vector3 move = screen + new Vector3(h, v, 0);

Ray ray = MainCamera.ScreenPointToRay(screen);

RaycastHit hit;

Physics.Raycast(ray, out hit, Mathf.Infinity, 1 << 8);

Vector3 world = hit.point;

ray = MainCamera.ScreenPointToRay(move);

Physics.Raycast(ray, out hit, Mathf.Infinity, 1 << 8);

Vector3 dir = (hit.point - world).normalized;

transform.position += dir * Speed * delta;

```

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


# Question
Title: Models loaded with Assimp have messed up UVs/normals
I've been trying to use Assimp to load models and so far I got it to load a few obj models, but all of them have messed up UVs (and maybe normals).

Here's what it looks like :

I tried several combinations of Assimp's loading flags, but to no avail.

Here are the used flags :

```
const aiScene* scene = importer.ReadFile(path, aiProcess_Triangulate | aiProcess_FlipUVs|aiProcess_GenSmoothNormals|aiProcess_ImproveCacheLocality|aiProcess_FixInfacingNormals|aiProcess_FindDegenerates|aiProcess_FindInvalidData|aiProcess_GenUVCoords|aiProcess_TransformUVCoords);

```

I'm only loading already triangulated (with Blender) obj models with no submeshes.

Thanks in advance for any help.

# Answer
The problem actually didn't come from Assimp but from the way I internally stored assimp's UVs. I didn't take into account the fact that there can be no UVs some times and thus, I had random values when there were none.
> 1 votes

---
Tags: opengl, assimp
---


# Question
Title: Fail to change multiple sprite mecanim state using C# scripts
Above is the attachment of my mecanim state, hierarchy and folder in Animator.

The problem I'm facing now is fail to change multiple sprite mecanim state using C# script. When I move my sprite, I can successfully change it from idle to backwalk state, however it limit my changes solely to backwalk state but not all other states. I want to make it like when I press right arrow key it change to rightwalk state, while press left arrow key to change it to leftwalk state and so on. Unfortunately the if else statement that I declare is not working making my changing movement only stick to one state. I wonder what mistake I made, and how I can fix my code?

I'm a newbie to Unity and not familiar with C#. I just learn it from the official Unity tutorials series. I been searching for many related question regard of the problem but still I can't figure out the solution. This is the first question I ask at Game Stack Exchange, sorry if I violate any rules and please guide me through it. Appreciate anyone help sincerely.

Here I attach my code:

```
using UnityEngine;
using System.Collections;

public class CharacterMove : MonoBehaviour
{
    public float MoveSpeed = 1;
    float aspectspeedx = Screen.width / 1366;
    float aspectspeedy = Screen.height / 768;

// Use this for initialization
void Start()
{
    GameObject anim = GameObject.Find("taoist");
    anim.GetComponent<Animator>();
}

// Update is called once per frame
void Update()
{
    float MoveSpeed = 1f;
    // change the string to your parameter

    string characterfrontwalk = "taoist_front_walk";
    string characterbackwalk = "taoist_back_walk";
    string characterleftwalk = "taoist_left_walk";
    string characterrightwalk = "taoist_right_walk";
    /* if you want corner walk
    string characterrightfrontwalk = "taoist_right_front_walk";
    string characterrightbackwalk = "taoist_right_back_walk";
    string characterleftfrontwalk = "taoist_left_front_walk";
    string characterleftbackwalk = "taoist_left_back_walk";
    // to use this corner setting , you must initialize yourself

    */
    GameObject character = GameObject.Find("taoist");
    GameObject theanim = GameObject.Find("taoist");
    theanim.GetComponent<Animator>();
    theanim.GetComponent<Animator>().SetBool(characterfrontwalk, true);
    theanim.GetComponent<Animator>().SetBool(characterbackwalk, false);
    theanim.GetComponent<Animator>().SetBool(characterleftwalk, false);
    theanim.GetComponent<Animator>().SetBool(characterrightwalk, false);
    character.transform.localPosition = new Vector3(character.transform.localPosition.x, character.transform.localPosition.y + 0.05f * MoveSpeed, character.transform.localPosition.z);
    character.transform.localPosition = new Vector3(character.transform.localPosition.x - 0.05f * MoveSpeed, character.transform.localPosition.y, character.transform.localPosition.z);

    if (!(Input.GetKey("up") && Input.GetKey("right")) && !(Input.GetKey("up") && Input.GetKey("left")) && !(Input.GetKey("down") && Input.GetKey("right")) && !(Input.GetKey("down") && Input.GetKey("left")))
    {
        if (Input.GetKey("up"))
        {
            theanim.GetComponent<Animator>().SetBool(characterfrontwalk, true);
            theanim.GetComponent<Animator>().SetBool(characterbackwalk, false);
            theanim.GetComponent<Animator>().SetBool(characterleftwalk, false);
            theanim.GetComponent<Animator>().SetBool(characterrightwalk, false);

            character.transform.localPosition = new Vector3(character.transform.localPosition.x, character.transform.localPosition.y + 0.05f * MoveSpeed, character.transform.localPosition.z);
        }

        if (Input.GetKey("down"))
        {
            theanim.GetComponent<Animator>().SetBool(characterfrontwalk, false);
            theanim.GetComponent<Animator>().SetBool(characterbackwalk, true);
            theanim.GetComponent<Animator>().SetBool(characterleftwalk, false);
            theanim.GetComponent<Animator>().SetBool(characterrightwalk, false);

            character.transform.localPosition = new Vector3(character.transform.localPosition.x, character.transform.localPosition.y - 0.05f * MoveSpeed, character.transform.localPosition.z);
        }

        if (Input.GetKey("left"))
        {
            theanim.GetComponent<Animator>().SetBool(characterfrontwalk, false);
            theanim.GetComponent<Animator>().SetBool(characterbackwalk, false);
            theanim.GetComponent<Animator>().SetBool(characterleftwalk, true);
            theanim.GetComponent<Animator>().SetBool(characterrightwalk, false);

            character.transform.localPosition = new Vector3(character.transform.localPosition.x - 0.05f * MoveSpeed, character.transform.localPosition.y, character.transform.localPosition.z);
        }

        if (Input.GetKey("right"))
        {
            theanim.GetComponent<Animator>().SetBool(characterfrontwalk, false);
            theanim.GetComponent<Animator>().SetBool(characterbackwalk, false);
            theanim.GetComponent<Animator>().SetBool(characterleftwalk, false);
            theanim.GetComponent<Animator>().SetBool(characterrightwalk, true);

            character.transform.localPosition = new Vector3(character.transform.localPosition.x + 0.05f * MoveSpeed, character.transform.localPosition.y, character.transform.localPosition.z);
        }

    }

}

    /*

    // THIS CODE IS FOR CORNER MOVE , UN-MODIFIED , because im too tired to modify it sorry , you need to think yourself ;)

    if( Input.GetKey("down") && Input.GetKey("left")){

        theanim.GetComponent<Animator> ().SetBool ("MoveUp", false);
        theanim.GetComponent<Animator> ().SetBool ("MoveDown", false);
        theanim.GetComponent<Animator> ().SetBool ("MoveLeft", false);
        theanim.GetComponent<Animator> ().SetBool ("MoveRight", false);
        theanim.GetComponent<Animator> ().SetBool ("MoveLeftUp", false);
        theanim.GetComponent<Animator> ().SetBool ("MoveLeftDown", true);
        theanim.GetComponent<Animator> ().SetBool ("MoveRightDown", false);
        theanim.GetComponent<Animator> ().SetBool ("MoveRightUp", false);
        theanim.GetComponent<Animator> ().SetBool ("NotMoving", false);
        character.transform.localPosition = new Vector3 (character.transform.localPosition.x, character.transform.localPosition.y - 0.05f * MoveSpeed, character.transform.localPosition.z);
        character.transform.localPosition = new Vector3 (character.transform.localPosition.x - 0.05f * MoveSpeed, character.transform.localPosition.y, character.transform.localPosition.z);

    }

    if( Input.GetKey("up") && Input.GetKey("right")){

        theanim.GetComponent<Animator> ().SetBool ("MoveUp", false);
        theanim.GetComponent<Animator> ().SetBool ("MoveDown", false);
        theanim.GetComponent<Animator> ().SetBool ("MoveLeft", false);
        theanim.GetComponent<Animator> ().SetBool ("MoveRight", false);
        theanim.GetComponent<Animator> ().SetBool ("MoveLeftUp", false);
        theanim.GetComponent<Animator> ().SetBool ("MoveLeftDown", false);
        theanim.GetComponent<Animator> ().SetBool ("MoveRightDown", false);
        theanim.GetComponent<Animator> ().SetBool ("MoveRightUp", true);
        theanim.GetComponent<Animator> ().SetBool ("NotMoving", false);
        character.transform.localPosition = new Vector3 (character.transform.localPosition.x, character.transform.localPosition.y + 0.05f * MoveSpeed, character.transform.localPosition.z);
        character.transform.localPosition = new Vector3 (character.transform.localPosition.x + 0.05f * MoveSpeed, character.transform.localPosition.y, character.transform.localPosition.z);

    }
    if( Input.GetKey("down") && Input.GetKey("right")){

        theanim.GetComponent<Animator> ().SetBool ("MoveUp", false);
        theanim.GetComponent<Animator> ().SetBool ("MoveDown", false);
        theanim.GetComponent<Animator> ().SetBool ("MoveLeft", false);
        theanim.GetComponent<Animator> ().SetBool ("MoveRight", false);
        theanim.GetComponent<Animator> ().SetBool ("MoveLeftUp", false);
        theanim.GetComponent<Animator> ().SetBool ("MoveLeftDown", false);
        theanim.GetComponent<Animator> ().SetBool ("MoveRightDown", true);
        theanim.GetComponent<Animator> ().SetBool ("MoveRightUp", false);
        theanim.GetComponent<Animator> ().SetBool ("NotMoving", false);
        character.transform.localPosition = new Vector3 (character.transform.localPosition.x, character.transform.localPosition.y - 0.05f * MoveSpeed, character.transform.localPosition.z);
        character.transform.localPosition = new Vector3 (character.transform.localPosition.x + 0.05f * MoveSpeed, character.transform.localPosition.y, character.transform.localPosition.z);

    }
    // Un-MODIFIED corner setting , initialize yourself
        */

}

public class LastDirection
{
    public string thelastdirection;
}

```

# Answer
Instead of editing my last answer , i now really understand your problem :) , your first statement is look like this ( and its wrong ) :

As you see , your statement **cannot go to other direction because they don't have the way** , and the **only way to go** to other statement is **through idle** .

Then , how to fix it ? its simple , you must create their way to other direction so they don't need to go idle first to go "there" ( the other direction ) :

***First , sorry for bad draw because i used paint ;) .***

What i try to mean in the picture is , that **each of your statement must connect to all other statement with its own condition** , **and not only connect to idle state** , i know it is a long job and can take an hour but you must do it if you want .

Well , goodluck in your project :) , i can sure you will meet other problem that i have too here and you can ask me how-to-fix it ;) , and i can help your project if you want :) .

EDIT :

Yesterday you upload the picture of the statement like this :

But honestly , its not what called " **connect each statement to all statement** " , but what i was trying to mean is the statement **must connect like this** :
> 1 votes

# Answer
Instead of editing my last 2 answer ,i will just create new :p .

I fixed your character move animation .

**It used new script , and new ability is added :<br>\- Character Moving script without vertical and horizontal**

Preview :

https://www.youtube.com/watch?v=b3T7xROtJ3A&feature=youtu.be

The animation play well except the animation it-self i think , you need to make the animation become better ;) .

How - To - Import :

1. Download the file - \> https://goo.gl/3Dt0HQ , if the link dead tell me
2. If you don't want to import inside your project , create new project as test-project so you can assure it won't destroy your current project
3. Open scene at asset , the scene is named "sceneone"

**4. Try to play it and learn the different with your current script :)**

---

In case the scene and script not imported :

1. Create empty scene
2. Create two empty object , one called " taoistmoverobject " and " taoist "
3. Put taoist object inside taoistmoverobject scene
4. Find the animator and the script then tag it as component at " taoistmoverobject "
5. ( Optional ) Put camera inside " taoistmoverobject " if you want to make camera follow when character moving

---

**That all ;) , don't forget to learn from it :)**
> 1 votes

# Answer
I know what problem was going on because i had the trouble with it too , the problem is at both side , **the scripting and animator** .

To make it instantly change like from left instantly to right , **you must connect / put transition between all animation with it own condition** .

Not just like from idle -\> right , but also right -\> left , right -\> down , right -\> up and ect .

**Never use vertical and horizontal method , its not work the best , just detect which button the user hold and do the movement .**

The preview is look like this :

https://www.youtube.com/embed/rivOHgxp2Cw
or
https://www.youtube.com/watch?v=rivOHgxp2Cw

and this is the script i used for your example ;) learn how the script work and watch the preview video .

```
using UnityEngine;
using System.Collections;

public class CharacterMove : MonoBehaviour {
 public float MoveSpeed = 1;
 float aspectspeedx = Screen.width / 1366;
 float aspectspeedy = Screen.height / 768;

 // Use this for initialization
 void Start () {
  GameObject anim = GameObject.Find("Character");
  anim.GetComponent<Animator> ();
 }

 // Update is called once per frame
 void Update () {
  LastDirection lastdirectionvar = new LastDirection ();
  GameObject character = GameObject.Find("Character");
  GameObject theanim = GameObject.Find("Character");
  theanim.GetComponent<Animator> ();
  /*

   Change one of them to true

    theanim.GetComponent<Animator> ().SetBool ("MoveUp", false);
   theanim.GetComponent<Animator> ().SetBool ("MoveDown", false);
   theanim.GetComponent<Animator> ().SetBool ("MoveLeft", false);
   theanim.GetComponent<Animator> ().SetBool ("MoveRight", false);
   theanim.GetComponent<Animator> ().SetBool ("MoveLeftUp", false);
   theanim.GetComponent<Animator> ().SetBool ("MoveLeftDown", false);
   theanim.GetComponent<Animator> ().SetBool ("MoveRightDown", false);
   theanim.GetComponent<Animator> ().SetBool ("MoveRightUp", false);
   theanim.GetComponent<Animator> ().SetBool ("NotMoving", false);
   */
  /* if (!(Input.GetKey ("up") || Input.GetKey ("down") || Input.GetKey ("left") || Input.GetKey ("right"))) {
   theanim.GetComponent<Animator> ().SetBool ("MoveUp", false);
   theanim.GetComponent<Animator> ().SetBool ("MoveDown", false);
   theanim.GetComponent<Animator> ().SetBool ("MoveLeft", false);
   theanim.GetComponent<Animator> ().SetBool ("MoveRight", false);
   theanim.GetComponent<Animator> ().SetBool ("MoveLeftUp", false);
   theanim.GetComponent<Animator> ().SetBool ("MoveLeftDown", false);
   theanim.GetComponent<Animator> ().SetBool ("MoveRightDown", false);
   theanim.GetComponent<Animator> ().SetBool ("MoveRightUp", false);
   // if (lastdirectionvar.thelastdirection == "down") {
    theanim.GetComponent<Animator> ().SetBool ("NotMoving", true);

   // }
  } */
  if( Input.GetKey("up") && Input.GetKey("left")){

   theanim.GetComponent<Animator> ().SetBool ("MoveUp", false);
   theanim.GetComponent<Animator> ().SetBool ("MoveDown", false);
   theanim.GetComponent<Animator> ().SetBool ("MoveLeft", false);
   theanim.GetComponent<Animator> ().SetBool ("MoveRight", false);
   theanim.GetComponent<Animator> ().SetBool ("MoveLeftUp", true);
   theanim.GetComponent<Animator> ().SetBool ("MoveLeftDown", false);
   theanim.GetComponent<Animator> ().SetBool ("MoveRightDown", false);
   theanim.GetComponent<Animator> ().SetBool ("MoveRightUp", false);
   theanim.GetComponent<Animator> ().SetBool ("NotMoving", false);
   character.transform.localPosition = new Vector3 (character.transform.localPosition.x, character.transform.localPosition.y + 0.05f * MoveSpeed, character.transform.localPosition.z);
   character.transform.localPosition = new Vector3 (character.transform.localPosition.x - 0.05f * MoveSpeed, character.transform.localPosition.y, character.transform.localPosition.z);

   }

  if( Input.GetKey("down") && Input.GetKey("left")){

   theanim.GetComponent<Animator> ().SetBool ("MoveUp", false);
   theanim.GetComponent<Animator> ().SetBool ("MoveDown", false);
   theanim.GetComponent<Animator> ().SetBool ("MoveLeft", false);
   theanim.GetComponent<Animator> ().SetBool ("MoveRight", false);
   theanim.GetComponent<Animator> ().SetBool ("MoveLeftUp", false);
   theanim.GetComponent<Animator> ().SetBool ("MoveLeftDown", true);
   theanim.GetComponent<Animator> ().SetBool ("MoveRightDown", false);
   theanim.GetComponent<Animator> ().SetBool ("MoveRightUp", false);
   theanim.GetComponent<Animator> ().SetBool ("NotMoving", false);
   character.transform.localPosition = new Vector3 (character.transform.localPosition.x, character.transform.localPosition.y - 0.05f * MoveSpeed, character.transform.localPosition.z);
   character.transform.localPosition = new Vector3 (character.transform.localPosition.x - 0.05f * MoveSpeed, character.transform.localPosition.y, character.transform.localPosition.z);

  }

  if( Input.GetKey("up") && Input.GetKey("right")){

   theanim.GetComponent<Animator> ().SetBool ("MoveUp", false);
   theanim.GetComponent<Animator> ().SetBool ("MoveDown", false);
   theanim.GetComponent<Animator> ().SetBool ("MoveLeft", false);
   theanim.GetComponent<Animator> ().SetBool ("MoveRight", false);
   theanim.GetComponent<Animator> ().SetBool ("MoveLeftUp", false);
   theanim.GetComponent<Animator> ().SetBool ("MoveLeftDown", false);
   theanim.GetComponent<Animator> ().SetBool ("MoveRightDown", false);
   theanim.GetComponent<Animator> ().SetBool ("MoveRightUp", true);
   theanim.GetComponent<Animator> ().SetBool ("NotMoving", false);
   character.transform.localPosition = new Vector3 (character.transform.localPosition.x, character.transform.localPosition.y + 0.05f * MoveSpeed, character.transform.localPosition.z);
   character.transform.localPosition = new Vector3 (character.transform.localPosition.x + 0.05f * MoveSpeed, character.transform.localPosition.y, character.transform.localPosition.z);

  }
  if( Input.GetKey("down") && Input.GetKey("right")){

   theanim.GetComponent<Animator> ().SetBool ("MoveUp", false);
   theanim.GetComponent<Animator> ().SetBool ("MoveDown", false);
   theanim.GetComponent<Animator> ().SetBool ("MoveLeft", false);
   theanim.GetComponent<Animator> ().SetBool ("MoveRight", false);
   theanim.GetComponent<Animator> ().SetBool ("MoveLeftUp", false);
   theanim.GetComponent<Animator> ().SetBool ("MoveLeftDown", false);
   theanim.GetComponent<Animator> ().SetBool ("MoveRightDown", true);
   theanim.GetComponent<Animator> ().SetBool ("MoveRightUp", false);
   theanim.GetComponent<Animator> ().SetBool ("NotMoving", false);
   character.transform.localPosition = new Vector3 (character.transform.localPosition.x, character.transform.localPosition.y - 0.05f * MoveSpeed, character.transform.localPosition.z);
   character.transform.localPosition = new Vector3 (character.transform.localPosition.x + 0.05f * MoveSpeed, character.transform.localPosition.y, character.transform.localPosition.z);

  }

  if ( !(Input.GetKey("up") && Input.GetKey("right")) && !(Input.GetKey("up") && Input.GetKey("left")) && !(Input.GetKey("down") && Input.GetKey("right")) && !(Input.GetKey("down") && Input.GetKey("left")) ) {
   if (Input.GetKey ("up")) {
    theanim.GetComponent<Animator> ().SetBool ("MoveUp", true);
    theanim.GetComponent<Animator> ().SetBool ("MoveDown", false);
    theanim.GetComponent<Animator> ().SetBool ("MoveLeft", false);
    theanim.GetComponent<Animator> ().SetBool ("MoveRight", false);
    theanim.GetComponent<Animator> ().SetBool ("MoveLeftUp", false);
    theanim.GetComponent<Animator> ().SetBool ("MoveLeftDown", false);
    theanim.GetComponent<Animator> ().SetBool ("MoveRightDown", false);
    theanim.GetComponent<Animator> ().SetBool ("MoveRightUp", false);
    theanim.GetComponent<Animator> ().SetBool ("NotMoving", false);
    character.transform.localPosition = new Vector3 (character.transform.localPosition.x, character.transform.localPosition.y + 0.05f * MoveSpeed, character.transform.localPosition.z);
   }
   if (Input.GetKey ("down")) {
    theanim.GetComponent<Animator> ().SetBool ("MoveUp", false);
    theanim.GetComponent<Animator> ().SetBool ("MoveDown", true);
    theanim.GetComponent<Animator> ().SetBool ("MoveLeft", false);
    theanim.GetComponent<Animator> ().SetBool ("MoveRight", false);
    theanim.GetComponent<Animator> ().SetBool ("MoveLeftUp", false);
    theanim.GetComponent<Animator> ().SetBool ("MoveLeftDown", false);
    theanim.GetComponent<Animator> ().SetBool ("MoveRightDown", false);
    theanim.GetComponent<Animator> ().SetBool ("MoveRightUp", false);
    theanim.GetComponent<Animator> ().SetBool ("NotMoving", false);
    character.transform.localPosition = new Vector3 (character.transform.localPosition.x, character.transform.localPosition.y - 0.05f * MoveSpeed, character.transform.localPosition.z);
   }
   if (Input.GetKey ("left")) {
    theanim.GetComponent<Animator> ().SetBool ("MoveUp", false);
    theanim.GetComponent<Animator> ().SetBool ("MoveDown", false);
    theanim.GetComponent<Animator> ().SetBool ("MoveLeft", true);
    theanim.GetComponent<Animator> ().SetBool ("MoveRight", false);
    theanim.GetComponent<Animator> ().SetBool ("MoveLeftUp", false);
    theanim.GetComponent<Animator> ().SetBool ("MoveLeftDown", false);
    theanim.GetComponent<Animator> ().SetBool ("MoveRightDown", false);
    theanim.GetComponent<Animator> ().SetBool ("MoveRightUp", false);
    theanim.GetComponent<Animator> ().SetBool ("NotMoving", false);
    character.transform.localPosition = new Vector3 (character.transform.localPosition.x - 0.05f * MoveSpeed, character.transform.localPosition.y, character.transform.localPosition.z);
   }
   if (Input.GetKey ("right")) {
    theanim.GetComponent<Animator> ().SetBool ("MoveUp", false);
    theanim.GetComponent<Animator> ().SetBool ("MoveDown", false);
    theanim.GetComponent<Animator> ().SetBool ("MoveLeft", false);
    theanim.GetComponent<Animator> ().SetBool ("MoveRight", true);
    theanim.GetComponent<Animator> ().SetBool ("MoveLeftUp", false);
    theanim.GetComponent<Animator> ().SetBool ("MoveLeftDown", false);
    theanim.GetComponent<Animator> ().SetBool ("MoveRightDown", false);
    theanim.GetComponent<Animator> ().SetBool ("MoveRightUp", false);
    theanim.GetComponent<Animator> ().SetBool ("NotMoving", false);
    character.transform.localPosition = new Vector3 (character.transform.localPosition.x + 0.05f * MoveSpeed, character.transform.localPosition.y, character.transform.localPosition.z);
   }

  }

  /* if (Input.GetAxisRaw ("Horizontal") > 0.5f || Input.GetAxisRaw("Horizontal") < -0.5f) {
   character.transform.Translate (new Vector3 (Input.GetAxisRaw ("Horizontal") * MoveSpeed * Time.deltaTime, 0f, 0f));
  }
  if (Input.GetAxisRaw ("Vertical") > 0.5f || Input.GetAxisRaw ("Vertical") < -0.5f ) {
   character.transform.Translate (new Vector3 (0f,Input.GetAxisRaw ("Vertical") * MoveSpeed * Time.deltaTime,0f));
  }

  anim.GetComponent<Animator> ().SetFloat ("MoveX", Input.GetAxisRaw ("Horizontal"));
  anim.GetComponent<Animator> ().SetFloat ("MoveY", Input.GetAxisRaw ("Vertical")); */

 }
}

public class LastDirection {
  public string thelastdirection;
}
```

This is code for your character :

```
void Update () {
        float MoveSpeed = 1f;

          // change it to your object name that work as character

           string charactername = "taoist";

        // change the string to your parameter

        string characterfrontwalk = "taoist_front_walk";
        string characterbackwalk = "taoist_back_walk";
        string characterleftwalk = "taoist_left_walk";
        string characterrightwalk = "taoist_right_walk";
        /* if you want corner walk
        string characterrightfrontwalk = "taoist_right_front_walk";
        string characterrightbackwalk = "taoist_right_back_walk";
        string characterleftfrontwalk = "taoist_left_front_walk";
        string characterleftbackwalk = "taoist_left_back_walk";
        // to use this corner setting , you must initialize yourself

        */
  GameObject character = GameObject.Find(charactername);
  GameObject theanim = GameObject.Find(charactername);
  theanim.GetComponent<Animator> ();
   theanim.GetComponent<Animator> ().SetBool (characterfrontwalk, true);
   theanim.GetComponent<Animator> ().SetBool (characterbackwalk, false);
   theanim.GetComponent<Animator> ().SetBool (characterleftwalk, false);
   theanim.GetComponent<Animator> ().SetBool (characterrightwalk, false);
   character.transform.localPosition = new Vector3 (character.transform.localPosition.x, character.transform.localPosition.y + 0.05f * MoveSpeed, character.transform.localPosition.z);
   character.transform.localPosition = new Vector3 (character.transform.localPosition.x - 0.05f * MoveSpeed, character.transform.localPosition.y, character.transform.localPosition.z);

   }

  /*

        // THIS CODE IS FOR CORNER MOVE , UN-MODIFIED , because im too tired to modify it sorry , you need to think yourself ;)

        if( Input.GetKey("down") && Input.GetKey("left")){

   theanim.GetComponent<Animator> ().SetBool ("MoveUp", false);
   theanim.GetComponent<Animator> ().SetBool ("MoveDown", false);
   theanim.GetComponent<Animator> ().SetBool ("MoveLeft", false);
   theanim.GetComponent<Animator> ().SetBool ("MoveRight", false);
   theanim.GetComponent<Animator> ().SetBool ("MoveLeftUp", false);
   theanim.GetComponent<Animator> ().SetBool ("MoveLeftDown", true);
   theanim.GetComponent<Animator> ().SetBool ("MoveRightDown", false);
   theanim.GetComponent<Animator> ().SetBool ("MoveRightUp", false);
   theanim.GetComponent<Animator> ().SetBool ("NotMoving", false);
   character.transform.localPosition = new Vector3 (character.transform.localPosition.x, character.transform.localPosition.y - 0.05f * MoveSpeed, character.transform.localPosition.z);
   character.transform.localPosition = new Vector3 (character.transform.localPosition.x - 0.05f * MoveSpeed, character.transform.localPosition.y, character.transform.localPosition.z);

  }

  if( Input.GetKey("up") && Input.GetKey("right")){

   theanim.GetComponent<Animator> ().SetBool ("MoveUp", false);
   theanim.GetComponent<Animator> ().SetBool ("MoveDown", false);
   theanim.GetComponent<Animator> ().SetBool ("MoveLeft", false);
   theanim.GetComponent<Animator> ().SetBool ("MoveRight", false);
   theanim.GetComponent<Animator> ().SetBool ("MoveLeftUp", false);
   theanim.GetComponent<Animator> ().SetBool ("MoveLeftDown", false);
   theanim.GetComponent<Animator> ().SetBool ("MoveRightDown", false);
   theanim.GetComponent<Animator> ().SetBool ("MoveRightUp", true);
   theanim.GetComponent<Animator> ().SetBool ("NotMoving", false);
   character.transform.localPosition = new Vector3 (character.transform.localPosition.x, character.transform.localPosition.y + 0.05f * MoveSpeed, character.transform.localPosition.z);
   character.transform.localPosition = new Vector3 (character.transform.localPosition.x + 0.05f * MoveSpeed, character.transform.localPosition.y, character.transform.localPosition.z);

  }
  if( Input.GetKey("down") && Input.GetKey("right")){

   theanim.GetComponent<Animator> ().SetBool ("MoveUp", false);
   theanim.GetComponent<Animator> ().SetBool ("MoveDown", false);
   theanim.GetComponent<Animator> ().SetBool ("MoveLeft", false);
   theanim.GetComponent<Animator> ().SetBool ("MoveRight", false);
   theanim.GetComponent<Animator> ().SetBool ("MoveLeftUp", false);
   theanim.GetComponent<Animator> ().SetBool ("MoveLeftDown", false);
   theanim.GetComponent<Animator> ().SetBool ("MoveRightDown", true);
   theanim.GetComponent<Animator> ().SetBool ("MoveRightUp", false);
   theanim.GetComponent<Animator> ().SetBool ("NotMoving", false);
   character.transform.localPosition = new Vector3 (character.transform.localPosition.x, character.transform.localPosition.y - 0.05f * MoveSpeed, character.transform.localPosition.z);
   character.transform.localPosition = new Vector3 (character.transform.localPosition.x + 0.05f * MoveSpeed, character.transform.localPosition.y, character.transform.localPosition.z);

  }
        // Un-MODIFIED corner setting , initialize yourself
            */
  if ( !(Input.GetKey("up") && Input.GetKey("right")) && !(Input.GetKey("up") && Input.GetKey("left")) && !(Input.GetKey("down") && Input.GetKey("right")) && !(Input.GetKey("down") && Input.GetKey("left")) ) {
   if (Input.GetKey ("up")) {
    theanim.GetComponent<Animator> ().SetBool (characterfrontwalk, true);
    theanim.GetComponent<Animator> ().SetBool (characterbackwalk, false);
    theanim.GetComponent<Animator> ().SetBool (characterleftwalk, false);
    theanim.GetComponent<Animator> ().SetBool (characterrightwalk, false);

    character.transform.localPosition = new Vector3 (character.transform.localPosition.x, character.transform.localPosition.y + 0.05f * MoveSpeed, character.transform.localPosition.z);
   }
   if (Input.GetKey ("down")) {
    theanim.GetComponent<Animator> ().SetBool (characterfrontwalk, false);
    theanim.GetComponent<Animator> ().SetBool (characterbackwalk, true);
    theanim.GetComponent<Animator> ().SetBool (characterleftwalk, false);
    theanim.GetComponent<Animator> ().SetBool (characterrightwalk, false);
    character.transform.localPosition = new Vector3 (character.transform.localPosition.x, character.transform.localPosition.y - 0.05f * MoveSpeed, character.transform.localPosition.z);
   }
   if (Input.GetKey ("left")) {
    theanim.GetComponent<Animator> ().SetBool (characterfrontwalk, false);
    theanim.GetComponent<Animator> ().SetBool (characterbackwalk, false);
    theanim.GetComponent<Animator> ().SetBool (characterleftwalk, true);
    theanim.GetComponent<Animator> ().SetBool (characterrightwalk, false);
    character.transform.localPosition = new Vector3 (character.transform.localPosition.x - 0.05f * MoveSpeed, character.transform.localPosition.y, character.transform.localPosition.z);
   }
   if (Input.GetKey ("right")) {
    theanim.GetComponent<Animator> ().SetBool (characterfrontwalk, false);
    theanim.GetComponent<Animator> ().SetBool (characterbackwalk, false);
    theanim.GetComponent<Animator> ().SetBool (characterleftwalk, false);
    theanim.GetComponent<Animator> ().SetBool (characterrightwalk, true);
    character.transform.localPosition = new Vector3 (character.transform.localPosition.x + 0.05f * MoveSpeed, character.transform.localPosition.y, character.transform.localPosition.z);
   }

  }

 }
```
> 0 votes

---
Tags: c#
---


# Question
Title: Why is OpenGL point (0,0) not in top-left corner of the screen?
Most of computer graphics systems use screen's top-left corner as staring point, but OpenGL uses bottom-to-top direction, why?

# Answer
Probably because that's how coordinate systems are traditionally set up when doing math. But to be honest, OpenGL can have its origin anywhere you want and its axes can point in any direction you want (well, so long as they are perpendicular to each other). If you want the origin in the top left and the Y-axis to point down, you simply set your model-view matrix to have a negative Y scale and a Y offset the height of the screen.
> 8 votes

# Answer
Think back to the graphs you would draw in school.

The (0,0) point is at bottom-left.

Now, OpenGL is an old, old API and it's derived from an even older one. There were no gaming graphics then; 3D graphics required an expensive workstation with an expensive professional accelerator, and were used for graphing, for CAD, for other professional tasks.

Hence OpenGL follows suit and places it's origin at bottom-left.
> 6 votes

# Answer
Perspective division performed on the Clip Coordinates produces Normalized Device Coordinates, ranging from -1 to 1 in all three axes. https://www.opengl.org/archives/resources/faq/technical/transformations.htm
> 2 votes

---
Tags: opengl, screen, axis
---


# Question
Title: Load the prefab in the array by name in Unity
I'm using this line of code to select my level, and currently I have different scenes for each levels. I want to be able to reuse the same scene to change levels as well but I don't know how, here's the line:

```
button.GetComponent<Button>().onClick.AddListener(() => Levels("Level " + button.levelText.text));

```

Since I'm using string to load my scene with the function below:

```
void Levels(string value)
{
    SceneManager.LoadScene(value);
}

```

I really wish I could use prefab name instead the scene name and I don't want to have 20 scenes for it. Any help would be appreciated.

# Answer
Sorry for being this late but I already solved it, here;s how I've done it

```
void Levels(string value)
{
    CreateLevel.currentLevel = int.Parse(value);
    SceneManager.LoadScene(1);
}

```

Since I'm using my

> button.levelText.text

to assign each buttons, I just convert the

> string value

to integer

And call the static int

> currentLevel

from this script

```
public GameObject[] Levels;
public static int currentLevel = 0;

void Start () {
    GameObject obj = Instantiate(Levels[currentLevel-1]) as GameObject;
}

```

and I just drag the prefabs into the inspector so when I click on the button with certain number, it will load the prefab with the same index number as the text on the button from previous scene.
> 0 votes

# Answer
Have a look at Resources.Load(). To work properly, the prefab must be in a folder called "Resources", and you load it by its filename (not including "Resources/" or ".prefab").

Use it like this:

```
GameObject nextLevel = Resources.Load<GameObject>("Levels/Level2");

```
> 1 votes

# Answer
In order to associate a button press with an index into your array of prefabs, you could create something like the following:

```
public class LevelLoader : MonoBehaviour
{
    public Object[] levelPrefabs;

    public void Load(int levelIndex)
    {
        if (levelIndex >= 0 && levelIndex < levelPrefabs.Length)
        {
            Instantiate(levelPrefabs[levelIndex]);
        }
        else
        {
            Debug.LogError("Invalid level index: " + levelIndex);
        }
    }
}

```

By adding this to a GameObject in your scene, you can register the Load method to the OnClick event and pass in the appropriate level index.

One further readability improvement could be to use an enum instead of plain ints:

```
public class LevelLoader : MonoBehaviour
{
    public enum Level
    {
        Tutorial,
        Level1,
        Level2,
        FinalBoss
    }

    public Object[] levelPrefabs;

    public void Load(Level level)
    {
        int levelIndex = (int)level;
        if (levelIndex >= 0 && levelIndex < levelPrefabs.Length)
        {
            Instantiate(levelPrefabs[levelIndex]);
        }
        else
        {
            Debug.LogError("Invalid level index: " + levelIndex);
        }
    }
}

```

This just ensures that in the editor you are using readable values, so is less error-prone (still no guarantee that your array is correctly setup).
> 1 votes

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


# Question
Title: How to calculate distance of travel needed get achieve speed x?
I have a boat traveling at 20 meters/second approaching destination x. Destination x has a range radius of 10 meters. What I would like to do is make sure by the time the boat arrives within 10 meters of destination x (i.e. boat gets to touch the orange circle) the boat speed is brought down to 5 m/s. The boat can decelerate at a rate of `0.5 m/s^2`.

**My solution:**

I believe I need to first calculate the distance required to slow down to 5 m/s.

using the following equation of motion:

`v^2 = u^2 + 2as`

where:

* v: final velocity
* u: initial velocity
* a: acceleration; -acceleration = deceleration
* s: displacement or distance

we can rearrange the variables in the formula above like so:

`s=(u^2-v^2)/(-2a)`

applying the following given variables:

* v = 5
* u = 20
* a = -0.5

we have:

`s=(20^2-5^2)/(-2(-0.5)) = (400-25)/1 = 375`

this means that at any moment of travel we need a distance of 375 meters to slow down from 20 m/s to 5 m/s. Now adding the fact that we need to slow down *before* we reach the circumference of the orange circle, we need to make sure we are at least 375 meters away.

Since we know location x, then we calculate distance from boat to `(x + 10 meters)`, call it d.

* We check if `375 <= d` then we start to decelerate the boat?
* Is the distance required to achieve speed 5 m/s while decelerating from 20 m/s is 375 meters?
* Is my approach correct? Are my calculations correct?

# Answer
First of all `v^2 = u^2 + 2as` rearranges to `s = (v^2 - u^2)/2a`.

> We check if 375 \<= d then we start to decelerate the boat?

Yes, but this assumes `u` and `a` are always known; but, **this assumes you're using radial coordinates.**

> Is the distance required to achieve speed 5 m/s while decelerating from 20 m/s is 375 meters?

Yes, given an initial velocity of 20m/s **in the direction of the destination**, an initial distance of 375m, and an acceleration of -0.5m/s. Again, this assumes these variables are known at the time of calculation.

> Is my approach correct? Are my calculations correct?

Your approach is technically correct; however, what's the use case? All we know is that the boat needs to travel to the specified point with the constraint that it decelerates to 5m/s within 10m of the post. Are you using X-Y Coordinates? if so, then the equations double!

```
x=(u_x^2-v_x^2)/(-2a_x)

y=(u_y^2-v_y^2)/(-2a_y)

```

If the boat's initial velocity is arbitrary, then it must be taken into account. If it's initial position is also arbitrary, then that as well must be accounted for!

```
X = x_target - x_boat

Y = y_target - y_boat

a_x = (v_x^2-u^2)/(2X)

a_y = (v_y^2-u^2)/(2Y)

```

Reset the boats acceleration to `a_x` and `a_y` and you don't have to make any further changes. It will 'naturally' reach the desired point.

If, the initial acceleration is also arbitrary, then you'll need to use an entirely different set of kinematic equations...
> 1 votes

# Answer
Yes to all three.

However I think it would be more clear to define the condition for deacceleration this way.

r0 = target radius around x (10m here); r = distance from x to boat.

So the condition would be `(r - r0) <= 375`. A point + a scalar (x + 10 meters) doesn't really make a lot of sense.
> 1 votes

---
Tags: collision-detection, physics, mathematics
---


title: How do you store uniform data?

text:
# Question
Title: How do you store uniform data?
In a general purpose C++ rendering engine, one way of organizing data is to divide mesh data into two classes: the geometry and the material. The geometry class includes indices, vertices, normals, and texture coordinates. The material class, as established by this answer, is often used to store the shader and uniforms.

Uniforms can be many types, such as an int or a float. So you can't just have one member variable in your material class defined `std::vector<GLint> uniforms`, as in that case you would only be able to add uniforms of integer type. There are two solutions that I know of:

1. **Adding a vector for each type of data you want to use**
In this case the material class would look like the following:

```
class Material {
  ....
  std::vector<GLint> intUniforms;
  std::vector<GLfloat> floatUniforms;
}

```

The problem with this is that it is very verbose and would probably require a lot of different functions (for each type) to add and delete uniforms.

2. **Creating a class called Uniform, having a member variable of type any.**

```
class Uniform {
  UniformType type;
  GLuint size;
  any value; // This will be a float/vec2/vec3 ...
}

class Material {
  std::vector<Uniform> uniforms;
}

```

However, using the 'any' class feels cheaty and seems to break the static typing design pattern used in C++.

My question was, is there another method of storing variable uniform data that supports a set of types without being verbose or using the any class? Or is there a design flaw with this approach and I should organize the Geometry/Shader/Uniform data differently?

# Answer
> 8 votes
Neither of your solutions are ideal.

First, realize that the `glUniform*` calls are mostly a *bad idea*. Don't use them. Use Uniform Buffers instead. The buffers offer several primary benefits.

One benefit is that you can separate out big blocks of "constant" uniforms (any per-model or per-instance data) into its own uniform buffer and then only need to bind that buffer rather than needing to bind many individual uniforms. Another is that the buffer binding can also be shared across many shaders if necessary. Third, you can bulk upload related sets of uniform data.

In general, uniform buffer objects are much closer to how the actual hardware works, and will results in faster graphics pipelines. That's not a hard rule, mind, but a decent guideline; you're best off testing and measuring, of course.

Once you move to uniform buffers you might find yourself facing the same problem though slightly rephrased: what uniforms exist in your buffer, what are their types, and what are their offsets?

There are two main solutions here. The first is to standardize your buffers. Different shaders should use an identical layout for, say, your per-frame camera information (eye position, screen dimensions, projection matrices, etc.). Then your CPU-side code doesn't need to "detect" anything or handle different layouts. It just prepares the per-frame uniform buffer in a single hard-coded way and all the shader consume that buffer is a single *ahem* uniform way (use a shader preprocessor to just #include shader code that declares the uniform buffer, its binding location, and its layout properties). If you change the shader code, change the C++ code to match.

That technique can take you surprisingly far. You're likely to find that the vast majority of your shaders use the same sets of inputs from the native code. Hardcode those and enforce that shaders consume the data in the format your CPU code prepares. This essentially reverses your original problem: instead of CPU code being dependent on shader layouts, the shader layout is dependent on CPU code. The shader preprocessor keeps the code in sync. (Depending on the shader language, you might even be able to share the exact same `.h` file between your shader and your CPU code.)

For content-driven shaders with per-model uniform attributes, the above may or may not work. In these cases, though, you might note two things: (1) the runtime code never modifies these values so the buffer contents only matter to the shader and the editor, and (2) since these values are per-model you probably want them in a separate buffer from your per-instance or per-frame values so you can make minimal rebinds and uploads.

The editor doesn't need to be particularly speedy. You can store your uniforms in whatever format you want, so long as you bake them down into the proper bag of bytes for export to the shader. One approach here is to use *metadata* to describe the uniform values of the model, something like:

```
struct ShaderUniformMetadata {
  char* data = nullptr;
  EType* uniformTypes = nullptr;
  uint16_t* uniformOffsets = 0;
  uint16_t size = 0;
  uint16_t uniformCount = 0;
};

```

The metadata contains information about the available uniforms and their types. To read/write a uniform, `memcpy` from/to `data + uniformOffsets[index]`, using the value in `uniformTypes[index]` to know the correct size.

To calculate the size of the buffer, sum up the appropriate sizes/alignments from the uniforms. An algorithm can pack the values appropriately to get the minimal size while maintaining the necessary alignment for each input.

To actually create the buffer at runtime, just load whole blob from your game data file and then pass the `size` and `data` values to `glBufferStorage`. Now you just bind that buffer before rendering that model.

Your per-instance buffers are the hard-coded layouts so there's not a lot of special magic to do there.

# Answer
> 0 votes
If you want to avoid storing a 'type' variable, then polymorphism is maybe what you're looking for.

An example:

```
struct Uniform
{
  int id;
  virtual void Send() = 0;
};

struct IntUniform : Uniform
{
  int value;
  void Send()
  {
    glUniform1i(id, value);
  }
};

struct FloatUniform : Uniform
{
  float value;
  void Send()
  {
    glUniform1f(id, value);
  }
};

struct Material
{
   std::vector<Uniform*> uniforms;
};

```

If you're willing to give up genericity for performance, here's how an engine I wrote works.

```
int activeShader;

struct Shader
{
 ... methods to create & bind shader
};

struct ShaderUniform
{
    Uint id;
    ShaderUniform() {}
    void Link(const char* identifier)
    {
        id = glGetUniformLocation(activeShader, identifier);
    }
    void operator<<(float value) {
        glUniform1f(id, value);
    }
    void operator<<(Vector4 value) {
        glUniform4fv(id, 1, &value[0]);
    }
    void operator<<(Vector3 value) {
        glUniform3fv(id, 1, &value[0]);
    }
    void operator<<(Vector2 value) {
        glUniform2fv(id, 1, &value[0]);
    }
    void operator<<(Matrix4 value)
    {
        glUniformMatrix4fv(id, 1, GL_FALSE, &value[0][0]);
    }
    (...)
};

struct : Shader
{
    ShaderUniform cameraMatrix, wind(...)

    void Initialise()
    {
       cameraMatrix.Link("cameraMatrix");
       wind.Link("wind");
       (...)
    }
} MyShaderABC;

```

Usage:

```
MyShaderABC.Use();
for (int i=0;i<objectsOfSomeKind.quantity;i++)
{
   Matrix4 someMatrix;
   float someFloat;

   MyShaderABC.cameraMatrix << someMatrix;
   MyShaderABC.someVariable << someFloat;
}

```

Note that there is no security, you can send the float into the matrix uniform, but if you're the one using the engine, that's not a problem.

---
Tags: opengl, c++, architecture
---


title: Shader or No Shader?

text:
# Question
Title: Shader or No Shader?
I have a question about something I don't really understand. In OpenTK, should I have shaders? Is it frowned upon not to? What are the pros and cons of having shaders? Can I go perfectly fine without having anything to do with vertex or fragment shaders?

# Answer
> -1 votes
> In OpenTK, should I have shaders?

Generally yes; however, it largely depends on the context. See below for why.

> Is it frowned upon not to?

Generally yes; however, it largely depends on the context:

If your game **uses lighting**: **Yes**

If your game **doesn't** use lighting: **No**, it's not necessary.

> What are the pros and cons of having shaders?

Bobobobo's answer at https://gamedev.stackexchange.com/a/22069/91298 answers this; however, I'll try to give a more in-depth explanation.

Shaders uses the texture, available light sources, and the camera position to color the objects in your scene appropriately. This results in objects casting shadows and carrying shades. Without it, everything carries a monotone color. The underside of a desk is the same color as the top side regardless of a floor or ceiling light. A character casts shadows that shrink and elongate as they pass by lights. Vehicles and large objects carry different shades on thier various faces that gives them character. Lighted objects, such as rockets, or energy pulses light up their surrounding area.

Alternatively, if you're designing a game without lighting, such as a puzzle game (luxor comes to mind) then it's not strictly necessary. That being said, adding lighting would give any 3d or 2d objects character which may improve User Experience. Using Luxor as an example, the marbles are 3d. Add lighting, and the 2d field simulates depth.

> Can I go perfectly fine without having anything to do with vertex or fragment shaders?

Technically: Yes. Shaders merely add coloring to the scene. If user experience isn't a big deal, then you can live without it. If you're new to this, then I'd recommend you try a few TK tutorials using shaders. Once you understand how to make them, then you can determine if the extra work you invest will be worth the UX they add to the game.

As an example, Minecraft has an option to turn off shaders. If you have the game, try flipping it on and off. In some places the difference is minute; in others, and with detailed textures, it's makes an incredible difference.

---
Tags: c#, shaders, opentk
---