# Question
Title: Efficient dynamic character shadows [SW Rasterizer]
I am working on a SW rasterizer for a quarter-century old console (think sub-100 MHz RISC CPU, no dedicated 3D HW, couple megs of RAM) and am approaching a stage where I will be adding dynamic character shadows. It's a next-gen engine for the platform, so there are no known or proven approaches. Basically, render stuff as fast as possible - e.g. in least amount of instructions (and least amount of RAM access).

The biggest performance bottleneck of the platform is memory read / write(e.g. fillrate). The RISC can do almost all instructions in 1-3 cycles (except division), but anything requiring access to main RAM is 10x slower (than from small cache).

I am not looking for some generic shadowing solution (I wrote few for PC/XBOX-using Shadow Volume and Shadow Mapping, so I have an idea how shadowing works). I am alright with writing multiple codepaths for multiple scenarios (e.g. one for characters, another for static objects).

**Known limitations**:

1. No Z-Buffer
2. No Stencil Buffer
3. Target resolution : 320x200
4. Shadows can be black (no need for transparent shadows)
5. A fallback shadowing solution is having pre-rendered shadows from each animation frame into texture and just drawing the texture below character (but it looks too lame). It's possibly the fastest solution, though (rotate shadow bitmap and just blit the texels)

Considering the above limitations, I have chosen the technique of **transforming the character mesh** (a low-poly version of the original mesh) **onto the floor plane** (from the position of the light) and drawing the shadow mesh on the floor (with black color). This should result in the desired sharp shadows without any pixelation effects (unlike shadowing methods based on projecting a shadow texture). But it will provide an effect of shadow being very large initially, and as character walks around, the shadow shrinks (until he is right below the light source) and then the shadow grows again.

**Advantage**:

1. Generic : If need be, I can apply it also on the walls, not just the floor
2. Fast : Transforms are fast on the RISC

**Disadvantage**:

1. Overdraw : I expect a major portion of the floor to be covered by the shadow (lightpos will be tweaked accordingly, for the sake of the effect). Since shadow is black, all the expensive lighting calculations on the floor are wasted, since they are \[mostly\] overwritten by the shadow.

The floor (basically one large rectangle) is internally divided into multiple square tiles (anywhere between 10-100 tiles per room). I think I can easily find out which floor tiles will be affected by shadow (I will calculate them during projection of the mesh onto the floor).

***Question* \- how can I easily merge the floor texturing routine with the shadowing** ? Ideally, each texel would be written just once. There are just two choices - either it is a floor texel or black (the shadow).

Anything - that merges the two approaches into one which will be faster than rasterizing a floor and then overdrawing majority of it with black shadow- is a win. Ideas ?

The most amount, I could theoretically spare, from the tiny cache (10x faster access than from main RAM) is about 1-2 KB for a temp buffer. Obviously, it is not enough to cover all shadow texels at given resolution, but it could perhaps prove useful for some other algorithm.

As of right now, I can only think of **span buffers** as the best solution for the overdraw. The spans would be short (e.g. easily fit into 1-2 KB), I just would have to rewrite the floor texturing algorithm - but if it was a faster solution, I could do that.

Any other ideas ?

# Answer
> 1 votes
If you eventually end up going with the pre-rendered shadow approach, or any other texture based solution...

To save some memory, and maybe also to be able to soften up the edges of the shadow (maybe even contact hardening shadows), have you considered using distance field textures?

They are useful for monochromatic textures (decals, fonts and shadows!), and each pixel encodes a signed distance to the shape. Positive = outside, negative = inside. You basically treat 0 to 255 as -1 to 1.

