title: Collision Detection XNA Using Vector2

text:
# Question
Title: Collision Detection XNA Using Vector2
How would I convert this into C#? This is for a pong game and I am having a difficult time understanding. This is detecting the collision between a ball and a paddle. Can you comment please to help me understand this further, thank you. We have a picture to help

And here is the C++ code that was used that I would like to see converted to c#

```
float minimum_distance(vec2 v, vec2 w, vec2 p) {
  // Return minimum distance between line segment vw and point p
  const float l2 = length_squared(v, w);  // i.e. |w-v|^2 -  avoid a sqrt
  if (l2 == 0.0) return distance(p, v);   // v == w case

  // Consider the line extending the segment, parameterized as v + t (w - v).
  // We find projection of point p onto the line.
  // It falls where t = [(p-v) . (w-v)] / |w-v|^2
  // We clamp t from [0,1] to handle points outside the segment vw.
  const float t = max(0, min(1, dot(p - v, w - v) / l2));
  const vec2 projection = v + t * (w - v);  // Projection falls on the segment
  return distance(p, projection);
}

```

# Answer
The code you provided in your question is syntactically correct C# already.

All that you lack are the vec2 structs and the mathematical functions being used in that code. Fortunately, the XNA library provides all of this for you in the Vector2 structure. ( https://msdn.microsoft.com/en-us/library/microsoft.xna.framework.vector2\_methods.aspx?f=255&MSPPError=-2147217396 )

I won't convert everything for you as that's not a good way for you to learn, but I will show you how to convert the first two lines of code.

In C++:

```
float minimum_distance(vec2 v, vec2 w, vec2 p) {

```

In C#:

```
private float minimum_distance(Vector2 v, Vector2 w, Vector2 p) {

```

This conversion is extremely simple, effectively just replacing the references to the C++ vec2 object with the C# Vector2 structure.

Now for the next line, In C++:

```
const float l2 = length_squared(v, w);

```

In C#:

```
float l2 = Vector2.DistanceSquared(v, w);

```

On this line, I've removed the const modifier, because although correct, it does not really do anything useful in this case from what I can see. I've then replaced the C++ function being used with the equivalent method provided by XNA. The name changes, but the operation should be identical.

This entire function can be converted in the same way as Vector2 also contains methods for Dot, Min, Max, and Distance.
> 0 votes

# Answer
Here you go, I just used a convertor so idk if it works but I converted it for you

```
private float minimum_distance(vec2 v, vec2 w, vec2 p)

// Return minimum distance between line segment vw and point p
const float l2 = length_squared(v, w);
// i.e. |w-v|^2 -  avoid a sqrt
if (l2 == 0.0) {
    return distance(p, v);
}
// v == w case
// Consider the line extending the segment, parameterized as v + t (w - v).
// We find projection of point p onto the line.
// It falls where t = [(p-v) . (w-v)] / |w-v|^2
// We clamp t from [0,1] to handle points outside the segment vw.
const float t = max(0, min(1, dot(p - v, w - v) / l2));
const vec2 projection = v + t * (w - v);
// Projection falls on the segment
return distance(p, projection);

```
> -2 votes

---
Tags: xna
---


title: C++ libtcod example doesn't work

text:
# Question
Title: C++ libtcod example doesn't work
I'm starting to learn C++ (I have a very basic programming background) and I have in mind to create an old-school ASCII-looking roguelike. I know it may be easier in Python, but it **has** to be in C++. I'm using **Windows 10**.

I want some eye candy beyond basic ASCII, I've seen **libtcod 1.5.1** offers a lot of possibilities so I wanted to try it and follow this tutorial. The problem is I'm stuck right at the beginning, because the libtcod demo "*samples\_cpp.exe*" **works** but not the example code:

```
#include "libtcod.hpp"

int main()
{
   TCODConsole::initRoot(80, 50, "libtcod C++ tutorial", false);
   while ( !TCODConsole::isWindowClosed() )
   {
       TCODSystem::checkForEvent(TCOD_EVENT_KEY_PRESS, NULL, NULL);
       TCODConsole::root->clear();
       TCODConsole::root->putChar(40, 25, '@');
       TCODConsole::flush();
   }

   return 0;
}

```

If I launch the .exe compiled with the command:

```
g++ src/*.cpp -o tuto -Iinclude -Llib -ltcod-mingw -static-libgcc -static-libstdc++ -Wall

```

by double-click, it opens and closes a window very fast, and if I execute it from the console I get the in-console message:

```
24 bits font.
key color : 0 0 0
character for ascii code 255 is colored

```

Any clues of what I'm doing wrong? The project has all the proper .dll and include folder. This should be pretty easy :/

Thanks a million!

---

**UPDATE:** Ok, I got some new info, gdb says this:

```
[New Thread 7468.0x1f24]
[New Thread 7468.0x203c]
[New Thread 7468.0x1bdc]
[New Thread 7468.0x190c]
[New Thread 7468.0x108c]
24 bits font.
key color : 0 0 0
character for ascii code 255 is colored
Using SDL renderer...

Program received signal SIGSEGV, Segmentation fault.
0x65e70d9f in TCODConsole::clear (this=0x1) at src/console.cpp:196
196     src/console.cpp: No such file or directory.

```

Not sure what that means, the console.cpp file of libtcode at line 196 has the following:

```
void TCODConsole::clear() {
    TCOD_console_clear(data);
}

```

# Answer
> 0 votes
Ok, I finally managed to make it work. The problem was I didn't compile libtcod myself, I was using the files found in this zip.

It was pretty useful the information @Tyyppi\_77 found in this forum thread:

> TCODConsole::clear method is located at line 196 in libtcod version 1.5.1, so the binary (.dll) library must be from 1.5.1 release. However, that release does not include MinGW libraries (libtcod-mingw\[-debug\]). Yet gdb cannot find src/console.cpp file implying you did not compile those libraries yourself. Which becomes really confusing: where did you get your libtcod-mingw-debug.dll from? Also, "this = 0x1" indicates that TCODConsole::clear has recevied totally wrong object pointer. Usually it happens when you call a method on non-exising object (which should not be the case here) or when linking against a library has gone haywire.
>
> I suggest you delete your current libtcod (and all traces of it) and try to unpack a clean 1.5.2 release. If that will not help, try to build the library as described here: http://doryen.eptalys.net/data/libtcod/doc/1.5.2/html2/compile\_libtcod\_mingw.html \[**NOTE: This link is broken**\] Note that you do not have to use the exact MinGW version mentioned on that page. When you're compiling library yourself you are fine as long as you're using the same version for everything.

In this thread of github I got the idea of using Brogue's dll files, and they worked. But I suppose the best approach is to compile libtcod myself.

---
Tags: c++, windows
---


title: How to create a separate bin folder?

text:
# Question
Title: How to create a separate bin folder?
I am now creating a 64 bit and 32 bit executable of my game.

How could I achieve so that the executable and dlls lie in a separate folder without changing all the path variables in the game?

To clarify I want to have a folder structure like this:

* Game
    + Bin
    - exe
        - dll, so, etc.
    + Data
        - textures and everything else.

My current is:

* Game
    + exes
    + dlls
    + data

So my path variables use something like: `./data/ ....`

How could I move my exes so they would find all dlls and data, so I wouldn't need to replicate the data folder for each version and have them nicely separated?

I am mainly looking for answers for Windows, but I am also interested in Unix solutions.

# Answer
> 3 votes
On Windows, you can shove everything under an architecture directory:

```
YourGame/
  x86/
    game.exe
    lib.dll
    data/
  x64/
    game.exe
    lib.dll
    data/

```

You need 64-bit DLLs to go with the 64-bit .executable, you can't load 32-bit ones into a 64-bit process. The Windows DLL search order will check the .exe directory.

This does mean duplicating your data though; if this isn't otherwise necessary (it may be if you're baking in pointers that are fixed up on load, for example), it's wasteful. You could solve this by creating hardlinks from one of the architecture data folders to the other, though.

Or you can move the data directory down:

```
YourGame/
  x86/
    game.exe
    lib.dll
  x64/
    game.exe
    lib.dll
  data/

```

...and then use "../data" for your data paths, relative to the application location, or stick launch shims (shortcuts, aliases, batch files, whatever) in the root of `YourGame` that do `x64/game.exe -data-path data`, to specify the data path on the command line).

You could also leverage the fact that, for native languages at least, you always know what architecture you're compiling for when you compile and it's generally a distinct project configuration. This means you can rename everything, and embed those names as appropriate:

```
YourGame/
  game32.exe
  game64.exe
  lib32.dll
  lib64.dll
  data/

```

You'd just need to change the names of the import libraries you link against for each architecture variant. This would also work for the data folder if you did need 32 and 64 bit copies, just fix up the subdirectory based on the compile-time architecture constant.

Linux and Unix environments use fairly different conventions for shared library search (see here for an example). You can adapt the above for those conventions, or use OS level functions to manually load shared libraries from the locations you store them in.

In short, there's no single solution that will work ideally on all platforms out of the box; the way to achieve "cross platform" functionality here is to either do it differently per platform in accordance with that platforms guidelines or use the platform's OS APIs to try to force it into adopting the convention of the *other* platforms.

# Answer
> 1 votes
The final solution I chose is very simple, and avoids any changes to existing code / path files:

In the main function, first make a call to `chdir("../")`

This will make static DLL loading work from the `x32/` or `x64/` folder, while all runtime data can be loaded as if the executable was in the main folder.

Such a method is even necessary if you have a DLL you can't recompile that has the same name on multiple architectures(Instead of `libfoox32.dll` just `libfoo.dll`)

---
Tags: cross-platform, filesystem
---


title: 2d grid for 3D game

text:
# Question
Title: 2d grid for 3D game
I have a 3D game dungeon crawler game. It's procedurally generated. I have a bunch of prefab rooms that are used to put together this dungeon. When not in combat the player uses a navmesh to move around and that works great. When in combat we switch to a turn based grid based system where we use A\* for moving in this grid.

In each room prefab I add some markers to help identify things. For example I add a start and end position marker which defines the center of the corner tiles mathematically for a grid. So each room can have its own little grid where battles are played out.

The orientation of the room, and hence the grid inside it, can be anything around the y axis which is up/down.

