# Question
Title: (LIBGDX) args instead of variables names
I added Kryonet to my libgdx project like this...

Created a "libs" folder in core project, droped kryonet.jar in there. In build.gradle of the root project added this line:

```
project(":core") {
   ...
   dependencies {
    ...
    compile fileTree(dir: 'libs', include: '*.jar')
   }
}

```

## But I keep seeing "arg" instead of the variable names

# When I try to see the class this is what it shows:

No button to attach source is being displayed.. Any Ideas?

# Answer
> 1 votes
I'm not an expert, but I believe the problem is that you're only including the binaries, so your IDE can't figure out what the original variable names were. If you include the source code as well, that lets your IDE be a little smarter.

I would propose an alternative implementation- instead of putting those JAR files in a libs directory, add them to your gradle file as maven imports instead as follows:

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

    dependencies {
        // ... your other compile lines here
        // Add the kryonet line below:
        compile "com.esotericsoftware:kryonet:2.22.0-RC1"
    }
}

```

This appears to add everything the IDE needs to both import the code and label the parameters.

---
Tags: java, libgdx
---


# Question
Title: How can I change the highlighted color of a Unity button when it's clicked?
I was playing around with buttons in Unity, and I wanted to see if I could change a button's highlighted color every time I clicked on it. I added a script in the same GameObject as a button component, and I had a `changeColor` function attached to the component's OnClick(). The function was in a ButtonScript class written like this:

```
public class ButtonScript : MonoBehaviour {
    public Button button;

    public void changeColor() {
        Debug.Log ("Changing highlighed color");
        int r = Random.Range (0, 255);
        int g = Random.Range (0, 255);
        int b = Random.Range (0, 255);
        Color currentColor = button.colors.highlightedColor;
        currentColor.r = r;
        currentColor.g = g;
        currentColor.b = b;
    }
}

```

I couldn't do `button.colors.highlightedColor = new Color(r,g,b);` because I got a "Consider storing the value in a temporary variable" error. When I tried a test play and clicked the button multiple times, the highlighted color didn't change. How can I make a function that changes a button's highlighted color when it's clicked, if it's possible?

# Answer
I found that I needed to reassign `currentColor` to `button.colors.highlighted` afterwards. Oddly, I couldn't do `button.colors.highlightedColor = currentColor`, but I could reassign to the `ColorBlock` that `button.colors` returns (I got the idea from vexe's comment here). I also saw that the Color constructor takes floats from 0 to 1, not ints from 0 to 255 (even so, should've been `Random.Range(0,256)`. Here's the class that worked for me:

```
public class ButtonScript : MonoBehaviour {
    public Button button;

    public void changeColor() {
        Debug.Log ("Changing highlighed color");
        float r = Random.Range (0f, 1f);
        float g = Random.Range (0f, 1f);
        float b = Random.Range (0f, 1f);
        ColorBlock colorVar = button.colors;
        colorVar.highlightedColor = new Color (r, g, b);
        button.colors = colorVar;
    }
}

```
> 4 votes

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


title: Finding N shortest paths

text:
# Question
Title: Finding N shortest paths
I know about several of path-finding algorithms that exist: depth-first search, Dijkstra's algorithm, A\* etc.

Now I would like an algorithm that gives me the N paths with lowest cost. Can this be obtained by some simple modification of one of the above? Or is a different algorithm needed, and if so which?

# Answer
> 3 votes
Yes, you can modify these algorithms to find different shortest paths, with a few caveats.

First, there can be an exponential number of shortest paths. Consider a simple chessboard example, where you're trying to travel from the top-left corner to the bottom-right corner. Since a chessboard has 8x8 squares, you just need to travel to the right 7 times, and down 7 times, in any order. One way to find different paths is to use **tie breakers that tend to produce different results**. For example, you can try a tie breaker that always moves horizontally before vertically to produce one path, then one that does the opposite.

Then there's the question of how different you want the paths to be. Would you prefer paths that are as short as possible, even if they are virtually identical? Or would you rather look for paths that are as different as possible, at the cost of taking long detours?

Here's one example algorithm you can try: **modifying A\* so that it penalises nodes that have been used previously**: http://jsfiddle.net/3huzrpyk/

This algorithm, based on this, simply looks for two paths. The second path (blue) uses a custom cost function (the g(x) part) that penalises nodes that are already used by the first path. The penalty can be customised - low values means it tries to maintain very short paths, high values (like the image) means it tries to avoid repeating nodes even if it must take a longer detour.

---
Tags: path-finding
---


title: Lwjgl on android

text:
# Question
Title: Lwjgl on android
How do I compile a lwjgl program written in java with openGL and glfw to run on android. I Should use openGL es for android..But how to create context for gles and input for touch screen.

Update:

In general how do I port openGL game written in java to android

# Answer
> 1 votes
You can't use LWJGL on android because it uses normal OpenGL, while android only supports OpenGL ES. You need to rewrite your app with the one given by the android SDK.

Although there is a support for normal GLES, you can't get inputs like touches, swipes, sensors, erc.

---
Tags: android, lwjgl3
---


# Question
Title: Can I develop games for mobile platforms in C++?
I have a good grasp in C++ and C and have also experience developing AAA game using C++. Now, I'm shamelessly thinking to dive into mobile game development either in iOS or Android. Unfortunately, I don't know objective-C and java and neither have courage to learn it. So, As above mentioned reason, Is there any possibility to do mobile development in C++ without using any single statement of JAVA and Objective-C ?

# Answer
Some objective C has to be written for iPhone apps. That being said, you can write a pretty thin layer of obj-c and then do all you game code in C or C++.

On android look up the NDK. I don't have any experience with it, but it promises to be a native sdk so you should be able to write most things in C or C++.

That being said, you're artificially limiting yourself with the language barrier. On iOS, if you want to do anything with the OS layer (like GameCenter, their social platform), or use any kind of middleware, you'd probably be faced with an objective C API.

I can kind of understand the sentiment. C++ in particular is a huge language. But obj-c isn't a big. It's a bolt on to C (so the fundamentals should be familiar) with a few extra things added on top. It isn't nearly as complex or deep as C++.
> 13 votes

# Answer
I've been writing a game for quite a while in c++ for Android. I have to touch the java code once every few weeks, but for the most part I modified one of the sample apps that comes with the NDK and have written c++ otherwise. I've had to do a bit of JNI work as well, which is never fun. However, I have many years of java experience, so having to write java or JNI doesn't particularly slow me down.

My game runs just as well on my linux box as it does on my test devices. The linux version is pure C++ and the trouble I went through to make this work pays for itself every time I make an iterative change to my game.

My project has 836 lines of java code, 331 lines of hideous jni C code and about 40k lines of C++ code.
> 7 votes

# Answer
There is also Marmalade which allows you to use c++ to create mobile applications for a broad range of devices such as iPhone, Android, Win Mobile, Bada, and some more.
> 4 votes

# Answer
I'm using cocos2d-x for a while, it's a game engine based on c++. (it actually a c++ port of cocos2d-iphone). using this engine you can easily run and test your codes on windows and then compile the same code for iphone/android export.
> 2 votes

# Answer
# If you really want just C++, Marmalade might be good for you

But for full capabilities you have to use at least some objective-C *(or java, but i'm talking about "full capabilities")*. But with a thin layer of objective-C you could do so much, so I reccomend you look in to iOS development with Xcode.

---

***If you have a mac look at Xcode, if not, try corona with lua instead.***

There are many ways to max your C++ code to be run on the iPhone. A **free program on the mac app store** could help increase C++ use in Objective-C based products:

## It's called objective-C++ Preprocessor Headers

This allows you to do even more with C++ rather than Objective-C.

**iOS programming:**
> 1 votes

# Answer
Yes, you can use C++ programing language to develop mobile games. C++ gaming application always feel a little snappier than Java on the same hardware. So, if you are expert in C++ and interested to develop Android game then it is now easy and zero-cost as programing in Java.
> -3 votes

---
Tags: c++, java, android, ios, objective-c
---


# Question
Title: What technologies are used to develop games for tablets and iPhones?
1. What technologies are used to develop games for tablets and iPhones?
2. Would Flash be commonly used?
3. Is HTML5 capable of animation and interactivity, or would a game file simply be placed within HTML5 code?
4. Is Flash and HTML5, and then wrapping the game for different phone/tablet operating systems a common combination?

# Answer
1. C/C++ and/or Objective-C are used to develop games for iOS (iPad/iPhone). Java or C++ (using NDK) is used to develop for Android. Usually OpenGL ES is being used for rendering on these devices. There are engines like Unity, Shiva or Corona that allow publishing to different devices. These engines usually come with an own editor and you program in C#, Lua or Javascript.
2. Flash isn't very common (at least when it comes to games) because of performance concerns.
3. Technically yes, but the tools and frameworks for HTML5 development are currently not on the same level as something like Unity. Also the different devices have different browsers which may require browser-specific workarounds. The performance is also heavily dependent on the JavaScript engine that's being used. You won't be able to achieve the same performance as with a native app (if that matters for your game).
4. No, because Flash content doesn't run on iOS and Adobe discontinued development of their mobile flash player. With Adobe Flash CS5.5 or Flex Builder 4.5 you can export your AIR app as native app for iOS, Android or Blackberry though.
> 6 votes

# Answer
iOS devices such as iPhones and iPads don't support Flash at all. There are a few HTML5-based games, s HTML5 is capable of animation and interactivity. You might want to look at OpenGL.

There's a great book called iPhone Game Projects, and another great book (for Android-based devices) called Pro Android Games.
> 0 votes

# Answer
Use of flash is good but the old concept. You can use HTML5 which is latest technology coming in mobile game development you should start. It is very much user-friendly and capable with animation and interactivity.
> 0 votes

---
Tags: iphone, flash, html5
---


title: Text shows the wrong way - Unity bug?

text:
# Question
Title: Text shows the wrong way - Unity bug?
I was working in the next scene, the font I used has worked well in another scene, but why when I go back to this "main menu" scene does the font look destroyed (previously show well)?

Screenshot :

I tried everything from resizing, reinputting text, and redownloading the font asset but it keep show like this. Any thoughts?

# Answer
> 2 votes
reinstalling unity fix the problem !

---
Tags: unity, bug
---


title: Null reference exception error

text:
# Question
Title: Null reference exception error
I want my gameObject 'spawned' to divert in the direction of vector divert when it collides with the GameObject with which this script is attached, but it keeps showing null reference exception every time when the collision occurs but diversion isn't happening! I don't know why this is happening..

Can anyone tell me how to do this.

```
public class BallCollision : MonoBehaviour {
  public Transform central;
  public Transform centre;
  BallMovement ballMovement = null;
  Vector3 horizontal ;
  Vector3 vertical;
  Vector3 divert;
  // Use this for initialization
  void Start () {
  }