The benefit here is that you can use a much smaller texture for really nice results. With knowledge of the distance in texture space, you can also do things like stroke and anti aliasing, or making the texture have a softer edge under certain conditions (;

The best part is that the logic to render it is essentially an alpha test that could be performed by FFP, so should be very efficient in your usage case.

As an example, this 1280x720 mustache decal image was generated using a 64x32 single channel source image with alpha test logic.

And here it is using smoothstep (y = 3\*x^2 – 2\*x^3) to give a little softness and AA to the edges.

My blog post on more details is here: http://blog.demofox.org/2014/06/30/distance-field-textures/

Valve's paper on it is here: http://www.valvesoftware.com/publications/2007/SIGGRAPH2007\_AlphaTestedMagnification.pdf

---
Tags: 3d, algorithm, shadows
---


# Question
Title: Unity - Plugin 'MFC100U.DLL' is used from several locations:
As per subject, I got this error message using Metaio SDK in Unity5. BTW, I'm using Mac, not Windows machine.

```
Plugin 'MFC100U.DLL' is used from several locations:
 Assets/Plugins/x86_64/MFC100U.DLL would be copied to <PluginPath>/MFC100U.DLL
 Assets/Plugins/x86/MFC100U.DLL would be copied to <PluginPath>/MFC100U.DLL
Plugin 'MSVCP100.DLL' is used from several locations:
 Assets/Plugins/x86/MSVCP100.DLL would be copied to <PluginPath>/MSVCP100.DLL
 Assets/Plugins/x86_64/MSVCP100.DLL would be copied to <PluginPath>/MSVCP100.DLL
Plugin 'pthreadVC2.dll' is used from several locations:
 Assets/Plugins/x86/pthreadVC2.dll would be copied to <PluginPath>/pthreadVC2.dll
 Assets/Plugins/x86_64/pthreadVC2.dll would be copied to <PluginPath>/pthreadVC2.dll
Plugin 'Shore140.dll' is used from several locations:
 Assets/Plugins/x86_64/Shore140.dll would be copied to <PluginPath>/Shore140.dll
 Assets/Plugins/x86/Shore140.dll would be copied to <PluginPath>/Shore140.dll
Plugin 'MSVCR100.DLL' is used from several locations:
 Assets/Plugins/x86/MSVCR100.DLL would be copied to <PluginPath>/MSVCR100.DLL
 Assets/Plugins/x86_64/MSVCR100.DLL would be copied to <PluginPath>/MSVCR100.DLL
Plugin 'metaiosdk.dll' is used from several locations:
 Assets/Plugins/x86/metaiosdk.dll would be copied to <PluginPath>/metaiosdk.dll
 Assets/Plugins/x86_64/metaiosdk.dll would be copied to <PluginPath>/metaiosdk.dll
Please fix plugin settings and try again.

UnityEditor.Modules.DefaultPluginImporterExtension:CheckFileCollisions(String)
UnityEditorInternal.PluginsHelper:CheckFileCollisions(BuildTarget) (at /Users/builduser/buildslave/unity/build/Editor/Mono/Plugins/PluginsHelper.cs:25)
UnityEditor.BuildPlayerWindow:BuildPlayerAndRun()

```

How I can fix this error? Please advice. Thank you.

# Answer
You have multiple versions of the dll that are both set to be used for the same platform or cpu. Unity 5 introduced new plugin settings so that you can compile different versions of the same dll, but you need to specify which platform or cpu each version is for. Checkout this link for more info.

http://docs.unity3d.com/Manual/PluginInspector.html

(Note: I originally gave this answer on Unity Answers. http://answers.unity3d.com/questions/988343/plesehelp-meplugin-systemdatadll-is-used-from-seve.html#answer-1017015)
> 1 votes

---
Tags: unity, augmented-reality
---


title: How can I add extensions to libGDX?

text:
# Question
Title: How can I add extensions to libGDX?
I had a problem with my Font in a game I am developing in libGDX. After some googling I was instructed to use the following code:

```
private void createFonts() {
    FileHandle fontFile = Gdx.files.internal("data/Roboto-Bold.ttf");
    FreeTypeFontGenerator generator = new FreeTypeFontGenerator(fontFile);
    FreeTypeFontParameter parameter = new FreeTypeFontParameter();
    parameter.size = 12;
    textFont = generator.generateFont(parameter);
    parameter.size = 24;
    titleFont = generator.generateFont(parameter);
    generator.dispose();
}

```

The problem is there is no FreeTypeFontGenerator class in any of the libGDX libraries I am using. I found that it was an extension. LINK

I can't seem to find clear instruction on how to import these extensions so that I may use them in my game.

I am using Android Studio for development.

# Answer
A lot of great Libgdx extensions have been added to the maven repository such as freetype, tools and many other great libraries. This means you can add extensions in a blink of an eye, at least if you used the gradle LibGDX setup.

In your case you want to add freetype, look it up in the link above and select the version you need. Now select the tab `Gradle` and copy that link.

Open up the `build.gradle` at the root of your project. This file takes care of building the project for you. You just have to add this line in the modules you want to use it. I show you a example of my desktop module in the `build.gradle` file.

```
project(":desktop") {
    apply plugin: "java"

    dependencies {
        compile project(":core")
        compile "com.badlogicgames.gdx:gdx-backend-lwjgl:$gdxVersion"
        compile "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-desktop"
        compile "com.badlogicgames.gdx:gdx-tools:1.6.3"
        compile 'com.underwaterapps.overlap2druntime:overlap2d-runtime-libgdx-my:0.1.0'
        //Let's add freetype from the link you got.
        compile ''com.badlogicgames.gdx:gdx-freetype:1.6.4'
'
    }
}

```

Now all you need is to sync the project with the gradle files. In Android Studio I would go `Tools > Android > Sync Project with Gradle Files`. If you do not use Android Studio and cannot find this just search google how to sync with gradle for your IDE.
> 6 votes

# Answer
You need to add the correct JARs to your project.

For example, you can see from this Gradle/Maven repository search that there are both `gdx-freetype` and `gdx-freetype-platform` JARs.

To add them to Gradle, you just need to add the dependency name and version under the `dependencies` section.
> 1 votes

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


# Question
Title: Get the current time of animation using script Unity3d
I want to know the current time of the played animation using script in Unity3d. I tried using `currentState.normalizedTime` but this time is not the time of the animation, like it's the time of the runtime I think. Any advice please?

# Answer
Try this:

```
    int frameNumber = Mathf.FloorToInt(normalizedtimeOfFrame* totalFrames);

```
> 1 votes

# Answer
You would use AnimationState.time

It can be larger than the length of the animation, so to get the value with this, you would need to modulo with the animation clip length.

```
float time = currentState.time % currentState.clip.length;

```

You can also use Normalized Time, but you would have to mulitply the value by the length instead of the animation (AnimationClip.Length)

```
float time = currentState.normalizedTime * currentState.clip.length;

```
> 1 votes

---
Tags: unity, unityscript
---


# Question
Title: Why does my code only work when there is a debug statement? (Unity)
I have a script that controls how the particles in a particle emitter should look. (XNA example here) Yet it doesn't seem to update correctly. With an orb that should have 50 particles only a few show up. I tried to debug it to see what was going on and it all started working again. I removed the debugging and I was back to only a few particles being visible.

I put in a simple debug message (Debug.Log("hi")) and it worked, but it was a little slow since I was putting out a debug message 50 times per frame.

I wanted to know if I wasn't getting the correct number of particles so I set the starting color to something with full alpha instead of 0 and all of the particles showed up even without the debug message, but they just pop in instead of fading now. This means that somehow it's not fading in correctly unless there's a debug statement. It makes no sense to me.

The issue seems to be in the "if (myParticles\[i\].ChangingColors)" section of Update.

Here are my start and update functions.

OrbBase - Handles the number of particles.
RotateParticleFinal - Holds the data that I want to set to the particle.

```
void Start ()
{
    myBase = gameObject.GetComponent<OrbBase>();

    emitter = (GameObject)Instantiate(ParticlePrefab);
    emitter.transform.parent = this.transform;
    emitter.transform.position = transform.position;

    myParticles = new List<RotateParticleFinal>();
    myRemovedParticles = new List<RotateParticleFinal>();

    for (int i=0; i < myBase.Particles; i++)
    {
        float r  = GetNewRadius();
        myParticles.Add(new RotateParticleFinal(r, color));
    }
}

void Update ()
{
    #region Deal with changing particle count
    while (myParticles.Count < myBase.Particles)
    {
        float r  = GetNewRadius();
        myParticles.Add(new RotateParticleFinal(r, color));
    }

    for (int i=myParticles.Count-1; i >= 0; i--)
    {
        if (myParticles[i].Dead)
            myParticles.RemoveAt(i);
    }

    while (myParticles.Count > myBase.Particles)
    {
        myParticles.RemoveAt(myParticles.Count-1);
    }
    #endregion

    //TODO: Do we really want 5000?  Can the number change to match our base particle count?
    ParticleSystem.Particle[] tempParticles = new ParticleSystem.Particle[5000];
    int count = emitter.GetComponent<ParticleSystem>().GetParticles(tempParticles);

    for (int i=0; i < count; i++)
    {
        if (i >= myBase.Particles)
        {
            //This is more than we want, destroy it immediately and make sure that we don't get more than we really want.
            tempParticles[i].lifetime = -1;
        }
        else
        {
            myParticles[i].Update();
            if (tempParticles[i].lifetime < 5)
            {
                //Don't let it die!
                tempParticles[i].lifetime = 1024;
            }

            tempParticles[i].position = myParticles[i].GetPosition();

            //Debug.Log("hi");

            if (myParticles[i].ChangingColors)
            {
                tempParticles[i].color = myParticles[i].MyColor;
                if (tempParticles[i].color.a == 1)
                {
                    //This is the only place that ChangingColors is set to false so it should never stop fading in until I've faded all the way in.
                    myParticles[i].ChangingColors = false;
                }
            }

            if (!myParticles[i].SetUp)
            {
                //This is a brand new particle, so I need to tell it a few things.
                //We don't want it moving on it's own.
                tempParticles[i].velocity = Vector3.zero;
                tempParticles[i].axisOfRotation = new Vector3(Random.Range(-0.1f, 0.1f), Random.Range(-0.1f, 0.1f));
                myParticles[i].SetUp = true;
            }
        }
    }
    emitter.GetComponent<ParticleSystem>().SetParticles(tempParticles, count);
}

```

Any ideas why this only works with a debug, and how to fix it?

# Answer
So, in RotateParticleFinal I have a part that updates the alpha. That's only using floats. But when I check the actual particle to see if the alpha is at 1... well, it's a byte now. It was working better with a lot of debug calls because it slowed everything down, meaning I got a lot more alpha on my deltaTime based fade-in. Been wrestling with this for a while now and I didn't figure it out until right after I finally posted this \>\_\<
> 1 votes

---
Tags: unity, particles
---


# Question
Title: The more appropriate way to find GameObject in the scene
Which way is the more appropriate to find GameObject in the scene.
I know that GameObject.FindGameObjectWithTag is faster than GameObject.Find but i wondering whether FindGameObjectWithTag is better solution than this:

```
public GameObject someObject;

public void SelectObject()
{
    someObject.SetActive(true);
    //or whatever i want
}

```

# Answer
> 2 votes
If you can have objects linked via the inspector and public/serialized fields, you should absolutely do it. It's the best way. `FindObjectWithTag` is for when your objects don't live in the same scene, and they don't have scripts for registering for each other. And finally, it's useful for when you need to reference a script before `Awake` has run, so it may not be found/registered.

The only occasional disadvantage of linked variables is when you need to reference a prefab that you usually won't need (or won't need all the time), and this object has large resources, like a collection of textures. If it's linked/serialized, the prefab will be loaded into RAM.

Note: To clarify, `FindObjectWithTag` will find objects that have not had `Awake` called because of timing, but it will not find inactive objects. (This is how all the `Find*` functions work.)

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


# Question
Title: Rotating 2D-Projectile towards mouse, hides the projectile (Maybe changes the layer)
I want to shoot towards my mouse, which is working fine now. After this was solved, I wanted to rotate the projectile, so that it's looking to the mouse. This is my code:

```
projectile.transform.LookAt (target);

```

I think this should work, but suddenly my projectile is gone, I can still see the particles behind it but the projectile for itself isn't visible. So I think, that it switched to another layer. Target looks like this:

```
Vector2 target = Camera.main.ScreenToWorldPoint (new Vector2 (Input.mousePosition.x, Input.mousePosition.y));

```

So it shouldn't be possible that the z value is wrong am I right?

# Answer
> 1 votes
Usually when a texture is hidden in a 2D game, it's because it goes "in the back" of the screen. When you do lookAt(target), you have to remember that a Vector2 is just a vector3 with z=0 (thus, if you have z=1 for your background for example, it might go behind).

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


title: Rotation in 3D space using Quaternion

text:
# Question
Title: Rotation in 3D space using Quaternion
## System Configuration

I have two simulation systems (which I am going to call Sim-A and Sim-B) where I am going to spawn an entity created in Sim-A inside Sim-B.

## Expected outcome

The entity created in Sim-A appears in Sim-B in the right position with the correct orientation.

## System Input

The position of the entity created in Sim-A received in Lat/Long/Alt format (it assumes WGS-84 spheroid) and the orientation in Euler angles.

The Euler angles would help me to transform an entity from its world coordinate system to entity coordinate system by applying the Euler angles in the order of heading, pitch and yaw. Below is how it is documented.

" The order of rotation is first, rotate about z by the angle psi (), then about the new y (y') by angle theta (T), then about the newest x (x'') by the angle phi (I). The positive direction of rotation about an axis is defined as clockwise when viewed toward the positive direction along the axis of rotation."

However, in Sim-B this rotation is defined in Quaternion and it assumes a perfect sphere for the world (not WGS-84). As a result, I have to convert Euler to Quaternion before sending the information to Sim-B.

I have achieved this by applying ZYX conversion (page A-11) given in \[here\]\[2\].

## Challenge

When I pass the position and orientation of an entity created in Sim-A to Sim-B ( Sim-B uses ECEF system, so I do another conversion to go from LLA to ECEF), it appears in the correct LLA position but its orientation is incorrect (shown in the figure.).

This can be fixed by adding some value to the pitch and roll but it is not mathematically sound. Also, these values might change (haven't tried) if you spawn the entity in a different location of the earth due to its shape.

So, I would like to know the right way of correcting this issue (i.e. how to make the entity to stand upright). Assume that I can get the Up, Front and Right vector of the entity when it is spawned in Sim-B.

# Answer
> 1 votes
If you can obtain the Up, Front and Right vector, you have a full orthonormal basis to reconstruct the quaternion, you don't need to worry about Euler angles, just forget the Euler angles and build the quaternion directly from the Orthonormal Basis (x axis = -Right, y axis = Up, z axis = Front).

The simplest way to do this is to build a rotation matrix from the basis and then construct the quaternion from the rotation matrix, should be straight forward and should always give you the expected result.

Here's how to do the first step: http://renderdan.blogspot.cz/2006/05/rotation-matrix-from-axis-vectors.html

Here's how to do the second: http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/

Hope it helps.

---
Tags: rotation, transformation, quaternion
---


# Question
Title: How can i handle collision response in a voxel game?
I'm making a voxel game with cubes - like in minecraft - and I have figured out how to check wether the player is colliding with a voxel, I have just done it by checking wether the player is within a voxel which is not air, however I don't know how to respond to that i know that the player is inside of a solid cube/voxel. Can anyone please suggest how to do it?

# Answer
> 2 votes
Voxels can be considered Axis Aligned Bounding Boxes (AABB)s. I suggest looking up the math surrounding collision detection and AABBs. It's actually quite simple as you can describe an AABB with just two Vectors (a maximum and minimum point).

Here's a super simple example: http://www.miguelcasillas.com/?p=30

Of course AABB collision detection is really easy if you're just colliding with points, AABBs and Spheres. If you want to handle collision detection with complex shapes you'll need to explore Oriented Bounding Boxes (OBB)s and the Separating Axis Theorem.

# Answer
> 1 votes
The answer to "How to handle collision" part of your question is something like this:

First you need to quickly discard pairs of voxels that are too far away to be colliding (think spatial partition).

Then for each pair of voxels that are candidate to collision you should:

* check if they really are colliding;
* generate the collision data {penetration, collision\_normal} (for voxels it's pretty easy, check which axis has the bigger penetration and output this as the penetration and the axis as the collision normal, just make sure to define a rule for the normal, for instance, it always point to the first voxel of the pair);
* then you resolve the penetrations (move the voxels away from each other by penetration amount in each axis);
* and finally you have to add a force OR an impulse (both methods have their pros and cons, I particularly prefer impulse than force) to the center of each non static voxel using the normal as base for impulse direction and penetration as base for impulse magnitude. And you don't have to worry about angular impulse and angular momentum since voxels don't spin.

Hope it helps.

---
Tags: collision-detection, 3d, game-mechanics, voxels
---


# Question
Title: How to use Input.GetAxis("Mouse X/Y") to rotate the camera?
I want to make a first person camera that rotates with the mouse.

I looked at the Input.GetAxis Scripting API page and found a sample code, which I have included at the bottom of my post. Upon trying it out, I realized that although it has the same basic functionality I hoped it would have, it does not keep the camera parallel to the xz plane, particularly when moving the mouse in circles. After a while the camera would be at an odd angle, and the player would be completely discombobulated!

Is there a quick fix to this code that would restrict the camera movement somehow, or is there a better way to rotate the camera?

```
 using UnityEngine;
 using System.Collections;

     public class ExampleClass : MonoBehaviour {
         public float horizontalSpeed = 2.0F;
         public float verticalSpeed = 2.0F;
         void Update() {
             float h = horizontalSpeed * Input.GetAxis("Mouse X");
             float v = verticalSpeed * Input.GetAxis("Mouse Y");
             transform.Rotate(v, h, 0);
         }
     }

```

# Answer
The problem is that you are updating the existing rotation instead of tracking it yourself and replacing it each update.

When you update the rotation it combines your new rotation with the old one which leads to unexpected behaviour.

The solution is to to keep track of your accumulated rotation and reset the rotation entirely each update with your new values.

Credit where due, I found the answer here: Unity Answers: how-to-lock-or-set-the-cameras-z-rotation-to-zero

Working Code:

```
using UnityEngine;
using System.Collections;

public class FirstPersonCam : MonoBehaviour {

    public float speedH = 2.0f;
    public float speedV = 2.0f;

    private float yaw = 0.0f;
    private float pitch = 0.0f;

    void Update () {
        yaw += speedH * Input.GetAxis("Mouse X");
        pitch -= speedV * Input.GetAxis("Mouse Y");

        transform.eulerAngles = new Vector3(pitch, yaw, 0.0f);
    }
}

```

Key differences:

* Store the yaw and pitch as class members, rather than local method variables so you can keep track of the accumulated values.
* Use += and/or -= to accumulate each update.
* Use eulerAngles (to overwrite the rotation value each update) instead of Rotate (which applies your new rotation onto the old one).
> 24 votes

# Answer
What if you make the camera child of an empty gameobject. Then with one script you manage the empty gameobject rotation relative to UP vector.(MouseX) With another script atached to the camera gameobject you manage rotation relative to Right vector (MouseY)
> 0 votes

---
Tags: unity, camera
---


# Question
Title: How to architect input code to utilise state machine?
I have an `InputController` which currently handles all user input, so it looks at button states and updates entity intentions according to some simple rules.

I'm looking to add a new `state` to the game which essentially means displaying the player's inventory on screen. During this state I want the background to continue animating but want the user input to **only** interact with the inventory *layer*.

As the code stands right now the background will animate just fine under the inventory layer but the `InputController` will continue to behave like the layer isn't there and attempt to map clicks etc. to the game world.

An easy solution would be to add simple conditional logic in the controller `if (currentState == x)` but wondered if I could better utilise my existing game state machine. I have states such as `game_loading`, `in_game`, `menu` etc.

The only ideas I can come up with is either calling out to something like `state.HandleInput()` from inside the controller, that way the state is in control of what the player can and can't do but the downside is that input specific logic is being handled by a `state` rather than input specific code, which I'm not comfortable with.

Alternatively, I could reverse that and get the state to be the entry point and then they call out to specific input classes. So something like `inGameState.HandleInput()` calls out to `inGameInputController` likewise with `inventoryState`. This seems like the better approach.

I'm clearly not sure which way round the dependencies should orient. Am I missing a layer of abstraction somewhere? Or am I overcomplicating things?

# Answer
> 1 votes
You aren't over complicating it at all. This is a great way to think about a game. It keeps the game flexible for any changes you want to add in the future (say a stats screen).

The first place I would look is using the Strategy Pattern: Wikipedia

Determine what input triggers you would need and add them to an abstract interface. Then, implement the interface for each game state. Keep track of what your current state is and forward any of those input triggers to the current state to handle what ever it is you want to handle.

# Answer
> 1 votes
In instances like this I use a stack of input maps. You already have certain buttons doing this or that while playing the game, if you can group that logic into a map (array of button/key =\> some event) then you can make multiple maps for the different states you have. From there you just need 'some event's that can be used to push and pop the maps from a stack.

I generally make the 'menu' map the initial one and so it can not be popped off, it is the one always around. When you go into a game I would push on the 'playing the game' map and so the inputs would then cycle through there. One of the inputs to go back to the menu would have to, ofcourse, toggle your menu on, but then just pop off the 'playing the game' map.

Edit: An extended feature you could add into this would be for partial or fallthrough maps. This would allow you to change some of the buttons but still use the majority of the existing maps. A use case for this would be having items you can use bound to the directions on a D-Pad and having a second button (a bumper or the like) be held down or tapped to toggle it to a second set of items to use instead.

Any questions feel free to ask, I have tried to keep this simple but it may be I can find a better way to explain.

# Answer
> 1 votes
I 'll try to manage InputController changing its behaviour at runtime (in c# can use some kind of delegates) Examples :

```
if activated in_game state then InputController.processInput = logic1

if activated menu state then InputController.processInput = logic2

if activated inventory state then InputController.processInput = logic3

```

Logic1..N are alternative implementation of input processing

---
Tags: architecture, input, state
---


title: Vision Cone for Enemy AI in Unity 2d

text:
# Question
Title: Vision Cone for Enemy AI in Unity 2d
I am trying to develop an Enemy AI with vision cone in unity 2d top down game, can you please suggest me some approach or sample script, so I can get an idea.

# Answer
> 1 votes
In the Enemy script Update

//assuming a as half of your vision cone angle

```
    //pseudo code
    foreach target {
        if (Vector3.Angle(target.position-trasform.position,trasform.forward) < a){
            //then target is inside vision cone
            //next you can check vision distance ...
            //next you can check obstacles with a raycast ....
        }
     }

```

# Answer
> 1 votes
The Unity documentation has a good example on how to achieve this with a useful example.

http://docs.unity3d.com/ScriptReference/Vector3.Angle.html (example included below for illustration purposes)

```
using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour {
    public Transform target;
    void Update() {
        Vector3 targetDir = target.position - transform.position;
        Vector3 forward = transform.forward;
        float angle = Vector3.Angle(targetDir, forward);
        if (angle < 5.0F)
            print("close");

    }
}

```

Essentially what you are doing is calculating the angle between the enemy and the target. You achieve this through getting the forward vector of the enemy and then using Vector3.Angle to calculate the angle. Once you have this value you can then check if the angle is less than whatever angle you want to be the enemy's field of vision. If the angle is less than your field of vision then the target is in the enemy's field of vision.

This in itself is enough to provide a reasonable detection system but you may also want to factor in distance from the enemy (as the enemy may be short sighted?) This can be easily discovered through the use of the rather nifty Vector3.Distance function which is used as shown below.

```
var dist = Vector3.Distance(target.position, enemy.position);

```

Providing both of these values gives your enemy detection cone a look similar to the diagram below.

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


# Question
Title: Render sprites onto a virtual 640x480 "screen"
I'm making a game, and in part of it, the player uses a computer terminal. I want to draw to a virtual 640x480 screen with pixel precision, and then draw that "virtual screen" to the player's *real* screen. The end result will *not* be "pixel perfect" because 99% of people won't play the game at 640x480 -- and, in fact, I want to then go on and add further effects on top of this so it looks more like a CRT display -- but trying to figure out how to do pixel rendering in Unity has proven pretty difficult so far.

Basically I want to render something that looks like this:

onto the screen, where I draw all of the text characters myself (using Sprites? subsections of a Texture?), and then I want to render this "virtual screen" out onto the player's screen. I know RenderTextures are a thing, and maybe that's part of it? I've tried a lot of different things so far and got nowhere, hence why I'm posting here.

Sorry if this is too nooby of a question, I'm an experienced programmer who is relatively new to Unity.

# Answer
> 2 votes
You will want to use Texture2D.SetPixel or Texture2D.GetPixels and Texture2D.SetPixels if you want to blit sprites onto your texture.

You could render your sprites to a RenderTexture. It may be faster but until Unity5 it was a Pro-only feature (which I don't have) so I haven't experimented with it yet. You can't draw individual pixels on the GPU without a lot of complications though anyway, so if that is a requirement then you will need to use Texture2D.

For a 640x480 image, it should be sufficient to just do it on the CPU with Texture2D, even if you update it every frame.

# Answer
> 1 votes
I think Fuzzy Logic answer is best suited for your question (he got my +1), but i'd like to give a naif alternative. You can setup a bunch of Unity objects like quads, text, sprites (call all that TerminalStuff) and use a separate camera (call it terminalCamera) that capture the terminalStuff (perpendiculary). Then set the render output of terminalCamera to a texture In this way you can change your Terminal elements (like moving unity text objects to simulate scrolling text) to simulate terminal activity.

---
Tags: unity, c#, pixel-art
---


# Question
Title: How do I refer to a native library with Unity 5 on Android?
I have a library called `mylibandroid.a`. This is given to me by another developer. I also have the iOS version of this lib, and have been able to access it from Unity.

It is supposedly built for android. I have included it in my Plugins folder in my Unity 5 project, but I renamed it `mylibandroid.so` as droid libs use this naming convention. I can see the library included in the .apk file, so Unity seems to know it should go in there.

My code looks like this:

```
public class AlmoTest : MonoBehaviour
{
#if UNITY_ANDROID
    [DllImport("mylibandroid.so")]
    private static extern void FreeGlobals();

    public void TestFreeGlobalsButtonPress()
    {
        Debug.Log("Pressed");
        FreeGlobals();
    }
#endif
}

```

When my function is called, I get this error:

```
E/Unity   ( 4188): Unable to find mylibandroid.so
I/Unity   ( 4188): Pressed
I/Unity   ( 4188):
I/Unity   ( 4188): (Filename: ./artifacts/generated/common/runtime/UnityEngineDebug.gen.cpp Line: 56)
I/Unity   ( 4188):
I/Unity   ( 4188): DllNotFoundException: mylibandroid.so
I/Unity   ( 4188):   at (wrapper managed-to-native) AlmoTest:TestFreeGlobalsButtonPress ()
I/Unity   ( 4188):   at AlmoTest.TestFreeGlobalsButtonPress () [0x00000] in <filename unknown>:0

```

# Answer
As bitter said,

Your file should be named "libmylibandroid.so"

Drag and drop this file into your Unity Project

Then, when you call the lib, just write :

```
[DllImport("mylibandroid")]
private static extern void FreeGlobals();

```

and not :

```
[DllImport("mylibandroid.so")]
private static extern void FreeGlobals();

```

Hope that will be useful for someone :)
> 3 votes

# Answer
I think the reason you are having problems is because your library has a weird name. Normally libraries are called lib{name}.so and you import them by just specifying {name}. So, assuming you want to call your library foobar you name the file libfoobar.so and you import it using \[DllImport("foobar")\].

If that doesn't work try to unpack your Apk and make sure the libraries didn't get stripped for some reason.
> 0 votes

---
Tags: unity, android
---


title: Viewport and debug session

text:
# Question
Title: Viewport and debug session
I define and set viewport using this piece of code:

```
D3D11_VIEWPORT viewport;

viewport.Width = (FLOAT)pBspWindow->GetWidth();
viewport.Height = (FLOAT)pBspWindow->GetHeight();
viewport.TopLeftX = 0.0f;
viewport.TopLeftY = 0.0f;
viewport.MaxDepth = 1.0f;
viewport.MinDepth = 0.0f;

pD3DContext->RSSetViewports(1, &viewport);

```

If I remove MaxDepth/MinDepth members and run my application under debug session triangle will not be shown.

This behaviour doesn't appear under release session.

I searched on MSDN, but couldn't find anything.

I'm interested why is this happening?

# Answer
> 0 votes
You rely on uninitialized state. `D3D11_VIEWPORT` is a POD type, without any constructors or so. In this case, you can get different result each time your app runs.

In Debug mode, compilers initialize variables in different manner - they use Magic Debug Values, add guard bytes and much more to check for validity of your code. For instance, if you check values of your uninitialized viewport under debug session, you will probably see -107374176, which is `~0x06666660 + 1`. Probably it is a value chosen by MS to flag uninitialized floating point numbers.

In release version, none of this happens - all additional checks are disabled. So you probably hit a values, that are valid for D3D. Coincidence.

Basically, you can classify that (using variables, that were not initialized) as undefined behaviour.

---
Tags: directx11, viewport
---


title: Java Slick2D Image Glow Effect

text:
# Question
Title: Java Slick2D Image Glow Effect
How can one achieve a dynamic glow effect in Java Slick2d? I want an image to be surrounded by a glow when I move my mouse over it for example.

Example:

No glow

Glow

Is it possible to make this programmatically?

# Answer
I would suggest just making the image with a glowing effect, but if you must have it done in game then you would:

1) Render your scene or "glow objects" to texture A

2) Bind texture A, then using the horizontal shader, render a quad to texture B

3) Bind texture B, then using the vertical shader, render a quad to texture A