My A\* path finding library needs to know row/col when asking for a path. I can get the position based on the mouse picking and need to convert that to file position if done inside the grid. Because the orientation of a room can be rotated what a row/col is changes from what I may have had in mind when I placed the start and end grid positions in the prefab.

I'm wondering how can I make getting this row/col based on mouse pick position unified no matter what position or rotation the room is.

# Answer
So from what I understand (this game has one of those concepts that takes lots of word to describe until you see i picture and understand immediately) the player is in charge of changing the rotation of prefab rooms, or at least some system that you've built...

What i'd suggest is that you keep updating and change the data that you use for navigation as the data changes, this way no matter how much the rooms shuffle around the navmesh should always be up to date.

If thats not possible can you use another thread on the CPU to regenerate a new navmesh path and then swap it out for the old one every few seconds (turns, minutes, depending on how it changes)? I'm guessing that there is a way to figure out the cost between nodes so it should be possible to to keep going though every node to check what the cost is to it's new/old neighbors, If you keep this on the other thread and tell A\* to only use the latest one you can even recycle the memory of old one, once you're sure that no one is using it, by using that for the new mesh while it is being generated.

Comment if this simply wouldn't work with your game and describe why? :)
> -1 votes

---
Tags: 3d, path-finding
---


# Question
Title: Rotate bone on 1 axis to look at another object - Unity 3D
I'm new to game development and I'm trying to create a basic 3D Tower Defence game as my first project. I've created a basic turret in Blender and I'm now trying to rotate 2 different bones to make the turret follow the enemy. The first bone (which I have working) rotates the turret to face the direction of the enemy. The second which I can't get right needs to rotate the gun at the top of the turret to look down at the enemy. I need it to keep facing the same direction as the rest of the turret and don't want it to tilt to either side. So it needs to move on 1 axis only.

I have tried various things, including examples from the Internet but I can't figure it out. So far I've managed to get it to look down at its base, up at the sky and spin like a wheel. Basically everything except where it's supposed to be looking.

Here is the code I have at the moment:

```
if (enemiesInRange.Count > 0)
    {
        //Rotate Platform //#### This section works fine
        Transform platform = transform.root.Find("Armature/BaseBone/PlatformBone");

        Quaternion targetRotation; //Final rotation (I.e. facing the enemy)

        Vector3 turretPosition = platform.position; //Store the turrets current position
        turretPosition.y = 0; //0 the Y axis to stop the turret tilting up or down

        Vector3 targetPosition = enemyManager.activeEnemies[enemiesInRange[0]].transform.position;

        targetRotation = Quaternion.LookRotation(targetPosition - turretPosition);

        float rotateSpeed = 2.0f * Time.deltaTime;
        platform.transform.rotation = Quaternion.Lerp(platform.transform.rotation, targetRotation, rotateSpeed);

        //Rotate GunBox //####TO DO: This part is not working
        Transform gunBox = transform.root.FindChild("Armature/BaseBone/PlatformBone/LowerArmBone/UpperArmBone/GunBoxBone");
        Vector3 gunBoxPosition = gunBox.position;

        float angle = Vector3.Angle(gunBoxPosition, targetPosition);

        gunBox.RotateAround(gunBox.position, Vector3.left, angle);

        Debug.Log(angle);

    }

```

Here's a picture of the turret to give you an idea what I'm working with. You can see in the screenshot that the bone's default X rotation is roughly -50.

Enemies walk through the trench around the turret. The PlatformBone rotates everything from the silver platform upwards.

I also don't understand why the line below makes the turret rotate instead of tilting it. I would expect to rotate the turret around the Y axis to keep it flat on the floor and face another direction. Yet I seem to have to do the opposite (If I select the PlatformBone its Y axis is facing up as expected):

```
turretPosition.y = 0; //0 the Y axis to stop the turret tilting up or down

```

# Answer
To make an object face another object in Unity you can simply use

https://docs.unity3d.com/ScriptReference/Transform.LookAt.html

> **public void LookAt(Vector3 worldPosition, Vector3 worldUp = Vector3.up);**
>
> Rotates the transform so the forward vector points at worldPosition.