  // Update is called once per frame
  void Update () {
    horizontal = this.transform.position - central.position;
    vertical = centre.position - central.position;
    divert = horizontal + vertical;

    Debug.DrawLine (central.position, this.transform.position, Color.red);
    Debug.DrawLine (central.position, centre.position, Color.blue);
    Debug.DrawRay (central.position, divert, Color.green);
  }
  void OnCollisionEnter2D(Collision2D collision)
  {
    Debug.Log ("Collided!");
    ballMovement.spawned.AddForce (divert*5000);
  }
}

```

# Answer
You are missing initialization of `ballMovement` variable. Collision occurs, game tries to access `ballMovement`, which is null - Null Reference Exception as result.
> 3 votes

# Answer
You are more than likely not setting your BallMovement variable:

```
BallMovement ballMovement = null;

```

Seeing as it is marked as private, and seeing that you are not setting this in code and then attempting to use it.
> 2 votes

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


# Question
Title: C# Monogame Enemy shooting at random intervals
I am currently coding a simple Monogame Space Shooter.

I have almost finished my enemy shooting behaviour, but I spent a long time on fixing it and got to the point where I wanted somebody to help me out.

Okay so basiclly I have my 9 enemies (instances of Enemy class) in my Level class, and in level update I do stuff like checking if enemy has been hit by player, if they are Dead so I can remove them from the list etc.

I made a simple Timer class that has only 1 function, uses

```
var timer += GameTime.ElpasedGameTime.TotalMiliseconds

```

and simply checks if timer is bigger or equal than function input parameter(or argument?), and func is a bool so it then returns T or F.

Now inside my Enemy.cs claas I have this function:

```
public bool IsShooting()
        {
            if (enemyTimer.Wait(randomFloat))
            {
                shot = true;
                return true;
            }
            else
            {
                shot = false;
                return false;
            }
        }

```

enemyTimer = new Timer() & randomFloat = field(variable at the top of the class) in my Enemy class.

And now last but not least(actually the problem here) is this, so now in my Level class I got this little update function:

```
public void Update(Weapon weapon)
        {
            if (enemies.Count == 0)
                isFinished = true;

            if(!isFinished)
            {
                for (int i = 0; i < enemies.Count; ++i)
                {
                    if (enemies[i].shot)
                    {
                        seconds = rand.Next(1, 10);
                        randMiliseconds = 1000f * seconds;
                    }

                    enemies[i].randomFloat = randMiliseconds;
                    enemies[i].Update();

                    if (enemies[i].isDead == true) // If enemy is dead, remove it from level
                    {
                        enemies.RemoveAt(i);
                        --i;
                    }

                    foreach (Bullet bullet in weapon.bullets)
                    {
                        if ( !(i < 0) && weapon.ShotEnemy(bullet, enemies[i])) // If not enemies count == 0 and if
                        {                                                      // enemy has been shot decrease its health
                            enemies[i].Health -= weapon.Damage;                          // and set bullet visibility to false;
                            bullet.isVisible = false;
                        }
                    }

                }

            }

        }

```

This for loop goes through all the enemies, first if block is used for checking that if the enemy has shot the bullet, then **set random value** again to something different, if shot has not yet been fired then use the old value and wether it has been changed or not it sets randomFloat field in Enemy class to that value.

**Now this is how it works:** First all of 9 enemies shoot 1 bullet at the same time (Just about when I open the window, cause I putted randomFloat = 1000f; in my Enemy CTOR), and then randomFloat value is set in Level class to something different, I have message output and FOR EVERY DAMN ENEMY randomFloat is the same.... now that is a problem, I want the rand value to be different for all of them, and it should, right? Becouse those 9 enemies are all different instances of that class and if in each for(;;) loop cycle in my Level.Update() if it gets positive value that enemies\[index\] has fired a shot it should change it to some number that is very unlikly to be the same for all 9 enemies (seconds = rand.Next(1,20); randomFloat = 1000 * seconds; ). So basiclly randomFloat get random, but it is the same every time for all enemies, and they all shot and will shot at the same random Time

**Expected result:** Every enemy shooting at different random time

# Answer
Update: Rerun through your code, probably found the culprit:

```
if (enemies[i].shot)
                    {
                        seconds = rand.Next(1, 10);
                        randMiliseconds = 1000f * seconds;
                    }

                    enemies[i].randomFloat = randMiliseconds;
                    enemies[i].Update();

```

In the for loop you are assigning the randomFloat value regardless if it has been updated after the first Enemy shot its projectile. Thus each enemy onwards will always get the same value, since they'll get that interval before they fire themselves and can generate a new value.

You should include the `enemies[i].randomFloat = randMiliseconds;`

In the Shot checking aswell.
> 2 votes

# Answer
Can not see this part of your code, but could it be that you are initializing a new Random rand object on every iteration?

That could make it start on the same sequence each time always giving the same number. Instead you should reuse the same object instance without doing

```
Random rand = new Random();