However This requires the following OpenGL extensions:

* GL\_ARB\_shader\_objects or GL20
* GL\_EXT\_framebuffer\_object or GL30

(You can find the full answer on the website below. The guy there explains it better than me)

http://slick.ninjacave.com/forum/viewtopic.php?f=3&t=4923
> 1 votes

---
Tags: java, slick, graphic-effects
---


# Question
Title: Why is my deferred lighting implementation so expensive?
I've implemented deferred lighting and I tried to put about 20-26 lights on the viewable space of my map, and it brings down the FPS from 61 to 28-31. It also makes my VGA temperature to go from 68°C to 72-73°C.

I feel this a bit weird, because it's just 2D, and I don't think my implementation should be so expensive as to halve my FPS. Is there a problem with my code and how I've implemented it? Or is there any other method for good lighting which costs much less then this?

My code is:

```
 Texture_Lights = RenderTargetBase.GetTexture();
 for (int i = 0; i < LightRef.Count; i++)
            {

                //Draw lights
                for (int techniqueindex = 0; techniqueindex < LightRef[i].Parent.effect.Techniques.Count; techniqueindex++)
                {
                    LightRef[i].Parent.effect.CurrentTechnique = LightRef[i].Parent.effect.Techniques[techniqueindex];

                    LightRef[i].Parent.effect.Parameters["time"].SetValue(((float)timer.Elapsed.TotalSeconds) * 0.0000158f);
                    LightRef[i].Parent.effect.Parameters["GameTime"].SetValue(timer.Elapsed.Seconds);
                    LightRef[i].Parent.effect.Parameters["lightPosition"].SetValue(
                        new Vector3(
                            (LightRef[i].Position.X-CameraX)/(1.0f/ZoomFloat),
                            (LightRef[i].Position.Y-CameraY)/(1.0f/ZoomFloat),
                            0
                            ));

                   LightRef[i].Parent.effect.Parameters["screenWidth"].SetValue(this.Width);
                   LightRef[i].Parent.effect.Parameters["screenHeight"].SetValue(this.Height);

                    for (int cx = 0; cx < LightRef[i].Parent.SelfTextures.Count; cx++)
                    {
                        LightRef[i].Parent.effect.Parameters[LightRef[i].Parent.SelfTextures[cx]].SetValue(RenderTargetBase.GetTexture());
                    }

                    foreach (EffectPass pass in LightRef[i].Parent.effect.CurrentTechnique.Passes)
                    {

                        GraphicsDevice.SetRenderTarget(0, RenderTargetLights);
                        GraphicsDevice.Clear(ClearColor);

                        spriteBatch.Begin(SpriteBlendMode.AlphaBlend, SpriteSortMode.Immediate, SaveStateMode.None);
                        LightRef[i].Parent.effect.Begin();
                        LightRef[i].Parent.effect.GraphicsDevice.RenderState.AlphaBlendEnable = true;
                        pass.Begin();

                        spriteBatch.Draw(
                         Texture_Lights,
                         new Vector2(0,0),
                        new Rectangle(0, 0, Texture_Lights.Width, Texture_Lights.Height),
                        Color.White,
                        0,
                        new Vector2(0, 0),
                        1.0f,
                        SpriteEffects.None,
                        0);

                        spriteBatch.End();
                        pass.End();
                        LightRef[i].Parent.effect.End();

                        GraphicsDevice.SetRenderTarget(0, null);
                        GraphicsDevice.Clear(ClearColor);

                        Texture_Lights = RenderTargetLights.GetTexture();
                    }

                }

            }

            GraphicsDevice.SetRenderTarget(0, null);
            GraphicsDevice.Clear(ClearColor);

            //Draw the Lightings #2
            if (Texture_Lights != null)
            {
                spriteBatch.Begin(SpriteBlendMode.AlphaBlend, SpriteSortMode.Immediate, SaveStateMode.None);

                spriteBatch.Draw(
                 Texture_Lights,
                 new Vector2(0, 0),
                new Rectangle(0, 0, Texture_Lights.Width, Texture_Lights.Height),
                Color.White,
                0,
                new Vector2(0, 0),
                this.ZoomFloat,
                SpriteEffects.None,
                0);

                spriteBatch.End();
            }

```