The interesting thing here is that if you have 2 objects (let's say A to rotate and B to look at) which have the same position.y, and you call A's transform.LookAt(B's position), A will be rotated to face B with rotation.y unchanged.

With that logic we can write a function that will rotate our object having the same rotation.y as before, it would look like:

```
public void LookAtXZ (Transform rotatingPart, Vector3 target )
{
    var origin = rotatingPart.position; // get origin point of rotation
    var targetXZ = new Vector3(target.x, origin.y, target.z); // "neutralize" target's position so that it has the same y as origin
    rotatingPart.LookAt(targetXZ);

}

```

Analogically we can write function that rotates only on X, Y or Z axis without difficulty.

```
public void LookAtY (Transform rotatingPart, Vector3 target )
{
    var origin = rotatingPart.position;
    var targetY = new Vector3(origin.x, target.y, origin.z);
    rotatingPart.LookAt(targetY);
}

```

Besides, transform.Find is not really a good way to get transform of an object, especially when you must do it every frame. Just create a public field in your class, attach the transform of part that needs to be rotated in Inspector and refer to it by reference in code, it would be way more performance-wise.

Your code would be like:

```
List<Transform> enemies;
Transform platform;
Transform gunBox;

void UpdateRotation ()
{
    foreach( var e in enemies )
    {
        var target = e.position;
        // For the sake of simplicity i'm going to take the use of 2 function above
        LookAtXZ(platform, target );
        LookAtY(gunBox, target );
    }
}

```

Hope this helps :)

p.s: how to make turret prefab with references to its parts

After setting up, save the object as a prefab and next time when you instantiate your turret from prefab, it will already have the references to platform and gunStation
> 0 votes

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


title: Better Way to Detect Line Cross

text:
# Question
Title: Better Way to Detect Line Cross
I am developing a very simple game in libGDX for android devices. Simply, the game is a character who runs and jumps over obstacles, every time the character jumps over one of said obstacles, a counter increments and the score is displayed.

I am currently detecting the character jumping over the obstacles by creating two Rectangle objects (invisible) - one small one for the center of the character and the second is a long thin line from the center of the obstacle. I use the 'overlaps()' command to check whether or not the character has passed said line.

This issue I am having is that because I am calling to check on the overlap in my update method, it is called many times in a second and hence sometimes adds two points to the score as the small rectangles are still overlapping on the second round of checking.

I have got the sizes down to a near perfect size with the occurrence of incorrect scores at a minimum, however they do still happen.

**So my question is what would a better way be to detect a line crossing / collision?**

# Answer
To me, your basic idea of checking overlapping rectangle is workable; you only miss a small part:

For each of your obstacles, have a two-state flag:

* untouched
* overlapping

When you create the obstacle, have the flag set to 'untouched'. When the player jumps over it, detect if there is an overlap between the two rectangles. If there is, first, check if the state of the flag is 'untouched' if it is, set the flag to 'overlapping' and increment the score counter. That's all :)

Pseudocode:

```
if ( this.jumpFlag == 'untouched' && character.jumpRect.overlaps(this.jumpOverRect) )
{
  game.scoreCount += 1
  this.jumpFlag = overlapping
}

```
> 3 votes

# Answer
I would suggest that you keep track of the position of the obstacle until you have passed it and added a point. I would also suggest against trying to make a perfect size object for a collision, this is because frame rate can vary a lot so for you it might be perfect but for somebody with higher frame rate it can still cause unwanted behaviour.

If you still want to do it with collision however I would suggest keeping track of the upcoming obstacle and checking whenever you have received a point from it already. This way you won't get multiple point for one obstacle because of multiple collision detections.

Hope my answer helped you a bit.
> 4 votes

# Answer
Your "long thin line" object is basically a funny shaped coin. Make the "long thin line" object wider (to avoid missing it), and simply delete it after it's collected rather than needing it to be as small as possible.
> 1 votes

---
Tags: android, collision-detection, libgdx, android-studio
---


title: Nested Coroutine Movement is slugish

text:
# Question
Title: Nested Coroutine Movement is slugish
So I have a few AIs walking between waypoints. What I want to accomplish here is to have my AI move to the waypoint, when he reaches it, he must stop, wait for a few seconds (Not walk just stand still), then move to the new waypoint. Lets pretend he was observing while at this point.

Issue right now - He moves to the waypoint with a twitchy behavior where he would usually avoid objects, sometimes gets stuck while moving to objects or its like the AI cant decide what to do, move or stand still. Without the Waitforseconds method the AI avoids objects perfectly.

Please note I want to use Coroutines for this even if you wouldn't use / recommend it for this. If you have a suggestion for using Unity's Random to decide when he stands still after reaching a point or not, that would be a bonus for me.

We define all fields and call the FSM() Coroutine with a default patrol state in the Start Method, from Here, This is my Code:

**Update** \- Implemented A Boolean IsMoving variable - This works to some extent. The AI now moves perfectly to the waypoint. The Twitching however continues once the AI reaches the waypoint vicinity until he leaves the waypoint radius - The movement then continues to a normal state.

```
IEnumerator FSM()
{
        while (alive)
        {
            switch (state)
            {
            case State.PATROL:
                StartCoroutine(Patrol());
                break;
            case State.CHASE:
                Chase ();
                break;
            default:
                break;
            }
            yield return null;
        }
    }

    /// <summary>
    /// Patrol will move to a waypoint if too far, otherwise move to a next waypoint if one is reached.
    /// </summary>
    IEnumerator Patrol()
    {

            //Sets a common speed for the agent to move in.
            agent.speed = patrolSpeed;

            //Now we want to check the position the character is at vs the waypoint location - If i am too far, move closer
            //                        My Position           Waypoint Indexes - We Set Multiple
            if (Vector3.Distance (this.transform.position, waypoints [wayPointIndex].transform.position) >= 2)
            {
                //Telling the navmesh agent where to go.
                agent.SetDestination (waypoints [wayPointIndex].transform.position);

                //                                  false, false - Specifies if we are jumping or crouching
                character.Move (agent.desiredVelocity, false, false);

            }
            //Now we want to check the position the character is at vs the waypoint location - If i am at a waypoint, move to a new index
            else if (Vector3.Distance (this.transform.position, waypoints [wayPointIndex].transform.position) <= 2)
            {
                character.Move (Vector3.zero, false, false);
                yield return new WaitForSecondsRealtime (6.0f);

                wayPointIndex += 1; //Move towards a new waypoint in the waypoint indexes flags

                //Move to a random waypoint
                wayPointIndex = UnityEngine.Random.Range (0, waypoints.Length);

            }
            else
            {
                //Doesn't move, plays the idle movement - We know this point wont be reached but if so...
                character.Move (Vector3.zero, false, false);
                yield return null;
            }
        }

```

# Answer
From what I seen in the code, there is a little problem: You are calling the patrol coroutine every frame, without considering if the previous call was completed. This have several side effecs/bugs/problems:

* Each cycle you are telling the character to calculate his path to its objective
* If the agent reaches the waypoint, the patrol coroutine waits for 6 seconds... but the FSM coroutine is still running, so it will make another decision.. which will probably be starting another Patrol coroutine and wait for 6 seconds, again.
* Once 6 seconds are passed, the Patrol coroutine will continue executing, which is good... but in the very next cycle, the other patrol coroutine that was called 6 seconds ago will finish waiting for 6 seconds.. and will decide another waypoint, again, and again. It will be making the same random decision, with a different result, once for each cycle that passed since the Patrol coroutine execution first waited for 6 seconds.

I guess this would make the agent move like twitching and erratically.

You could add a bool to your class that would indicate if the FSM should be executed next cycle.

```
IEnumerator FSM()
{
    while (alive)
    {
        if(runFSM){
            switch (state)
            {
            case State.PATROL:
                runFSM = false;
                StartCoroutine(Patrol());
                break;
            case State.CHASE:
                Chase ();
                break;
            default:
                break;
            }
        }
        yield return null;
    }
}

/// <summary>
/// Patrol will move to a waypoint if too far, otherwise move to a next waypoint if one is reached.
/// </summary>
IEnumerator Patrol()
{

    //Sets a common speed for the agent to move in.
    agent.speed = patrolSpeed;

    //Now we want to check the position the character is at vs the waypoint location - If i am too far, move closer
    //                        My Position           Waypoint Indexes - We Set Multiple
    if (Vector3.Distance (this.transform.position, waypoints [wayPointIndex].transform.position) >= 2)
    {
        //Telling the navmesh agent where to go.
        agent.SetDestination (waypoints [wayPointIndex].transform.position);

        //                                  false, false - Specifies if we are jumping or crouching
        character.Move (agent.desiredVelocity, false, false);

    }
    //Now we want to check the position the character is at vs the waypoint location - If i am at a waypoint, move to a new index
    else if (Vector3.Distance (this.transform.position, waypoints [wayPointIndex].transform.position) <= 2)
    {
        //THIS IS WHERE I NEED HELP - I try to stop the AI here to wait for a few seconds before moving to the new waypoint.
        character.Move (Vector3.zero, false, false);
        yield return new WaitForSecondsRealtime (6.0f);

        wayPointIndex += 1; //Move towards a new waypoint in the waypoint indexes flags

        //Move to a random waypoint
        wayPointIndex = UnityEngine.Random.Range (0, waypoints.Length);

    }
    else
    {
        //Doesnt move, plays the idle movement - We know this point wont be reached but if so...
        character.Move (Vector3.zero, false, false);
        yield return null;
    }
    runFSM = true;
}

```

Make sure to set `runFSM=true` in the `Awake()` callback
> 1 votes

# Answer
The proper way to do a nested coroutine is

```
IEnumerator MainCoroutine ()
{
    yield return StartCoroutine(NestedCoroutine01());
    yield return StartCoroutine(NestedCoroutine02());
}

```

With this set-up the NestedCoroutine02 will wait until NestedCoroutine01 is finished.

With that being said, the FSM function should look like below to make sense:

```
IEnumerator FSM()
{
    while (alive)
    {
        switch (state)
        {
        case State.PATROL:
            yield return StartCoroutine(Patrol());
            break;
        case State.CHASE:
            yield return StartCoroutine(Chase());
            break;
        default:
            // if state is not PATROL or CHASE, we do nothing but wait
            // for a small amount of time before continuing,
            // in most cases FSM for AI doesnt need to be updated every frame

            yield return new WaitForSeconds(0.5f);
            break;
        }
    }
}

```

The whole process is held until the selected action is done, the rest of code can remain unchanged.

Besides, I noticed in your code that **yield return null** is used at the end of function or block that doesn't make much sense.

In the FSM function, if the reason is that in coroutine at least one yield instruction must be present than you can safely place a **yield break** at the end of function, ie:

```
IEnumerator FSM()
{
    while (alive)
    {
        switch (state)
        {
        case State.PATROL:
            yield return StartCoroutine(Patrol());
            break;
        case State.CHASE:
            yield return StartCoroutine(Chase());
            break;
        default:
            // if state is not PATROL or CHASE, we do nothing but wait
            // for a small amount of time before continuing,
            // in most cases FSM for AI doesnt need to be updated every frame

            yield return new WaitForSeconds(0.5f);
            break;
        }
    }
    yield break;
}

```

Of couse in my code there are already other yield instructions in the function so it actually doesnt need **yield break** at the end, I added for the sake of demonstration. By placing **yield break** at the end of function, your code's functionallity stays unchanged and problem's gone.
> 0 votes

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


# Question
Title: How to balance spawn system with multiple objects?
I'm trying to make a top-down endless runner.

I have divided my screen into 3 columns. Right now I have some objects spawned from the bottom of the screen that go up towards the top. I have 3 different types and each of them has a random speed between 4 and 8 and can be spawned at intervals that vary from 0.2f to 2f.

I've noticed though that it may happen that these objects are spawned in a way that it is impossible for the player to dodge them (all the 3 columns are occupied by these obstacles on the same line).

Is there a way to check if this scenario is going to happen in the next wave and to, for instance, destroy one obstacle out of those. How could this be done?

# Answer
**Precaution**

What i'm going to write here is **not** a solution to your problem, in my solution, the movement speed of obstacles is **constant**. Consider it to be a simplified case of your. I just want to show you a possible way to solve this kind of problem.

---

First you need to define the distance (the space) between 2 obstacle of 2 different columns that will allow the player to dodge. Let's say:

```
float safeDistance = 10f;

```

Next you create an array/list that holds references to the last object spawned on each column, like:

```
Transform[] lastObstacles = new Transform[3];

```

Make an event that's fired anytime an obstacle is spawned, update the list

```
void OnObstacleSpawned (Transform obstacle, int onColumn )
{
    lastObstacles [onColumn] = obstacle;
}

```

Assuming that the obstacles move along the vertical axis OY, the distance from the spawn point to the closest obstacle on given column can be easily calculated by

```
float DistanceSpawnPointToLastObstacle(int column)
{
    if( lastObstacles[column] == null ) return float.MaxValue;
    return Mathf.Abs(lastObstacles[column].position.y - spawnPoint.position.y);
}

```

or between two obstacles

```
float DistanceBetweenObstacles(int column01, int columnt02)
{
    if( lastObstacles[column01] == null ) return float.MaxValue;
    if( lastObstacles[columnt02] == null ) return float.MaxValue;
    return Mathf.Abs(lastObstacles[column01].position.y  - lastObstacles[columnt02].position.y);
}

```

And now make a condition check function that gives the answer that you want to know ;)

```
bool ShouldISpawnObstalce(int onColumn)
{
    switch (onColumn)
    {
        case (0):
            // there is already space to dodge
            if (DistanceBetweenObstacles(1, 2) > safeDistance) return true;
            // if not then check if there would be enough space between obstacles on column 0 and on column 1
            if (DistanceSpawnPointToLastObstacle(1) > safeDistance) return true;
            break;
        case (1):
            if (DistanceSpawnPointToLastObstacle(0) > safeDistance) return true;
            if (DistanceSpawnPointToLastObstacle(2) > safeDistance) return true;
            break;
        case (2):
            if (DistanceBetweenObstacles(0, 1) > safeDistance) return true;
            if (DistanceSpawnPointToLastObstacle(1) > safeDistance) return true;
            break;

    }
    return false;
}

```

Hope this somehow helps.

Edit 01: The whole code block:

```
// assign in Inspector, spawn points for column 0-1-2
public Transform[] spawnPoints;

public Transform[] obstacles;

private Transform[] lastObstacles = new Transform[3];
private float safeDistance = 10f;

public void SpawnObstacle()
{
    int randomColumn = RandomFunction();

    if(ShouldISpawnObstalce(randomColumn))
    {
        int randomObstacleType = RandomFuntion02();
        var obstacleToSpawn = obstacles[randomObstacleType];
        var spawnedObject = Instantiate(obstacleToSpawn);

        // do set-up/ initialization for obstacle here
        spawnedObject.position = spawnPoints[randomColumn].position;

        //
        OnObstacleSpawned(spawnedObject, randomColumn); // you can make an event here for further use
    }
}

void OnObstacleSpawned(Transform obstacle, int onColumn)
{
    lastObstacles[onColumn] = obstacle;
}

float DistanceSpawnPointToLastObstacle(int column)
{
    if (lastObstacles[column] == null) return float.MaxValue;
    return Mathf.Abs(lastObstacles[column].position.y - spawnPoints[column].position.y);
}

float DistanceBetweenObstacles(int column01, int columnt02)
{
    if (lastObstacles[column01] == null) return float.MaxValue;
    if (lastObstacles[columnt02] == null) return float.MaxValue;
    return Mathf.Abs(lastObstacles[column01].position.y - lastObstacles[columnt02].position.y);
}

bool ShouldISpawnObstalce(int onColumn)
{
    switch (onColumn)
    {
        case (0):
            // there is already space to dodge
            if (DistanceBetweenObstacles(1, 2) > safeDistance) return true;
            // if not then check if there would be enough space between obstacles on column 0 and on column 1
            if (DistanceSpawnPointToLastObstacle(1) > safeDistance) return true;
            break;
        case (1):
            if (DistanceSpawnPointToLastObstacle(0) > safeDistance) return true;
            if (DistanceSpawnPointToLastObstacle(2) > safeDistance) return true;
            break;
        case (2):
            if (DistanceBetweenObstacles(0, 1) > safeDistance) return true;
            if (DistanceSpawnPointToLastObstacle(1) > safeDistance) return true;
            break;

    }
    return false;
}

```