```

in between the rand.Next calls.

This explains the background further and also mentions that objects created within 15 milliseconds tend to get identical number sequences: https://msdn.microsoft.com/en-us/library/system.random(v=vs.110).aspx
> 0 votes

# Answer
I found a solution to my problem, well at least where it came from, and it came from here:

```
public void Update(Weapon weapon)
    {
        if (enemies.Count == 0)
            isFinished = true;

        if(!isFinished)
        {
            for (int i = 0; i < enemies.Count; ++i)
            {

```

---

```
if (enemies[i].shot)
{
    seconds = rand.Next(1, 10);                 // THIS---------------------
    randMiliseconds = 1000f * seconds;          // THIS---------------------
}

```

---

```
               //THIS line below gets deleted after the solution below becouse I dont even use randMiliseconds variable anymore
               enemies[i].randomFloat = randMiliseconds;

                enemies[i].Update();

                if (enemies[i].isDead == true) // If enemy is dead, remove it from level
                {
                    enemies.RemoveAt(i);
                    --i;
                }

                foreach (Bullet bullet in weapon.bullets)
                {
                    if ( !(i < 0) && weapon.ShotEnemy(bullet, enemies[i])) // If not enemies count == 0 and if
                    {                                                      // enemy has been shot decrease its health
                        enemies[i].Health -= weapon.Damage;                          // and set bullet visibility to false;
                        bullet.isVisible = false;
                    }
                }

            }

        }

```

I made a function which gets that enemys instance and changes its value directly:

```
if (enemies[i].shot)
 {
     EnemyRandom(enemies[i]);
 }

```

---

```
 void EnemyRandom(Enemy enemy)
        {
            enemy.randomFloat = (rand.Next(1, 10) * 1000f);
        }

```

Now it works better I should play around to make it even more randomized becouse still like 3 or 4 of them somtimes shoot at the same time :P

Thank you everyone for helping out
> 0 votes

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


# Question
Title: Unity C# Microphone input in Android different than on PC?
I'm working on a mobile app inside Unity, in which I need to input and repeat microphone input almost immediately..

I've worked it out and it works great when I play it from within the Unity Editor. I get some very strange behavior though when I try it from my Android phone (Galaxy Note 3)..

So I decided to run some tests and noticed quite different behavior..

Using this sample code:

```
using UnityEngine;
using System.Collections;

public class testingMicScript : MonoBehaviour {

    void Start () {
        audio.loop = true;
        audio.clip = Microphone.Start (null,true,10,44100);
        while(!(Microphone.GetPosition(null)>0)){}
        audio.Play ();
    }
}

```

and playing it from withing the Editor it works great, I speak and hear myself back after a few milliseconds. I compile the app and run it from my phone and when I speak I get a very strange echo which goes on until the sound is completely distorted and I get a strange hiss, until audio is completely muted..

Why is that? Is there any particular setting I should go through? Or do I have to change something in my code?

# Answer
> 1 votes
In case anyone else is having this issue, Im working on the same kind of app but Iam also muting the recorded feedback using an audio mixer and parsing the data to get sound volumes and pitch.

I noticed unity and android are different when it comes to the mic. I had to query the specific device microphone to determine what its max frequency is. The following snippet is a simple method i used to start a microphone

```
public void BeginListener(int index)
{
    int min = 0;
    int max = 0;

    Microphone.GetDeviceCaps(Microphone.devices[index], out min, out max);

    _AudioSource.clip = Microphone.Start(Microphone.devices[index], true, 2, max);

    while (!(Microphone.GetPosition(Microphone.devices[index]) > 1))
    {
        // Wait until the recording has started
    }

    _AudioSource.loop = true;
    _AudioSource.Play();
}

```

I feel this is a good solution to start listeniing on a microphone on device and works with multiple microphones. If anyone else knows of a better way please feel free to correct anything

Thanks!

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


title: Prefab won't change to custom shader

text:
# Question
Title: Prefab won't change to custom shader
I am writing here as I have encountered a problem with Unity. I have written my own surface shader and want to use it for a prefab. However, when I drag and drop the shader to the prefab in the editor, it recognizes it but it doesn't change the prefab. The prefab is a prefab for some objects which stays pink. What's the problem? The shader works, and I know that as I have tried to drag and drop the shader directly to some of the objects. In addition to that, I have also tried to create a material an drag and drop the shader that and then drag and drop the material to the prefab. That didn't work either.

# Answer
Make sure the game isn't running and drag your prefab into a scene and select it in the Hierarchy. There should be details in the *Inspector* that will allow you to apply your shader.

First, find the part of the prefab that contains a renderer (probably a `MeshRenderer`). Under that component, there will be a "*Materials*" list which should have a size you can adjust and then elements to select the materials you'd like.

When your materials are set, there will be drop-down menus to select which shaders those materials are using; this is where you select the shader you want.

Finally, as with any adjustments to prefabs, you must click the "Apply" button in the upper right on the *Inspector*. **If you make changes while the game is running or without clicking "Apply", the changes will not be saved to the prefab.**
> 1 votes

---
Tags: unity, shaders
---


# Question
Title: Using Quaternions: What can I do with them? (without the maths)
I am a Game Developer and did not study Mathematics. So I only want to use Quaternions as a tool. And to be able to work with 3D rotation, it's necessary to use Quaternions (Or Matrixes, but let's stay at Quaternions here in this Question). I think it's important for many developers to use them. That's why I want to share my knowledge and hopefully fill the holes I have. Now....

So as far as I understood:

A Quaternion can describe 2 things:

1. The current orientation of a 3d Object.
2. The rotation transformation a Object could do. (rotationChange)

You can do with a Quaternion:

**Multiplications:**

1. Quaternion endOrientation = Quaternion rotationChange * Quaternion currentOrientation;

So for example: My 3D Object is turned 90° to left - and my rotation I multiply is a rotation 180° to right, in the end my 3D Object 90° is turned to right.
2. Quaternion rotationChange = Quaternion endRotation * Quaternion.Inverse(startRotation);

With this you get a rotationChange, which can be applied to another Orientation.
3. Vector3 endPostion = Quaternion rotationChange * Vector3 currentPosition;

So for example: My 3D Object is on Position (0,0,0) and my rotation I multiply is a rotation 180° to right, my endposition is something like (0,-50,0) . Inside that Quaternion there is a Axis - and a rotation around that axis. You turn your point around that axis Y Degrees.
4. Vector3 rotatedOffsetVector = Quaternion rotationChange * Vector3 currentOffsetVector ;

For example: My start direction is showing UP - (0,1,0), and my rotation I multiply is a rotation 180° to right, my end direction is showing down. (0,-1,0)

**Blending (Lerp and Slerp):**

5. Quaternion currentOrientation = Quaternion.Slerp(startOrientation, endOrientation , interpolator)

if the interpolator is 1 : currentOrientation = endOrientation

if the interpolator is 0 : currentOrientation = startOrientation

Slerp interpolates more precise, Lerp interpolates more performant.

**My Question(s):**

Is everything I explained until now correct?

Is that "all" you can do with Quaternions? (obv. not)

What else can you do with them?

What are the Dot product and the Cross product between 2 Quaternions good for?

Edit:

Updated Question with some answers

# Answer
## Multiplication

At least in terms of Unity's implementation of Quaternions, the multiplication order described in the question is not correct. This is important because 3D rotation is not commutative.

So, if I want to rotate an object by `rotationChange` starting from its `currentOrientation` I'd write it like this:

```
Quaternion newOrientation = rotationChange * currentOrientation;

```

(ie. Transformations stack up to the left - same as Unity's matrix convention. The rightmost rotation is applied first / at the "most local" end)

And if I wanted to transform a direction or offset vector by a rotation, I'd write it like this:

```
Vector3 rotatedOffsetVector = rotationChange * currentOffsetVector;

```

(Unity will generate a compile error if you do the opposite)

## Blending

For most cases you can get away with Lerping rotations. That's because the angle used "under the hood" in a quaternion is *half* the angle of rotation, making it substantially closer to the linear approximation of Lerp than something like a Matrix (which in general will *not* Lerp well!). Check out around 40 minutes into this video for more explanation.

The one case when you really need Slerp is when you need consistent speed over time, like interpolating between keyframes on an animation timeline. For cases where you just care that an output is intermediate between two inputs (like blending layers of an animation) then usually Lerp serves quite well.

## What Else?

The **dot product** of two unit quaternions gives the cosine of the angle between them, so you can use the dot product as a measure of similarity if you need to compare rotations. This is a little obscure though, so for more legible code I'd often use Quaternion.Angle(a, b) instead, which more clearly expresses that we're comparing angles, in familiar units (degrees).

These types of convenience methods that Unity provides for Quaternions are super useful. In almost every project I use a this one at least a few times:

```
Quaternion.LookRotation(Vector3 forward, Vector3 up)

```

This builds a quaternion that:

* rotates the local z+ axis to point exactly along the `forward` vector argument
* rotates the local y+ axis to point as close as possible to the `up` vector argument, if provided, or to `(0, 1, 0)` if omitted

The reason the "up" only gets "as close as possible" is that the system is overdetermined. Facing z+ to `forward` uses up two degrees of freedom (ie. yaw and pitch) so we have only one degree of freedom remaining (roll).

I find quite often I want something with the opposite exactness properties: I want local y+ to point exactly along `up`, and local z+ to get as close as possible to `forward` with the remaining freedom.

This comes up for example when trying to form a camera-relative coordinate frame for movement input: I want my local up direction to stay perpendicular to the floor or inclined surface normal, so my input doesn't try to tunnel the character into the terrain or levitate them off of it.

You might also get this if you want the turret housing of a tank to face a target, without peeling up off of the tank's body when aiming up/down.

We can build our own convenience function to do this, using `LookRotation` for the heavy lifting:

```
Quaternion TurretLookRotation(Vector3 approximateForward, Vector3 exactUp)
{
    Quaternion rotateZToUp = Quaternion.LookRotation(exactUp, -approximateForward);
    Quaternion rotateYToZ = Quaternion.Euler(90f, 0f, 0f);

    return rotateZToUp * rotateYToZ;
}

```

Here we first rotate local y+ to z+, and local z+ to y-.

Then we rotate the new z+ to our up direction (so the net result is local y+ points directly along `exactUp`), and the new y+ as close as possible to the *negated* forward direction (so the net result is local z+ points as close as possible along `approximateForward`)

Another handy convenience method is `Quaternion.RotateTowards`, which I often use like so:

```
Quaternion newRotation = Quaternion.RotateTowards(
                             oldRotation,
                             targetRotation,
                             maxDegreesPerSecond * Time.deltaTime
                         );

```

This lets us close in on `targetRotation` at a consistent, controllable speed regardless of framerate - important for rotations that affect the outcome/fairness of gameplay mechanics (like turning a character's movement, or having a turret track-in on the player). Naively Lerping/Slerping in this situation can easily lead to cases where the movement gets snappier at high framerates, impacting game balance. (That's not to say these methods are wrong - there's ways to use them correctly without changing fairness, it just requires care. `RotateTowards` gives a convenient shortcut that takes care of this for us)
> 24 votes

# Answer
## Where's the dot product used?

In Unity, one of the most common users of the dot product is whenever you check if two quaternions are equal via `==` or `!=`. Unity computes the dot product to check similarity rather than directly comparing the internal x,y,z,w values. It's worth keeping this one in mind as it makes the call more expensive than you might expect it to be.

We also use it in an interesting use case too..

## Fun with quaternion dot products - Spherical worlds and orbitals

Simulations of entire planets and even entire solar systems are getting increasingly common. In order to pull this off in realtime, we need the quaternion dot product too. Lots of them. The quaternion dot product is very underused but it certainly has its uses - Let's take a look!

Firstly, we have a whole series of rotations to consider:

1. (Optionally) The star around the galactic centre
2. The planet around the star
3. **The tilt of the planet**
4. The spin of the planet
5. The position of nearby grid cells (rotated about the planets core)\*
6. Multiple orbital planes

Combine them all together and you end up with a lot of complexity (and a lot of huge numbers!). When the viewer is standing on the surface of the planet, we don't want them to be hurtling at some crazy speed through our gameworld space. We'd actually rather they were stationary and somewhere near the origin - move the universe around the player instead.

Importantly, in order for us to be able to get the planet's spin and tilt correct in this scenario, we need to axis lock the pole so it can only swing up/down on the image above (i.e. swinging "up" as the player travels north). **That's where a quaternion dot product comes in.** If we didn't use a dot product here and instead just multiplied the tilt too, this would happen:

*Notice how the poles of our orbiting 'planets' are always tilting towards the star. This isn't what happens in reality - the tilt is in a fixed direction.*

Without going too far off topic, here's a quick summary:

* On a sphere, an orientation also neatly describes a surface position.
* We've got lots of rotations to combine together.
* Describe everything as rotation; the position of the viewer, too. This helps boost performance as ultimately we end up doing less operations.
* The angle between rotations (our dot product) then helps measure longitude and works particularly well at dealing with tilts.

By obtaining only the angle, we **drop some of that unwanted rotation**. At the same time we also ended up with a *longitude measurement* which is useful for navigation as well as the local climate.

* Planets are constructed from lots of grid cells. Only the nearby ones actually get displayed.
> 15 votes

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


# Question
Title: Resolve Unity error about "Constructors and field initializers" on the loading thread
The code below is producing an error message I don't understand:

> Constructors and field initializers will be executed from the loading thread when loading a scene. Don't use this function in the constructor or field initializers, instead move initialization code to the Awake or Start function

I don't know where the problem is in my code or what I need to change - can someone please explain?

```
var XPos : float = transform.position.x;
var YPos : float = transform.position.y;
var ZPos : float = transform.position.z;
var Waiting : float = 0.02;

function OnTriggerEnter (col : Collider) {
    if (col.gameObject.tag == "Player") {
        this.transform.position = Vector3(XPos, YPos+0.1, ZPos);
        yield WaitForSeconds(Waiting);
        // ...similar code omitted
        transform.GetComponent.<Collider>().isTrigger = true;
        Destroy(gameObject);
    }
}

```

# Answer
In newer versions of Unity, the error message for this is helpfully explicit:

> get\_transform is not allowed to be called from a MonoBehaviour constructor (or instance field initializer), call it in Awake or Start instead. Called from MonoBehaviour 'BadJSTest' on game object 'My Object Name'. See "Script Serialization" page in the Unity Manual for further details. UnityEngine.Component:get\_transform() BadJSTest:.ctor() (at Assets/Serialization/BadJSTest.js:3)

Let's unpack this a bit...

A **field** is a variable that you've defined outside of a function, like this:

```
var Waiting : float;

```

A field **initializer** is code that assigns a value to that variable in the same line where it's defined. (Since you're defining an *initial* value for the variable to hold, we say you're "initializing" it)

```
var waiting : float = 0.02;

```

In Unity, these initial assignments happen as the object is loaded, which is done on a **loading thread** separate from the main game thread.

This is good because it lets us stream in content dynamically in the background while the player enjoys the game, without halting gameplay or stuttering the framerate (if we do it right).

But it has limitations: code that's not running on the main thread is more limited in what it's allowed to do. In this case, Unity lets us know that field initializers and other code on the loading thread aren't allowed to try to read the object's transform - it's likely not ready yet.

So, we can hold off and populate these variables in Awake, Start, or OnEnable instead, like so:

```
#pragma strict

var XPos : float;
var YPos : float;
var ZPos : float;
var Waiting : float = 0.04;

function Awake() {
    XPos = transform.position.x;
    YPos = transform.position.y;
    ZPos = transform.position.z;
}

```

These methods run on the main thread after the object is completely loaded (but still before most other events we might want to respond to), so it's safe to reference the transform and other attached scripts here.
> 1 votes

---
Tags: unity, javascript
---


# Question
Title: Vertex shader with extrusion, what am I doing wrong?
So for a simple surface shader, you can use vertex modifier:

```
    void vert (inout appdata_full v) {
        v.vertex.xyz += v.normal * _Amount;
    }

```

I was thinking the same would work as vertex shader:

```
    // vertex shader
    VectexOutput vert (VectexInput i) {
        // init output
        VectexOutput o;
        UNITY_INITIALIZE_OUTPUT(VectexOutput, o);

        // vertex extrusion
        i.vertex.xyz += i.normal * _Multiplier;

        // world space normal
        half3 normal = UnityObjectToWorldNormal(i.normal);

        // standard diffuse lighting
        half nl = max(0, dot(normal, _WorldSpaceLightPos0.xyz));

        // input to output
        o.vertex = UnityObjectToClipPos(i.vertex);
        o.color = i.color;
        o.diff = nl * _LightColor0;
        o.diff.rgb += ShadeSH9(half4(normal, 1));
        o.uv = TRANSFORM_TEX(i.uv, _MainTex);

        return o;
    }

```

But it doesn't, and since surface shader is compiled to vertex/fragment shader, I am wondering what am I missing?

# Answer
The answer is simple:

I declared `_Multiplier` incorrectly in the `SubShader` block.

It should have been `uniform float _Multiplier`, but I wrote `uniform float4 _Multiplier;`

Interesting part is: no error will be produced, because `float4 _Multiplier` defaults to `(0,0,0,0)`, so `i.vertex.xyz += i.normal * _Multiplier;` result in zero float3, hence no change in vertex position.
> 1 votes

---
Tags: unity, shaders
---


# Question
Title: What are some standard stair dimensions for good level navigation?
I am trying to establish some scale standards for a level. I have been following this guide: http://www.worldofleveldesign.com/categories/ue4/ue4-guide-to-scale-dimensions.php

So far I have walls at 3m high, doors at 2.1m by 1.1m, with the character standing at 1.82m by 0.6m. I am now trying to work out a "good" staircase size. I have tried the above guide's suggestion of 0.15m high by 0.3m deep for each step. To reach 3m however would require 20 steps with these dimensions, which means a single staircase would be 6m long! Visually this looks quite silly in my opinion. If I compare this to real life using the following calculator: http://www.calculator.net/stair-calculator.html, using realistic step heights and depths the same staircase can be achieved at less than 4m length. This seems more realistic to me.

My main concern is not simply the visual appearance of the staircase, but how much space it will take up in a given building. If in each smaller building the staircase is taking up the majority of the floor space, this won't leave much for the more important elements. At the same time, I am concerned that if I make the staircase too steep it will have a negative effect on the gameplay and navigation. I understand that each level is different, however is there a good rule of thumb for getting started with this?

# Answer
> 5 votes
Architecture in FPS games differs from real life in a number of ways, including:

* Much wider interior spaces
* More straight sections, less turns
* Less vertical movement

All of this to accommodate the typical FPS avatar, which usually runs around (even indoors) and has a very limited field of view, especially vertically. Realism in general helps immersion, but when it is in conflict with gameplay, you need to make a choice. My opinion is to **let the architecture serve the gameplay**.

While there doesn't seem to be any published guidelines for staircase design in games, the guide you linked seems ok, of having a **30 degree staircase** (where step depth-to-height is 2:1). Shallower stairs means players don't have to look up/down as much, and there's less danger of running off the top and taking a fall if the stairs are too steep.

30 degrees works in reality too, although it's towards the shallower end. Consider this reference image from California's Code of Regulations:

> https://www.dir.ca.gov/title8/3231.html

According to this, ideal stairs have an angle between 30 and 37 degrees, although it could be as shallow as 18 and as steep as 50. Any steeper and you enter ladder territory, any shallower and a ramp is preferable.

One difference between games and real life is **flights**. In real life, flights should be limited in size (e.g. *Building Code of Australia* limits flights to 2-18 risers), otherwise there's a safety risk. Usually a single flight isn't enough to span two stories, so stairs usually have *landings* or *winders* between flights.

> Apple Store staircase with two landings

This can also save space if the stairs turns back on itself, as in a stairwell. However, **in an FPS you want to avoid turns in stairs**. The player is already handicapped in a narrow, sloping space; adding turns only makes them more vulnerable.

To summarise, stairs in an FPS should be **wider**, **shallower** and **straighter** than real life.

# Answer
> 0 votes
If you want a smaller footprint use a spiral staircase or a ladder

# Answer
> -1 votes
This is a specific case of a common problem that you often want your character to be able to step up onto ledges or steps that are taller than the rounded bottom of the capsule would normally allow. I haven't used Unreal enough to know if there's a simpler solution to the problem, but the approach I've used in previous games is to modify the character controller. This may require more code than you'd like, but the basic algorithm is:

1) Am I hitting a blocking surface normal? 2) If so, perform an additional shape cast of the character's capsule starting some max-step-height above the current position and extending forward from there 3) if the cast shows enough space to pop up and move forward and still be supported, move to that location. Otherwise, you have encountered blocking geometry and can stop

An alternative, even simpler approach is to use a ramp for the physics geometry and stairs for the render geometry. As long as your IK operates on the render geo, it should look fine for walking but will allow a wider range of staircase angles.

Hope that helps a little.

---
Tags: level-design, scale
---


# Question
Title: Libgdx OrthographicCamera culling problem with zooming
When I set zoom on an orthographic camera to anything above 1 I get a strange black border on the bottom of the screen.

I suspect that this might be some sort of culling problem. I use a viewport to control the game resolution, and no matter the size the borders are there.

The camera is set on a direction (-1,-1,-1) basicaly isometric. Also it is positioned well above to origin at (1113,1113,-1113). Far plane at 7777 near at 0.00001f. The ground plane is at 0,0,0 laying in the xz axis, with an other plane on top of it sligtly off to the left and with a 45 degrees on its axis to face the camera.

Here is an image of the problem:

Posting code wont really help here since I only use defaults almost everywhere, but if you need it just tell.

# Answer
> 1 votes
It seems there is some bug with the viewport code. I had to define the y coordinate manually..

---
Tags: libgdx, camera, culling
---


# Question
Title: How to securely store xml/json information about actors in a game?
I'm developing a 2D "small" offline rpg game, and to this point I have many actors (mobs, heroes, NPCs) and what I did, is created a class named "Actor" and each time I have a new actor I create a whole new class extending it.

I was thinking if I could limit it and go with a single class (prototype pattern?) were each instance of it gets its info and properties from stored files (name, weight, HP, attack, playable, ...)

I thought first to use xml to store every actor I have in the game, so it would be a lot easier to modify or add new actors, and this goes for also weapons, gear, potions, etc.

I'm afraid to use XML or JSON, because this would make the game content open and then anyone can modify it.

So, any thoughts on how to implement that, because i'm totally new to game dev?

# Answer
> 2 votes
You could use JSON and zip it with a password (encrypt), then use a runtime zip library like DotNetZip to extract it for inspection by the game only, no-one else.

Or you could access it on a secured server that requires login to get the file.

The question boils down to, *How do I secure plain text?* \- perhaps this form of the question will help you find the best answer.

# Answer
> 0 votes
Also think about how you will be parsing the data, does your language have easy methods to parse JSON for example? Not all languages do.

Also you are probably aware but you will also only want to send diffs of your data rather than the whole data each time.

But as the other answer states, if you are sending sensitive data, encryption is a must regardless of how you send it.

---
Tags: savegame, xml, storage, npc, data-driven
---


title: Unity - Stuttering character rotation

text:
# Question
Title: Unity - Stuttering character rotation
Am working on the controls and camera movement for my character. What I am trying to do is have the character head be able to rotate left and right and then when the head is rotated a certain amount, the whole character rotates around. I have kinda of done it, the head can move smoothly, but it stutters when it starts rotating everything.

Hopefully it is visible in this GIF.

You may be able to see that the head does rotate smoothly, but when the body starts rotating, it stutters.

Here is the code that is in LateUpdate that handles all the rotations.

```
this.current_rotation = Quaternion.Lerp(this.current_rotation, Quaternion.Euler(new Vector3(this.pitch, this.yaw, 0)), this.mouse_sensitivity * Time.deltaTime);

this.cam.transform.rotation = this.current_rotation;
this.head.transform.rotation = this.current_rotation;

if(this.head.transform.localRotation.y > 0.3 || this.head.transform.localRotation.y < -0.3){
    Quaternion from = Quaternion.Euler(0, this.player.transform.eulerAngles.y, 0);
    Quaternion to = Quaternion.Euler(0, this.current_rotation.eulerAngles.y, 0);

    Quaternion q =  Quaternion.Lerp(from, to, this.mouse_sensitivity * Time.deltaTime);
    this.player.transform.rotation = q;
}

```

# Answer
OK, I couldn't get the sample project working in Unity, but I used the script to recreate it with a couple assumptions, as follows:

* Your Camera\_Control.cs script is on the body cube.
* The head cube is a child of the body cube.
* The camera is a child of the head cube

I was able to fix this in two ways:

1. Move the head cube off of the body, so that rotating the body doesn't automatically rotate the head as well.
2. Or, counter-rotate the head when you do rotate the body, to neutralize the effect.

I assume the latter is the style of solution you wanted. So, I add two new `Quaternions` (essentially reversed), `Lerp` between them, and assign that to the cam/head transforms.

```
this.current_rotation = Quaternion.Lerp(this.current_rotation, Quaternion.Euler(new Vector3(this.pitch, this.yaw, 0)), this.mouse_sensitivity * Time.deltaTime);

this.cam.transform.rotation  = this.current_rotation;
this.head.transform.rotation = this.current_rotation;

if(this.head.transform.localRotation.y > 0.3 || this.head.transform.localRotation.y < -0.3){
    Quaternion from = Quaternion.Euler(0, this.player.transform.eulerAngles.y, 0);
    Quaternion to   = Quaternion.Euler(0, this.current_rotation.eulerAngles.y, 0);

    // Reverse 'y' rotation, maintain x/z rotation
    Quaternion headFrom = this.current_rotation;
    Quaternion headTo   = Quaternion.Euler(headFrom.eulerAngles.x, this.player.transform.eulerAngles.y, headFrom.eulerAngles.z);

    Quaternion q = Quaternion.Lerp(from,     to,     this.mouse_sensitivity * Time.deltaTime);
    Quaternion r = Quaternion.Lerp(headFrom, headTo, this.mouse_sensitivity * Time.deltaTime);
    this.player.transform.rotation = q;
    this.cam.transform.rotation    = r;
    this.head.transform.rotation   = r;
}

```

That should fix the jitter. You'll still have other rotation work to do afterwards, but at least it'll be smooth. :)
> 1 votes

# Answer
From your screenshots it looks like the problem may be from the colliders on your head and body object. You are directly manipulating the transform in your code, but while this is happening the physics engine is also trying to handle the collisions between the two colliders and this will result in erratic movement.

If that is the issue, there are a number of ways to avoid that problem, from changing what objects have colliders to having colliders ignoring each other using layering.
> 0 votes

---
Tags: unity, rotation, quaternion, character
---


title: Scale sprite between two points

text:
# Question
Title: Scale sprite between two points
I need to start a sprite at a scale .6 (`scale1`) at a y position 40 (`yPos1`). Knowing the end y position 560 (`yPos2`) and the end scale 1 (`scale2`):

How do I calculate the scale at various y positions between `yPos1` and `yPos2`?

# Answer
> 0 votes
First get the difference of both scale and y pos

```
difY = y2-y1;
difS = s2-s1;

```

Then if you have a y position between the two given y positions, convert that to a normalised position 0-1

```
posY = ?
normY = (posY- y1)/difY; // get the normalised distance between the points

```

Then you can use that normal to calculate the scale

```
scale = (difS * normY) + s1

```

If you want to easeInOut you can do that to the normal first

```
function easeInOut(n,p){  // n val 0-1. p > 1 the amount of ease p=1 none 2 a little ease, 4 a lot of ease
   nn = pow(n,p);  // pow is a raise n to the power of p
   return nn / (nn + pow(1 - n,p));
}

scale = (difS * easeInOut(normY,2)) + s1;

```

There are many functions that you can apply to the normalised position to modify the movement between two points.

If you have more than two points and you want the easing to be smooth along the whole path consider using beziers for the easing functions as they provide a simple way to get parabolas to fit between a given set of points (namely the 0 and 1 of the normalised y positions);

---
Tags: transformation, mathematics, motion
---


# Question
Title: How do I find an accurate current speed of a navmesh agent?
So I have a blendtree of an idle/walk/run animation of a character (the navmesh agent). I want to use a normalised float of the speed of the navmesh agent to control the blend of the animation cycles. Currently I use this:

```
void FixedUpdate ()
{
    speed = (transform.position - lastPosition).magnitude;
    lastPosition = transform.position;

    print(speed);
}

```

However the result is fluctuating all over the place and the animations blends look crap. How do I find a more accurate speed of the navmesh agent?

# Answer
It seems that the thing I needed was to divide the speed by `Time.deltaTime`.

This is what works now:

```
void FixedUpdate()
{
    speed = Mathf.Lerp(speed, (transform.position - lastPosition).magnitude / Time.deltaTime, 0.75f);
    lastPosition = transform.position;

    print(speed);
}

```
> 0 votes

# Answer
You are doing it right way, the problem is that on navmesh object can change its speed rapidly. You should interpolate object speed in order to get rid of rapid changes. Just update your method like this:

```
void FixedUpdate()
{
    speed = Mathf.Lerp(speed, (transform.position - lastPosition).magnitude, 0.7f /*adjust this number in order to make interpolation quicker or slower*/);
    lastPosition = transform.position;

    print(speed);
}

```
> 1 votes

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


# Question
Title: LibGDX, How to create a 2d collision terrain
How can I create a surface so my bike collides with the ground? I'm thinking of placing x,y coordinates, but that will be too straight and I want it more smooth. (I don't want to place 1 million dots)

# Answer
Let's look at a popular example: the once so famous Hill Climb racing for mobile devices (seriously, everyone and their grandma played this thing).

If you look at this image from a normal distance (aka. from a distance that doesn't make you go blind in 10 minutes), then this looks insanely smooth. But if you look at it from close up (especially at the valley on the left) you notice, that it's actually out of line segments.

Because the distance between 2 vertex is very small, a normal user doesn't notice it.

You can also make the terrain have more vertices around the parts, where the terrain is more curvy, kind of like how bézier curves work.
> 1 votes

# Answer
Using many small line segments is a good, simple, practical solution, but if you want actual smooth curves that's possible too without much extra effort or processing power.

One easy way to do it would be to use one dimensional bezier curves, also known as explicit bezier curves, but also known as just polynomials.

The formula for a quadratic bezier curve is:

y=A\*(1-x)^2+B\*2x(1-x)+Cx^2

The values A,B,C are scalar values that control the y value (height) of the curve for the different values of x.

The A value is the height when x is 0, the C value is the height when x is 1. The B value controls the height in the middle but the curve doesn't pass through that height.

How you can use this information is you can decide that you are going to make a bezier curve control every 10 units on x as an example.

What you do then is if you want to find how high the ground is at a given x location, you divide x by 10 and floor that value (cast to an integer) to get the index of the curve that controls that height.

You then calculate what percentage the x value is on that curve using this formula:

percent = (x-curveIndex\*10)/10

That percent value is what you use as the x value in the bezier curve equation to give you the y value which is the height of the terrain.

You can then use that height to know if something is above or below the terrain and take appropriate action.

In practical terms you'll probably want the A and C points to match up with the curves next to them to make the curves continuous and smooth, but it isn't a requirement.

The only other thing I want to mention is that 1d Bezier curves aren't your only option, but they are IMO easier to explain and use compared to other curve choices.

You can read more about 1d bezier curves here: http://blog.demofox.org/2014/08/28/one-dimensional-bezier-curves/
> 1 votes

---
Tags: java, libgdx, box2d
---


# Question
Title: How to have random and different colors on multiple objects with one material?
I want to have one material applied to multiple objects that has a random color on each object. How can I achieve this so that I don't need to use a different material for every object? This is in Unity 5 by the way.

# Answer
You can change the color of the same material, on different objects, from script. Do the following:

1. Create a materialand assign it to the target game object.
2. Create a new C# script, and copy in the following code. Inside "parent" the objects whose color should change is placed in the unity editor.

---

```
using UnityEngine;
using System.Collections.Generic;

public class RandomColor : MonoBehaviour
{
    public Transform parent;

    List<Transform> objectstoColor;

    void Start ()
    {
        objectstoColor = new List<Transform>();

        foreach (Transform item in parent)
        {
            objectstoColor.Add(item);
        }
    }

    <summary>Method for changing the material color</summary>
    public void SwitchColors()
    {
        foreach (Transform item in objectstoColor)
        {
            Renderer rend = item.gameObject.GetComponent<Renderer>();
            rend.material.color = Random.ColorHSV(0f, 1f, 1f, 1f, 0.5f, 1f);
        }
    }
}

```

---
> 2 votes

---
Tags: unity, random, objects, materials
---


# Question
Title: Minimum hardware requirements for developing for iOS and Android with Unity, Cocos2d-x and GameSalad on a Mac
I intend to create iOS and Android games. My main priority is to create 2D games. The software that I’m planing to use are Unity, Cocos2d-x and GameSalad.

I am a bit interest in the Mac Mini, because it is cheap compared to other Apple machines. What are the minimum hardware requirements for an Apple machine?

# Answer
> 1 votes
Actually, the base system requirements for developing with Unity, Cocos2d-x and GameSalad are quite minimal, and are just within the system specifications advertised of the Mac Mini. In fact, the hardware requirements are fairly loose, and you should find support in any current or future generation Macintosh.

Note that there is a difference between your hardware *running the software* and *running the software as required to make games*. Just as different games have different system requirements, you will definetly need a better computer if you intend to work on more complex games.

This should not be an immediate problem, and you should have no trouble actually *running* the game, assuming you have appropriate devices to test your iOS and Android variations.

Note that *most* listed requirements are *software* based; you *may* be required to perform system updates and download additional dependencies for full support.

---

## Unity System Requirements.

According to the Unity website, the system requirements for a Macintosh are as follows:

* Running OS X 10.9.4 +
* Running Xcode 7.0 +
* Graphic card with support for
    + Direct3D 9.0 + with support for shader models 3.0 + , *or*,
    + Direct3D 11 + with support for level 9.3 capabilities

You will also need to download the *Android SDK* and the *Java Development Kit* to publish to Android devices. Both of these are freely and easily accessible from their respective developer's websites.

## Cocos2d-x System Requirements

According to the official Cocos2d-x wiki, the system requirements for Macintosh are as follows:

* Running OS X 10.7 +
* Running Xcode 5.1 +
* Running Python 2.7.5

You will also need to install Android NDK r9d to provide Android support. Android games will be limited to supporting Android 2.3 +, while iOS games will be limited to supporting iOS 5.0 +.

## GameSalad System Requirements

According to the official GameSalad website, the system requirements for a Macintosh are as follows:

* Core 2 Duo + processor
* 2GB + RAM
* Running OS X 10.7 +
* Graphic card with OpenGL 2.0 + support

You will need to update to at least OS X 10.9 + and be running Xcode 6.0 +, to develop for iOS, while Android development requires Java 6 + and the Android SDK.

## Mac Mini System Specifications

According to \[the official Apple website\]( http://www.apple.com/au/shop/buy-mac/mac-mini), the lowest model of Mac Mini has the following system specifications:

* 1.4GHz Intel Core i5 dual-core processor
* 4GB RAM
* 500GB hard drive
* Intel HD 5000 graphics

At minimum, the Intel HD 5000 graphics range reports support for Direct3D 11.0 and OpenGL 4.3, which meets the minimum requirements for the above mentioned software.

---

Note that this will give you the *minimum* support; if you intend to work with more intense graphics, you might want to consider whether you would need a better graphic card. If you want to work with more complex concepts, you might want to consider whether you would need a better processor. While you *can* opt to purchase a Mac Mini with an upgraded processor, you might wish to move to a more powerful device, should you choose to explore a faster graphic card.

Ultimately, devices that run iOS and Android do not tend to have powerful graphic cards, and one would target an average level of processor, to support a greater variety of devices. Neither of these additional upgrades should be required to develop for iOS or Android devices.

---
Tags: unity, android, ios, cocos2d, gamesalad
---


# Question
Title: How is text/scripts/dialogue stored and accessed in games?
For large, complex games, I imagine that text descriptions, dialogue lines, etc, are organized in some sort of database, and not actually hardcoded into the source.

Are there any conventions on how such textual data is organized and inserted/loaded into the game? And how does this "database" get "compiled" into the executable along with the source code? (Because for most AAA games there aren't additional files containing said database, etc).

In particular, I'd like to know how to load text into a game, without opening some external client-side file (so the client can't just browse the file and read the ending!). I don't see how an external file/database could be bundled into the compiled source executable (for example, how would you do this in C)?

# Answer
**Use an external file but obscure/encrypt it**

One good solution (and what I am currently doing in my project) is to write the text in a *source* file in your game project (if using say Visual Studio, make sure not to copy content) written in your choice of XML/JSON or custom format.

This makes it easy for you to read and edit and in particular easy for any other designers or script writers to read and edit.

When it comes to building your project, you have two options, the first is to convert the text into binary and save the binary file. This would prevent most people being able to read it, you could read it easily back into your project and use the text as you wish in the game.

With just a binary file any slightly technical person could quite easily open and read it as they wish, so you may want to go for a second option. This would be to encrypt the text before saving it as a file. Depending on the method or encryption used only the most hardy hackers can get into and read the file.

The above methods have many benefits, it is readable and editable by non technical people on your team yet on release it is unreadable by the game players. It can be scalable and expandable to add more text to your game without the need to recompile your game (depending how this is done!).
> 1 votes

---
Tags: databases, loading, text
---


# Question
Title: Undetected Null Pointer Exception in TextureRegions
I have an error regarding Null Pointer Exception and I can't find the exact location of the error in my program. I have searched for probable solutions online but I find none of them helpful. I know what Null Pointer Exception is but I can't pinpoint what went wrong in my code. Any help will be appreciated, thanks.

Here's my code:

LevelOneScreen.java

```
public class LevelOneScreen implements Screen {

    private final ThumbChase app;
    WalkAnimate walkAnimate;
    private Stage stage;
    private Image levelOneImage;
    private Image holdStartImage;
    public Image walkRightImage;
    public Image walkLeftImage;
    public float deltaTime = Gdx.graphics.getDeltaTime();

    public LevelOneScreen(final ThumbChase app){
        this.app = app;
        this.stage = new Stage(new StretchViewport(app.screenWidth,app.screenHeight , app.camera));

    }
    @Override
    public void show() {

        Gdx.input.setInputProcessor(stage);
        walkAnimate = new WalkAnimate();

        levelOneBackground();
        holdStart();
        ninjaWalk();                            ==>ERROR1:LevelOneScreen.java:54

    }

    public void holdStart(){
        Texture holdStartTexture = new Texture("HoldStart.png");
        holdStartImage = new Image(holdStartTexture);
        float holdStartImageW = holdStartImage.getWidth();
        float holdStartImageH = holdStartImage.getHeight();
        float holdStartImgWidth = app.screenWidth*0.8f;
        float holdStartImgHeight = holdStartImgWidth *(holdStartImageH/holdStartImageW);
        holdStartImage.isTouchable();
        holdStartImage.setSize(holdStartImgWidth,holdStartImgHeight);
        holdStartImage.setPosition(stage.getWidth()/2-holdStartImgWidth/2,stage.getHeight()/2-holdStartImgHeight/2);
        stage.addActor(holdStartImage);
        holdStartImage.addListener(new ActorGestureListener(){
            public void touchDown (InputEvent event, float x, float y, int pointer, int button){
                holdStartImage.setVisible(false);
            };
        });

        }

    public void levelOneBackground(){
        Texture levelOneTexture = new Texture("BGBlue Resize.png");
        levelOneImage = new Image(levelOneTexture);
        levelOneImage.setSize(app.screenWidth,app.screenHeight);
        levelOneImage.setPosition(0,0);
        stage.addActor(levelOneImage);
        levelOneImage.addListener(new ActorGestureListener(){
            public void touchDown (InputEvent event, float x, float y, int pointer, int button){
                holdStartImage.setVisible(false);
            };
        });
    }
    public void ninjaWalk(){

ERROR2==>   TextureRegion ninjaWalkRight = new TextureRegion(walkAnimate.getCurrentFrameRight());
            TextureRegion ninjaWalkLeft = new TextureRegion(walkAnimate.getCurrentFrameLeft());
            walkRightImage = new Image(ninjaWalkRight);
            walkLeftImage = new Image(ninjaWalkLeft);
            float walkImageW = walkRightImage.getWidth();
            float walkImageH = walkRightImage.getHeight();
            float walkImageWidth = app.screenWidth*0.15f;
            float walkImageHeight = walkImageWidth*(walkImageH/walkImageW);
            walkLeftImage.isTouchable();
            walkRightImage.isTouchable();
            walkRightImage.setSize(walkImageWidth,walkImageHeight);
            walkLeftImage.setSize(walkImageWidth,walkImageHeight);
            walkRightImage.setPosition(stage.getWidth()/2-walkImageWidth/2,0);
            walkLeftImage.setPosition(stage.getWidth()/2-walkImageWidth/2,0);
            walkLeftImage.addAction(moveBy(3f,3f,3f));
            stage.addActor(walkLeftImage);

        }

        @Override
        public void render(float delta) {

            Gdx.gl.glClearColor(0, 0, 0, 1);
            Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
            walkAnimate.update(deltaTime);
            update(delta);
        }

        public void update(float delta){
            stage.act(delta);
            stage.draw();
            app.batch.begin();

            app.batch.end();
        }

        @Override
        public void resize(int width, int height) {

        }

        @Override
        public void pause() {

        }

        @Override
        public void resume() {

        }

        @Override
        public void hide() {

        }

        @Override
        public void dispose() {
            stage.dispose();

        }
    }

```

WalkAnimate.java

```
public class WalkAnimate {

        public ThumbChase app;
        public Stage stage;

        private Animation walkAnimationRight;
        private Animation walkAnimationLeft;
        private Texture walkSheetRight;
        private Texture walkSheetLeft;
        private TextureRegion[] walkFramesRight;
        private TextureRegion[] walkFramesLeft;
        private TextureRegion   currentFrameRight;
        private TextureRegion   currentFrameLeft;
        private float stateTime;
        private Rectangle bound; //used for positioning and collision detection
        private static final int  FRAME_COLS_WALK = 3;
        private static final int  FRAME_ROWS_WALK= 2;
        private float screenWidth = Gdx.graphics.getWidth();
        private float screenHeight = Gdx.graphics.getHeight();
        public float currentFrameWidth = (float)(screenHeight*0.15);
        public float currentFrameHeight = (float)(screenHeight*0.15);
        public float walkSheetWidth;
        public float walkSheetHeight;

        public WalkAnimate () {

            walkSheetRight = new Texture("ninjaWalkRight.png");
            walkSheetWidth = walkSheetRight.getWidth();
            walkSheetHeight = walkSheetRight.getWidth();
            TextureRegion[][] tmp = TextureRegion.split(walkSheetRight, (int) walkSheetRight.getWidth() / FRAME_COLS_WALK, (int) walkSheetRight.getHeight() / FRAME_ROWS_WALK);
            walkFramesRight = new TextureRegion[FRAME_COLS_WALK * FRAME_ROWS_WALK];
            int index = 0 ;
            for (int i = 0; i < FRAME_ROWS_WALK; i++) {
                for (int j = 0; j < FRAME_COLS_WALK; j++) {
                    walkFramesRight[index++] = tmp[i][j];
                }
            }
            walkAnimationRight = new Animation(0.044f, walkFramesRight);
            stateTime = 0f;

            walkSheetLeft = new Texture("ninjaWalkLeft.png");
            walkSheetWidth = walkSheetLeft.getWidth();
            walkSheetHeight = walkSheetLeft.getWidth();
            TextureRegion[][] tmp1 = TextureRegion.split(walkSheetLeft, (int) walkSheetRight.getWidth() / FRAME_COLS_WALK, (int)walkSheetLeft.getHeight() / FRAME_ROWS_WALK);
            walkFramesLeft = new TextureRegion[FRAME_COLS_WALK * FRAME_ROWS_WALK];
            int index1 = 0;
            for (int i = 0; i < FRAME_ROWS_WALK; i++) {
                for (int j = 0; j < FRAME_COLS_WALK; j++) {
                    walkFramesLeft[index1++] = tmp1 [i][j];
                }
            }
            walkAnimationLeft = new Animation(0.044f, walkFramesLeft);
            stateTime = 0f;

        }

        public Rectangle getBound(){
            return bound;
        }

        public void update(float delta){
            stateTime += delta;
            currentFrameRight = walkAnimationRight.getKeyFrame(stateTime, true);
            currentFrameLeft = walkAnimationLeft.getKeyFrame(stateTime, true);
        }

        public TextureRegion getCurrentFrameRight(){
            return currentFrameRight;

        }
        public TextureRegion getCurrentFrameLeft(){
            return currentFrameLeft;
        }
    }

```

And here's the error:

```
> java.lang.NullPointerException
>                                                                                at
> com.badlogic.gdx.graphics.g2d.TextureRegion.setRegion(TextureRegion.java:112)
>                                                                                at
> com.badlogic.gdx.graphics.g2d.TextureRegion.<init>(TextureRegion.java:63)
>                                                                                at
> com.jpfalmazan.thumbchaseninja.GameScreens.LevelOneScreen.show(LevelOneScreen.java:54)
>                                                                                at com.badlogic.gdx.Game.setScreen(Game.java:61)
>                                                                                at
> com.jpfalmazan.thumbchaseninja.GameScreens.MenuScreen$1.clicked(MenuScreen.java:82)
>                                                                                at
> com.badlogic.gdx.scenes.scene2d.utils.ClickListener.touchUp(ClickListener.java:89)
>                                                                                at
> com.badlogic.gdx.scenes.scene2d.InputListener.handle(InputListener.java:58)
>                                                                                at com.badlogic.gdx.scenes.scene2d.Stage.touchUp(Stage.java:353)
>                                                                                at
> com.badlogic.gdx.backends.android.AndroidInput.processEvents(AndroidInput.java:379)
>                                                                                at
> com.badlogic.gdx.backends.android.AndroidGraphics.onDrawFrame(AndroidGraphics.java:457)
>                                                                                at
> android.opengl.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:1516)
>                                                                                at android.opengl.GLSurfaceView$GLThread.run(GLSurfaceView.java:1240)