And my shader:

```
float GameTime;
float time;

texture2D colortexture;
texture2D normaltexture;

float ambient = 1.00;
float4 ambientColor = (1, 1, 1, 1);

float3 lightPosition = (230,230,0);
float4 lightColor = (120,120,120,120);
float lightPower = 0.27;

float screenWidth = 1000;
float screenHeight = 600;

sampler ColorMap = sampler_state
{
 Texture = <colortexture>;
};

sampler NormalMap = sampler_state
{
 Texture = <normaltexture>;
};

float4 DeferredNormalPS(float2 texCoords : TEXCOORD0) : COLOR
{
 float4 base = tex2D(ColorMap, texCoords);
 float3 normal = tex2D(NormalMap, texCoords);

 float3 pixelPosition = float3(screenWidth * texCoords.x, screenHeight * texCoords.y,0);

 float3 direction = lightPosition - pixelPosition;
 float distance = 1 / length(lightPosition - pixelPosition) * lightPower;
 float amount = max(dot(base + normal, normalize(distance)), 0);
 lightColor *= lightPower;

 float4 finalColor = (base * ambientColor * ambient) +
 (base * distance * amount * lightColor * ambient);

finalColor.a = base.a;

 return finalColor;
}

technique Deferred
{
 pass Pass1
 {
 PixelShader = compile ps_3_0 DeferredNormalPS();
 }
}

```

# Answer
Do not use full screen quads for your light volumes.

A simple way is to draw a sphere for each light, in the position that the light occupies and of the same radius.

This way, only the fragments actually affected by the light will be affected and your fragment shader will not be executed for the entire screen surface.
> 1 votes

---
Tags: xna, c#, 2d, hlsl
---


# Question
Title: Unity 3D - Confine a gun rotation within certain degrees
I am having troubles making my gun rotate up and down, and have limits, for example, I want the down limit to be 0 degrees, and the up limit to be 90 degrees.

Currently I can't figure out how to define that, and when the gun gets to one of the extremes, it gets stuck there and doesn't want to go back. Whats wrong?

Here's how I rotate the gun using an on-screen joystick

```
float lookAxisX = CrossPlatformInputManager.GetAxisRaw("VerticalLook");

        if ((transform.localEulerAngles.x <= 360 && transform.localEulerAngles.x > 270) ||
            (transform.localEulerAngles.x >= 0)
            ) {
            transform.localEulerAngles += new Vector3(-lookAxisX * 2f, transform.localEulerAngles.y, transform.localEulerAngles.z);
        }

        Debug.Log("transform: " + transform.localEulerAngles);

```

Also right now, when the gun is at the default rotation (facing forward, its X angle is 0, and when it rotates up, it goes from 0 to 359,9, and then at 270 it gets stuck

# Answer
First, it won't solve your problem, but there are a few general problems with your code.

1. The conditions for your `if` branch will always be true if transform.localEulerAngles.x \>= 0 and \<= 360. The \> 270 part is redundant since if x is less than 270, it is still possible to be \>= 0.
2. If x is 0 and lookAxisX is \> 0, then adding -lookAxisX will make x \< 0, meaning your `if` branch will never be enter again, unless you reset the rotation somehow. Vice versa if x = 359.9 and lookAxisX is \< 0.

That said... it's easier to use Mathf.Clamp(), as Marc Uberstein pointed out in his answer.

You also need to keep track of your angles separately from the transform, since as soon as you apply the angles to localEulerAngles, the 360 value will be reset to 0 and cause problems. That doesn't happen if you store it separately.

Tip: 360 degrees == 0 degrees! which is why it maxes at 359.9 :)

Try this:

```
using UnityEngine;
using System.Collections;

public class Example : MonoBehaviour {

    public float speedX = 2.0f;
    private float lookAxisX = 360.0f;

    void Update () {
        lookAxisX -= speedX * CrossPlatformInputManager.GetAxisRaw("VerticalLook");

        lookAxisX = Mathf.Clamp(lookAxisX, 270, 360);
        transform.localEulerAngles = new Vector3(lookAxisX, transform.localEulerAngles.y, transform.localEulerAngles.z);

        Debug.Log("transform: " + transform.localEulerAngles);
    }
}

```
> 2 votes

# Answer
You can always try to use the clamp method: Ref: http://docs.unity3d.com/ScriptReference/Mathf.Clamp.html

Example

```
transform.localEulerAngles = new Vector3(Mathf.Clamp(transform.localEulerAngles.x, 0f, 90f), 0, 0);

```

\**This is just a push in the right direction (above is untested)
> 1 votes

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