RandomFunction of course should return a valid value, like an int from 0 to 3 (exclusive) in case of random column number or an int from 0 to obstacleToSpawn.Length (exclusive) in case of random obstacle choice. Its implementation is all up to you
And dont forget to assign the needed references in inspector.
> 0 votes

# Answer
At any given moment, you know each obstacle's position and speed and so you can calculate the start and end times of when that obstacle would collide with the player if the player happens to be in the column.

Whenever an obstacle spawns, check all obstacles in the other two columns to see if their start time and end time overlaps the new obstacle's start and end time. If both of the other lanes have at least one obstacle with overlapping start and end times then do not use the new obstacle.
> 2 votes

---
Tags: random, balance
---


# Question
Title: How is structural analysis done in games (e.g.: bridge building, Dig or Die, and 3D)?
From what I understand a typical interactive truss system would need substantial calculations since every component affects the entire system. I think you could arbitrarily stop at a given number of iterations at cost of accuracy in the simulation, but I don't know if that's the approach these games use (bridge building games are an example of truss systems). On the other hand, games like Dig or Die have a quite complex structural system that also takes torque into account (I believe) and compression and is very fast and works on very extensive systems. I guess the basic calculations could be similar, but if not I'm interested in both approaches.

Do you guys know how these are made? Do they have an arbitrary limitation or do they use a different algorithm altogether? Also, I guess whatever you guys come up with can be applied to 3D systems but if not or if it's not obvious please at least give a clue on how you could use it for 3D since I'm interested in this for both 2D and 3D games.

I know I'm not supposed to thanks here but I find unfair not to at least thank you for your time in advance, I hope this paragraph don't get removed.

EDIT: If I were to make a guess I'd say Dig or Die stores vectors for each block and then run an iterative algorithm up to a point that the extra accuracy in the simulation is meaningless for the limits of the system (for example, the system would be too large to not collapse anyway), so it's limited by a semi-arbitrary (because it's based on application) number of iterations. But I could be wrong.

# Answer
> 5 votes
I am the dev of Dig or Die, so I can give a little more details about the game physics

Indeed the most crucial point was the performances, as in the game you can build thousands of physical blocks, and much important I have other things more complex to simulate (rain/water) so I can spare very very few CPU time for the building physics.

So I actually did a sort of... I don't know, a custom personal algorithm not very accurate, but it works fine enough for the game. I've 1 vector for each block intersection (so each block is linked by up to 4 vector, one on each side of it). Each block has a "weight", and "pushes" the vectors around it (equally) so the total of the vectors magnitude is equal to its height. When a block is anchored to the ground, all the forces/weight that are pushed into it are never "pushed back", so naturally with enough iterations the whole system find a balance. The weight/force will sort of "flow" to the anchoring points, and manage very well changes on the structure. You can see the result here (with the ingame "Eiffel Glasses" item):

About torques, I simulate it by multiplying the forces that are transmitted horizontally. It's not perfect but it's enough to feel the big difference between building horizontally and vertically

But honestly I don't like that much my system, for some cases it's not very accurate ; mostly because I don't manage the compression and extension. There is probably a way to do a more accurate simulation than mine without more CPU, but my skills (and time) about it were very limited so I did what I could :-)

(PS: you guesses were very good :-) )

# Answer
> 4 votes
I've personally had good success with Iterative Relaxation. I think it follows the laws of physics quite nicely when dealing with objects made of aggregates of blocs. I believe the BridgeBuilder series is based on such a method, though I have no source to confirm this.

Iterative Relaxation is widely used for trusses, but I've successfully simulated large solid objects (concrete) with it: it's quite simply a truss, whose joints carry load instead of being free-turning.

---

What is interesting, is that relaxation is a technique for resolving static trusses, so it is accurate. In that regard, it is used to iteratively compute a displacement that brings a structure to equilibrium.