```

# Answer
You don't initialize your `currentframeRight` and `currentFrameLeft` in the constructor.

Put this in the constructor of `WalkAnimate`:

```
currentFrameRight = walkAnimationRight.getKeyFrame(0f, true);
currentFrameLeft = walkAnimationLeft.getKeyFrame(0f, true);

```

So it looks like this:

```
public WalkAnimate () {

        walkSheetRight = new Texture("ninjaWalkRight.png");
        walkSheetWidth = walkSheetRight.getWidth();
        walkSheetHeight = walkSheetRight.getWidth();
        TextureRegion[][] tmp = TextureRegion.split(walkSheetRight, (int) walkSheetRight.getWidth() / FRAME_COLS_WALK, (int) walkSheetRight.getHeight() / FRAME_ROWS_WALK);
        walkFramesRight = new TextureRegion[FRAME_COLS_WALK * FRAME_ROWS_WALK];
        int index = 0 ;
        for (int i = 0; i < FRAME_ROWS_WALK; i++) {
            for (int j = 0; j < FRAME_COLS_WALK; j++) {
                walkFramesRight[index++] = tmp[i][j];
            }
        }
        walkAnimationRight = new Animation(0.044f, walkFramesRight);
        stateTime = 0f;

        walkSheetLeft = new Texture("ninjaWalkLeft.png");
        walkSheetWidth = walkSheetLeft.getWidth();
        walkSheetHeight = walkSheetLeft.getWidth();
        TextureRegion[][] tmp1 = TextureRegion.split(walkSheetLeft, (int) walkSheetRight.getWidth() / FRAME_COLS_WALK, (int)walkSheetLeft.getHeight() / FRAME_ROWS_WALK);
        walkFramesLeft = new TextureRegion[FRAME_COLS_WALK * FRAME_ROWS_WALK];
        int index1 = 0;
        for (int i = 0; i < FRAME_ROWS_WALK; i++) {
            for (int j = 0; j < FRAME_COLS_WALK; j++) {
                walkFramesLeft[index1++] = tmp1 [i][j];
            }
        }
        walkAnimationLeft = new Animation(0.044f, walkFramesLeft);
        stateTime = 0f;

        // add this !
        currentFrameRight = walkAnimationRight.getKeyFrame(0f, true);
        currentFrameLeft = walkAnimationLeft.getKeyFrame(0f, true);

    }