# Question
Title: Increasing friction or Adding force relative to transform position in Unity 2D?
Back again with a quick question! I have a few basic platforming mechanics going on in this scene. I have a prefab platform with an animation that loops back and forth between two different x positions, but does not begin looping until OnCollisionStay2D activates with my player object with the tag "Red cube".

But once the animation starts the red cube has very little friction with the platform and falls off. I have attempted to fix this AddRelativeForce in this script. Is there any way to increase the friction to where my player cube isn't slipping off? Or is there anyway to script my platform to add constant force to my player where I will move with platform seamlessly? Thank you so much for your time! You guys are a great help :)

```
using UnityEngine;
using System.Collections;

public class PlatformMovement : MonoBehaviour {

    public Rigidbody2D rb;
    public float speed;

    void Start()
    {
        rb = GameObject.FindGameObjectWithTag ("Red Cube").GetComponent<Rigidbody2D> ();
    }

    void OnCollisionEnter2D(Collision2D coll)
    {
        if (coll.gameObject.tag == "Red Cube")
        {
            Debug.Log ("Something has entered this zone.");
            GetComponent<Animation> ().Play ("Side To Side");
        }
    }

    void OnCollisionStay2D(Collision2D coll)
    {
        if (coll.gameObject.tag == "Red Cube")
        {
            rb.AddRelativeForce(new Vector2(speed, 0), ForceMode2D.Force);
        }

    }

    }

```

# Answer
> 1 votes
Try creating a physics material and adding it to your object and then in your code write the code below whenever you want to change the friction:

collider2D.material.dynamicFriction = YOUR VALUE HERE; collider2D.material.staticFriction = YOUR VALUE HERE;