But the added value for a *game* (where we're interested in dynamic environments, because static, at-equilibrium structures are boring) is that we get the chance to *actually displace* the structure's joints between each iteration, based on the constraints computed so far. You get two major benefits:

* You have a dynamic structure, which responds correctly to any exterior perturbations
* You have a structure which responds accurately to loosing supporting members (think rapid unplanned disassembly) by shifting its strain around to other members. It's actually quite enjoyable watching stress flow being moved as joints get broken in a chain event
* You have a non-linear simulation! Further explanation of what I mean:
*Usually*, static analysis makes the hypothesis of small deformation, where the structure does not move far off its initial state. Within these bounds, the static analysis is correct because the joints aren't *actually displaced* much. But as the structure deforms under crumbling weight, you'll get accurate results all the way the the end with a non-linear simulation, whereas you'll simply get a invalid state from a linear solver

Iterative relaxation is quite simple to put in place, Numerical Stability. I've used RK4 scheme tsuccessfully to achieve stability with large conrete structures. The drawback is it usually has quite small stiffness for performance reason, so may feels quite like soft jelly at times.

---
Tags: physics, algorithm, voxels, simulations
---


# Question
Title: What is the best method to share the projection matrix and view matrix with all graphic entity shaders in a custom game engine?
What is the best method to share the projection matrix and view matrix with all graphic entity shaders in a custom game engine? The refer graphic entities have `glUseProgram({shader_program_id}); glDrawArrays(GL_XXXX, x);`

One of my ideas is to have a camera object that manages the current view and projection matrix. Then, I pass a reference of that camera object to all the entities. However, my issue with that approach is syncing the current camera across all the entities/objects when switching views.

I could make the Camera global, however, that could have many issues.

# Answer
> 6 votes
In this answer I am assuming that you have a standard 3-matrix setup: projection, view and model. For your static objects the model matrix will be identity; for moving objects it will not. In your shaders you have something like:

```
out = projection * view * model * in;

```

Therefore projection and view don't change, model does, and hence your question.

This is actually an inefficient way of doing it. Instead you should premultiply the 3 matrices on the CPU and upload a single combined MVP matrix to the GPU.

So, in your C or C++ code:

```
MVP = projection * view * model;
glUniformMatrix4fv (..., MVP, ...);

```

And in your GLSL:

```
out = MVP * in;

```

This solves your initial problem in that you now no longer need to upload global projection or view matrices; since you're uploading a new model matrix per-object *anyway* you have no change there aside from the fact that it's now a combined MVP rather than an isolated model matrix.

This also solves your performance problem because you're now calculating the combined MVP once per-object only, rather than once per-vertex.

# Answer
> 1 votes
Did i get that right that you have the actual render method specified in the code for each different graphic entity? That is super inefficient, code-wise. Make a renderer-class and put all your shaders and draw-methods into there. Have a main render method that calls all the other render-methods specific to shaders or types of entities. Then you just have to pass your view matrix and projection matrix to that renderer object once and you can use it for each drawable.

In my engine, i store the projection matrix in that renderer class (it never changes though) and pass my camera to the renderer in each call of the render-method.

# Answer
> 1 votes
I'm working in DX11 so idk how this will work for you.

I have one constant buffer that is common over all of my standard shaders, it has view, projection, far clip and camera position.

I update this one constant buffer at the start of the frame and have it set to slot 0 for all my drawing and then just set it once, so its update CB-\>set CB-\> draw everything that uses the same buffer.

I hope I'm close to what u wanted to know?

# Answer
> 0 votes
In my "engine" I have a Scene class which contains all entities and cameras available. I also have a material component which is attached to the entity. At the rendering phase I call the entities material component from the Scene and passing the camera(s) to it.

---
Tags: opengl, shaders, architecture
---


title: Game data structure in node.js

text:
# Question
Title: Game data structure in node.js
I am building a simple turn-based game in node.js using sockets.io. My web experience with node.js has typically involved saving everything to a relational database. I set this up for my game. I am using sqlite3 for development and I might use something like PostgreSQL or MySQL for production. I will be doing this for account information regardless of what I set up for handling the actual game.

My concern is that, every time an event is emitted from the socket the whole game-state is loaded into memory from the server. I feel that in practice this will be less efficient than just keeping all of the gamestate data in memory. Events will probably be emitted every 5 seconds or so. A gamestate consists of a set of about 120 groups of small strings and integers (about 10 per group but subject to change).

Is it good practice to keep this type of data in memory?

Should I stick with relational databases?

Should I switch to a third option like a file-based storage structure?

Should I not load the whole gamestate in for every event even though that will lead to a lot more read/writes (at least triple)?

Edit\* Clarification: Even though the game is turn based I want the player to be able to see what the opponent is doing on their turn in real time and give the player real time feedback about illegal actions.

# Answer
The exact answer depend on your exact use case so I'll try to stay general.

Basicaly, memory is cheap and fast. If you can afford to keep X games states in memory at once, then go away with that. The only thing you have to take care of is to store only one version of each game so that the state stay in sync between players. Also don't forget to store that state somewhere else where you can load it (in case of a crash)

Database are made for consistency and performance. They arn't as cheap and as fast as diret memory access, but their job is to store data across mltiple clients and they are better at that than anything you can come up with. If you need to make sure the game state as to stay 100% consistent no matter what, even in case of a crash, even with multiple node instance, then go with a database.

The best approach for performance is an hybrid of the two: use memory for rapid access, save to database on each change, and load from database when there is nothing in memory. It adds a lot of complexity I don't really recommend it neither (like: when to load games? how to resolve conflics when two players commands are executed at the same time? when to clear old party data).

I think the best way for you is to go with the safest and fastest route: use a database handle all that complexity and focus on making your game playable and fun.

As a side note, maybe give a try to a noSQL database. They can be faster than relationnal database. And you can store your gameplay objects (or concepts) directly as documents.
> 1 votes

---
Tags: databases, memory-efficiency, node.js, websocket, sql
---


title: 2D "digging" method in unity

text:
# Question
Title: 2D "digging" method in unity
I am in the process of developing a 2D digging game for mobile. I need an efficient method to dig tunnels through the levels (Similar to the game play in Death Worm), and build colliders around the tunnels.

How would I go about it?

# Answer
You should look into isosurfaces (mainly marching squares)

The idea is very simple, you have points in a 2d space, each of them has a value between 0 and 1 attached to them.

Whenever the terrain changes you need to run the points through the marching squares algorithm and that gives you a mesh around the contour of the points with a value higher than a certain threshold.

If you want to dig a hole in the mesh, then you can get every point in a certain radius from the center of the bew hole and decrease their value so it will be under the thresholdof the algorithm.
> 1 votes

---
Tags: unity, mobile, terrain-rendering
---


# Question
Title: Should a wall be created as a plane or as a box?
What are the benefits of a wall being as a plane or as a box? Should I use a plane with a box collider instead of mesh collider?

# Answer
There's going to be a couple different things that you'll need to consider.

**Note:** that the benefits from the optimizations described below only really matter with a ton of walls. At that point, it might be wise to consider a different solution like binary space partitioning (BSP) for making your walls in your game. This would make your levels highly optimized for rendering (if designed correctly) and for physics (as you have a very good definition of what collides and what doesn't.

### Rendering

A box is going to take more to render than a plane. It has more vertices and triangles meaning your vertex shader and the rasterizer are going to have to be run over more data. Therefore, only use a box when you need to in terms of visibility. Remove faces as needed for what the player will need to see.

### Physics

You should always use a `BoxCollider` as opposed to a `MeshCollider` when you can. `MeshCollider`s have to apply collisions per face (or as a convex hull) of the mesh and make raycasting and physics slower (but it's a negligible amount for just one box). Another thing with `BoxColliders` is that it's much harder for the player to phase through them when they are going really fast. Even with continuous collisions, if you find yourself still having things phase through walls, you can always just expand the `BoxColliders`

### Productivity

If you're much faster working with planes with `MeshColliders` (because you don't need to adjust all the `BoxColliders` to match their dimensions) it may be fine to just use those if you get the performance you desire.
> 15 votes

# Answer
Expanding a bit on "Coburn"'s points:

**Rendering**: If you render the wall as only a plane, then the wall will only be visible from one side, as the plane (or more exactly its faces) only has one rendered side. So if the player is able to move around the wall, you would need multiple planes to cover all the sides, which means you end up with a box anyway.

**Physics**: Simple geometry colliders (spheres, boxes, etc.) are always faster to compute compared to full mesh colliders since not all faces of the mesh have to be checked individually. Instead "simple" raycasts can be used or distance calculations (e. g. distance to center of sphere minus sphere size).

For other physics engines that have a separate "plane collider" (which Unity doesn't), there is no "better" one. A plane might be slightly faster performance-wise, but you might then run into the issue of fast objects passing through it without actually colliding. Then you are left with either having thicker colliders (so box instead of plane) or move to Continous Collission Detection (CCD), as explained here.
> 11 votes

# Answer
One more thing about Rendering: When you have your own shadow-mapping implementation, walls made out of boxes can be superior to walls made out of planes due to peter-panning that can appear with planes.

Here's an explanation of the symptom:

http://www.opengl-tutorial.org/intermediate-tutorials/tutorial-16-shadow-mapping/#peter-panning
> 4 votes

# Answer
I was always told that if u are going to have shadows that its best to make it solid to help with light bleeding because the difference in depth is to small and it will bleed.

I could be wrong, but I make all of my walls and stuff like that two sided, a wall will only be a few verts so it shouldn't be that much of a saving by having it a plane.

There are some things that I leave sides of but its mostly the bottom or top of stuff that has lots of stuff around it to help with light bleeding.

I do the same for physics, didn't every really think about it but to me it seemed right to use a wall as a wall and a plane as a plane but that is just me
> 1 votes

---
Tags: unity, meshcollider
---


title: Play/Stop All Animations in a Project

text:
# Question
Title: Play/Stop All Animations in a Project
I see that there's a way to get each animation clip like the following, but is there a way to get all of the animations in a given project and play/stop them at the same time?

```
public class Anim: MonoBehaviour {

protected Animation anim;

// Use this for initialization
void Start () {

    anim = GetComponent<Animation>();

}

void PlayAnimation
{
    if ()//some sort of condition
    {
        anim.Play ("Roll Dice");
    }
    else {
        anim.Stop();
    }
}

```

# Answer
What you are looking for is :
https://docs.unity3d.com/ScriptReference/Object.FindObjectsOfType.html

> public static Object\[\] FindObjectsOfType(Type type);
>
> Returns a list of all active loaded objects of Type type. It will return no assets (meshes, textures, prefabs, ...) or inactive objects.

or its generic version (more prefered)

> public static T\[\] FindObjectsOfType();

And to get all the objects of type Animation and stop the running animations you will do:

```
void StopAllAnimation()
{
    var allAnims = FindObjectsOfType<Animation>();
    foreach( var anim in allAnims )
    {
        anim.Stop();
    }
}

```

p.s: this function will return list of all objects of given type that are present in current scene, no matter where you call the function or which game object the animation object belongs to
> 1 votes

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


title: Snapping shapes together in game

text:
# Question
Title: Snapping shapes together in game
I'm trying to work out how to snap shapes together the player may move around on a canvas.

As the square approaches the other object, I want to pull that shape in (given a certain proximity) and have it snap perfectly along that objects edge.

Rules:

* Only if the edges are parallel to one another
* If a child square (being dragged) is half the size of the parent square (being approached), then the midpoint of the parent square edge can determine if the child snaps either to the left/right/up/down

Has anyone done anything like this? I'm using c# and unity. Cheers.

# Answer
I've written a prototype of something like this. I created some resources that looked like this:

So basically this "ShipPart" object has pre-defined snap points. These four colliders will help with determining if you are attempting to snap an object into place or not.

Next I created a ShipPart class, that contains some things such as:

```
//Neighbor information
ShipPart Left, Right, Top, Bottom;

//current rotation
float Rotation;

//The ship core it is attached to
Ship Ship;

//The coordinates in references to the ship core
int X ;
int Y ;

```

It also contains functions and properties to help with the drag and drop, and checking the state of the neighboring ShipParts.

An important function is the Attach() function, which will connect this ShipPart to your Ship.

```
public void Attach(Ship ship, int x, int y)
{
    GetComponent<Rigidbody2D> ().isKinematic = true;

    Ship = ship;

    X = x;
    Y = y;

    transform.parent = Ship.transform;
    transform.position = Vector2.zero;
    transform.localPosition = new Vector2(x, -y);
}

```

Then finally, the Ship class, keeps track of your Core piece, all of the attached parts, all of the ships data is managed here. You can raycast for ship parts in this class. Check the part that you are currently dragging to see if any of the colliders are colliding with other parts.

If there is a collision, check if the rotation is within your specified threshold and then snap it into place.

This is actually a lot more complicated to explain than I thought it would be. Let me know if you have questions and I will elaborate on whatever you need more help with.
> 8 votes

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


# Question
Title: Can't assign animation to animation variable declared in script Unity2D
So I'm trying to have my script pause an animation when the user clicks. Here's what I have so far:

I defined the animation up at the top

```
public Animation anim;
```

and then further down,

```
 void Update () {
        if (Input.GetMouseButtonDown(0))
        {
            anim["myAnimation"].speed = 0.0f;
        }

 }
```

Code gives no error, however in Unity I have a GameController object to which this script is attached to. The gamecontroller object has a vacant field into which I drop my animation to. The issue is that when I try and drag and drop my animation or try to place it into that field, nothing happens, I keep getting the error down at the bottom saying that "The variable anim of GameController has not been assigned." How do I go about assigning myAnimation to the variable anim?

When I try and drag and drop my animation file to this, nothing happens. This is under the GameController script which I assigned to a GameController object.

# Answer
> 2 votes
First of all, you must clarify which animation you are talking about.

This one

Or this one

The first one is a Component, which can be assigned to public field of script in the Inspector, the second one is a animation clip, which can be attached to animation controller like Animation or Animator.

So if you are trying to drag-drop an animation clip into an Animation field, nothing will happed.

# Answer
> 0 votes
You have just run into the difference between *declaration* and *definition* of a variable. Just because you did this:

```
public Animation anim;

```

Does not mean that you're done! This variable currently holds the value `null` which means "nothing is here." Attempting to act upon a null object at runtime will cause the application to crash with a NullPointerException ("you tried to access something that doesn't exist").

In order to turn a declaration ("this is a variable") into a defined object ("this is a variable with a value") you need to assign something *to* it, either by using the assignment operator (`=`) or by using Unity's property inspector. What you assign this variable to, however, is entirely on you to figure out (you haven't supplied enough information about your project).

---
Tags: unity, animation
---


# Question
Title: Game Loop getting 58-62 FPS. Why not exactly 60FPS? (SDL/C++/OSX)
Here's my game loop:

```
uint64 target_fps = 60;
  uint64 ticks_per_s = SDL_GetPerformanceFrequency();
  uint64 target_ticks_per_f = ticks_per_s/target_fps - (ticks_per_s/1000); //aim for (target - 1ms) to err on side of > 60fps

  uint64 ticks_per_cur_f = 0;
  uint64 t_last_render = 0;
  uint64 t_last_update = SDL_GetPerformanceCounter()-target_ticks_per_f;
  int max_updates = 3;
  int updates = max_updates-1;

  while(!done)
  {
    while(
      t_last_update > SDL_GetPerformanceCounter() - target_ticks_per_f &&
      t_last_render > SDL_GetPerformanceCounter() - target_ticks_per_f
    )
    {
      SDL_Delay(1);
    }

    //update
    updates = 0;
    while(updates < max_updates && t_last_update < SDL_GetPerformanceCounter() - target_ticks_per_f)
    {
      t_last_update += target_ticks_per_f;
      updates++;
      pollEvents(); //possibly sets done = true
      simData();
    }
    if(updates >= max_updates) t_last_update = SDL_GetPerformanceCounter();

    if(t_last_render < SDL_GetPerformanceCounter() - target_ticks_per_f)
    {
      ticks_per_cur_f = SDL_GetPerformanceCounter()-t_last_render;
      t_last_render = SDL_GetPerformanceCounter();
      render();
      SDL_GL_SwapWindow(window);
      glFinish();
    }
  }

```

It's a fixed timestep (to simplify/make consistent any updates).

It essentially just does this:

* Wait (SDL\_Delay()) until enough time has passed requiring either an update or a render
* While "last update" was \> 16ms ago, update() and add 16ms to when "last update" was (maxing out at 3 updates assuming it got really far behind)
* If "last render" was \> 16ms ago, render (and set "last render" to "now")
* Repeat

Even when I do nothing in update() or render(), it fluctuates anywhere between 58FPS and 62FPS. Why would this be? I understand that SDL\_Delay only has a fidelity of 1ms, but I even set "target ticks" to be 1ms less than necessary to try to account for this.

Any ideas?

Thanks!

# Answer
`SDL_Delay()` doesn't really have fidelity of any sort; it puts your main thread to sleep, and once your thread is sleeping it's up to the OS to decide when to wake you up again, which could happen at any time. It certainly won't happen on a reliable schedule, or be guaranteed to be "within 1ms" of your nominated time or anything of the sort. It's this unpredictability, I believe, that's leading to the variation you're seeing.

If you want to hit a solid frame rate by locking up your main CPU thread, you either need to spinlock (don't put the thread to sleep; instead just spin inside that 'while' loop until enough time has passed; effectively, just comment out the call to `SDL_Delay()`), or else turn on vsync so that swapping will delay until vblank.
> 7 votes

# Answer
In my understanding you are trying to implement an accurate fps cap. I dealt with this problem yesterday and came up a solution I posted over at stackoverflow below a related question:

How can I implement an accurate (but variable) FPS limit/cap in my OpenGL application?

The most important part is the following code snippet displaying a sample gameloop:

```
//FPS limit
unsigned int FPS = 120;

//double holding clocktime on last measurement
double clock = 0;

while (cont) {
    //double holding difference between clocktimes
    double deltaticks;

    //double holding the clocktime in this new frame
    double newclock;

    //do stuff, update stuff, render stuff...

    //measure clocktime of this frame
    //this function can be replaced by any function returning the time in ms
    //for example clock() from <time.h>
    newclock = SDL_GetTicks();

    //calculate clockticks missing until the next loop should be
    //done to achieve an avg framerate of FPS
    // 1000 / 120 makes 8.333... ticks per frame
    deltaticks = 1000 / FPS - (newclock - clock);

    /* if there is an integral number of ticks missing then wait the
    remaining time
    SDL_Delay takes an integer of ms to delay the program like most delay
    functions do and can be replaced by any delay function */
    if (floor(deltaticks) > 0)
        SDL_Delay(deltaticks);

    //the clock measurement is now shifted forward in time by the amount
    //SDL_Delay waited and the fractional part that was not considered yet
    //aka deltaticks
    the fractional part is considered in the next frame
    if (deltaticks < -30) {
        /*dont try to compensate more than 30ms(a few frames) behind the
        framerate
        //when the limit is higher than the possible avg fps deltaticks
        would keep sinking without this 30ms limitation
        this ensures the fps even if the real possible fps is
        macroscopically inconsitent.*/
        clock = newclock - 30;
    } else {
        clock = newclock + deltaticks;
    }

    /* deltaticks can be negative when a frame took longer than it should
    have or the measured time the frame took was zero
    the next frame then won't be delayed by so long to compensate for the
    previous frame taking longer. */

    //do some more stuff, swap buffers for example:
    SDL_RendererPresent(renderer); //this is SDLs swap buffers function
}

```

With this method your fps won't fluctuate anymore, it will be exactly 60fps. From what I understand my method works similarly to yours except I only call SDL\_Delay once per frame and use doubles for variables like your `target_ticks_per_f` because the ms required for each frame to achieve an avg fps is not an integer. I suggest you visit the post i referenced because I make an attempt to explain more details there. I hope this helps you and I hope that it is not frowned upon to reference my own post like this.
> -2 votes

---
Tags: c++, sdl, game-loop, timing
---


# Question
Title: translation and rotating at the same time and waiting before animation?
I am having difficulties here. I want to move my character with the buttons and I want the character to rotate wherever he is going.

Also I want to play an animation when there is no keys pressed. I am able to do that but I want the animation to play after 10 seconds of no key being pressed, and only once. Than after a movement that resets and again after 10 seconds of no key the animation plays. (The animation works but it happens right after I stop pressing a key and continuously.)

```
IEnumerator Test()
{
    yield return new WaitForSeconds(10.0f);
}

void Update()
{
    if (Input.GetKey(KeyCode.W))
    {
        counter += Time.deltaTime;
        transform.Translate((Vector3.forward) * moveSpeed * Time.deltaTime);
        Debug.Log("Pressing W key");
    }
    if (Input.GetKey(KeyCode.S))
    {
        counter += Time.deltaTime;
        transform.Translate((Vector3.back) * moveSpeed * Time.deltaTime);
        Debug.Log("Pressing s key");
    }
    if (Input.GetKey(KeyCode.A))
    {
        counter += Time.deltaTime;
        transform.Rotate(Vector3.down * rotateSpeed);
        Debug.Log("Pressing a key");
    }
    if (Input.GetKey(KeyCode.D))
    {
        counter += Time.deltaTime;
        transform.Rotate(Vector3.up * rotateSpeed);
        Debug.Log("pressed D");
    }
    if (!Input.GetMouseButton(1))
    {
        moveSpeed = 20;
    }

    if (!Input.anyKey)
    {
        if (counter >= 2)
        {
            StartCoroutine(Test());
            anim.Play("Animation");
            counter = 0;
            Debug.Log("A key or mouse click has been detected");
        }
    }
}

```

# Answer
> 1 votes
You can do it in a more simple way, like this:

```
float lastKeyPressedTime;

void Update()
{
    if(Input.anyKey )
         lastKeyPressedTime = Time.time;

    if(lastKeyPressedTime + 10f < Time.time )
    {
        PlayAnimation();
        lastKeyPressedTime = Time.time;
    }
}

```

About the animation, don't forget to uncheck the Loop checkbox in Inspector

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


title: Help in 2d platform script

text:
# Question
Title: Help in 2d platform script
Now I finished my 2d game but when I set up it in my mobile it becomes like this so I change some scripts in Maincamera but it's still the same

How can I change the screen to become horizontal in my mobile like this?  what I need that how can I make it fit my mobile screen.

# Answer
You have to change the property in the Player settings:

`Edit -> Project settings -> Player`

In the inspector will be a tab for each Player your project supports. You have to change the `Default orientation` to landscape:
> 2 votes

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


# Question
Title: How to apply a shader to only one side of an object in Unity3D
So I have this rather simple surface shader that essentially cuts a hole in the object based on another texture.

```
Shader "Custom/NewSurfaceShader" {
    Properties {
        _MainTex("Texture (RGB)", 2D) = "white" {}
    _SliceGuide("Slice Guide (RGB)", 2D) = "white" {}
    _SliceAmount("Slice Amount", Range(0.0, 1.0)) = 0.5
    }
    SubShader {
        Tags { "RenderType"="Opaque" }
        Cull OFF
        CGPROGRAM

#pragma surface surf Lambert addshadow
        struct Input {
        float2 uv_MainTex;
        float2 uv_SliceGuide;
        float _SliceAmount;
    };
    sampler2D _MainTex;
    sampler2D _SliceGuide;
    float _SliceAmount;

    void surf(Input IN, inout SurfaceOutput o) {

        clip(tex2D(_SliceGuide, IN.uv_SliceGuide).rgb - _SliceAmount);
        o.Albedo = tex2D(_MainTex, IN.uv_MainTex).rgb;
    }
    ENDCG
    }
        Fallback "Diffuse"
}

```

This produces the following effect.

Now as cool as this looks I want to only apply it to, let's say, one side of the cube and its opposite side. Any suggestions on how do I go about doing this will be appreciated.

# Answer
I have an idea:

* Shoot Raycast from camera (if first person).
* Use textureCoord to find the UV coordinates.
* Pass the coordinates into the shader, and use them to draw the decal.

This should take care of one side of the object, the part facing the raycast. I can suggest a way to detect the other side of the object. But i do not know if this is efficient:

**Suggestion:** Shoot a 'backtrace' ray starting from quite a distance from the original ray:

You use the ray info from ray i described above and you see in the picture below (*1st Ray*), find the distance between the origin of the *1st Ray*, and its hitPoint's (*Hitpoint A*) position. Then add some distance to that, and use that point in space to shoot a ray (*2nd Ray*) back to the *1st Ray*'s origin. Find the Hitpoint on the opposide side of the object and apply textureCoord again -\> pass to shader -\> use for second decal.

*Keep in mind that there can be other objects hitting the rayCast that are in between the backtrace's origin and hitpoint on your desired object. A RaycastAll and a comparison should fix that possible problem.*
> 1 votes

---
Tags: shaders, unity, shaderlab
---


title: Unreal - AI's can't target buildings

text:
# Question
Title: Unreal - AI's can't target buildings
After following some of the Unreal tutorials, I was able to create an AI that tracks the player. Now I want it to target specific buildings. I have tried various methods of modifying what was demonstrated in the Unreal videos but all I can get my AI controller to do is either stand in place or walk to the center of the nav mesh. Here is an example of what I have done:

If anyone can help, how can I get my AI to attack the Armory? Thanks.

# Answer
> 1 votes
I have figured it out. Since a building is so large it messes with the acceptance radius making the AI think it has reached its location so it just stays still. I instead made an empty class called Waypoint that I planted around the outside of the building and had the AI move to that location instead. It works just fine now.

---
Tags: ai, unreal-4, unreal, blueprints
---


title: The value of gameplay hours

text:
# Question
Title: The value of gameplay hours
When you buy flooring there is a price per sq foot and it's based on the quality of the material. Some want expensive, some want cheap, some want middle of the road. Can the same idea be applied to video games to apply pricing and if so what tiers would we be looking at? I ask this because we plan on making a dungeon game where we release new dungeons frequently and I'm just thinking how many gameplay hours each dungeon needs for a .99, 1.99, or 2.99 price point?

Is it .99 cents per hour of gameplay that is aimed for?

# Answer
> 1 votes
Some players value the price they'll pay for a game the way you just explained: how much does it cost and how long will I play, how much $ per hour?

But that's not the only way you should take to price your game.

How is the competition pricing theirs? How much will it cost *you* to create, publish and market the game? How many copies do you expect to sell? How long will it take you to sell that much copies?

If you think you'll sell 1000 copies at 1$ each week starting at the first week, great! you have a salary of 700$ per week (stores take 30% of what you make). Now if you took only one week to make the game, that's nice, but how long did it take for you to make the game?

You have to think about profitability and having a sustainable business. Unless you have unlimited funds, that is, in which case you're very lucky :)

---
Tags: pricing
---


# Question
Title: What causes this InvalidOperationException when drawing primitives?
I'm working on implementing a 2D masking effect in my current game. To do so, I have two textures, one for the source image and one for the mask. The source image is just a regular texture, so that's easy. The mask I'm generating by rendering to a render target through the use of `graphicsDevice.DrawUserIndexedPrimitives`, but when I try, the following error pops up.

This is the function that attempts to render to the mask's render target. Vertices are of type VertexPositionColor.

```
private void RenderMaskTarget(SpriteBatch sb)
{
    graphicsDevice.SetRenderTarget(maskTarget);
    graphicsDevice.Clear(Color.Transparent);

    sb.Begin(SpriteSortMode.Deferred, null, null, null, null, basicEffect, camera.Transform);

    graphicsDevice.DrawUserIndexedPrimitives(PrimitiveType.LineStrip, vertices, 0, vertices.Length, indexData, 0, primitiveCount);

    sb.End();
}

```

And this is the function that creates my basic effect.

```
private void CreateBasicEffect()
{
    Matrix projection = Matrix.CreateOrthographicOffCenter(0, Constants.ScreenWidth, Constants.ScreenHeight, 0, 0, 1);
    Matrix halfPixelOffset = Matrix.CreateTranslation(-0.5f, -0.5f, 0);

    basicEffect = new BasicEffect(graphicsDevice)
    {
        World = Matrix.CreateOrthographicOffCenter(0, graphicsDevice.Viewport.Width, graphicsDevice.Viewport.Height, 0, 0, 1),
        View = Matrix.Identity,
        Projection = halfPixelOffset * projection,
        VertexColorEnabled = true,
        LightingEnabled = false
    };
}

```

I've searched everywhere I can on this site and Google in general, but nothing I've tried has worked. I think my problem is a fundamental misunderstanding of what the exception above actually means. Based on its wording, the current vertex declaration doesn't include all required elements, and it then goes on to list the elements I do have, but it doesn't tell me what the required ones are. Further, where is the current vertex declaration defined? Is it VertexPositionColor that defines it or the BasicEffect?

I realize that similar questions to this have been asked before, but like I said, no solutions I've seen have worked. I think part of that is XNA vs. Monogame, where an XNA solution might not work for Monogame. I apologize if this is a true duplicate question.

Thank you :)

# Answer
> 2 votes
This section is not correct:

```
sb.Begin(SpriteSortMode.Deferred, null, null, null, null, basicEffect, camera.Transform);

graphicsDevice.DrawUserIndexedPrimitives(PrimitiveType.LineStrip, vertices, 0, vertices.Length, indexData, 0, primitiveCount);

sb.End();

```

You're using a `spriteBatch` and then bypass it by calling the `DrawUserIndexedPrimitives` directly. I'm not entirely sure but it seems to me that your drawcall simply has no shader active at the time you call it. Since the spriteBatch starts drawing at the `sb.End()`.

So what I think happens here is

1. you start a spriteBatch.
2. attempt to draw something without the batch.
3. close the spriteBatch- but it is empty so nothing happens.

At the point 2, no shader is actively set.

Replace the draw section by:

```
private void RenderMaskTarget()
{
    graphicsDevice.SetRenderTarget(maskTarget);
    graphicsDevice.Clear(Color.Transparent);

    basicEffect.CurrentTechnique.Passes[0].Apply();
    graphicsDevice.DrawUserIndexedPrimitives(PrimitiveType.LineStrip, vertices, 0, vertices.Length, indexData, 0, primitiveCount);

}

```

# Answer
> 0 votes
Your active vertex declaration includes `SV_Position0` and `COLOR0` elements, as you have surmised. Your active *shader* expects a different set of elements, and thus cannot be used to render the geometry you are sending.

You need to make your vertex declaration and your shader match (you also need to make sure you actually send the type of data the vertex declaration asserts).

You're using MonoGame's `BasicEffect`, which I believe is a "built in" shader that expects positions, colors and *texture coordinates*. Your vertex declaration doesn't contain texture coordinates and you may not actually be sending them in the vertex data, either.

The simplest thing you can probably do is set `TexturesEnabled` to false on your effect, which should stop it from requiring texture coordinates. Alternatively, provide texture coordinates in your vertex data and declaration.

---
Tags: shaders, monogame, hlsl, vertex-shader
---


# Question
Title: In my tile-based game, GameObjects are stored in a std::map<Vec2Int, GameObject>, but I want the GameObjects to be in control of their position!
GameObjects are stored in a Tilemap class, within a `std::map<Vec2Int, GameObject>` container. The `Vec2Int` struct describes the object's x and y coordinates. Each GameObject also contains a Vec2Int describing the same thing.

There are two things I would like to do (unless there is an entirely different/better way):

* The Tilemap should be able to traverse all GameObjects so that they may be drawn to the screen. The Tilemap uses a Camera class so that it can figure out which tiles/objects can be seen in the current camera view.
* However, GameObjects should be in control of their own position, not the Tilemap! The GameObject should be able to reposition itself by simply changing its x or y coordinates

For reference (I've only included the relevant stuff):

```
struct Vec2int {
    int x, y;
};

class Tilemap {
    public:
        Tilemap(const int &w, const int &h);
        void LoadLevel();
    private:
        //A 2D array of Tile pointers
        std::vector<std::vector<Tile*>> _tileMap;
        std::map<Vec2int, GameObject*> _objects;
};

class GameObject : public Tile {
    public:
        GameObject(const int &tileID, const Vec2int &position);
        //virtual void Update() = 0;
    private:
        Vec2int _position;
};

```

# Answer
Crucially (and your question title is wrong here, because it omits the \*), you've got a map of **pointers** to GameObjects, so the Tilemap **isn't** in control of the GameObjects. It's really just a helpful look-up table.

Fundamentally you need a back-reference to the Tilemap in every GameObject, so they can remove themselves from the tilemap and re-add themselves in their new position. This is less about control than it is about deciding where the maintenance of your look-up table should be. If you think about it, it makes no sense to consider a GameObject in isolation; it has a position field, and that means it always has to be somewhere on your Tilemap. There's no concept of a GameObject that's not actually on the Tilemap somewhere, so they are already intimately related.

If this feels a little squinky, it's probably because you've got the same information in two places. You could keep the location information wholly in the GameObject (and just maintain a flat list of tiles in the Tilemap), or you could make the GameObjects ignorant of their position, just reference them by ID and move them in the Tilemap, and both would work equally well, but leave you having to do some awkward queries in one place or another.

If you are going to maintain the information in two different places, you want to make one function that maintains both sets of information at the same time, so they can never get out of sync. That means you either put it in the Tilemap (and don't allow GameObjects to change their own position), or you put it in the GameObject (and don't allow the Tilemap to alter its own information about GameObject location). If you do the latter, then every GameObject needs to know about the Tilemap it's associated with so that it can modify the std::map itself.

This sort of relationship is awkward in C++ because to preserve encapsulation you end up wanting to make the GameObject a 'friend' of the Tilemap, so it can access private/protected members, which should already be ringing alarm bells. The only alternative is to initialise the GameObject with a direct reference to the std::map object itself (so it doesn't know it's part of a Tilemap, it just knows that it's got a look-up table that will have a reference to itself, and it should maintain that lookup table)
> 1 votes

---
Tags: c++, tiles, tilemap, maps
---


title: OnMouseUp not working in unity

text:
# Question
Title: OnMouseUp not working in unity
A common problem in Unity - my OnMouseUpAsButton() is not being called, and I do not understand why. I have attached box collider 2d (though its size is set up during runtime, but by the time I click on it it has proper size and covers the whole button). My object is an UI element, created from prefab during runtime. Here you can see its inspector info:

Code:

```
using UnityEngine;
using System.Collections;

public class button_controller : MonoBehaviour {
void OnMouseUpAsButton()
{
    Debug.Log("Clicked event button");
    switch(click_action){
        case action.NONE:
            action_none();
            break;
    }
}

```

I tried going through other threads where people had similar problems but nothing seems to work. Any ideas what might be happening?

EDIT: I found out that if I add a new button , directly from the inspector to the canvas, whose collider is within the canvas all other buttons start working. Interestingly I cannot put this new button anywhere, it has to be at least a bit within the canvas

# Answer
> 2 votes
Attempting to recreate the above environment, I was quickly able to recreate the problem. This stems from one or two small problems. Primarily, you have not set your collider up for interface through the `OnMouseUpAsButton()` method.

### Using `OnMouseUpAsButton()`

Lets have a look at the API documentation on using this method. One particular line stands out:

> This function is called **on Colliders marked as Trigger** if and only if Physics.queriesHitTriggers is true.

Sure enough, you do not have your collider set as a trigger. Enabling "trigger" via the inspector will allow your collider to trigger the `OnMouseUpAsButton()` method.

### Make sure your collider is actually there

The above solution did not immediately fix the problem on my end, but I sourced the other issue down to the physical size of my collider. Due to the particular nature of my problem, and the unexplained absence of the size variables on the example BoxCollider2D, I will make note of them now.

First and foremost, without an image on the object, you will still see an outline. I *assumed* this was the collider, as you can always see the outline. This assumption was *wrong*. When I deliberetly selected **Edit Collider** the collider appeared in an alternate colour, and was considerably smaller than the original outline. As it appears, my button *was* working, I just had to enlargen the collider to make the clickable space more available. Previously, size has also been a reflection of scale, with a value of 1 always completely filling the object. This was also an incorrect assumption, in this case, as I instead had to have a size that matched the exact size value of the object.

I would strongly suggest you perform the same check. If this does appear to be an issue, **Edit Collider** should also make gizmos available to drag out the size of the collider. Oddly enough, in the example provided above, the size variable is completely absent from the BoxCollider2D component. While my current version of Unity is a single version out of date, this is not something I have ever seen before, so would not advise you alter the size from the inspector.

# Answer
> -1 votes
There are a few issues here: it's late and I need sleep but why are you using a box collider on a canvas element ? Totally unnecessary and probably causing problems. If I wasn't on my phone I'd be of more help, sorry.

All that's required is you drag and drop the go with your button code into the button event field (might have to add the field first by clicking + button) and then select the function from the drop down menus. The function must be public and take zero to one arguments.

It's that simple.

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


# Question
Title: How Can Create Line Renderer Runtime When Player in Gravity
I want to Create functionality Like Rock Runner Game.when player into the gravity and hold the button then generate line and player hold the line and move forward. After So many Research i couldn't find anything in google and also in YouTube then i post the question. I put some snippets to very well understand what i want actually. if any one have idea how to do this then tell me. thanks in advance

# Answer
> 0 votes
I found the solution to Create Line when player in Gravity.

When holding the finger pressed and the player is within the range of the "ceiling object" i Create a **LineRenderer** , create One Empty Object Child of "celling object" and attached linerenderer to Empty Object.& For Calculate the Distance using **Vector3.distance**

```
public GameObject StarObj,EndObj;
private LineRenderer lineRenderer;
private HingeJoint2D hingJoint;

// Use this for initialization
void Start () {

    lineRenderer = GetComponent<LineRenderer> ();
    hingJoint = GetComponent<HingeJoint2D> ();
}

// Update is called once per frame
void Update () {

    if (Vector3.Distance (transform.position, StarObj.transform.position) <= 8f) {
        lineRenderer.enabled = true;
        lineRenderer.SetPosition (0, StarObj.transform.position);
        lineRenderer.SetPosition (1, EndObj.transform.position);

        if (DemoLongPress.instance.jointTrue) {
            hingJoint = EndObj.GetComponent<HingeJoint2D> ();
            hingJoint.connectedBody = StarObj.GetComponent<Rigidbody2D> ();
            hingJoint.connectedAnchor = new Vector2 (0, 1f);
            hingJoint.anchor.Set (0, 1);
        }

    } else {
        lineRenderer.enabled = false;
    }
}

```

When Player Hold the finger Player Can Stick to the LineRenderer using **HingJoint2D** When player enter to the distance to create line between player to "ceiling object" and when player hold the finger then joint is connected between player to "ceiling object" and player stick to the line. And if the player releases his finger delete the line game object. if any correction or mistake then tell me i correct it...The rest should be configuration of the line renderer component to match the look of the line as you want it. Thanks

# Answer
> 2 votes
Watching a video of the game this looks like a simple straight line between the player and the object of the ceiling.

For that you can use a Line Renderer component

When holding the finger pressed and the player is within the range of the "ceiling object" you just

* create an empty game object
* add a line renderer component
* and add some script like

```

[RequireComponent(typeof(LineRenderer))]
public class LineController : MonoBehaviour {

    public GameObject startObject;  //e.g. the player
    public GameObject endObject;    //e.g. the object on the ceiling

    private LineRenderer lineRenderer;

    void Start () {
        lineRenderer = GetComponent(); //stackoverflow cut out the generic part ;-)
    }

    void Update () {
        lineRenderer.SetPosition(0, startObject.transform.position);
        lineRenderer.SetPosition(1, endObject.transform.position);
    }
}

```

The rest should be configuration of the line renderer component to match the look of the line as you want it. And if the player releases his finger delete the line game object.

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


title: How do graphics libraries work?

text:
# Question
Title: How do graphics libraries work?
I have made many different game engines with OpenGL, but still struggle to understand how they work and the process in which the library tells the computer what to do.

How do graphics libraries such as DirectX or OpenGL work?

# Answer
**Neither DirectX nor OpenGL is a graphics library.**

This is important to understand: neither is actually responsible for drawing graphics.

Instead how they work is that they provide an *interface* between your program and your graphics hardware.

Your graphics hardware is what actually does the drawing, so what DirectX or OpenGL do is provide a hardware-independent way for your program to tell the graphics hardware what to draw.

In summary:

* Your program issues drawing commands using DirectX or OpenGL.
* Your DirectX or OpenGL driver takes those commands, converts them to something that your hardware can understand, and passes them on to your hardware.
* Your hardware does the actual drawing.
> 3 votes

---
Tags: opengl, directx, graphics
---


# Question
Title: How to get the 2d field of view using dot or atan2?
I tried to implement from this site linear-algebra on how do I check the field of view using dot product. But when I check the angle to the given fov angle, I am not getting the desired result. Instead of getting the field of view of 45 degree, I am getting 90 degree. What am I doing wrong?

```
Vector2 start = Mapper.transform.get(owner).position;
Vector2 end = Mapper.transform.get(target).position;
float facingAngleRad = 0;
Vector2 ownerOrientation =
   new Vector2((float)Math.cos(facingAngleRad), (float) Math.sin(ficingAngleRad));
Vector2 targetOffset = tmp1.set(end).sub(start);

float product = ownerOrientation.nor().dot(targetOffset.nor());
float checkAngle = (float) Math.acos(product);
float FIELD_OF_VIEW_ANGLE = 45 * MathUtils.degeeToRadians;
if(checkAngle < FIELD_OF_VIEW_ANGLE) {
    // in the field of view
}

```

In the below image, green is the desired field of view (45 degree), but I'm getting 90 degree (red)

# Answer
> 1 votes
If you want the field of view to be 45 degrees, then you need to check that the angle is less than 45/2. This is because you are checking if the angle is between the "center" and one of the outer bounds, and for a center angle of 0, the outer bounds are -22.5 and 22.5, not -45 and 45.

---
Tags: libgdx, box2d, linear-algebra
---


# Question
Title: How do I get a Light's Range value in Shader?
I'm trying to write a simple frag/vert shader that, depending on whether it is in the range of a light, will paint the appropriate colour from either the 'lit' texture or from the 'unlit' texture.

Therefore, I need to compare the distance between the light to the range of the light. I've been googling all kinds of things, but I can't seem to find a way of accessing the range value of the light. Is there a way to do so? If not, is there some kind of derived data I could use as an alternative?

I was able to find this method here, which seems to be the most promising so far, however after playing around for a bit, I still can't seem to get what I need. There's some talk about `_LightMatrix0` not being populated. Can anyone confirm?

I've also had it suggested to use `SetFloat()` and pass in the range like that...however, that provides no easy way of telling one light apart from another short of using the light's position as a key. As several key lights in the game will be moving this is just ugly and inefficient.

**Update**

I found the variable `unity_LightAtten` in the Unity Shader Variables documentation. However, this is only used for Vertex Lit shading, which isn't exactly ideal, especially considering the lack of console support. Could there be a way to pipe this variable to Forward Rendering?

**Update 2** For clarification, shading should otherwise be 'flat' (ie no need for diffuse etc):

Also, what I've currently got (albeit, not currently working as desired and currently using a workaround):

```
Shader "Lantern/Flat Pullup" {
Properties {
    _LitTex ("Lit (RGB)", 2D) = "white" {}
    _UnlitTex ("Unlit (RGB)", 2D) = "white" {}
    //_Falloff ("Falloff", 2D) = "white" {}
    _Pullup ("Pull up Point", Range(0,1)) = 0.7
}
SubShader {
    Pass{
        Tags { "LightMode"="ForwardBase" }
        LOD 200

        CGPROGRAM
        #pragma vertex vert
        #pragma fragment frag
        #include "UnityCG.cginc"

        uniform sampler2D _UnlitTex;
        uniform float4 _UnlitTex_ST;
        uniform sampler2D _LitTex;
        uniform float4 _LitTex_ST;
        uniform float _Pullup;

        uniform float4 _LightColor0;

        struct VI {
            float4 vertex : POSITION;
            float4 tex : TEXCOORD0;
        };

        struct V2F {
            float4 pos : SV_POSITION;
            float4 tex : TEXCOORD0;
            float4 posWorld : TEXCOORD1;
        };

        V2F vert(VI v){
            V2F o;
            o.pos = mul(UNITY_MATRIX_MVP, v.vertex);
            o.tex = v.tex;
            o.posWorld = mul(_Object2World, v.vertex);
            return o;
        }

        float4 frag(V2F i) : COLOR {
            float3 flatReflection = _LightColor0.xyz *
                (1 / length(_WorldSpaceLightPos0.xyz - i.posWorld.xyz));
            float4 color;
            //Improve for light color etc
            if(length(flatReflection) > _Pullup){
                color = tex2D(_LitTex, i.tex.xy * _LitTex_ST.xy + _LitTex_ST.zw);
            }else{
                color = tex2D(_UnlitTex, i.tex.xy * _UnlitTex_ST.xy + _UnlitTex_ST.zw);
            }
            return color;
        }

        ENDCG
    }
}
FallBack "Diffuse"
}

```

# Answer
> 1 votes
Have opted to use my 'workaround' shader as posted in the question. `_Pullup` can be tuned appropriately in the material to match the range of the light as closely as possible when working by eye.

# Answer
> 0 votes
I believe you can use: \_WorldSpaceLightPos0.xyz

Source: https://docs.unity3d.com/Manual/SL-UnityShaderVariables.html

---
Tags: unity, fragment-shader, cg, shaderlab
---


# Question
Title: Recommended polycount for a MMORPG character
> "How much polygons is too many for a MMORPG character?"

I did some research and found a few discussions about the matter. But the answers I found was mostly "*Polygons has nothing to do with networking*" and they just start to argue and flame each other.

I think the question wasn't received well because it wasn't clear. So, I'll try to make it a bit clearer.

Consider the main character of an offline game, it has so much details, but it is the only character on the scene for most of the time.

Now, on a MMORPG everyone is a main character. Let us say 100 players are in sight of each other at a given time. If we had the same character from the offline game we'd have too many polygons and frame-rate/performance would suffer.

If I target a minimum system requirement of 4GB memory, Intel i3 (3rd gen) CPU, and at-least a laptop GPU (cheap nvidia mobile?).

* How much polygon should my characters be limited to?
* or, How much polygons should be on the scene/sight at a time? (including terrain, other objects...)
* or, Is there a rule of thumb for polycount that applies to any genre of games?

# Answer
A first gen laptop intel i7 is **several times slower** than a 6th gen desktop i3. A 6th gen laptop intel i7 is still significantly slower than a 6th gen desktop i3.

A cheap laptop GPU from 2010 is several times slower than some built-in intel graphics from 2016.

And your choice of shader and different texture resolutions will affect performance far more than polycount.

You will learn all this while programming your game. For the game itself, you will need to test the actual performance on test hardware to know how fast it is. But you need a starting point, so here you go:

* Use a LoD algorithm. If load is too high you use low poly models, if load allows it and the models are close to the camera, use high poly models.
* At the beginning, your models should be around 500-5000 polys. 500 for low level of detail, 5000 for high level of detail.

This is a starting point. As you build the game you may want to adjust these values.
> 1 votes

---
Tags: 3d, multiplayer
---