```

**Why?**

In your `show()` method you call `ninjaWalk()`, and `ninjaWalk()` calls this: `walkAnimate.getCurrentFrameRight()` **but** walkAnimate didn't update yet so it doesn't have assigned any texture in currentFrameLeft or Right.

**And here is why it isn't animating**

```
@Override
public void render(float delta) {

    Gdx.gl.glClearColor(0, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    walkAnimate.update(deltaTime); // you have two deltas, use delta
    update(delta);
}

```

You have two deltas in your class. Remove the whole `deltaTime` variable and use only `delta` from `render()` like this `walkAnimate.update(delta)`;
> 3 votes

---
Tags: libgdx, scene2d
---


title: Is reusing BitmapFonts possible in GDX?

text:
# Question
Title: Is reusing BitmapFonts possible in GDX?
I'm loading multiple labels (100+) with different font types (max 10), but they have different sizes.

As I read the code and did the research, it's not possible to 'reuse' the font.

For instance, I have 5 labels made with GILL\_SANS font but these labels must have different scales (font scales).

Should I really make 5 different `BitmapFont` objects for different scales (AND LOAD THESE TERRIBLE GRAPHICS AGAIN AND AGAIN) or is there any way to optimize this (without loading `.fnt` and `.png` again)?

One load takes 2mbs of RAM (huge png) + ~2ms which is unacceptable for 100 labels.

**Edit** I've check that. Label caches fonts so you can scale the same font and use setFontScale() on each label. But what about TextField?

# Answer
As written here: http://www.badlogicgames.com/forum/viewtopic.php?f=15&t=24124&sid=afb7ff8255e632d2dfcc9383c8001603

The best way to achieve this is to copy the whole `Textfield` class, add some variables like:

`float fontScaleX, fontScaleY;`

and scale and unscale them in `draw()`.
> 0 votes

---
Tags: libgdx, fonts, memory-efficiency
---


# Question
Title: LibGDX - how to close game and dispose objects properly
can someone tell me how to close game and dispose objects properly? I tried several methods but always have problems. I have ImageButton with `ClickListener`.

Here's code of listener:

```
exitListener = new ClickListener(){
            @Override
            public void clicked(InputEvent event, float x, float y) {
                getGame().dispose(); // reference to GameClass
                Gdx.app.exit();
                super.clicked(event, x, y);
            }
        };

```

but something causes problems because I have error:

> buffer not allocated with newUnsafeByteBuffer or already disposed

and logs show that stage.dispose() causes problems.

# Answer
The problem is because you're trying to dispose of the Stage while you're still inside the clicklistener, and it isn't done processing yet. Instead of trying to quit at that point, I would set a variable like `stillRunning = false;` in your listener, and then check it at the end of your game loop in `render()` when you know your process is outside of the Stage.
> 1 votes

# Answer
Some people argue that the proper way to dispose of your game properly is by letting the Operating System do it. That means, don't free any resources at all, just quit the program and let the OS do the clean up. Of course, that only goes for resources that the OS is defined to clean up, and also of course, not everybody agrees with this mentality.
> 1 votes

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


# Question
Title: Gamemaker: images appear blurred in application
I'm making a practice game (generic space invaders clone) in Gamemaker Studio. However, there appears to be a problem with the images. While they look acceptable in Gamemaker Studio (not amazing, due to stretching effects, but acceptable for a practice project):

However, once I compile the project down to an application I get this blurring effect:

Can anyone tell me what's causing this, and how to turn it off?

# Answer
> 1 votes
As far as my eyes see on your example, the upper part of those sprites have hard edges.

Bilinear interpolation blends from color to color, if you use a bigger resolution for your sprites than the sprites base resolution.

sooo Turn off the Bilinear Interpolation on the Sprite images. Set it to "point". https://docs.yoyogames.com/source/dadiospice/002\_reference/drawing/texture\_set\_interpolation.html

This probably leads to another problem, depending on sprite resolution and virtual resolution and screen resolution, see here:

https://gamedev.stackexchange.com/a/129363/86773

# Answer
> 0 votes
It appears as if the view port size (which can be adjusted in the Views tab) is larger than the background you're using, so the image is stretched. If this is the size you want, go into the Global Game Settings, open "Windows" and uncheck "Interpolate colors between pixels" and the background should be stretched in a more pixelated way.

---
Tags: sprites, game-maker, image, blur, image-processing
---


title: ERROR: MissingComponentException

text:
# Question
Title: ERROR: MissingComponentException
I want my gameObject to play an audio clip when it collides with other gameObjects. So I attached a script named "ImpactSound" with it, but it's keep showing MissingComponentException: There is no "AudioSource" attatched to the ball(clone)game object, but a script is trying to accept it.

```
    using UnityEngine;
    using System.Collections;

    public class ImpactSound : MonoBehaviour {

    public AudioClip impact;
    AudioSource source;

    // Use this for initialization
    void Start () {
    source = GetComponent<AudioSource>();
    }

    // Update is called once per frame
    void OnCollisionEnter2D() {
    Debug.Log ("Sound was supposed to play on collision!");
    source.PlayOneShot (impact);
    }
    }

```

# Answer
> 2 votes
It seems you don't have an Audio Source attached with that following game object.

# Answer
> 0 votes
The RequireComponent attribute automatically adds required components as dependencies.

> When you add a script which uses RequireComponent to a GameObject, the required component will automatically be added to the GameObject. This is useful to avoid setup errors. For example a script might require that a AudioSource is always added to the same GameObject. Using RequireComponent this will be done automatically, thus you can never get the setup wrong. Note that RequireComponent only checks for missing dependencies during the moment the component is added to a GameObject. Existing instances of the component whose GameObject lacks the new dependencies will not have those dependencies automatically added.

```
using UnityEngine;
using System.Collections;

[RequireComponent (typeof (AudioSource))]
public class ImpactSound : MonoBehaviour
{
    public AudioClip impact;
    AudioSource source;

    // Use this for initialization
    void Start()
    {
        source = GetComponent<AudioSource>();
        source.clip = impact;
    }

    // when collide with other with tag enemy play sound
    void OnCollisionEnter2D(Collision2D other)
    {
        if (other.gameObject.tag == "Enemy")
        {
            source.PlayOneShot(impact);
        }
    }
}

```

other way for prevent missing error that checking object have AudioSource component.in this example I use Property for checking it.

```
using UnityEngine;
using System.Collections;

public class ImpactSound : MonoBehaviour
{
    public AudioClip impact;
    AudioSource source
    {
        get
        {
            if (GetComponent<AudioSource>() == null)
            {
                gameObject.AddComponent<AudioSource>();
                return GetComponent<AudioSource>();
            }else
            {
                return GetComponent<AudioSource>();
            }
        }
        set
        {
                source.clip = impact;
        }
    }

    void OnCollisionEnter2D(Collision2D other)
    {
        if (other.gameObject.tag == "Enemy")
        {
            source.PlayOneShot(impact);
        }
    }
}

```

if you don't like have error you can use AudioSource.PlayClipAtPoint , in this way your object Instantiate empty gameObject with AudioSource component in position that is easy way for play sound.

```
using UnityEngine;
using System.Collections;

public class ImpactSound : MonoBehaviour
{
    public AudioClip impact;

    // when collide with something play sound
    void OnCollisionEnter2D()
    {
            Debug.Log("Sound was supposed to play on collision!");
            AudioSource.PlayClipAtPoint(impact, transform.position);
    }
}

```

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


# Question
Title: How do I implement semi-random level generation?
I am trying to make a platform game that generates semi-random levels. I want it to read in the segments of a level and then choose a random one from among these segments. I am stuck. I have absolutely no clue how to set up a system like this and I can't find any good tutorials.

# Answer
> 2 votes
The answer to this is highly dependent on what you want out of your semi-random levels, but I'll assume for now that you are moving horizontally and want chunks of level such as a pit with a platform over it or a constrained space with enemies in it that you set up beforehand.

To take this approach you need to have the ability to load one of these level chunks on the fly. This means that you need to be able to have everything that describes one (tile layout if tile based, types of objects and locations/orientations for everything else) in an object that you can reference such as a class. This could be as simple as an object containing an array of what to spawn and where, but you can also add other things as necessary.

Once you have the ability to have these chunks in memory, you then need to set up your game to be able to take one of these chunks and a location so you can spawn all the objects relative to that location. This location could be the top left corner, the place where the edge of the ground touches the new edge of the ground, whatever. So long as the level chunk object locations are also described as positions relative to this anchor.

From here you have a couple options. Assuming you create a number of level chunks, you can then choose from them randomly to set up your random level.

If you know you want the level to be a fixed set and/or finite, at this point you can simply load x random segments at the appropriate positions (perhaps with one or two fixed to things you want at certain locations like a level end or a checkpoint).

If you want to generate your levels on the fly and/or have an infinite level, load enough level chunks to cover the camera plus at least one off each edge the player can move in. These are your buffer so the player never sees empty space (also so enemies off screen can do things if that's how you like it). When one of those buffer chunks would come into the camera, load a new random chunk out of camera as the new buffer. Depending on your gameplay you can also remove the level chunk you moved away from to avoid having too much in memory or if you know you're not going back that way.

There are of course a lot of modifications that can be made to this general formula as well as refinements for various behaviour; but hopefully this will give you a good jumping off point for exploring the world of level generation.

---
Tags: c++, game-design, game-mechanics
---


# Question
Title: Control Camera with gyroscope and place a gameobject always in front of it
Actually I have came here after searching from past 5-6 hours. Actually I am making a small game in which I have a camera and a gameobject. The Game Object is place in the center of the scene at 0,0,0 . My scene doesn't include anything but a skybox. I wanted to move my camera with gyro input, I got that working. My problem is that I want my object which is at 0,0,0 is to face camera always. The camera is controlled by gyro so the object should always remain infront of the camera. I have taken a script from wiki.unity3d and it seems to be somewhat working. Actually I want an offset for the transform.lookAt or if it's not possible I'll require some solution for it.

```
public class CameraFacing : MonoBehaviour
{
    public Camera m_Camera;

    void Update()
    {
        transform.LookAt((transform.position) + m_Camera.transform.rotation * Vector3.forward,
                m_Camera.transform.rotation * Vector3.up);
    }
}

```

Actually I have tried 3rd person and FPS shooter camera and Camera Follow script as well besides knowing it doesn't fit my need. As In most cases we want the camera to follow object. But in this case my input is through gyro of mobile device and I want the center object to always remain in front of camera.

Here is the code for gyroscope. I have made the object which I want to always stay infront of camera as suggested by comment but the camera rotate with gyro but not the object that is child of it, which is pretty strange.

```
private float initialYAngle = 0f;
private float appliedGyroYAngle = 0f;
private float calibrationYAngle = 0f;
void Start()
{
    Input.gyro.enabled = true;
    Application.targetFrameRate = 60;
    initialYAngle = transform.eulerAngles.y;
}

void Update()
{
    ApplyGyroRotation();
    ApplyCalibration();
}

public void CalibrateYAngle()
{
    calibrationYAngle = appliedGyroYAngle - initialYAngle; // Offsets the y angle in case it wasn't 0 at edit time.
}

void ApplyGyroRotation()
{
    transform.rotation = Input.gyro.attitude;
    transform.Rotate(0f, 0f, 180f, Space.Self); // Swap "handedness" of quaternion from gyro.
    transform.Rotate(90f, 180f, 0f, Space.World); // Rotate to make sense as a camera pointing out the back of your device.
    appliedGyroYAngle = transform.eulerAngles.y; // Save the angle around y axis for use in calibration.
}

void ApplyCalibration()
{
    transform.Rotate(0f, -calibrationYAngle, 0f, Space.World); // Rotates y angle back however much it deviated when calibrationYAngle was saved.
}

```

# Answer
While I agree that making your object a child of the camera should work (though it won't stay at 0,0,0); If you want to keep the object at it's current position and **only** adjust it's rotation to face the camera, you can use LookRotation to get the behavior you want.

To do so simply set the center object's rotation equal to Quaternion.LookRotation which takes one or two parameters. The first is the position to look at relative to the position of the object. To get this simply subtract the target position from the object's position. The second is the up direction, which you can ignore unless the camera also rolls around the Z from your gyro movement and you want the object to match that, in which case you can just pass it the .up from your camera's transform.

In the end you should end up with something like this:

```
transform.rotation = Quaternion.LookRotation(m_Camera.transform.position - transform.position);

```

or

```
transform.rotation = Quaternion.LookRotation(m_Camera.transform.position - transform.position, m_Camera.transform.up)

```

**Note that neither of these will move the object, so if you rotate your camera without moving it in space to keep it facing the object the object will leave the center of your screen when you turn the camera!**

If you want the object to stay in the center of the screen upon rotating the camera then it's impossible to leave it at 0,0,0 without major shenanigans and making it a child object remains your best option (any setting of the position by you would just be duplicating a good chunk of what making an object a child does already)

If making the object a child of the camera doesn't seem to be working, make sure it's parented to the gameobject that's actually rotating and not a container object which only shifts position. This is an easy mistake to make that's tripped me up before when working with camera objects where the object with the actual camera component was actually one or two children down in the hierarchy.
> 1 votes

# Answer
Well I think I was overthinking as I was doing it for VR Headset so I was thinking there should be some really complex thing to achieve this. But this is super simple. You need to make the object child of your camera and keep in mind that you need to position it locally. Thanks.
> 0 votes

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


# Question
Title: Apply shading to Solid Sphere? OpenGL C++
To Apply shading to an object. Let's say earth (which was textured using an image). So how to apply smooth shading to that? What are the steps I need to write? Using which functions? Thank you.

**Code**

```
void drawScene()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glBindTexture(GL_TEXTURE_2D, textureOfSun);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glEnable(GL_TEXTURE_2D);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glPushMatrix(); // Push matrices

// Draw Sun

gluQuadricTexture(quadricSun,1);
gluSphere(quadricSun,2,20,20);
glPopMatrix();

//Draw Earth
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, textureOfEarth);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

