# Question
Title: libGDX, Android Studio assets not found but linked properly
I used the libGDX setup UI to create a new project, copied sources from my tablet project and fixed all the errors due to libGDX version changes. Finally at the point to test and run, but first I hate the setup UI for libGDX . It's broken horribly as necessary folders were not created as they used to be, or were not properly imported by Android Studio. Regardless, when I run the desktop launcher the first file it attempts to load causes a file not found crash:

```
    skin = new Skin(Gdx.files.internal("/data/defaultSkin.json"));

```

The JSON, Atlas, and PNG files are all in android/assets/data folder. Desktop launcher config is using that folder for the working path as is the ONLY thing I've found online to look at for Android Studio and this particular issue. However I still get the file not found error. And I am using the default skin that I pulled off GitHub. Funny that all this code worked fine on my tablet and Eclipse, however Android Studio is being a broken POS, and this is the "preferred" IDE for development? I had less problems with Eclipse and AIDE (for mobile) except that AIDE pushes libGDX for game development but doesn't fully support the Gradle build that libGDX pushes for uses to utilize rather than downloading the simple to use zip folder with the libs in it. Why the hell fix what isn't broken? It almost always breaks what was perfectly fine.....

# Answer
> 1 votes
You have to set the working folder in the Run Configurations.

Go to Run =\> Run Configurations.. =\> choose DesktopLauncher, Arguments Tab =\> Working Directory =\> Others then browse to yourproject-android/assets/ and click Apply =\> Run

# Answer
> 1 votes
Did you make sure to set the file path to ".../android/assets/" in the configuration settings? Your error message is exact same as one I had and I remember that was my problem anyway

---
Tags: libgdx, android-studio
---


# Question
Title: Does my conditional statement contain a syntax error? C++
I am not entirely new to coding, but I am new to C++. I receive the error below often, but find that it comes due to some sort of syntax error (using a minus sign instead of an equal sign, or misspelling a variable name I've already declared elsewhere), but I can't seem to find what's wrong with my most recent error:

And here's the code itself:

```
void ARCCharacter::Raycast()
{
  FHitResult* HitResult = new FHitResult();
  FVector StartTrace = FirstPersonCameraComponent->GetForwardVector();
  FVector EndTrace = (StartTrace* 5000.f) + StartTrace;
  FCollisionQueryParams* CQP = new FCollisionQueryParams();

  if(GetWorld()->LineTraceSingleByChannel(*HitResult, StartTrace, EndTrace, ECC_Visibility, *CQP))
  {

    DrawDebugLine(GetWorld(), StartTrace, EndTrace, FColor(255, 0, 0) true);

    if(HitResult->GetActor() != NULL)
    {
        HitResult->GetActor()->Destroy();
    }

 }

}

```

Also, I'm following along with a tutorial, so I'm not sure where my code diverges from the teacher's: link. I'm using XCode to work with C++ in the UE4 editor, and while I'm sure there's a simple solution to this problem, I'd like to learn about common errors beginners may encounter so I can understand the language.

# Answer
I think you're simply missing a comma before true on this line:

DrawDebugLine(GetWorld(), StartTrace, EndTrace, FColor(255, 0, 0) **,** true);
> 0 votes

---
Tags: c++, unreal-4, xcode
---


# Question
Title: Elastic Circle-Circle collision detection and response / Slime Volleyball physics
I am trying to recreate the Slime Volleyball game; however I am unsure how to go about implementing the physics of the ball movement.

The game consists of a circular ball and semi circle players that hit the ball over a net and against a wall. The ball cannot touch the floor.

I need to understand how exactly to implement the hitting of the ball against the player and what the physics entails.

I have already implemented gravity with a bouncing ball.

It is hard to find information related to implementing such physics from a game development perspective and I only have vague ideas about change in momentum from googling. If anyone could explain how to do so, I would greatly appreciate it.

# Answer
> 3 votes
Basically, you want to implement circle-cirle collision detection and response. I consider your character a static object and the ball a dynamic object. I do this because it makes everything a lot easier, and the character doesn't move too much anyways.

First, your ball should have a velocity vector and a position. You need to get it's old and new position (the new position is just old position + velocity) and it's radius. You should also have the position and radius of the player.

The old and new position of the ball forms a line, get the distance of the line and the player's position:

In case you don't know how to calculate the distance between a line and a point, here's a great StackOverflow answer for that.

`d` will always be the closest the 2 circles get to each other. If it's bigger than the sum of the 2 radiuses, then they never collide. This is the end of the broad phase.

Now we can get the exact point the 2 circles collide:

`d` is the closest the 2 circles get, `t` is the sum of the circles' radiuses. `s` is the distance of the collision point from the closest point, this is unknown but you can calculate it with the Pythagorean theorem:

```
s = sqrt(t * t - d * d)

```

Now calculate the distance between the closest point and the old position (get the distance from the old position and the player, then use the Pythagorean theorem again with the distance and d), divide s from it, then multiply the normalized velocity vector of the ball with the result. Again, in pseudo code:

```
func get_position(float s, float d, vec2 old_position, vec2 player, vec2 velocity) {
    u := mag(player - old_position)
    dist := sqrt(u * u - d * d) - s
    return player + normalize(velocity) * dist
}

```

Now the bouncing part. The normal at the intersection of the 2 circles is always equal to the normalized version of the vector between the intersection point and the center of the circle, thus it's also the normalized version of the vector going from the player's position to the ball's new position.

Let's call the normal `n` and the velocity vector `v`

Based on this other nice Mathematics answer, you can get the new velocity vector with the following formula:

```
v2 := v - 2 * dot(v, n) * n

```

Set the velocity of the player to v2 and done. Now, here's the complete answer in pseudo code (I assume you have a way to set the player's velocity and position, here I use the `set_player(vec2 new_pos, vec2 new_velocity)` function):

```
func intersect(vec2 ball_pos, float ball_radius, vec2 ball_velocity, vec2 player_pos, float player_radius) {
    d := line_point_dist(ball_pos, ball_pos + ball_velocity, player_pos)
    t := ball_radius + player_radius
    if (d > t) do
        # The balls never intersect
        return
    end
    s := sqrt(t * t - d * d)
    pos := get_position(s, d, ball_pos, player_pos, ball_velocity)

    n := normalize(pos - player_pos)
    new_velocity := ball_velocity - 2 * dot(ball_velocity, n) * n

    set_player(pos, new_velocity)
}

func line_point_dist(vec2 start, vec2 end, vec2 point) {
    l := pow(mag(end - start), 2)
    if (l == 0) do
        return mag(end - start)
    end
    t := max(min(1, dot(point - end, end - start) / l))
    proj := start + t * (end - start)
    return mag(point - proj)
}

func get_position(float s, float d, vec2 old_position, vec2 player, vec2 velocity) {
    u := mag(player - old_position)
    dist := sqrt(u * u - d * d) - s
    return player + normalize(velocity) * dist
}

```

# Answer
> 0 votes
In addition to madneon's answer, when you've detected a collision with the player, take the result of:

```
A = P - B

```

where P and B are position vectors representing the position of the player and the ball, respectively. Multiply the resulting vector A by a static amount (force used) and then apply it as acceleration to the ball. This should give you the physics of the ball rebounding off the players.

# Answer
> -1 votes
Its not very complicated, all you need is to consider 3 things:

1. Ball's position (`x`, `y`) and velocity (`vx` and `vy`).
2. Constant gravity (`g`).
3. Bounce conditions.

On every game loop you need to apply gravity, like:

```
vy += g;

```

Then apply velocity:

```
x += vx;
y += vy;

```

Then check these result for **collision** with players and/or screen edges and ground.