(Dynamic friction is the friction while object moves and static is hen it isn't moving)

Make sure you have rigidbody on your game object.

You can find more on physics material here: http://docs.unity3d.com/Manual/class-PhysicMaterial.html

---
Tags: unity, platformer, rigid-body-dynamics, moving-platforms
---


title: How to draw a line in 3d space?

text:
# Question
Title: How to draw a line in 3d space?
I have a top down billiard game. And on click / tap the ball moves in the clicked direction like in the image below:

Now, I want a line to be drawn in the direction where the mouse is hovers or the finger is swiped, here is my update code:

```
void Update () {

        //this should make the line, why not working?
Vector3 forward = transform.forward;
Debug.DrawRay(transform.position, forward);
Debug.DrawLine(transform.position, transform.position + forward * 10000);

        if (Input.GetMouseButtonDown (0)) {

            //
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;

            if (Physics.Raycast(ray, out hit, 100.0f)){

                //

                //
                Vector3 startPos = transform.position;
                Vector3 clickPos = new Vector3(hit.point.x, hit.point.y, transform.position.z);
                Vector3 direction = Direction (clickPos - startPos);

                //direction
                rb.velocity = new Vector3(direction.x * 5, direction.y * 5, 0);

            }

        }

    }

```

I tried DrawLine, Drawray, any ideas?

# Answer
> 1 votes
Use a LineRenderer. That's a component which draws a line in 3D space.

# Answer
> 0 votes
Ask jhocking said you could use a LineRenderer and then apply a texture to it for the Ray to get the effect you want. LineRenderer could be easily controlled from a script.

---
Tags: unity
---


# Question
Title: What are the units when reading depth using glReadPixels()?
Suppose I use glReadPixels() to read the depth of a pixel from the depth buffer. What are the units of this? Is it the distance from the camera? Or the distance from the near clip plane? And is the distance normalized to clip space, or in real units?

# Answer
> 2 votes
Whatever you want them to be. From the documentation:

> Each component is converted to floating point such that the minimum depth value maps to 0 and the maximum value maps to 1. Each component is then multiplied by GL\_DEPTH\_SCALE, added to GL\_DEPTH\_BIAS, and finally clamped to the range 0 1.

Beyond the given ranges, it is up to you to interpret the data as whatever "units" you see fit, depending on the data you wrote *into* the depth buffer in the first place and what it means to you.

---
Tags: opengl, depth-buffer
---


# Question
Title: How to make sprite move in any direction?
I have an arrow sprite that rotates based on where my cursor is pointed, I can only make it move up,down,left and right.How about in a diagonal way?

```
//this is the rotation
nt x=Gdx.input.getX();
        int y=Gdx.graphics.getHeight()-Gdx.input.getY();

        double radians= Math.atan2(y - arrowSpr.getY(), x - arrowSpr.getX());
        float angle=(float)Math.toDegrees(radians)-85;
        arrowSpr.setRotation(angle);

//then the movement
arrowSpr.translateX(speed.x);
arrowSpr.translateY(speed.y);

```

# Answer
> 2 votes
I personally never calculate an angle like that. I like to work with vectors, it might be slightly less efficient but this way you can do it step by step, it gets more readable and easier to understand.

So what is a vector? A vector is essentially a direction and a magnitude together. Often in games it is used as a position data structure too but essentially a `Vector(10,10)` is vector pointing north east with a magnitude of `14.14` = `√(10²+10²)` (Pythagoras).

So what can we do with a vector? We can calculate direction, velocities, angles and more in 2D or 3D space. LibGDX does most of the math for you. You just have to know a couple of basic Vector rules to get the result you are after.

So let's first start by rotating your arrow.

```
//We need the origin of your arrow we will be rotating around and calculate the direction with.
Vector2 arrowOrigin;
//We need to mouse position to rotate the arrow to.
Vector2 mousePosition;

```

We can create a rotated vector between the points by subtracting the origin from the target.

```
Vector2 direction = mousePosition.sub(arrowOrigin);

```

We now have the direction from arrowOrigin to mousePosition. If you want to know the angle of the arrow to point to your mouse all we need to do is:

```
float angle = direction.angle(); // Angle in degrees from -180 to 180

```

Now we can use the direction vector to move your arrow towards the mouse. But remember when I said a vector is a magnitude as well? Currently that angled vector stretches has the same length as the distance between the two other vectors we got direction from. So if we add `direction` to `arrowOrigin` it would be instantly be on top of the mouse pointer. We can deal with this by normalizing the direction and make the total magnitude of it `1`.

```
direction.nor();

```

We can still use this vector for our rotation since nothing has changed there. If we a origin of `0, 0` and a target of `10,10` the previous direction vector would have been `10, 10`. what we just did is shrank the length of it to 1 by maintaining it's rotation. If we do this to all our vector movement we have a equal starting magnitude of 1.

Now let's make a velocity vector. At this time I have to warn you about how LibGDX deal with vectors. A vector is passed by reference by default and it's methods will work on the method itself. So if you do `velocity = direction.scl(100);` Then not only both velocity and direction have been scaled by 100, velocity is just a reference of direction. If there is something strange going on 99% of the time it's because of this. It gave me headaches when I started out with LibGDX. But luckely, we can just copy the vector.

```
float arrowSpeed = 10;
Vector2 velocity = direction.cpy(); //created a copy
velocity.scl(arrowSpeed); //scaled vector by the arrow speed

arrowOrigin.add(velocity); //Now move our arrow with the created velocity

```

I know it's a long wall of text and you didn't ask for it but as you can see. it are really just a couple of lines of very understandable code. Since Vectors in LibGDX make use of chaining methods you can even shorten all this.

```
//                     subtract       normalize/scale
velocity = mousePosition.sub(arrowOrigin).nor().scl(arrowSpeed);
angle = velocity.angle();

```

Now if you actually start adding velocity to your arrow it is important to know when to stop. If you are inventive enough you can calculate it yourself with the information I gave you, it's fairly simple. But why bother, LibGDX took care of everything.

```
//Distance
float distanceToTarget = arrowOrigin.dst(mousePosition);

if (distanceToTarget <= speed)
{
    //We have or almost arived on our destination.
    //We might want to set out arrow to it's destination
}

```

I love to work with Vectors this way so whether you use this or not, I hope you learned something from it.

I have created a very basic program for you that does what you want. Get it from github:

https://github.com/madmenyo/FollowMouse

The readme shows how to make it work.

# Answer
> 0 votes
I can't help you exactly with code because I'm not sure where all your variables are coming from. If you provide some context to this code, I can help more specifically.

In the meantime, take a look at this picture:

If you know how far you want the sprite to travel, and you know the angle. You can calculate the x and y distances using the formulas from the picture.

Hope this helps!

---
Tags: java, libgdx, rotation
---


# Question
Title: What's the difference between an .nbt and an .mca file?
What do I have to do if I want to save a .nbt file as .mca file? I got a byte array and all the data is OK. If I save the contents as a .nbt file I can open and view it with NBTExplorer. If I save it as .mca file NBTExplorer can't open it. What is the difference?

# Answer
The difference, based on the Minecraft wiki documentation, appears to be that `.nbt` is a binary format for storing arbitrary tree data. The Anvil format a type of region format, specifically for storing chunks of a Minecraft world.

An Anvil file might *contain* NBT formatted blobs of data describing individual aspects of the region, but the Anvil file itself is more a container of `.nbt` (and possible other data) than a a singular `.nbt` itself, and consequently it's very possible the `NBTExplorer` explorer tool simply isn't designed to open that kind of file.

It's also possible that despite your assertion, the data is not "ok" and may be malformed in such a way that it's parseable as a `.nbt` alone but when put within the structure of the `.mca` file, it causes some checksum or something to fail.
> 1 votes

# Answer
After a long and difficult research I finally found a post which describes how the anvil is saved in .mca files. Have fun! https://web.archive.org/web/20150405111040/http://wiki.vg/User:Sprenger120
> 0 votes

---
Tags: minecraft-modding
---


title: How animated block in voxel engine?

text:
# Question
Title: How animated block in voxel engine?
In my voxel engine (XNA 4.0) I'm use a vertex buffer for the entire chunk and update it after the set block, changing block metadata or light level. This is not too frequent operation compared with the time of mesh rebuild. But now I want animate some blocks, for example, make door opening or lever switching smooth.

If I remember right, in Minecraft all draw on the fly using OpenGL (correct if wrong), but in my case this is not an option.

I'm know what is a bone animation and how it works, and I think that I can make something like this for animatable block X:

1. rebuild chunk mesh without animated part of block X;
2. create entity looking like removed animated part and animate it;
3. remove entity and rebuild chunk mesh with that part in another static position.

I'm not shure this is a correct way. Any better ideas?

Also, how to make a block with animated textures? Do I need to use for this purpose a separate shader or I can somehow a correct texture coordinates of vertices in existed meshe?

Thanks.

# Answer
It's a good idea to keep your static terrain in a single buffer. Updating it for small changes is totally reasonable. However for something like an animation I think you're going to need to diversify your terrain system. Objects like doors, levers, and other objects that need to be animated should not be drawn with the same buffer as the terrain buffer. You're going to have to re-update a lot of data that hasn't changed every frame of the animation.

I think it's more reasonable to keep these animated objects as separate objects in your scene that are disconnected from the terrain. When you load your terrain from a file when you come across a door that you should draw, don't store that door block as a piece of your terrain, keep it as a separate block that has distinct logic and its own model matrix.

Some animated objects like blocks of water or lava could actually just be "animated" by using a fancy shader effect. Likewise other lighting effects could actually be handled by a shader (research physically based shading and hardware lighting).
> 3 votes

---
Tags: xna, c#, animation, voxels, minecraft-modding
---


title: Ray tracing - soft shadow

text:
# Question
Title: Ray tracing - soft shadow
I'm implementing my own ray tracer as an iPad app for a school project. At the moment this is the result:

I need to add the last requirement, **soft shadows**, but I can't find a complete reference anywhere. If I understood well, to implement this feature I have to shoot many rays from an intersection point to mt light source. This one must be an area light. Suppose i use a sphere, my questions are:

* which point on the sphere i must use to calculate the shadow ray?
* how do I average the result?

Thanks for helping me.

# Answer
First of all, you can implement soft shadows with a simple trick that doesn't even use area lights. This won't be as accurate, but is easy to implement and might be a good first step for you to get a feel for how soft shadows work. The idea is to shoot many test rays from your intersection point towards the point light source (as you mentioned) but to add a bit of an offset to each one, so that it goes close to your point light, but just misses. This offset can be a regular grid (good uniformity, but causes banding), completely random (non-uniform, but less banding), or a combination of the two, which I think gives the best of both worlds. You can then test these rays for intersection against other objects in your scene, as you would for sharp shadows. Then you can simply add up the number that hit something and divide it by the number of test rays. That fraction will range from 0 (no shadow) to 1 (fully occluded), and you can light your point based on that value.

Area lights add a bit of accuracy by giving you a specific area to target. By shooting your test rays at a collection of points on the area light, you get the same effect as the offset in the point light case above, but based on the actual shape of the light, rather than just a trick. Averaging the result will work just like the point light case. Selecting the collection of points in the shape can be done in a few different ways. I don't know which is best, but you can experiment and see which looks best to you. A few ideas to get you started could include random points inside the sphere, a uniform grid within the sphere, points on the surface of the sphere (uniformly or randomly distributed), or points on a disc within the sphere facing your intersection point.
> 2 votes

---
Tags: shadows, raytracing
---


# Question
Title: 2d character generator for android games
I am a developer, and not an artist. is there a 2d character generator that i can feed one picture and it will generate the proper files to be displayed for a running animation?

# Answer
There is no magical piece of software to do your art for you.

However there are tools to make it easier and I can recommend Spine. It was used at a studio I interned at. The artist there really liked it and it integrated well into Unity.

http://esotericsoftware.com/

Here's a tutorial that said artist wrote:

http://www.darkwindmedia.com/wulverblade-intro-to-skeletal-animations/

It's pretty straightforward but it should give you an idea about what the tool can do.

There are libraries to integrate Spine with Unity, Cocos2D, LibGDX and many more: http://esotericsoftware.com/spine-runtimes
> 0 votes

---
Tags: android, game-design, animation
---


title: Error SDK facebook and Unity3d 5

text:
# Question
Title: Error SDK facebook and Unity3d 5
I've tried everything anyone has seen this error?

Clicking the invite: I get the message "App Request dialog is not implemented in the Unity editor."

```
public void InviteFriends()
     {
         FB.AppRequest(
             message: "T...",
             title: "...."
             );
     }

```

Clicking share: "Share Link is not implemented in the Unity editor"

```
public void ShareWithFriends()
     {
       //FB.Feed or
       FB.ShareLink (
             contentURL: "http://apps.facebook.com/" + FB.AppId + "/?challenge_brag=" + (FB.IsLoggedIn ? FB.UserId : "guest"),
             contentTitle: "...",
             contentDescription: "....",
             photoURL: ";....",
             callback: LogCallback
             );
     }

     void LogCallback(FBResult response) {
         Debug.Log(response.Text);
     }

```

# Answer
> 0 votes
Solution for **Unity3d 5** And **facebook sdk 7.0.2**

first trade code

```
//GUI.ModalWindow(GetHashCode(), new Rect(windowLeft, windowTop, windowWidth, windowHeight), OnGUIDialog, "Unity Editor Facebook Login");
for
GUI.Window(GetHashCode(), new Rect(windowLeft, windowTop, windowWidth, windowHeight), OnGUIDialog, "Unity Editor Facebook Login");

```

in following path

> C:..\Assets\Facebook\Scripts\PlatformEditor\EditorFacebookAccessToken.cs

and "App Request" of "Share Link is not implemented in the Unity editor"

"App Request dialog is not implemented in the Unity editor."

just run the application simulating the cell

---
Tags: facebook, unity
---


# Question
Title: Move a sprite in a sine wave along different angles
I understand this piece of code

`Enemy.position.Y = StartPosition.Y + (-(float)Math.Cos(position.X / 100) * 100);`

However it only works along the X axis. What I want to be able to do is move it along an arbitrary axis; Set an angle as the x axis. How would I go about this?

# Answer
I'm not sure if I understand your question but here goes:

I think you want the sprite to wave over an angle back and forth: Not this is pseudocode (as you didn't state the language):

```
t=(t+wavespeed)%TwoPi;
a = Sin(t)*amplitude;
Position.X=StartPosition.X + Cos(angle) * a;
Position.Y=StartPosition.Y + Sin(angle) * a;

```

`t` controls the waving motion; the `wavespeed` variable is a small value like `0.01` (note that it should slowly range from 0 to TwoPi). `amplitude` is the maximum you want your sprite to move, `a` is calculated as the amplitude for that frame. `angle` is the angle of the axis you want your sprite to wave along.
> 2 votes

---
Tags: mathematics, graphics
---


# Question
Title: 2D Infinite Runner: how to manage the generation of dynamic terrain?
I'm creating a infinite runner game with Unity3d, i've been using math to generate the terrain by calculating the size/pos of the terrain and place the new one next to it, and it's working correctly, but i think it's a overkill, so the question is, Is there a better way(performance) to generate terrain/floor in 2d scrolling infinite runners?

I also tried this method which consist of using empty gameobject, and when you hit them it create the terrain it was okay, but then problem started when i started using different terrain generation

# Answer
As long as the player is alive, you can increase the offset of the texture. Basically the player stays still and the texture moves. Little cheating in this method as it takes around 20 lines of code and isn't fancy.
> 1 votes

---
Tags: c#, side-scroller, unity
---


# Question
Title: Are references to other games considered an infringement of copyright?
My team frequently reminisces about the games we grew up with in the 1990s, and we'd like to include references and Easter eggs that pay homage to this decade and that will invoke nostalgia or even make players smirk.

One example would be a character calling out another character: "Dude, why on Earth are you hiding in a stupid box?" (a reference to hiding in cardboard boxes from Metal Gear). Think of it as being similar to when the characters from Bad Company 2 teased the snowmobile level from Modern Warfare 2.

Would these sorts of references be considered copyright infringement? As far as I'm aware, this falls under parody and fair use, as it is neither used to capitalize on a specific game element (like basing our gameplay on people hiding inside cardboard boxes) nor does it directly reference a game character. To me, it seems more like paying homage to the companies making those games. Of course, when the time comes, we will consult with a lawyer and are willing to go as far as asking direct permission from the copyright owners.

But until then, I'd like to be informed on the topic.

# Answer
> 7 votes
It depends. You should consult a lawyer for each case to be sure (in particular since there are intellectual property laws *beyond* copyright that may or may not be involved, such as trademarks and - though it is unlikely - patents); I am *not* a lawyer and this is not legal advice.

If you have a character who sneaks around, and you have an Easter egg where that character hides in a cardboard box and somebody comments on it, that's fine. The concept of "using a cardboard box to hide" is not covered by copyright; you cannot copyright a concept.

If that character begins to bear a substantial similarity to any version of Solid Snake, then you're starting to get closer to the line, however. Parody and fair use can cover you here, but parody and fair use is surprisingly complicated and you will definitely want to involve a legal expert.

Copyright only covers works that have been put into a fixed and tangible form. This includes works of literature, musical composition and recordings of performance, recorded sound, architecture, and art (graphics, drawings, sculptures). But it doesn't include *systems and processes* and it doesn't prevent you from *talking about* or referring to the *existence* of a copy-written work. You just cannot use the work itself or anything derived from it.

(The above is only applicable to US copyright law; copyright law in other jurisdictions varies somewhat.)

*See 17 U.S.C. § 102*

# Answer
> 4 votes
No.

Concepts are not copyrighted.

If you use art from another game, that probably is copyrighted.

Given how many games actually intentionally copy previous games in very deliberate ways for the purpose of trying to sell well like the other games did, any humorous or nostalgic references should be far safer, as long as they aren't copying specific content.

# Answer
> 0 votes
There are 4 factors when bulding a defense of Fair Use to consider -

1. The purpose and character of the use, including whether such use is of a commercial nature or is for nonprofit educational purposes;
2. The nature of the copyrighted work;
3. The amount and substantiality of the portion used in relation to the copyrighted work as a whole; and
4. The effect of the use upon the potential market for or value of the copyrighted work

These four factors often play differently weighted roles from case to case,

See American Bar - Satire/Parody Fair Use

It would probably be really hard to prove damages from such "infringement".

The main idea behind copyright is to protect the vested interest of the copyright holder from losing value due to someone stealing the holder's work and passing it off as their own. Without a copyright law, the stealer could gain profit from the holder's work and the holder would have no legal recourse to gain back the lost value. When referencing other's work, you have to consider, does their work benefit from your perspective and provide mutual gain, or does your work benefit from the reference and hinder their's?

> One example would be a character calling out another character: "Dude, why on Earth are you hiding in a stupid box?" (a reference to hiding in cardboard boxes from Metal Gear).

Consider the factors:
1 - purpose of this character is commercial in nature, as even if it's a small event in your game, everything about it would be a commercial for the game
2 - no actual work is being copied here, only a reference to an idea
3 - no amount is copied, again only an idea is used
4 - one could hardly claim that MGS series would be out any consumers due to a minor reference in your game

Now for extreme contrast suppose you had this example:

> A character calling out to another character, who has a mullet and is smoking a cigarette while dressed in tactical sneaking gear, "Folid Flake, why on Earth are you hiding in a stupid box?"

Consider the factors:
1 - purpose of this character is commercial in nature, as even if it's a small event in your game, everything about it would be a commercial for the game
2 - the persona of Solid Snake is clearly captured in this work,
3 - the combination of the hair style, personality trait(smoking), similar appearance, and very close sounding name create a large portion of copied work,
4 - it is possible that some potential consumers of MGS thought your work was a legitimate MGS work, and those consumers only purchased your product because they thought it was Solid Snake

In the first example, it would probably be very easy to win the defense case of Fair Use due to each factor strongly favoring the defense. In the second example, the case could go either way, and depends on how strongly each factor was argued and how much it was shown to weigh into the argument. It's key to remember that copyright claims are 'reactive', so a copyright holder has to feel infringed upon to enact it. Therefore, the "grey area" cases are only an issue when actual damages are occurring.

In any case, an extreme example, like one where Solid Snake's persona was so accurately copied that you would think Konami/Kojima was credited but was not, is a clear violation.

# Answer
> -2 votes
If creating easter eggs and pop culture references to other media was copyright infringement, I doubt games that are filled with them like World of Warcraft (an entire zone dedicated to Indiana Jones), Sam & Max (an entire episode dedicated to spoofing MMOs) and many others would still have them.

In fact, if it's clear that you're making fun of them, and the reference isn't the schtick of the entire game, it likely falls under the parody clause of fair use. IANAL, so consult a lawyer.

However, I am going to give the related remark that pop culture references can and will be outdated quite fast, and can even make it cringeworthy. To give an example from a popular webcomic: Andrew Hussie's Homestuck had a major character use a computer that looks like Bill Cosby. Back in those days, that was just a goofy reference. Nowadays though, with Cosby being involved in sexual abuse scandals, it was somewhat cringeworthy to read how a teenage boy praises his machine.

In addition, you might run into a player that does not get the reference at all. MGS may have sold millions of copies and be quite known, but if you make a reference to a game that didn't sell as well, there's a good chance the player gets confused about it.

Now, I'm not saying you shouldn't put references into them. I'm just saying that your game should still make sense without them. References are a good way to add some flavor to areas that would otherwise be uninspired and bland. For example, if your game is an open world gangster game and you have a coffee table that would otherwise be empty, put a magazine on it with a cover dedicated to Devil's Column or something (as a reference to Saint's Row).

In short: you're generally fine with references, but don't go overboard with them, make them audience-appriopriate (don't go putting blow-up dolls in kiddie games) and be aware that they might be misunderstood or even cringeworthy if the wrong events happen.

# Answer
> -3 votes
this Will help even More not a copyright 1-Hyperdymention neptunia: refrence " hey look at those guys using martial art to break a car.. geez dont they have any thing better to do?" cuz its a parody 2-Skyrim: in a mountain u can find a Pick Axe called Great Notch Pick Axe. is not a copyright since its Paying respect for a real guy. 3- dont remember which game i heard this from but a character was mocking another character for having a spikes on his back like sonic and have some other superpower and said to him "oh i thought the only thing you can do is spin really fast and collect Rings" (lol) any those are examples for non copy rights references you can see more in youtube

by the way make your character pays condolences on other character from another game company (Like bow infront a tomb stone that hints its for whom (without writing the character name since name is copy right) which other company like to see stuff like this and might ends in them paying you with the same respect or more) Which is this what am doing now for my game its preferred to notice them in advanced if its the first time referencing them.

Your welcome

---
Tags: legal, copyright
---


# Question
Title: How do I get GL.IssueRenderEvent to work on iOS with Unity 5?
I'm trying to get GL.IssuePluginEvent to work, according to this: http://docs.unity3d.com/Manual/NativePluginInterface.html

I have a plugin made with this code:

```
extern "C"
{
    void UnityRenderEvent (int eventID)
    {
        NSLog(@"Got render event.");
    }
}

```

I can call that function directly from Unity, and it works; I'm sure I've built the plugin correctly, and included it in the project correctly. But when I do `GL.IssuePluginEvent(0)`, nothing happens. Some idea what I could be doing wrong? According to Unity's demo, this is all that has to be done. I think.

I know that in their example, they have it defined as `void EXPORT_API`, but I found this in their code example:

```
// Attribute to make function be exported from a plugin
#if UNITY_METRO
#define EXPORT_API __declspec(dllexport) __stdcall
#elif UNITY_WIN
#define EXPORT_API __declspec(dllexport)
#else
#define EXPORT_API
#endif

```

So on iOS, `EXPORT_API` becomes `""`.

# Answer
From Unity 4.5, you have to register the event.

"iOS: Added support for render events (GL.IssuePluginEvent). Please note that you need to manually register them, as iOS do not support dynamic libraries. Check trampoline for UnityRegisterRenderingPlugin function."

For example:

```
#import <UIKit/UIKit.h>
#import "UnityAppController.h"

extern "C" void UnitySetGraphicsDevice(void* device, int deviceType, int eventType);
extern "C" void UnityRenderEvent(int marker);

@interface MyAppController : UnityAppController
{
}
- (void)shouldAttachRenderDelegate;
@end

@implementation MyAppController

- (void)shouldAttachRenderDelegate;
{
    UnityRegisterRenderingPlugin(&UnitySetGraphicsDevice, &UnityRenderEvent);
}
@end

```

So you just have to do some editing of UnityAppController.mm after you build the project. If you do "Append" it will leave your edits in place.
> 0 votes

# Answer
This is a comment, but I don't have enough rep on this site (though I do on stack exchange). Re: Almo's answer, there's a bit of a bug (at least for me) in the whole plugin setup in that if you have more than one plugin, and they both implement `UnityRenderEvent`, XCode seemed to resolve my callback to the other plugin's function. Mine never got called.

On one hand, this made sense, all the functions are compiled statically and linked and have unmangled C names, so I can easily see how it can jump to the wrong one... BUT, I would have expected a multiple-symbol link error, and never got one.

My solution to this was just to have a different function name for IOS and call that above. But hopefully this might help someone...
> 0 votes

---
Tags: unity, plugin
---


# Question
Title: Why is my enemy hovering in the air when chasing the player?
In Unity, I have created an enemy AI and applied a script for it to move and chase the player. But when moving, the enemy hovers in the air. My character also does not have a rigid body, he just has character controller and my enemy AI is child object and an empty object as parent object. I added this to do animation. This is my enemy AI script created in C#:

```
using UnityEngine;
using System.Collections;

public class AdvancedAi : MonoBehaviour

{
    float distance;

    public float lookAtDistance, chaseRange, attackRange, moveSpeed, damping, gravity, attackRepeatTime;
    public Transform target;
    public CharacterController controller;

    private Vector3 moveDirection = Vector3.zero;
    private float attackTime;

    //TODO: add in a function to find controller and to locate and assign the player as the target

    void Start()
    {
        attackTime = Time.time;
    }

    void Update()
    {
        distance = Vector3.Distance(target.position, transform.position);

        if(distance < lookAtDistance)
        {
            LookAt();
        }

        if(distance > lookAtDistance)
        {
            GetComponent<Renderer>().material.color = Color.green;
        }

        if (distance < attackRange)
        {
            AttackPlayer();
        }

        else if (distance < chaseRange)
        {
            ChasePlayer();
        }
    }

    void LookAt()
    {
        GetComponent<Renderer>().material.color = Color.yellow;
        Quaternion rotation = Quaternion.LookRotation(target.position - transform.position);
        transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * damping);
    }

    void ChasePlayer()
    {
        GetComponent<Renderer>().material.color = Color.red;

        moveDirection = transform.forward;
        moveDirection *= moveSpeed;

        moveDirection.y -= gravity * Time.deltaTime; // doesn't seem to work right :(
        controller.Move(moveDirection * Time.deltaTime);
    }

    void AttackPlayer()
    {
        //TODO: Need Attack Animations
        if (Time.time > attackTime)
        {
            Debug.Log("Attack");
            attackTime = Time.time + attackRepeatTime;
        }
    }

    void ApplyDamage()
    {
        chaseRange += 30;
        moveSpeed += 2;
        lookAtDistance += 40;
    }
}

```

# Answer
> 2 votes
```
CharacterController controller

```

Has a `radius` and `height` that define its space occupation. (the green cage in the image). That cage (capsule) interact with othe colliders (i.e : the terrain). If the cage its too big respect the enemy shape, you see it fluctuate, because the cage bottom touches the ground.

# Answer
> 0 votes
Your todo can be done with, FindGameObjectWihTag ("Player") as there will only ever be one player per instance unless you're doing multi-player.

Damping has no value.

You need a value for gravity on the empty otherwise you have 0 gravity and you're reducing to \<0 which would cause it to float.

---
Tags: unity
---


# Question
Title: Rotating the view around the origin of the world coordinate system
In OpenGL (using shaders), I want to implement a system that will take the user's mouse as input, and then rotate the view about the origin of the rendered scene. So, I need to compute the view matrix (assume the model matrix is identity) that represents this rotation. If the view were to rotate around its own origin, then I could do this by applying a simple rotation operation to the view matrix. However, I don't want to do this -- I want to rotate about the origin of the world coordinate system. So, given a rotation angle "theta", how can I compute this matrix? Thanks!

# Answer
I would recommend you use the mat-library `glm` and something like the following:

```
double theta = glm::radians(90);
glm::vec3 camera(cos(theta), 0, sin(theta));
camera *= 5; // To get some space between camera and object
glm::mat4 matrix = glm::lookAt(camera, glm::vec3(0.0, 0.0, 0.0), glm::vec3(0.0, 1.0, 0,0));

```

This *should* give you the result you're looking for.
> 1 votes

---
Tags: opengl, rotation
---


title: Personal Custom Card Game

text:
# Question
Title: Personal Custom Card Game
I had the idea, to make a custom card game based off an Anime i like. I was wondering if it would be legal to have such printed out (using a custom card/board game service) for personal use. I would only play it with friends and not make any money off of it.

# Answer
A printer service probably don't want to print such cards. I am not a lawyer, but the way it has been explained to me is that from a legal perspective, they print the cards and *sell them to you*. If you have them print cards of your design you basically license them to print that design on a set of cards. The printer could be in legal trouble if they print stuff and sell the printed materials to you.

Quote from The Game Crafter:

*Can I make a game using copyrighted items if I don't intend to sell it to others?*
We are **not** able to print games containing copyrighted items used without permission, **even if they are intended for personal use only**. https://www.thegamecrafter.com/help/intellectual-property

It doesn't mean *all* print-on-demand services verify or comply to this, but this is the legal stuff what I understood from TGC staff.

Some services out there try to move the legal burden to you by having you tick a box "yes I own all rights", but in the end AFAIK the printer could still be sued for infringement if they knowingly print and sell you the stuff.
> 2 votes

---
Tags: game-design, legal, card-game
---


# Question
Title: Character controller passes through mesh collider
I need a little help figuring out what's going on with an NPC's character controller. Here are the character controller settings for the NPC.

The problem I'm running into is that the NPC isn't walking up a slight gradient as it should; instead, it moves **through** the ground.

Below are the settings for the ground.

The NPC isn't on the ground- it is a few units off. Any help is greatly appreciated.

Thanks in advance...

# Answer
Use a raycast or this script. http://forum.unity3d.com/threads/groundnpc.181705/#post-1241872

Don't add a `Rigidbody` if you use the controller. It breaks it big time.

And check off convex on the mesh collider for your terrain. Try this first before adding a script. I remember having this problem before and that's all it took.
> 0 votes

# Answer
This is an update to a script found here:

This is a simple fix that prevents NPCs from walking through sloped mesh.

```
#pragma strict

var gravity = 20.0;
var verticalSpeed= 0.0;
private var collisionFlags : CollisionFlags;  // The last collision flags returned from
                                              // controller.Move

function Update()
{
    ApplyGravity();

    // Calculate actual motion
    var movement = Vector3 (0, verticalSpeed, 0) + Vector3.zero;
    movement *= Time.deltaTime;

    // Move the controller
    var controller : CharacterController = GetComponent.<CharacterController>();
    collisionFlags = controller.Move(movement);
}

function ApplyGravity()
{
    verticalSpeed = IsGrounded() ? 0.0 : verticalSpeed - gravity * Time.deltaTime
}

function IsGrounded()
{
    var controller : CharacterController = GetComponent.<CharacterController>();
    return (controller.collisionFlags == CollisionFlags.Below);
}

```
> 0 votes

---
Tags: unity, collision-detection, game-design
---


# Question
Title: Best way to manage weapons as GameObject on a script in Unity with C#
I have a player game-object with a script Player. In the Player script I have a public properties weapons.

I want to have to just drag in this properties a script/prefabs. And the Player script must can get the properties of the weapons selected.

**For example:** imagine, we have two weapons, one is a **pistol** with **5 attack power**, the other is a **knife** with **7 attack power**.

Now I want to set pistol in the Player script.

What should I drag here ? A game-object with a weapon script ? Or a weapons script who instantiate a weapon ? Or maybe an another solution ...

The idea is to be able to create easily some weapons without scripting more. Just place a sprite, and modify some properties.

# Answer
> 1 votes
You can always just stuff all weapons in one big list and access them with an index.

```
[System.Serializable]
public class Weapon
{
    public string name;
    public float damage;
}

[System.Serializable]
public class Player
{
    public Weapon[] weapons;
    public int currentWeapon;
}

public Player player;

```

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


title: LibGDX buttons bounds are wrong

text:
# Question
Title: LibGDX buttons bounds are wrong
I am making a simple gui in libgdx and run into this problem ; when you click on the button it's bounds (?) are wrong since if I click under it, the game registers it as a click.

On the other end, if I click it at the top it won't get the click. It seems like the bounds are a bit under the button. I tried to set manually but nothing.

Also i tried changing sizes.

Looked here : too this is almost the same but no answer..

```
tabl = new Table();
    stage =new Stage();
    tabl.setSize(stage.getWidth()/2, stage.getHeight()/2);
    tabl.defaults().size(500, 40);

    g = game;

    Gdx.input.setInputProcessor(stage);

    skin = new Skin();

    TextureAtlas te = new TextureAtlas(Gdx.files.internal("uiskin.atlas"));

    skin.addRegions(te);
    skin.add("default-font", new BitmapFont());
    skin.load(Gdx.files.internal("uiskin.json"));

    Pixmap r = new Pixmap(100,100,Format.RGBA8888);
    r.setColor(0xff0000ff);

    r.fillRectangle(1, 1, 13, 13);
    Texture s = new Texture(r);
    SpriteDrawable s1 = new SpriteDrawable(new Sprite(s));

    TextButton gam = new TextButton("new games",skin);

    gam.addListener(new InputListener() {
        @Override
        public boolean touchDown(InputEvent event, float x, float y,
                int pointer, int button) {
            // TODO Auto-generated method stub
            //g.setScreen(null);
            new Logger("e").setLevel(10);
            return true;
        }
    });

    /*super.getS*/
    LabelStyle tt = new LabelStyle(new BitmapFont(), Color.BLUE);
    Label l = new Label("d",tt);

    tabl.add(gam);

    tabl.setDebug(true);

    stage.addActor(tabl);

```

# Answer
Not exactly sure what is going but I always create a stage with a viewport (with or without a camera). Something like this:

```
stage = new Stage(new ScreenViewport());

table = new Table();
table.alight(Align.top | Align.center);
table.setFillParent(true); //To have it fill the screen

TextButton button = new Button("Click me", skin);
button.addListener(new ClickListener()
{
     @Override
     public void clicked(InputEvent event, float x, float y)
     {
          system.out.println("You clicked me!")
     }
});

table.add(button);

stage.addActor(table);

```

I did not test the above but it should create a table with a button at the top of the screen. The bounds should be perfect as well. Try it, there is not much code and recreate it step by step. If the code above does not work let me know, sometimes this scene2D stuff gives me headaches too :).
> 0 votes

---
Tags: libgdx
---


# Question
Title: Make camera follow and rotate with player without childing it
I want to have a camera, that follow the player, without childing it to the player object. So far I have this one line, that follows the player, but does not rotate with it (meaning the camera should look where the player's front is looking, how can I do it?

```
transform.position = player.transform.position + offset;

```

# Answer
Something like this:

```
transform.position = player.transform.position - player.transform.forward * distance;
transform.LookAt(player.transform);

```

where float distance is the distance of camera form player

Consider also the solution 2 : Make camera child of player and in your player die script , you can "deatach" camera from player object

```
transform.parent = null;

```
> 2 votes

# Answer
You can multiply vector3 by using vector3.cross(vector a, vector b);

And here, its not multiplying to vector3. Its multiplying to just z axis. Transform.forward is z axis.
> 0 votes

---
Tags: unity, camera, rotation
---


title: glm Z coordinates are flipped

text:
# Question
Title: glm Z coordinates are flipped
I am trying to render a 3D model using OpenGL. For the projection and transformation matrices, I am using glm. I've got my model on the screen and it works just like I intended it to; except one small problem.

I am setting the model's translation matrix as

`glm::translate(glm::vec3(0, 0, 4))`

to move the model a little bit forward so that I can see it. Since in OpenGL, by default, negative z is out towards the 'camera' and positive z is forward, I expected this to work but it doesn't. It only works if I set it to

`glm::translate(glm::vec3(0, 0, -4))`

But this seems weird to me, as I am setting my `zNear` to 0.01 and `zFar` to 1000. Is glm's z values flipped or am I doing something wrong here?

Here is my code:

```
glm::mat4 rotation = glm::mat4(1.0f);
glm::mat4 translation = glm::translate(glm::vec3(0, 0, -4));
glm::mat4 scale = glm::mat4(1.0f);

glm::mat4 modelMatrix = translation * rotation * scale;

glm::mat4 projectionMatrix = glm::perspective(70.0f, aspectRatio, 0.01f, 1000.0f);

glm::mat4 transformationMatrix = projectionMatrix * modelMatrix;

```

# Answer
> Since in OpenGL, by default, negative z is out towards the 'camera' and positive z is forward

You're wrong. OpenGL uses a right-handed coordinate-system where `x` is right, `y` is up and `z` is into the camera, therefore `negative z` is forwards.
> 1 votes

---
Tags: opengl, c++, 3d, transformation, glm
---


title: How to package a Windows c++ game?

text:
# Question
Title: How to package a Windows c++ game?
**When you buy a game at the store, and want to play it on your computer, you do the following:**

1. Run a setup.exe
2. Install on computer
3. End up with an exe on your desktop (separate from its source files, asset files, etc.)

**How do I format my program (created from Visual Studio) to be like that?**

The farthest I have toward this goal is how my folder is currently structured:

**If you do not know how to completely separate my .exe from my source and asset files, then do you know how to be able to put my source, header, and sfml DLL's into a folder like the following:**

**Or do you know how to just bundle everything into one executable package?**

# Answer
> 1 votes
Visual Studio Professional has a "Setup project" type of project that creates a Windows Installer (msi) setup program. For versions up to 2010, it was bundled, and for 2013, there is an extension which does this.

As it is bundled with Visual Studio, it has only the most basic features, but can make a complete installer that will install prerequisites, do custom actions, and allows for some basic customization of the GUI.

When testing it, I recommend you create a virtual machine with a pristine copy of each Windows version you want to target, save the image, and try the installer. When you're finished, revert to the pristine copy, and try again if necessary. I use Virtual Box, but any virtual machine software should work.

The reason behind this is that depending on the libraries you use, a pristine install may not have the necessary DLLs, and a mere file copy will not be sufficient for the user to play your game. The Setup project helps you create an installer which includes all the necessary prerequisites so the game can be safely distributed to end users.

---
Tags: c++, distribution
---


title: How to use custom font in Phaser?

text:
# Question
Title: How to use custom font in Phaser?
I am trying to load `WebFont` in Phaser. I have seen the Phaser example, but I can't understand what asset do I need, what function I have to call, & what exactly should my javascript file look like?

# Answer
> 0 votes
```
var game = new Phaser.Game(480,350,Phaser.CANVAS,"GameContainer");

var GameState = function(){
//var font;
};

GameState.prototype.preload = function(){
    this.load.bitmapFont('pixelArt',"assets/fonts/pixel-Art.png","assets/fonts/pixel-Art.xml");
    // note : The xml file should be saved with UTF-8 encoding or some browsers won't load it.
};

GameState.prototype.create = function(){
   this.font = this.add.bitmapText(20,80,"pixelArt","This is a test line",15);
                // add.bitmapText(x,y,"fontKey",'Text',fontSize);
};

    game.state.add("gameState",GameState);
    game.state.start("gameState");

    // Here I am giving some tips about rendering font and tools that may help.

    //1. Bitmap font generator (Online) - http://kvazars.com/littera/
    //2. Bitmap font editor             - http://www.angelcode.com/products/bmfont/

    // Note : when you generate bitmap font using the first link,
    // Make sure you select XML (.fnt) as the output under the format dropdown.
    // It should by enabled by default. After download the exported zipfile you found a .png file and
    // .fnt file simply change the extension of .fnt to .xml then your are done.

```

and save it into a javascript file and link to a html file and you are done.

---
Tags: javascript, phaser
---