//Rotation around Sun

//Revolve of Earth

glPopMatrix();
gluQuadricTexture(quadricEarth,1);
gluSphere(quadricEarth,0.75,20,20);

glutSwapBuffers();
}

```

This is the rendering part,

```
void initRendering()
{
glEnable(GL_DEPTH_TEST);
glEnable(GL_NORMALIZE);
glEnable(GL_COLOR_MATERIAL);
quadricSun = gluNewQuadric();
quadricEarth = gluNewQuadric();

textureOfSun = LoadTexture(location1);
textureOfEarth = LoadTexture(location2); /* location1 and 2 says the locations of images */
}

```

# Answer
Google should have had an answer for you on this on, if you did try :).

But try putting this in your function 'initRendering' at the beginning for example:

```
glEnable(GL_LIGHTING);
GLfloat global_ambient[] = { 1.0f, 1.0f, 1.0f, 1.0f };
glLightModelfv(glShadeModel(GL_SMOOTH), global_ambient);
glShadeModel(GL_SMOOTH);

```

This is old legacy code
> 0 votes

---
Tags: opengl, c++, shading
---


title: LibGDX - huge font

text:
# Question
Title: LibGDX - huge font
I have big problem with drawing font. My virtual world is 20x15 meters (viewport and camera too). I use `FreeTypeFontGenerator`. But something is wrong because for example if I have font 40px (40px = 1 meter) my font is very huge. I tried scaling but effect is bad. I read somewhere that using second SpriteBatch will solve problem? or maybe someone have different idea?

# Answer
> 2 votes
You can use different view ports to make sure the font doesn't get to streched out.

For example, if your viewport is **20x15** then a `BitmapFont` rendered at font size 12 (for example) will look very big, but you can let the view port used when rendering the text be a special one, that's been set to a larger size.

Example rendering text in the **20x15** view port size:

But if the viewport for the text is scaled up:

A code example of how to achieve that could look something like this;

```
package com.bornander.androidstudiosandbox;