Depending on your game engine, you might need to "correct" these calculations by multiplying them by your current **tick time** (eg. `vy += g * tick_time`), setting proper constant gravity, and setting proper starting/after-bounce velocity (eg. `vx` and `vy` depending on player's bounce angle - you might have to use sin/cos functions).

# Answer
> -2 votes
The lazy solution: Use an existing 2d physics engine which is able to handle elastic collisions between circles (and circles with rectangles for the net). There is no reason to reinvent the wheel.

---
Tags: projectile-physics
---


# Question
Title: How do I ground my character using capsule colliders?
I have a problem checking if my character is grounded, and it is tied to the position of the capsule collider. I just started using Unity, so I'm not sure what I did wrong. The problem is that the `Physics.SphereCast` returns `false`, like it didn't hit anything.

When I start with the default `CapsuleCollider`, it seems to work, but my character floats in the air. I only have to lift it's y-position by 0.1, and it stops working. This is demonstrated, in the below image, but you can see this in more detail Here.

---

Here is the code showing how I detect if I'm grounded. Keep in mind that I'm working with a `RigidBody`, and not a `CharacterController`.

```
  bool IsGrounded()
  {
    Vector3 p1 = transform.position;
    float distanceToObstacle = 0;
    RaycastHit hit;
    Collider collider = GetComponent<Collider>();

    // Cast a sphere wrapping "controller" 0.1 meter down to check if it hits anything
    if (Physics.SphereCast(p1,  collider.bounds.size.x / 2, new Vector3(0,-10,0), out hit))
    {
      distanceToObstacle = hit.distance;
      if (distanceToObstacle < 0.1f)
      {
        return true;
      }
      else
      {
        return false;
      }
    }
    else
    {
      return false;
    }
  }

```

# Answer
You could always try using the `onCollision`methods that Unity has already (You may also want to play around with rigidbodies). Look into their Physics stuff because it offers collision and grounding already, , all you would have to do is play with sizes, numbers and so on. https://docs.unity3d.com/ScriptReference/Collision.html

As for your code in particular, make sure that your character doesn't have some sort of mesh or something (maybe set to invisible) around them that is actually the location your detection is starting at. So basically if he has a box around him that's 50cm, then your check for what's just underneath him may be working, it just might be starting at the bottom of that box.
> 1 votes

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


# Question
Title: Problem calculating screen point for a point in a 3D world with view matrix and projection matrix
I am trying to calculate the 2D screen point of a 3D world position. For this I use the multiplication `ViewMatrix * ProjectionMatrix`. But I am not getting good results and I think I am messing up my calculations or my ViewMatrix itself is wrong (I think the latter).

This is a snapshot of how my `ViewMatrix` looks like when the camera is looking downwards (at my feet):

```
 0.362,    0.932,    0.000,    0.000
-2.241,    0.094,   -0.966,    0.000
-0.900,    0.350,    0.259,    0.000
 8.100,  -16.860,    4.598,    1.000

```

I calculate my left handed perspective `ProjectionMatrix` manually using `4/3` aspect ratio `60` FOV and using `0.1` and `1000` for my near and far Z. This is the ending projection matrix:

```
-0.117,    0.000,    0.000,    0.000
 0.000,   -0.156,    0.000,    0.000
 0.000,    0.000,    1.000,    1.000
 0.000,    0.000,   -0.100,    0.000

```

I multiply the previous 2 matrices with `ViewMatrix * ProjectionMatrix` and use that as my `ViewProjectionMatrix`.

Now I need to calculate the clipping space coordinates of the 3D point. I do this as follows:

```
XMFLOAT4 clipCoords;
clipCoords.x = pos.x * viewMatrix._11 + pos.y * viewMatrix._21 + pos.z * viewMatrix._31 + viewMatrix._41;
clipCoords.y = pos.x * viewMatrix._12 + pos.y * viewMatrix._22 + pos.z * viewMatrix._32 + viewMatrix._42;
clipCoords.z = pos.x * viewMatrix._13 + pos.y * viewMatrix._23 + pos.z * viewMatrix._33 + viewMatrix._43;
clipCoords.w = pos.x * viewMatrix._14 + pos.y * viewMatrix._24 + pos.z * viewMatrix._34 + viewMatrix._44;

```

Now I convert this to normalised device coordinates:

```
XMFLOAT3 NDC;
NDC.x = clipCoords.x / clipCoords.w;
NDC.y = clipCoords.y / clipCoords.w;
NDC.z = clipCoords.z / clipCoords.w;

```

As a final step I convert it to the 2D point on a screen for a given size:

```
XMFLOAT2 screen;
screen.x = (windowWidth / 2 * NDC.x) + (NDC.x + windowWidth / 2);
screen.y = -(windowHeight / 2 * NDC.y) + (NDC.y + windowHeight / 2);

```

Can you spot the problem with the above calculation?

Steffen

# Answer
Matrix multiplication is non-cumulative, aka `A * B` doesn't always equal to `B * A`. The order of the multiplications should be

```
projection * view * model * vector

```

Your projection matrix is also messed up, the values should be this way:

I would say where the values in your matrix are, but I have zero idea.
> 1 votes

---
Tags: mathematics, camera, linear-algebra, projection-matrix
---


title: ball reflection angles Xna c#

text:
# Question
Title: ball reflection angles Xna c#
I'm trying to find a way to handle reflections for a breakout clone.

I would upload an image to the post instead of the following paragraph, however i have not yet gained the privilege of that yet.

If the ball intersects the left hand side i want it to bounce off to the left. if the ball intersects the right hand side i want it to bounce off to the right. if the ball intersects the middle section i want it to bounce up the way. i want to learn how to make it bounce in a varying direction dependant on what side of the left, right, or middle section was intersected

I would like to not use three separate rectangles for this, i want to learn how to do it with one.

I use a Vector2 for ball velocity, `projVel`.

It's position is `projPos`.

A rectangle for the paddle `lightRect.`

The reason I use `proj.collRect` for the beginning of the if is because I cannot use the intersect method with Vector2.

This is my makeshift collision handler at present, which does work but the speed changes to an extent which renders the game unplayable. The speed clamp i have only slightly slows it down i think. i have a variable for `projSpeed` i cannot clamp that or it will never be able to stop.

```
if (proj.collRect.Intersects(lightSaber.lightRect))
{
            proj.projPos.Y = lightSaber.lightRect.Y - proj.projTxr.Height;
            proj.projVel.Y *= -1;

    proj.projVel.X = 10 * (proj.projPos.X - lightSaber.lightRect.Center.X) / (lightSaber.lightRect.Center.X);
}

        proj.projVel.X = Math.Max(-4, Math.Min(proj.projVel.X, 4));
        proj.projVel.Y = Math.Max(-4, Math.Min(proj.projVel.Y, 4));

```

Help me by showing me how I could do this, maybe in the Math. method, or even an alternative to .Intersects so I can use `projPos` instead of `collRect`.

I really am not sure where to start, if there is another way I could do it an example would be great.

# Answer
> 1 votes
I assume you mean the horizontal speed changes too much. If that is the case, there are two potential problems in this line of code:

```
 proj.projVel.X = 10 * (proj.projPos.X - lightSaber.lightRect.Center.X) / (lightSaber.lightRect.Center.X);

```

First, I assume you're attempting to normalize the position of the projectile with respect to the distance between the endpoints of the paddle. If this is the case, you want to change this to

```
 proj.projVel.X = 10 * (proj.projPos.X - lightSaber.lightRect.Center.X) / (lightSaber.lightRect.Length * .5);

```

Second, you did not mention if the speed is too large or too small. If it is too large, perhaps the factor of 10 you are using is too large.

---
Tags: c#, xna, collision-detection
---


# Question
Title: How to do I make my sprite move when it's instantiated in Unity5?
Here's the code I currently try to use to move my instantiated sprite:

```
time++;

    if (cow == 1 && time >= wait)
    {
        Cow0Walk();
    }

    if (cow == 2 && time >= wait)
    {
        Cow1Walk();
    }

    if (cow == 3 && time >= wait)
    {
        Cow2Walk();
    }

    if (cow == 4 && time >= wait)
    {
        Cow3Walk();
    }

    if (cow == 5 && time >= wait)
    {
        Cow4Walk();
    }

    if (time >= walkTime)
    {
        wait = rnd.Next(45, 140);
        cow = rnd.Next(1, cowAmount);
        walkTime = rnd.Next(1, 4);
        direction = rnd.Next(1, 4);
    }

```

Heres the one of the walk methods:

```
    void Cow0Walk()
{
    if (time <= walkTime && direction == 1)
    {
        cows[0].transform.Translate(Vector2.up * speed);
        cows[0].transform.Translate(Vector2.right * speed);
    }

    if (time <= walkTime && direction == 2)
    {
        cows[0].transform.Translate(Vector2.up * speed);
        cows[0].transform.Translate(Vector2.left * speed);
    }

    if (time <= walkTime && direction == 3)
    {
        cows[0].transform.Translate(Vector2.down * speed);
        cows[0].transform.Translate(Vector2.right * speed);
    }

    if (time <= walkTime && direction == 4)
    {
        cows[0].transform.Translate(Vector2.down * speed);
        cows[0].transform.Translate(Vector2.left * speed);
    }
}

```

# Answer
> 1 votes
### Using a prefab

I don't know what kind of game it is, but for most cases a good option is to use a prefab for the character movement. You can find it in the standard assets.

### Making your own

If you still want to make your own movement script, the best option is to add a component called `CharacterController` to your character, and try to avoid moving the `Transform` component. This is because when you move the `CharacterController`, it will automatically check for collision.

```
float dx = 1; // desired movement along the x axis
float dz = 1; // desired movement along the z axis
float dy = 1; // desired movement along the y axis

GetComponent<CharacterController>().Move(new Vector3(dx, dy, dz));

```

---

If you still want to use the `Transform`, you might want to view this similar question, at Stack Overflow.

# Answer
> 0 votes
If you want to directly translate your game object, you should do so with `Transform.Translate`. It is worth noting that we almost *always* call this sort of movement from an `Update` method, and need to account for the time delta between update frames. If we do not, we will get varying speeds, based on the number of `Update` calls our build is currently performing per second.

```
public float speed;

void Update()
{
    MoveInLocalSpace(Vector3.forward);
    // or
    MoveInWorldSpace(Vector3.forward);
}

void MoveInLocalSpace(Vector3 direction)
{
    // Move in direction by a rate of speed * current delta time.
    // We do not need to specifiy that we are moving in local space, as
    // that is the default.
    transform.Translate(direction * speed * Time.deltaTime);
}

void MoveInWorldSpace(Vector3 direction)
{
    // If we want the direction to be interpreted as world coordinates (and not relative to
    // the actual transform position), we need to specify the world space.
    transform.Translate((direction * speed * Time.deltaTime), Space.World);
}

```

---

Note that in the above mentioned question example, it is unclear why this does not work off the bat. That said, you should be ensure that you are accessing the `Transform` of the actual `GameObject` that you wish to move.

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


title: Why isn't my rotation smooth?

text:
# Question
Title: Why isn't my rotation smooth?
I'm currently working on a twin stick shooter but I encountered a problem when I rotate my player. The rotation snaps to right angles. I'm guessing it's a problem, due to the value that the joystick gives me back. Here is a screen recording, via Giphy.

How do I go about fixing this problem?

This is my code:

```
 void FixedUpdate()
{

    float hR = gamepad.GetStick_R().X;
    float vR = gamepad.GetStick_R().Y;

    float lastHR = hR;
    float lastVR = vR;
    // This part was added recently in the hope of smoothing the rotation
    float lerpHr = Mathf.Lerp(lastHR, hR, Time.deltaTime * speedRotation);
    float lerpVr = Mathf.Lerp(lastVR, vR, Time.deltaTime * speedRotation);

    PlayerRotation(lerpHr, lerpVr);
}

void PlayerRotation(float h, float v)
{
    rotation.Set(h, 0f, v);

    if (rotation != Vector3.zero)
    {
        currentRotation = Quaternion.LookRotation(rotation);
        playerRigidbody.MoveRotation(currentRotation);
        lastRotation = currentRotation;
    }
    else
        playerRigidbody.MoveRotation(lastRotation);
}

```

I also tried two other ways, but each time, I got the same results. I tried every way I could think of, with these lines of code. I don't know where else to look.

```
// Attempt Two
playerRigidbody.transform.rotation = Quaternion.Slerp(p
    layerRigidbody.transform.rotation, currentRotation, Time.time * speedRotation);

// Attempt Three
transform.eulerAngles = new Vector3(0, Mathf.Atan2(v, h) * 180 / Mathf.PI, 0);

```

# Answer
Unity uses an axial dead zone this causes the joystick to "snap" at 90 degrees (up, down, left, right). What you need is a radial dead zone.

First, you need to go into the Unity Input Manager and set the dead zone ("dead") value to zero (0), to disable their axial dead zone.

Then, do your own radial dead zone:

```
float hR = gamepad.GetStick_R().X;
float vR = gamepad.GetStick_R().Y;

float deadzone_squared = 0.1f * 0.1f;

// calculate and compare magnitude squared (skip the square root)
if((hR * hR + vR * vR) < deadzone_squared)
{
  hR = 0;
  vR = 0;
}

```

This will create a deadzone that is a circle, rather than a cross.
> 2 votes

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


# Question
Title: Unity3D CrossPlatformInput StandardAsset Multitouch
I have a small game I am working on, and I am trying to add touch support to it. Before I try to add that into the real game I wanted to do a test run on a small project. The project consists of a capsule to be the player, and the application accepts movement from a on screen joystick, and accepts a button click from a UI button. The button triggers the attack, and the joystick triggers the movement.

Both of these controls work as designed but they will not work together, meaning I can do one or the other. I was hoping to use the standard asset as to not re-invent the wheel for speed...

below is the code that "Should" be triggering when both controls are used, just as a note this same code works when I use mouse and keyboard together so this is something to do with the mobile stuff..

```
using UnityEngine;
using System.Collections;
using UnityStandardAssets.CrossPlatformInput;

public class PlayerController : MonoBehaviour
{
    public float playerSpeed = 10f;
    Transform weapon;

    // Use this for initialization
    void Start ()
    {
        weapon = transform.FindChild("Weapon");
    }

    // Update is called once per frame
    void Update ()
    {
        DirectionalMovements();
        ButtonPresses();
    }

    void ButtonPresses()
    {
        if (CrossPlatformInputManager.GetButtonDown("Fire1"))
        {
            weapon.GetComponent<Sword>().AttackOne();
        }
    }

    void DirectionalMovements()
    {
        float moveVertical = CrossPlatformInputManager.GetAxis("Vertical") * playerSpeed * Time.deltaTime;
        float moveHorizontal = CrossPlatformInputManager.GetAxis("Horizontal") * playerSpeed * Time.deltaTime;

        Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
        transform.Translate(movement, Space.World);

        if (movement != Vector3.zero)
        {
            transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(movement.normalized), playerSpeed);
        }
    }
}

```

Any thoughts would be greatly appreciated.. I just do not see why both controls are not picked up here.

# Answer
> 0 votes
not sure what fixed it but i reimported the asset package and redeployed.. this fixed it

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


# Question
Title: What is the logic behind these design decisions regarding difficulty levels?
1. In some games you are unable to play on the harder difficulties before complete it on a lower difficulty. Why?
2. Achievements are popular. In some games you do not get an achievement for completing the game on the hardest difficulty (e.g. Bethesda RPG's) but for just about everything else, Why?

# Answer
> 4 votes
First of all: Why someone made a specific design decision is pure speculation. We can not read the designer's mind. Also, do not assume that every design decision you see in a popular game is necessarily a *good* design decision. You can find a couple of design flaws in every game. The best games are those which compensate for them by having plenty of greatness in other regards.

Regarding unlocking a harder difficulty after the player completed the game on a lower one, *possible* motivations can be:

* It prevents frustration. The hardest difficulties are usually balanced for players who already completed the game, already mastered all the game mechanics and are now looking for a proper challenge of their mastery. The designers believe that a new player will be overburdened by this challenge and will just be frustrated by the experience.
* It is a cheap way to increase long-term motivation. The player won't really feel like they completed the game before they completed it twice: Once on normal difficulty and once on the now available hardest difficulty.
* It is a reward for completing the game. When the player gets something new to do after completing a goal, that's a form of positive reinforcement.

Regarding achievements for completing the game on different difficulty levels: Bethesda games usually allow the player to change the difficulty level at any time. They even encourage that: When the player dies a lot while on a higher difficulty, they will often get a loading screen hint suggesting to try a lower difficulty. But when you want the player to continually adjust the difficulty to their liking, you can't really give a reward anymore for completing the game on a specific difficulty. Not just because that would go against your design decision, but also because it now gets hard to measure how much of the run was played on what difficulty.

---
Tags: game-design, difficulty
---


title: FBO Depth Buffer not working

text:
# Question
Title: FBO Depth Buffer not working
I'm trying to get the depth buffer for my 2D game working by offsetting the z value of the rectangles. For some reason, *my depth buffer is coming back empty*. The value is always 0. I'm assuiming there is something wrong with how I attach the depth buffer to the FBO? But I've looked over that code many times and don't see anything wrong with it. Let me know if you need more information.

* I have depth testing enabled with GL\_LEQUAL.
* I have znear and zfar set to 1.f, -10.f and I have 9 quads setup at three different depths.
* I have set glClearDepth(1.0) and I clear bot the COLOR\_BUFFER\_BIT and DEPTH\_BUFFER\_BIT before I draw to the FBO, however the value is still 0.

FBO setup:

```
RenderTarget::RenderTarget(int width, int height) {

    mWidth = width;
    mHeight = height;
    mVbo = 0;

    // Create the color buffer
    glGenTextures(1, &mTextureId);
    glBindTexture(GL_TEXTURE_2D, mTextureId);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, mWidth, mHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);

    // Create the depth buffer
    glGenTextures(1, &mDepth);
    glBindTexture(GL_TEXTURE_2D, mDepth);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT32, mWidth, mHeight, 0, GL_RED, GL_BYTE, NULL);

    /*glGenRenderbuffers(1, &mDepth);
    glBindRenderbuffer(GL_RENDERBUFFER, mDepth);
    glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT32, mWidth, mHeight);*/

    // Create the frame buffer
    glGenFramebuffers(1, &mFbo);
    glBindFramebuffer(GL_FRAMEBUFFER, mFbo);

    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, mTextureId, 0);
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, mDepth, 0);

    GLenum err = glCheckFramebufferStatus(GL_FRAMEBUFFER);
    assert(err == GL_FRAMEBUFFER_COMPLETE);

    glBindFramebuffer(GL_FRAMEBUFFER, 0);

    createVbo();
}

```

Fragment shader

```
#version 120

uniform sampler2D diffuseMap;
uniform sampler2D lightmap;
uniform sampler2D depthMap;

varying vec4 texCoord[2];

void main()
{
    vec4 color = texture2D(diffuseMap, gl_TexCoord[0].st);
    vec4 light = texture2D(lightmap, gl_TexCoord[0].st);
    vec4 depth = texture2D(depthMap, gl_TexCoord[0].st);

    vec4 final = color * vec4(0.1);
    final += color * light;
    gl_FragColor= vec4(depth.r, depth.r, depth.r, 1.0);
}

```

Method to draw sprites to the screen/framebuffer

```
void GraphicsDevice::drawSprite(ISprite *sprite, float x, float y, float z, Material::TextureType type, Color c) {

    glActiveTexture(GL_TEXTURE0);
    glEnableClientState(GL_VERTEX_ARRAY);
    glEnableClientState(GL_TEXTURE_COORD_ARRAY);

    glBindBuffer(GL_ARRAY_BUFFER, sprite->getVbo());

    glBindTexture(GL_TEXTURE_2D, sprite->getMaterial()->getTexture(type)->getId());

    glPushMatrix();
    glTranslatef(x, y, z);
    glColor4f(c.r, c.g, c.b, c.a);

    glVertexPointer(3, GL_FLOAT, sizeof(Vertex), (void*)offsetof(Vertex, x));
    glTexCoordPointer(2, GL_FLOAT, sizeof(Vertex), (void*)offsetof(Vertex, tx));

    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

    glPopMatrix();

    glBindBuffer(GL_ARRAY_BUFFER, 0);
    glDisableClientState(GL_TEXTURE_COORD_ARRAY);
    glDisableClientState(GL_VERTEX_ARRAY);

}

```

# Answer
> 6 votes
The problem was I was creating and binding the depth buffer texture to GL\_DEPTH\_ATTACHMENT. I found some random code that attached the depth buffer to GL\_DEPTH\_STENCIL\_ATTACHMENT, so I tried that out and it works exactly as I expect it to. So the new FBO code looks like this

```
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH24_STENCIL8, mWidth, mHeight, 0, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8, NULL);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D, mDepth, 0);

```

I would really appreciate it if someone could explain why this works and my previous one doesn't.

# Answer
> 1 votes
I needed depth buffer to my application as well and indeed this:

```
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH24_STENCIL8, mWidth, mHeight, 0, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8, NULL);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D, mDepth, 0);

```

worked but sadly `GL_DEPTH_COMPONENT32` and `GL_DEPTH_COMPONENT` failed as well.

So i've read the documentation for **glTexImage2D** and i found the *following* on the error section:

```
GL_INVALID_OPERATION is generated if format is GL_DEPTH_COMPONENT and internalFormat is not GL_DEPTH_COMPONENT, GL_DEPTH_COMPONENT16, GL_DEPTH_COMPONENT24, or GL_DEPTH_COMPONENT32F.

GL_INVALID_OPERATION is generated if internalFormat is GL_DEPTH_COMPONENT, GL_DEPTH_COMPONENT16, GL_DEPTH_COMPONENT24, or GL_DEPTH_COMPONENT32F, and format is not GL_DEPTH_COMPONENT.

```

So in the case above if you change `..GL_RED..` to `..GL_DEPTH_COMPONENT..` it should work, it worked for me. All in all, `internalFormat` and `format` should be `GL_DEPTH_COMPONENT`, otherwise you'll get `GL_INVALID_OPERATION`.

# Answer
> 0 votes
Did you miss `glEnable(GL_DEPTH_TEST)`? I don't see it anywhere in your code (although I'm aware you didn't post it all, it might be somewhere else.)

Also, both zNear and zFar **MUST BE** positive in perspective projection (not sure about orthogonal.) Actually, it doesn't make sense (at least syntactically) to have the planes reversed. Bear in mind that even if OpenGL looks towards the negative Z axis, z-planes are positioned relative to the viewpoint (positive being forwards from it.)

I'd be glad if someone posted a use case where negative planes are useful, and even more glad if it made sense to have the planes reversed (zFar being behind the viewer as you do.)

---
Tags: opengl, glsl
---


title: Questions about Libgdx

text:
# Question
Title: Questions about Libgdx
This question might be naive, I'm just making sure I grasp the API. Suppose you have an array of 3 objects

* Is `array.get(o)` the same as `array.first()`; and `array.get(2)` the same as `array.peek()`?

Suppose you have an object moving on screen

* Is `array.get(o).x` the same as `array.get(o).getX()`

By reading the API it seems to me that `x` returns position of the object while `getX()` returns the position of the mouse, or the user's finger whenever he touched the screen. But if that's true then I shouldn't be allowed to use `getX()` on an object like I did above

# Answer
> 3 votes
## **Yes** and **probably**.

`Array#first()` returns the first element in the array, I.e. element 0. So it's the same as `Array#get(0)`.

`Array#peek` (or `Array#pop()`) returns the last element in the array, I.e. element `array.size - 1` (which in your case is `3 - 1 = 2`).

As for the question that `object.x` is the same as `object.getX()` depends on the definition of the `getX()` method in the object's class. Most likely they are equal since `getX()` is the typical syntax of a getter which gets the variable `x`. There's no reason to think that it returns the mouse position unless the `object` is `Gdx.input` since `getX()` in the `Input` class gets the mouse position.

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


# Question
Title: Best way to implement Finite State Machine for player character in Unity?
I'd like to implement the player in my game as an FSM as described in this guide to programming patterns in games.

What is the best way to accomplish this? Should I implement each state as a monobehaviour with a state interface that can be enabled/disabled when the state transitions? Or would it better to the states as plain classes (with their own Update method) where the main player monobehaviour calls StateName.Update() from its own Update method (.e.g. `void Update() { currentState.Update() }`)

# Answer
I personally like to create a private enum with different states, with a private States variable that holds my actual state. Then in the Update function I create a switch-case to test in which state I am right now, and I call the relative function. Then inside the called function I assign the new value to the actual state. This is an easy to mantain solution, in my opinion.

```
{
    private enum States { state_0, state_1, state_2 };
    private States state_now;

    void Start () {
        state_now = States.state_0;
    }

    void Update () {
        switch (state_now) {
            case States.state_0 : state_0(); break;
            case States.state_1 : state_1(); break;
            case States.state_2 : state_2(); break;
            default : break;
        }

    void state_0() {

        // Business logic
        state_now = States.state_1;
    }

    // Others function, one for each state
}

```

I wrote this snippet without Unity on my PC to give you an idea, it's not intended to be a complete example.
> 1 votes

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


title: Checking for alignment on an axis

text:
# Question
Title: Checking for alignment on an axis
Suppose I have an array of 5 objects, each time the touches the screen I generate a new array and save the previous objects in another array.

Is there a way to check if the object align perfectly on only axis with a reasonable error margin and detect objects wrongfully aligned?

I could do it using mathematics but I want to see if I could take advantage of `overlaps` in Libgdx or a similar method.

# Answer
You can't check if actors are aligned with the overlap method. (I assume your objects are actors, or anything with x and y positions as attributes)

To check if some actors are aligned on the same axis you just have to check if their x position (or y if you want to compare by y) are the same

```
private boolean objectsAligned(Array<Actors> actors)
{
    // Get the base X value you want to align on, here i take the first actor's x position
    float x = actors.get(0).getX();

    for (Actor actor : actors)
    {
        if (actor.getX() != x)
            return false;
    }

    // If the condition above is never true, everything is aligned
    return true;
}

```

Now, if you want to add a margin to this alignement. You need to compute your min X and max X values with the error margin as a range and check if every actor's X is in this range.
> 1 votes

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


title: Add object to a Terrain?

text:
# Question
Title: Add object to a Terrain?
It's possible to add object made by blender to unity terrain ? this object will become a part of it. I can add grass and trees on it.

# Answer
Edit: Link and info with it from before is no longer valid/usable.

If your goal is adding things on top like bushes then you'd just want to import the model. Go to terrains and build your terrain as you want it. Then import your model into the scene and place it in/along the terrain where you want it. A quick/rough solution would be merging the two things together in the hierarchy or just placing the models as children under the terrain.

As for replacing the mesh, the closest thing I think you could get would be adding in a custom texture for the terrain, since you can build terrain yourself with Unity's tools and then just paint on the texture, and eventually add pre-made bushes, etc on top.
> 1 votes

---
Tags: unity, terrain
---


# Question
Title: What is the point of a borderless fullscreen window?
Quite a lot of game allow user to play in a "borderless fullscreen window" instead of a "fullscreen mode". I've been wondering. Why would one prefer a fullscreen window over the "built-in" fullscreen mode?

Simple test of my own showed me, that using fullscreen mode instead yields better performance. I also tried to search on Google and on SO, but most answers are gaming related or on how to actually create those windows in API X,Y or Z.

So what is the point of having a borderless fullscreen window? Are there any technical reasons?

# Answer
> 238 votes
"Regular" fullscreen involves taking "exclusive" access of the GPU, which means a lot more work in handling resolution switching, resource management (in older APIs, in particular) and so on, *especially* around supporting correct alt-tab behavior. This might seem odd at first, but it arises because when you lose exclusivity (when alt-tabbed out), your game's GPU resources are effectively evicted and must be restored when you tab back in.

A "borderless fullscreen" window is just a regular window, with window chrome disabled, that is the size of the whole screen. This means it acts just like a regular window and doesn't incur the extra complication and overhead of exclusive GPU access, which makes things easier for developers at the cost of some negligible performance. This is the main *technical* reason: less work.

It also makes things easier on users, usually, because many games that use exclusive fullscreen modes also happen to not handle alt-tab very well, and crash, or act oddly when restored to fullscreen. This can be exceedingly annoying for players who want to alt-tab to look at GameFAQs, chat on Discord or IRC, or whatever. It's also more friendly to multi-monitor setups.

# Answer
> 131 votes
In addition to Josh Petries very thorough answer, I would like to add a more practical upside of borderless fullscreen.

Having a setup with multiple monitors makes regular fullscreen a bit of a pain. Because changing focus to another window takes longer and causes the fullscreen application to minimize.

With borderless fullscreen on the other hand, the window in question is a regular window. This means, it can be in the background. Still visible while other windows overlap. With multiple monitors, it allows streamers for example to interact with their viewers while still focusing on the game.

# Answer
> 18 votes
# Things for which borderless fullscreen windows are useful

* Double screen setups;
* Recording games (LPers, tutorials); A lot of content creators use software that allows for window capture, so capturing just the game window. This allows the creator to switch context to other programs without the risk of revealing sensitive information. If the game is exclusive fullscreen, capture software would have to capture the entire monitor, forcing the creator to either edit out context switches from the final video or to turn his screen black when livestreaming.;
* Multitasking;
* Avoiding bugs in the fullscreen implementation (wrong resolution, cut off edges, no mouse, infinite cycle of focus/defocus etc.);
* Sometimes performance; although real fullscreen should run faster, sometimes it has the exact inverse effect;
* Many games bug out when Alt-Tabbed (no sound, buggy graphics, long Alt-Tab reaction time which is annoying, cannot run anymore after trying to Alt-Tab back into the game, some block Alt-Tab altogether to the annoyance of the player);
* Often real full screen is reserving more space than necessary on smaller monitors, e.g. on 1370 it still reserves 1980 pixel width, so any other fullscreen window on the other screen is offset by 600 pixels to the right;
* Switching mouse between screens is a pain in the arse with fullscreen mode as well, wanna switch your music playlist? Takes 1 minute because of Alt-Tab loading times and slow reaction, not only does it take 15 seconds until you're out of the game, but getting in again takes longer and sometimes even bugs out in normally functional games.
* On low end computers your game might not be able to run smoothly in full screen mode but, when making the window smaller, the performance often improves as well. (Some content creators use this to capture downscaled games and upscale the video.)

---
Tags: window-management
---


# Question
Title: How do you make a camera look at a box and ensure all of it is visible?
In most game engines (Unity, UE4) if we select a model and press `F`, the camera moves and focuses to the selected model. I want to implement that for my models.

I have a perspective camera and world space bounding box of the model.

How do I calculate the appropriate distance to view the entire model in the camera?

# Answer
> 6 votes
Take every point (vertex), project them into screen space (basically multiply them with the `projection * view * model` matrix).

After you got this, take every point and get the 2 with the biggest x difference and repeat the same for y. This way you get the bounding box of these points.

Now, you'll also need 2 things: the aspect ratio of the camera, and the vertical FOV.

Take the bounding box, multiply it's height by the aspect ratio, and check if it is bigger or smaller than the width. If it's bigger, then we need to take the height into consideration when we position our camera, if it's smaller, we need to take the width into consideration.

Now we need the vertical FOV (and some trigonometry). If you need to place your camera based on the vertical, then you simply use the following formula (height is the bounding box height, FOV is the FOV):

```
dist := height / 2 / tan(FOV / 2)

```

If you need to base it off of the width, then you need to do a slight modification (width is the width of the bounding box, aspect is the aspect ratio):

```
dist := width / 2 / tan(FOV * aspect / 2)

```

(Every angle is in radian BTW)

Now, you now how far you need to place the camera.

Now, if you need the distance based on width, then let the 2 farthest points on the horizontal axis be `A` and `B`. If you need the height version, then let the farthest points on the vertical axis be `A` and `B` (Doesn't matter which one's which).

Now, `A` and `B` form a line (marked with `AB`). Get this line's center (`(A + B) / 2`), let this be `M`. Now the last part. Take the direction vector (it should be normalized), negate it, multiply it with `dist` you got earlier, add it to `M` and done, you have the position of the camera.

Because many people don't understand math, and because I'm a nice guy, here's this in pseudo-code:

```
func find_pos(mat4 proj_view_model, float aspect, float FOV, vec3[] points, vec3 camera_direction) {
    vec4[] projected_points
    foreach (vec3 pos in points) do
        push(projected_points, proj_view_model * vec4(pos, 1))
    end

    vec4 A1, B1, A2, B2

    float width, height

    for (i = 0 .. length(projected_points) - 1) do
        for (j = i .. length(projected_points)) do
           float new_width := abs(projected_points[i].x - projected_points[j].x)
           float new_height := abs(projected_points[i].y - projected_points[j].y)

           if (new_width > width) then
               A1 := projected_points[i]
               B1 := projected_points[j]
               width := new_width
           end
           if (new_height > height) then
               A2 := projected_points[i]
               B2 := projected_points[j]
               height := new_height
           end
        end
    end

    vec4 A, B

    float dist
    if (height * aspect > width) then
        dist := height / 2 / tan(FOV / 2)
        A := A1
        B := B1
    else
        dist := widh / 2 / tan(FOV * aspect / 2)
        A := A2
        B := B2
    end

    vec3 center := vec3((A + B) / 2)
    vec3 camera_pos = center - camera_direction * dist
    return camera_pos
}

```

This function is very fast if you're wondering, the biggest drawback is getting the 2 farthest points. If you know any other algorithms, feel free to use that.

If you find any errors in my logic, post a comment below.

---
Tags: mathematics, matrix, frustum
---


# Question
Title: Error binding indices to device context [ STATE_SETTING ERROR #241: IASETINDEXBUFFER_INVALIDBUFFER]
This is how i initialized the D3D11\_BUFFER\_DESC for my indices. When i go to bound it to the deviceContext i get this error.

D3D11 ERROR: ID3D11DeviceContext::IASetIndexBuffer: The Buffer trying to be bound as an IndexBuffer did not have the appropriate bind flag set at creation time to allow the Buffer to be bound as an IndexBuffer. \[ STATE\_SETTING ERROR #241: IASETINDEXBUFFER\_INVALIDBUFFER\]

And is kinda of strange becouse i setted the bindFlags to "D3D11\_BIND\_INDEX\_BUFFER"

```
   D3D11_BUFFER_DESC buffDescIndices;

    ZeroMemory(&buffDescIndices, sizeof(D3D11_BUFFER_DESC));
    buffDescIndices.MiscFlags = 0;
    bufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
    buffDescIndices.Usage = D3D11_USAGE_DEFAULT;
    buffDescIndices.ByteWidth = sizeof(UINT) * ARRAYSIZE(indices);
    buffDescIndices.StructureByteStride = 0;
    buffDescIndices.CPUAccessFlags = 0;

    D3D11_SUBRESOURCE_DATA subResData2;
    subResData2.pSysMem = indices;
    HRESULT hr=device->CreateBuffer(&buffDescIndices, &subResData2, &mBoxIB);

```

And this is the deviceContext call

```
    deviceContext->IASetIndexBuffer(mBoxIB, DXGI_FORMAT_R32_UINT, 0);

```

# Answer
> 1 votes
Yes i am totally the stupidest person on this planet i setted

```
bufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;

```

Instead of

```
 buffDescIndices.BindFlags = D3D11_BIND_INDEX_BUFFER;

```

...

---
Tags: directx, directx11, c++
---


# Question
Title: Error suddenly when compiling Desktop on Android Studio - all projects - nothing changed - LibGDX
I have just gone into Android Studio to open a project. It will run in Android but not my Desktop configuration. Nothing of the code has been changed and I have now tried 3 projects, also a brand new project straight from the LibGDX Project Generator .jar file.

The error I get in Studio is: Exception in thread "LWJGL Application" java.lang.NullPointerException at com.badlogic.gdx.backends.lwjgl.LwjglGraphics.createDisplayPixelFormat(LwjglGraphics.java:322) at com.badlogic.gdx.backends.lwjgl.LwjglGraphics.setupDisplay(LwjglGraphics.java:216) at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:142) at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:124)

Process finished with exit code 0

Please can anybody help me here? thanks

# Answer
> 1 votes
I had the same problem. After I updated my NVidia drivers yesterday, I noticed that all my LibGdx Projects caused the same exception you've written above. After a lot of research on google, I found many complaints from other players which had artifacts with the new driver version and a file from NVidia about current driver problems. I tryed to rollback to the previous version and now everything works fine again. Use your "Hardware Manager" -\> "Graphics Adapters" -\> \[Your NVidia Card\] -\> "Roll Back Drivers". Then you can go on with your programming project.

NVidia PDF Page 14

Problem Discusion

---
Tags: libgdx, lwjgl, android-studio, ide
---


title: Optimised server structuration

text:
# Question
Title: Optimised server structuration
I've been wondering a lot lately about how to make an optimised server structuration, and i came to the conclusion that i severely lack knowledge on the subject.

I'll be doing this with either C, C++ or C#, with a preference for the latter.

**Context:**

I have a server that can operate more than 3K clients at one time.

This server is a game server, hence it only receives key inputs from the clients, for security measures.

Therefore the server is doing every operation on the user's data, and send back enough information to the client in order to display a personal GUI. (The server is of course a console application, don't get me wrong.)

**Approaches:**

*1- 1 Client = 1 Logic Thread*

(The thread does the player calculation)

Pros: every client runs his own server code, the server is more responsive to a particular client's request.

Cons: I do not have the insurance that a particular client will iterate its code 14 times while another would have iterated it 10, (so the two players, side by side, if it was for a movement operation, can become 4 squares afar, which should not be the case, as every player should move at an exact same speed)

Locking every thread to perform actions until a next logic loop happens can be quite devastating if something bad happens on any of the client, leading to severe lags in worst cases.

*2- 1 Client = 1 Entry Thread, Main logic loop*

(The thread receives the keys pressed by its client)

Pros: As the logic is all in the same loop, there is no desynchronization problems anymore.

Cons: Iterating ALL the game logic in one loop will most probably cause severe latency if the operations becomes advanced.

Moreover, if many clients are to catch up with all the current data being processed (sudden peak of connections), it would also cause additional latency, a partial solution would be to retrieve those datas in the Entry Thread.

*3- 1 Client = 1 Entry Thread, X Logic threads, 1 Logic Thread synchronizer*

(Entry thread receives keys, register the client in the concerned threads (One for each kind of action (Moving, Acquiring user data, Battle, Etc...)), Those threads gives the information whenever they can, and the Logic thread synchronizer ensures that tasks that needs to be "Ordered" in time are ordered.)

Pros: Share computation resources among all the Logic Threads, ensuring minimum latency for clients.

Cons: High vulnerability to resources concurrency, and if a particular task is done faster than another task that is to be synchronized with it, becomes as slow as the latter.

**Question:**

As i said earlier, i certainly lack knowledge about networking, threading, and concurrency, to efficiently order the structure of my program. Therefore, I'm asking it here:

What would be the best approach to take, and how should the global skeleton should be ordered to minimize latency, and permits a large number of synchronous users to play on the server.

**Additional information**

Maybe a bit of information about the idea behind this all will help.

My goal here is to create a server that will be used to run a simple RPG, which needs to have movement synchronization on the map (old school square-to-square movements), turn by turn instanciated battle (e.g. Dragon Quest, Final Fantasy, Pokemon), and exchange of user data (seeing X's profile, see how many monsters he killed, his guild, etc.)

If i'm asking for more than 3K clients at the same time, it is because i do not want to make a pile of junk that holds in place by a miracle. I want to further my knowledge on networking and its applied logic, would it be programmative logic or structuration logic.

So basically the problem is "Having a maximum of clients, on a minimally powerful server, therefore optimizing it as much as possible."

# Answer
Don't have a thread for each client - you'll be shooting yourself in the foot by thrashing the CPU cache more as more players connect. If you're not looking to run multiple server processes per machine, then you'd ideally want your number of threads to match your number of cores to reduce context switching. One thread should be enough to read in input packets for all connected players and update data structures for the logic thread(s) to operate on.
> 1 votes

---
Tags: c#, performance, optimization, mmo, client-server
---


# Question
Title: line segment triangular-prism intersection
What is the best way how to perform intersection test between triangular-prism (used as bounding "box") and line-segment (NOT ray)? The triangular prism is not axis-aligned and it is stored as a triangle (3x 3D coordinates) and the height of the triangle?

If you advise me some "mathematicaly" optimalized solution (not just simple geometric but something like Moller-Trumbore for simple triangle) I will be grateful. I don't need the distance, just bool value (intersect/not intersect).

# Answer
> 1 votes
You could try decomposing the prism into triangles and then test line against each triangle:

as you say Moller-Trumbore triangle intersection can be used for this, for example:

```
bool rayIntersectTriangle(vector3 line_a, vector line_b, vector tri_a, vector tri_b, vector tri_c)
{
    vector edge1 = tri_b - tri_a;
    vector edge2 = tri_c - tri_a;
    vector line  = line_a - line_b;

    vector tri_normal = cross(edge1,edge2);

    // if d<=0 line pointing away for tri, no intersection
    float d = dot(line,tri_normal);
    if(d<=0.0f)
        return false;

    // if parametric intersection t if <0.0f or >d then segment does not intersect
    vector aa = line_a - tri_a;
    float t = dot(aa,tri_normal);
    if(t<0.0f || t>d)
        return false;

    // calculate barycentric coords to check if segment within bounds
    vector e = cross(line,aa);
    float v = dot(edge2,e);
    if(v<0.0f || v>d)
        return false;
    float w = -dot(edge1,e);
    if(w<0.0f || v+w>d)
        return false;

    // we must have intersection...
    return true;
}

```

# Answer
> 1 votes
As far as I know the only somewhat efficient way is to take the line segment, iterate over the 5 planes of the triangular prism (one for each side), and "cut" the line segment by each plane. You keep the part of the line segment that is inside the shape. If, after one of the cuts, there is nothing left of your line segment, you have determined the line segment does NOT intersect the volume of the prism. Note that this doesn't work for concave 3D shapes.

---
Tags: intersection
---


title: Unit collision avoidance for RTS

text:
# Question
Title: Unit collision avoidance for RTS
I'm developing an RTS, and having a little difficulty with collision detection. From what I understand RTS generally don't bother with collision detection and just try to avoid collision, and that is what I am trying to accomplish.

My game uses a grid for static obstacles, but units are not bound to the grid for movement. How do I allow for units to avoid collisions, both with static obstacles and with other units? Right now my workaround is to redirect units around static obstacles every time they move from point to point (and every time a new obstruction is placed on map, units replan their routes). This doesn't seem like an ideal solution, but it works. I have no idea how to handle unit-unit collisions.

# Answer
You are on the right track.

I have re-implemented collision avoidance for my RTS taking Recast as example. General approach is quite simple: Each agent (that's how they call units in collision-avoidance) checks for neighbours and obstacles and chooses path depending on its desired movement direction, other agents desired directions and allowed space. Complications arise from making this efficiently.

All agents are usually implemented as circles. Each agent keeps a list of 6-8 closest agents and sees if they are in their way. Obstacles are usually circles or NavMesh boundaries. Agents emit rays and check if they collide with any obstacles edges.

There are many pitfalls in implementation, so unless you want to make your game specifically-unique collision-avoidance based, better take an existing library.

---

I have researched the topic and have made a list of available libraries (actualized in 2014), that implement agents navigation and collision avoidance:

* Recast Navigation/Detour/Crowd
* ORCA: Optimal Reciprocal Collision Avoidance
* RVO2
* HRVO
* ClearPath: Highly Parallel Collision Avoidance
* OpenSteer
* SimplePath

You might want to see their sites, some had explanatory videos and texts.
> 1 votes

---
Tags: collision-detection, rts, collision-avoidance
---


# Question
Title: Calculate resources real-time. Sockets or not?
I'm currenly developing a game in Javascript. It's a Single Page Application so every change should be pulled from the server without page refresh. I'm currently wondering how I should handle the 'resources in stock' (like wood, food and gold).

**I know there are more questions like this around here (regarding websockets and Ajax requests) but I'm currently looking for the best solution in my specific case.**

### Scenario

Resources are produced every second. So for example, every minute 100 resources are produced. This should be updated live. I know, in this case it's not necessary to really update them live. I mean, I can simply calculate how much resources are produced in the current time minus the last updated time.

So no problem here, but there are a lot of different factors regarding the production of resources:

* If a player is attacked, the enemy could have robbed some of his resources. So after an attack, the resources should be updated too.
* If a player is attacked, and one of his 'productionbuildings' are damaged, he, for example, doesn't produce 1000 resources a hour, but 800 resources instead. So after a building has been demolished, the application should know the new building level to calculate the right amount of new resources.

### Possibilities

So, how should I update the resources for the user? These are the options I think could possibly work:

* Ping a script on the server, which calculates and updates the resources, every 5 seconds.
* Set up a websocket stream and trigger it after each activity (after an attack, demolished building, ...)

Are there any other options? What would be the best way?

# Answer
# Introduction

There are pros and cons to each method of synchronization you gave that depend on a couple of factors. First, is your game singleplayer or multiplayer, second, how real-time is your game? If your game is only single player, you may want to consider having a client side only game which would make things simpler. However, assuming you need a server backend to validate what the client does, here are some points.

# Pulling & non-realtime game elements:

For non-realtime games, pulling would work just fine. The client could send updates about what the player did over the last few seconds to the server and in the same update, the server could send an updated game state back to the client. To smooth out the updates the client can model the updates that the server is performing, but refer back to the server whenever it pulls for updates.

# Pulling & realtime game elements:

Using pulling in a realtime game is a little trickier because you would have to increase the pulling frequency significantly so that other players (or NPCs) won't appear glitchy. This would in tern cause an increase in traffic and html connections have a certain amount of overhead with each request.

# Websockets:

Now lets talk about Sockets! If I remember correctly websockets are just a thin layer over a tcp connection which means it doesn't have all the overhead that the pulling approach has of establishing an html connection. This makes it ideal for realtime games because you can send more two-way communications with less overhead. Also, websockets have the additional benefit of allowing the server to push updates to the client whenever it needs to. Most modern browsers support websockets too (http://caniuse.com/#search=sockets).

# Also Note:

Also keep in mind that if you are building a multiplayer game or a game that publishes scores that others can see, you should probably make sure that your server verifies all the actions that the client says it does. Basically, it's best to program most of the game logic on the server and have a 'thin' client that transmits the player actions to the server. If needed, the client can run the same logic as the server to make for a more immersive experience for the player.

# Conclusion:

Overall, I don't see any reason not to use websockets.

Good luck with your project.
> 5 votes

# Answer
I would advise using socket.io because of the ease of learning it and that it will be great to have updates live.

I use socket.io for each multiplayer game.
> 0 votes

# Answer
The best way to calculate the resources is to use times and events.

Just imagine you have your timestring

```
|----------|
10:00-----12:00

```

the first line is last time the user was online, the second line is the time when the user comes online now. so now you can calculate the time difference in seconds for example. if you know how many resources are produced per second you just need to multiply difference * production.

now events

```
|-----|----|----|

```

each time, something happens to the player (building upgraded,got attacked, building downgraded) you store the data in events table.

so when the player got attacked or goes online,you loop through events and calculate again with time difference.

as long as you store on each request the current datetime you can calculate everything without to pull or use websockets.

beside websockets working only in a non persistent world, you a player can log off and get resources, websockets are useless here.

Cheers
> 0 votes

---
Tags: server, browser-based-games, php, synchronization, websocket
---


# Question
Title: Building TMX in the MonoGame Pipeline using MonoGame Extended
I updated MonoGame to the latest development build and noticed the Tiled Map Importer and Processor wasn't in the content pipeline anymore (even after adding both MonoGame Extended Content DLL and MonoGame Extended Tiled Content DLL).

Am I supposed to build TMX maps into .xnb files using the MonoGame XML Importer and No Processing or am I doing something wrong?

# Answer
> 0 votes
It sounds like you're either using the pre-release NuGet packages or building from source. Either way, you're using code that changes fairly frequently in the `develop` branch.

It sounds like you're on the right track though. The Tiled content importer has recently been split out from the main one, so referencing it from the MonoGame Content pipeline is the way to go.

The best way to see how things work is to take a look at the demos. We try to keep those up-to-date with the latest changes.

For example, the demo shows that there's now two DLL's referenced in the `Content.mgcb` file.

```
#-------------------------------- References --------------------------------#

/reference:../../../MonoGame.Extended.Content.Pipeline/bin/MonoGame.Extended.Content.Pipeline.dll
/reference:../../../MonoGame.Extended.Content.Pipeline.Tiled/bin/MonoGame.Extended.Content.Pipeline.Tiled.dll

```

The exact path to these files will change depending on if you're building from source or referencing the NuGet package but other than that it's straightforward.

It's not really clear from your question what might be wrong exactly, but I hope this answer leads you in the right direction.

---
Tags: c#, monogame, monogame-extended
---


# Question
Title: Character on Moving Platform Shaky. How to Fix?
I have an elevator (rigid body platform) that is meant to transport a character. The character (RigidBodyFPSController) shakes while platform descends.

What is an elegant way to fix their relative motions while the elevator is in motion, still allowing the character to move around in it?

NOTE: I tried parenting the character but that flips him on his side.

# Answer
> 1 votes
The first simple trick I would recommend is making the character the rigidbody instead of the elevator. Using Unity's collisions you only need one member of the collision to be an actual rigidbody.

The other thing I notice in my experience with Unity and rigidbodies is that they can get quite shaky when pushing each other forcefully. From what it sounds like you're doing, the elevator is just colliding with the controller and shoving it up which is not the most graceful thing. If you have not already I would try having the elevator exert a force onto the controller so that their velocity increases upwards to move them rather than just shoving their position straight up which the base collision may be doing.

Check out this on the unity forums/answers, you may find some extra help there.

---
Tags: unity, rigidbody
---


title: How to use Libgdx Accelerometer?

text:
# Question
Title: How to use Libgdx Accelerometer?
I am developing a game with libgdx for android.I want use accelerometer for motion control.I am controlling a coin within screen bounds. I want to apply gravity according to device orientation as you can see in the image. I know i can use `Gdx.input.getAccelerometerX()`(or y,z) But i can't understand how to use to get desired result.

Here i have attached two sample image for simple understanding

# Answer
Gravity is a type of acceleration, this is what the sensor gives you.

Acceleration is a vector value, because it has a direction. The length of the gravity vector is always around 9.81 becahue that's the average gravity (of course it can be different, for example on the Mount Everest you have a smaller gravitational force than on the bottom of the see)

If you want the ball, to always fall to the ground with an acceleration matching the gravity, then using the acceleration sensor is not enough. If you start waving the device around, then the acceleration will change. The accelerometer also doesn't register anything when the phone is freefalling. If you don't care about this, then you can skip the next paragraph.

You should instead use the orientation of the device, create a unit vector out of that and multiply it with 9.81.

Then, to apply this to an object, you need to increase it's velocity by this vector multiplied by the amount of time that's passed between calls (time should be in seconds, with 60 fps it should be around 0.016666 seconds)
> 2 votes

---
Tags: android, libgdx, game-mechanics, accelerometer
---


# Question
Title: How to cause delay of 1 second of bullets when space pressed
I was wondering how to cause the bullets to delay since at the moment, they fire pretty much one after another. So I was wondering how to make each bullet be delayed by one second when the space bar is pressed/held down.

```
public class TheGun extends GunType{

  private Rectangle bullet;
  private final double speed = 3d;

  public TheGun(double xPos, double yPos, int width,int height){
    this.setxPos(xPos);
    this.setyPos(yPos);
    this.setWidth(width);
    this.setHeight(height);

    this.bullet = new Rectangle((int) getxPos(),(int) getyPos(), getWidth(), getHeight());
  }

  @Override
  public void draw(Graphics2D g) {
    if(bullet == null)
      return;

    g.setColor(Color.YELLOW);
    g.fill(bullet);
  }

  @Override
  public void update(double delta, BlockyBlocks blocks) {
    if(bullet == null)
      return;

    this.setyPos(getyPos() - (delta * speed - 1));
    bullet.y = (int) this.getyPos();
    wallCollide(blocks);
    isOutofBounds();
  }

  @Override
  public boolean collisionRect(Rectangle rect) {
    if(this.bullet == null)
      return false;

    if(bullet.intersects(rect)){
      this.bullet = null;
      return true;
    }

    return false;
  }

  @Override
  public boolean collisionPoly(Polygon poly) {
    // TODO Auto-generated method stub
    return false;
  }

  @Override
  public boolean destroy() {
    if(bullet == null)
      return true;

    return false;
  }

  @Override
  protected void wallCollide(BlockyBlocks blocks) {
    for(int i = 0; i < blocks.wall.size(); i++){
      if(bullet.intersects(blocks.wall.get(i))){
        blocks.wall.remove(i);
        bullet = null;
        return;
      }
    }
  }

  @Override
  protected void isOutofBounds() {
    if(this.bullet == null)
      return;

    if(bullet.y < 0 || bullet.y > Sea_InvadersDisplay.HEIGHT || bullet.x < 0 || bullet.x > Sea_InvadersDisplay.WIDTH){
      bullet = null;
    }
  }
}

```

# Answer
What you can simply do is keeping the last bullet launched time, and when trying to fire check if the ellapsed time is over 1 second to launch the next bullet.

It could look like this

```
uint timeLastBullet = 0; // Initialize before game loop

if (spacePressed) // In game loop
{
    if (GetTime() - timeLastBullet >= 1000) //If GetTime returns milliseconds
    {
        Fire();
        timeLastBullet = GetTime();
    }
}

```
> 2 votes

---
Tags: java, timer
---


# Question
Title: Frustum Culling behaves incorrectly with vertex shaded objects
I have a scene with a straight path. It looks something like this:

I've also wrote a vertex shader that bends the path. After applying the shader, it looks something like this:

If you were to look at the walls on the right, the emptiness is created by wall tiles that were culled by the camera's default frustum culling.

Is there a way fix this without disabling frustum culling completely?

# Answer
One of the solutions is to increase the size of bounding boxes of your meshes so they still touch the frustum. Usually it's much easier but in your case it depends on the distortion caused by vertex shader and you didn't say much about that.

You'll probably need some experiments to find optimal way to compute BBox extends for each mesh. For start try to increase them by some constant amounts and see if that's what you need.

I assume that at the Camera position you don't change the vertices and the vertex shader influence increases with Camera.forward vector. In your current example meshes at the right should have increased bounds but for meshes at the left you can actually decrease them.

Here you have an answer how to change mesh BBox.
> 1 votes

---
Tags: shaders, unity, camera, frustum-culling
---


# Question
Title: How can I use GPL software like Stockfish Chess Engine in my Unity game?
I am working on a 3D Chess game and I want to implement an A.I bot to play with the player. I found a chess engine called Stockfish which serves this purpose, and I would like to implement that engine in my project.

Is it as simple as including the Stockfish code in my project or importing a binary as a plugin, or do I have to do something more complex because of the GPL licence?

# Answer
You can implement their code as a plugin in your game, **as long as you plan for your game to also be GPL-licensed**.

You cannot incorporate Stockfish into a proprietary product, in the sense of bundling them together so that the user perceives them as a single program - which arguably describes typical methods of using 3rd-party plugins within your Unity project.

> You cannot incorporate GPL-covered software in a proprietary system. The goal of the GPL is to grant everyone the freedom to copy, redistribute, understand, and modify a program.

---

You still have other options if your game is proprietary:

> However, in many cases you can distribute the GPL-covered software alongside your proprietary system. To do this validly, you must make sure that the free and non-free programs communicate at arms length, that they are not combined in a way that would make them effectively a single program.
>
> ...
>
> If the two programs remain well separated, like the compiler and the kernel, or like an editor and a shell, then you can treat them as two separate programs—but you have to do it properly.

I am not an expert in this matter, so I will leave this as a community wiki to be updated by other users. Here is a sketch of how I think you could proceed:

* Create an installer for your game that installs your Unity executable and assets in one place, and Stockfish separately.
* Your game runs the Stockfish program, communicating with it using Universal Chess Interface commands.
* You provide a configuration setting where a player can choose to redirect this behaviour to use a different UCI-compatible chess engine if they so choose, so the two programs can operate independently of each other.
> 5 votes

---
Tags: unity, chess
---


# Question
Title: A script isn't showing in the Content Browser
Just to set the tone, I'm very new to game development.

I'm currently taking an online video course for Unreal Engine 4 that required me to create a C++ script. After I created the script and it compiled it did not appear in the Content Browser where it should be. I received the following text boxes:

and

# Answer
> 2 votes
With the information you've provided, my first thought would be to try the following:

* Compile your project in Unreal
* Clean and Compile your project in Visual Studio

Compiling your project in Unreal if you haven't already done it is straight forward, just press the Compile button in the toolbar above the Viewport.

To open your project inside Visual Studio, you can just right click on the Content folder inside the Content Browser, and select 'show in explorer' which will take you straight to the Content folder of your project inside file explorer. Navigate up one directory to go back to the main folder of your project. Assuming you are using Visual Studio with your project there should be a Microsoft Visual Studio Solution file located towards the bottom of this directory, named after the name of your project- 'SpaceShooter.sln' in your case. If you double click on this file, Visual Studio will open your solution, containing all of your C++ files.

To clean your project, select Edit, then Clean from the menu at the top of Visual Studio. Then select Edit and Build, or just press Ctr + Shift + Build to compile your project. Now go back and compile your project again inside Unreal using the tool bar. Hopefully your files should show inside the content browser at this point.

It's also worth noting that your C++ files aren't shown directly in the Content folder of the Content Browser, just on the off chance that you're looking in the wrong place after trying the steps above. To show your C++ classes in the Content Browser, you need to press the 'show or hide sources panel' indicated by an arrow pointing to the left on the side of the content browser, and then select the C++ Classes folder.

These might seem like fairly trivial suggestions, but hopefully it's a trivial problem to begin with. Without more information it's hard to know where else to go from there though. Try to give as much info as you can when asking questions as it makes it easier to give you a targeted answer- the output log is a good start, but it would be more useful to know specifically what you did leading up to the issue you're experiencing, in addition to anything you tried after experiencing the issue to try and remedy it. What steps did you take to create the script for example? Did you attempt the above suggestions already? What version of Unreal Engine are you using?

Not having a go at you by any means, just a tip to help you ask better questions so that you can get better answers in the future.

---
Tags: c++, unreal-4
---


# Question
Title: How to Capture Vive's USB-Audio Data from Playback Devices
I am developing a music visualizer software for Vive so I am trying to get FFT data from music that users listen to. However, I couldn't take any data from USB audio devices versus my soundcard.

What I have done is

1. Using **FMOD**, I could access recording devices but there is no usb-audio device in the recording device list so I can only access the speaker(What U Hear)

> system-\>recordStart(0, sound, true); // only I can capture data from recording devices
> system-\>playSound(FMOD\_CHANNEL\_FREE, sound, false, &channel);

2. Using **WASAPI** in Windows SDK, I tried to get the data although It also takes only data from the speaker not USB-Audio. I am not sure I did correct here but the SDK's example, WASAPICaptureSharedTimerDriven, doesn't seem to work for USB-AUDIO but it works fine with data from my soundcard (What U Hear)

If anyone has captured any audio data through USB-audio, please tell me the approach.

# Answer
> 0 votes
This is a bit outside my expertise, but you might need to use the USBAudio class system driver.

---
Tags: audio, htc-vive
---


title: Decal implementation

text:
# Question
Title: Decal implementation
I had issues finding information about decals, so maybe this question will help others. The implementation is for a forward renderer.

Could somebody confirm if i got decal implementation right?

* You define a cube of any dimension that'll define the projection volume in common space. You check for triangle intersection with the defined cube to recieve triangles that the projection will affect.
* You clip these triangles and save them.
* You then use matrix tricks to calculate UV coordinates for the saved triangles that'll reference the texture you're projecting.
* To do this you take the vectors representing height, width and depth of the cube in common space, so that f.e. the bottom left corner is the origin.
* You put that in a matrix as the i, j, k unit vectors, set the translation for the cube, then you inverse this matrix.
* You multiply the vertices of the saved triangles by this matrix, that way you get their coordinates inside of a 0 to 1 size cube that you use as the UV coordinates.
* This way you have the original triangles you're projecting onto and you have UV coordinates for them (the UV coordinates are referencing the texture you're projecting).
* Then you rerender the saved triangles onto the scene and they overwrite the area of projection with the projected image.

Now the questions that i couldn't find answers for. Is the last point right? I've never done software clipping, but it seems error prone enough, due to limited precision, that the'll be some z fighting occuring for the projected texture. Also is the way of getting UV coordinates correct?

# Answer
Take a look at this article:

http://blog.wolfire.com/2009/06/how-to-project-decals/

It seems he is using the exact same approach you're using. He doesn't talk about z-fighting, but it could definitely become an issue at larger distances.

My suggestion would be to disable decals after a certain distance if the z-fighting becomes very visible.
> 5 votes

# Answer
What I did to solve the Z fighting was to bump the vertex's Z value by a small amount, in my decal shader, after it's in screen coordinates.

OK..... I use fitted mesh decals. I create a mesh n x n with Y sitting on the terrain. I use code to find the Y on the terrains polygon mesh. After all the transfroms, I'm drawing over the top of existing geometry in screen coordinates. The depth buffer is in screen coordinates so by moving the Z of the decals polygons a slight bit towards the screen, it stops the Z fighting. By doing this I reduced the amount of polygons making up my fitted decals meshes by half. This is old 120 code

```
 vec4 v = gl_ModelViewProjectionMatrix * gl_Vertex;
 v.z -= .03;
 gl_Position = v;

```

Hope this explains it better.. (as requested)
> 3 votes

---
Tags: graphics-programming, decal-system
---


title: Game Loop, Deltas. What is wrong?

text:
# Question
Title: Game Loop, Deltas. What is wrong?
For my Android app this is the gameloop:

```
public void run(){
    while(true){
        if(frames == 0)
            cTime = System.currentTimeMillis();

        if(System.currentTimeMillis() >= lastUpdate + 5){
            if(gameState == PLAYING)
                updatePhisic();

            updateSprites();
            this.postInvalidate();
            lastUpdate = System.currentTimeMillis();
        }

        /*try{
            Thread.sleep(sleeptime);
        }catch(InterruptedException e){}*/

        if(System.currentTimeMillis() >= cTime + 1000){
            frameRate = frames;
            frames = 0;
        }
        else
            frames++;
    }
}

```

Please consider this should work for multiple devices.

Testing in some devices:

* My phone: 180 FPS
* A Smaller phone: 200 FPS
* A Tablet: 120 FPS

I'm trying to put it at 60 FPS but the player moves so slow, I don't know how to calculate the Delta for player. I mean that at 180 FPS in my phone works fine, that is the speed that I want. But at 120 FPS in a tablet freezes a bit.

I think that painting the screen 60 times in a second would be enough.

And this freezes sometimes:

```
if(System.currentTimeMillis() >= lastUpdate + 5)

```

This does not:

```
try{
    Thread.sleep(sleeptime);
}catch(InterruptedException e){}

```

Why?

# Answer
> 1 votes
There are two things that stand out here. First, having 4 calls to `System.currentTimeMillis()` is at best confusing and could be the source of bugs. If `lastUpdate` is used outside of this function, it's going to represent the idle time *between* frames, not the time since the last frame. Try locking in the current time at the top of your loop instead:

```
while(true) {
    long currTimeMs = System.currentTimeMillis();

    if(frames == 0)
            cTime = currTimeMs;

    if(currTimeMs >= lastUpdate + 5){
        ...
        lastUpdate = currTimeMs;
    }

    if(currTimeMs >= cTime + 1000){
        ...
    }
    ...
}

```

Along the same lines, you should have a fixed delta and pass that around:

```
if(currTimeMs >= lastUpdate + 5){
    deltaMs = currTimeMs - lastUpdate;
    ...
    // Make use of deltaMs
    ...
    lastUpdate = currTimeMs;
}

```

This gives the rest of the code a consistent view of time.

Second, you're not counting your frame rate correctly, so the numbers you mentioned are likely misleading. `frames++` happens outside your update block, meaning that you increment the frame count even if you didn't render a frame.

---
Tags: android, game-loop
---


# Question
Title: How can I separate gameview from UI most efficiently in Unity?
Let me provide an image to illustrate what I mean. It is from a game called Runescape.

# Answer
> 3 votes
Like most things in Unity, there are many ways to skin this cat depending on your game's needs and your preferred workflows.

So, to narrow things down, I'm going to focus on one specific issue: **rendering efficiency**.

In the example you've presented, the 3D game view occupies only about 2/3 of the frame's width or height, with the rest occupied by opaque UI. If we were to render the game across the whole window, then layer the UI on top, we'd end up covering over half those pixels - so we would waste a lot of our frame time (and battery, on mobile) rendering content the player will never see.

To fix this, we can **set up our 3D camera so it renders into only the screen pixels we want**. We can do this using the Rect property of a camera (called "Viewport Rect" in the inspector), which lets us specify the horizontal and vertical fractions of the viewport the camera should render into. That way we skip rendering to areas of the screen that will be covered over (and the camera's center of projection will automatically align with the middle of the viewport, as expected, rather than the center of the screen, making the viewport appear subtly skewed)

Then we can layer UI over the whole screen using a canvas set to screenspace overlay.

As examples, you can see this answer about multiple projections or this answer's animations, which were accomplished using this viewport trick to render each view to its own designated rectangle of the game window.

If you need to do something a bit fancier - say, having the game viewport in a window element that can float around your UI, or cropping the game view to an unusual shape, you can accomplish this by creating a RenderTexture of your desired resolution for your camera to render into (using its targetTexture property), and then referencing that RenderTexture in a UI RawImage component, to be able to manipulate or animate the rendered view similar to how you would with any other UI widget.

# Answer
> 0 votes
I would suggest to have two cameras :

The first one to render only the game view by modifying the `rect` of the camera : https://docs.unity3d.com/ScriptReference/Camera-rect.html

Set it to something like :

```
camera.rect = Rect (0, 0.2f, 0.8f, 0.8f);

```

Then, create an other camera used to render an overlay canvas, and make sure all your elements are outside the rect given above.

---
Tags: unity, gui
---


# Question
Title: 2D HUD overlay drawing based on 3D coordinates and camera azimuth and elevation
Assume you have the 3d coordinates of the player and another unit `N` as well as the azimuth and elevation of a camera always looking at the player. In the following illustration the sun would be the camera of course:

<sub>(source: permetix.com)</sub>

Let's say one wants to draw something on a different transparent window (not using the game window or any hooks) that is always displayed on top of the unit. An example would be TurboHUD for Diablo. In the linked video you can see that it displays affixes using textboxes right on top of the blue elite mobs.

In Diablo doing this is much simpler since the camera cannot be rotated and moved thus only simple projections depending on the distance are necessary, but what about situations with more degrees of freedom? How can one estimate 2d coordinates to draw at that match the position of the 3d units on the screen without access to more than described in the first paragraph? What is the mathematical background and what are the necessary computations?

# Answer
So I came up with a solution that is basically a World-to-Camera matrix chained with a Camera-to-Projection matrix. For this I only need to rotate the vector `(cameraDistance, 0, 0)` based on elevation and azimuth to start with and apply the following computations:

```
cameraDirection = normalize(cameraPosition - playerPosition)
cameraRight = normalize(crossProduct((0, 0, 1), cameraDirection))
cameraUp = normalize(crossProduct(cameraPosition, cameraRight))

```

This is essentially the Gram-Schmidt proccess and yields the following view matrix

With `R_i` being the components of the `cameraRight`, `U_i` the components of the `cameraUp`, `D_i` the components of the `cameraDirection` and `P_i` the components of the `cameraPosition` vector respectively. Thus an object with homogenized coordinates `v` would appear at `V * v` for the camera. To project this to the screen I am using the following projection matrix:

The value `r` is the aspect ratio, `FOV` the field of view in degrees, `F` the distance of the far plane and `N` the distance of the near plane.

To get the final 2d coordinates the vector `u = P * V * v` must be dehomogenized and thus all components must be divided by the fourth component of `u`. Finally the first and second component are values in `[-1,1]` thus one must add 1 and multiply with 0.5 then with the width or height respectively to map the relative positions to screen coordinates.
> 0 votes

---
Tags: 2d, 3d, camera, projection, hud
---


# Question
Title: How to make a game object scale up from another game object
I have a `GameObject`. I'm trying to make another `GameObject` grow in scale from touching `this GameObject`, and when a set amount of scale is reached, destroy `this GameObject`. My problem is that when I access `ScaleUp`, it dosn't add any scale to the other `GameObject`.

How do I scale another `GameObject`? Here is my `ScaleUp` script:

```
using UnityEngine;
using System.Collections;

public class ScaleUp : MonoBehaviour
{

    public GameObject Player;
    public PlayerMovement PlayerScript;

    private float playerScaleX;
    private float playerScaleY;

    public float scaleUp = 10.0f;

    void Start()
    {
        Player = GameObject.FindGameObjectWithTag ("Player");

        PlayerScript = Player.GetComponent <PlayerMovement>();

        playerScaleX = Player.transform.localScale.x;
        playerScaleY = Player.transform.localScale.y;
    }

    void OnTriggerEnter2D (Collider2D other)
    {
        if (other.tag == "Player")
        {
            playerScaleX += scaleUp;
            playerScaleY += scaleUp;

            Debug.Log ("GROW");
        }
    }
}

```

# Answer
You want to actually assign a new value to `Player.transform.localScale` then, not just change the local variables `playerScaleX` and `playerScaleY`.

```
Vector3 playerScale = Player.transform.localScale;
playerScale.x += scaleUp;
playerScale.y += scaleUp;
Player.transform.localScale = playerScale;

```

or, it you really want to use the existing variables `playerScaleX` and `playerScaleY`:

```
playerScaleX += scaleUp;
playerScaleY += scaleUp;
Vector3 playerScale = Player.transform.localScale;
playerScale.x = playerScaleX;
playerScale.y = playerScaleY;
Player.transform.localScale = playerScale;

```
> 1 votes

# Answer
This is a good example of why we *must* know the difference between a *reference* data type and a *value* data type. In this case, values are being provided *as values*. Without the actual *reference* back to your player scale, changing these values will have no effect on the original values, what so ever.

---

There are a couple of ways you could scale up another game object. *Thelo's* answer offers a solution involving a simple additional step, where you just update your new values directly back into `player.transform.scale`. You might also consider working with the `Transform` type, or passing the `Vector3` by reference.

### Working with the automatic `Transform` reference

Classes *always* pass as reference. In this example, we have are trying to change the values of a `Vector3` in a `Transform`. If we grab a reference to the `Transform`, we can directly change the *original* `Vector3`.

```
// Note the use of SerializeField to make a private accessible to the inspector.
[SerializeField] private GameObject player;
[SerializeField] private Transform playerTransform;

// The scale increment applied by this scriptl.
public float scaleIncrement = 10f;
// The amount of scale this script has already applied.
public float appliedScale = 0f;
// The maximum scale this script can apply.
public float maxScale = 100f;

void Start()
{
    player = GameObject.FindGameObjectWithTag ("Player");
    playerTransform = player.GetComponent<Transform>();
}

void OnTriggerEnter2D (Collider2D other)
{
    if (other.tag == "Player")
    {
        // Apply the scale to player and add the increment to our local total.
        playerTransform.localScale += Vector3.One * scaleIncrement;
        appliedScale += scaleIncrement;

        if(appliedScale >= maxScale)
        {
            // If we have reached our max scale, destroy the local game object.
            Destroy(gameObject);
        }
    }
}

```

### Working with the `ref` keyword

You might find situations where you absolutely *must* use a type that would normally pass by *value*, but be able to access it as a *reference*. In these situations, we can use the `ref` keyword in a method signature. It is important to note that this should be done sparingly.

In the below method, you scale a `Vector3` that is passed by reference. We will assume, in context, that it is contained in the above script. You can then call for the method with `ScaleVector(ref player.transform.localScale)`. We are now passing in `player.transform.localScale` by *reference*, so we are directly editing the *original value*.

```
void ScaleVector(ref Vector3 vector)
{
    vector += Vector3.One * scaleIncrement;
}

```

---

### Further Reading

It is worth completing the Unity - Data Types tutorial. This is a beginner tutorial, and will help you understand this problem. In C#, it is also good to remember that `struct` (e.g. `Vector2` and `Vector3`) and primitive types (e.g. `int` and `float`) automatically pass the values, while everything else (mainly `class` types) automatically pass the reference.
> 0 votes

# Answer
Your main problem is that the object `Player.transform.localScale` is a reference value. When you change it's value, the change persists in the original place. But `Player.transform.localScale.x` and `Player.transform.localScale.y` aren't reference values. When you create a copy of those values in

```
playerScaleX
playerScaleY

```

and you modify them, `Player.transform.localScale` does not receive the modification. As a result, your game object does not scale. You must do something like in Thelo's sample code.
> -1 votes

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


# Question
Title: Should I care about CPU affinity of threads?
I am currently developing a rendering engine, which I plan to use for creating games. The engine makes heavy use of multithreading; I have a thread for OpenGL rendering, a thread for updating, a thread for processing user input, a thread for audio, etc. I have heavily tested it, and the threads work like clockwork. The multithreading approach has shown to be faster, more robust and flexible on a multicore processor, which I verified by profiling.

However, something which I have not considered is CPU-core affinity for threads. Should I care about it? What benefits does pinning threads provide, and to which CPU core do I pin which thread?

# Answer
> 6 votes
I wouldn't bother unless you have a very specific issue which you know is solved by this. (And if you have to ask, you probably don't.)

Modern OSs are quite good at distributing threads around CPU cores to balance the workload well and avoid overworking individual cores, plus your code is not going to be the only running code that needs to use CPU cores. Threads in your drivers, in any libraries you use, and in other programs or background processes will also need CPU time, and you certainly don't have knowledge of exactly what is going on there. You don't want to be at the risk of starving your GPU's driver of the CPU time it needs just because you were greedy with your own code, do you?

For example, and just to illustrate, here's a Task Manager shot of a single-threaded game running on Windows 10:

Bearing in mind the usual caveats about Task Manager as a profiling tool, we can nonetheless make a few observations.

* The game itself is single-threaded (and, in fact, runs flat-out).
* At no stage is any CPU core pegged at 100% usage.
* Average CPU usage exceeds 25% (not visible in this shot, it was 35%).
* So over 4 cores we can roughly say that 25% was the game running flat-out and 10% was other work.
* And the OS nicely moved the work around cores to keep the system running well.

# Answer
> 5 votes
I agree Le Comte du Merde-fou's answer is the best general rule here:

> I wouldn't bother unless you have a very specific issue which you know is solved by this.

For the curious though, I'd like to posit a couple examples of the types of "very specific issue" which might make this worthwhile. The ones I know of mainly come up when developing for consoles - where the hardware is fixed and you can optimize to its particular behaviour, rather than needing to scale to arbitrary core configurations & execution environments.

1. When running on some consoles, certain cores may be earmarked for OS tasks or occasional interruptions. I won't get into details that might tread on NDAs, but on a general level you may want to use these cores for work that's tolerant to throttling (asynchronous background tasks, or workers in a job system that can scale to use the core when available, without starving when it's not), and keep tasks on your critical path for the frame on cores where you know you have exclusive control.
2. When doing (very) large amounts of batch work with predictable data locality, paying attention to which threads use which data and which cache that data will be in can sometimes let you reduce redundant fetching & synchronization work between cores' private caches. Shared cache mechanisms are already lightning-fast compared to a trip to main memory though, so this is almost certainly micro-optimization unless you've already fine-tuned just about everything else in your engine.

---
Tags: architecture, multithreading, cpu
---