import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator;

public class MyAndroidStudioSandboxGame extends Game {
    private SpriteBatch batch;
    private OrthographicCamera camera;
    private OrthographicCamera textCamera;
    private BitmapFont font;

    @Override
    public void create () {
        batch = new SpriteBatch();

        // I am not setting my viewport to be 20x15, but 20x<whatever make sense for the aspect ratio to be maintained>
        float aspectRatio = (float)Gdx.graphics.getHeight() / (float)Gdx.graphics.getWidth();
        float viewPortWidth = 20;
        float viewPortHeight = viewPortWidth * aspectRatio;

        float cameraViewPortWidth = 1024; // Set the size of the viewport for the text to something big
        float cameraViewPortHeight = cameraViewPortWidth * aspectRatio;

        camera = new OrthographicCamera(viewPortWidth, viewPortHeight);
        textCamera = new OrthographicCamera(cameraViewPortWidth, cameraViewPortHeight);

        font = buildFont("Arial.ttf", 8, "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890\"!`?'.,;:()[]{}<>|/@\\^$-%+=#_&~*");
    }

    private static BitmapFont buildFont(String filename, int size, String characters) {
        FreeTypeFontGenerator generator = new FreeTypeFontGenerator(Gdx.files.internal(filename));
        FreeTypeFontGenerator.FreeTypeFontParameter parameter = new FreeTypeFontGenerator.FreeTypeFontParameter();
        parameter.size = size;
        parameter.characters = characters;
        parameter.kerning = true;
        parameter.magFilter = Texture.TextureFilter.Linear;
        parameter.minFilter = Texture.TextureFilter.Linear;
        BitmapFont font = generator.generateFont(parameter);
        font.getData().markupEnabled = true;
        generator.dispose();
        return font;
    }

    @Override
    public void render () {
        Gdx.gl.glClearColor(0, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        camera.update();
        textCamera.update();

        batch.begin();
        batch.setProjectionMatrix(camera.combined);
        // Render you game here using the "game" camera

        // Here we change the projection, and render the text
        batch.setProjectionMatrix(textCamera.combined);
        font.draw(batch, "ABC", 0 ,0);

        batch.end();
    }
}

```

Note that the actual size of the window or display that is used to show the game also has some bearing on the result.

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