# Question
Title: How to model muscle contraction force acting on two bones connected by joint in Unity/PhysX?
I'm trying to understand what is a correct way to model a muscle contraction in a physics engine like PhysX (Unity3D). Muscle that I'm modelling is connected to a bones in 2 points A and B.

Having a total force for the muscle `fTotal`, I'm trying to apply two forces in points A and B on corresponding bones, where magnitude of each force is a half of the total force. And of course force vectors are lying on the same AB line and pointing to the opposite directions towards the center of the muscle.

```
fTotal = ||fA|| + ||fB||

```

One thing that bothers me is a situation when one bone is fixed in space. Intuitively, all contraction force should be applied only to a single attachment point, however, my model will apply only 1/2 of a force. Can you suggest a better way to implement this?

# Answer
> -2 votes
just saw your idea and it helped me on my project! As for your problem: I think that the presence of a fixed object ("kinematic" I guess) is a problem specific enough to deserve a solution of it own. Just check if the other part is kinematic. If yes, then apply the full force on the movable part.

---
Tags: unity, physics
---


title: How to set parent for prefab in Unity

text:
# Question
Title: How to set parent for prefab in Unity
I have a prefab of a button (btn) that I need to set parent (\_canvos) for it after it spawned (online)...

I have try this code:

```
public Transform btn;
public Transform mkn;
public Image _canvos;

public void test ()
{
    Transform InTank = Network.Instantiate (btn, mkn.transform.position, Quaternion.identity, 0)as Transform;
    btn.SetParent(_canvos);
}

```

But it doesn't work.

> error: MissingReferenceException: The object of type 'Object' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object. what's the problem??

# Answer
Setting parent should be like:

```
InTank.SetParent(_canvos.transform);

```

First error is because of not set parent with a transform.

Second error is because of not using with the instantiated Transform.
> 1 votes

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


# Question
Title: How to render a single texture across multiple tiles? (Unity2D)
I'm making a top-down style game in Unity 5 (2D). The floor is made up of many tiles (which are each game objects) of different types, eg sand and dirt.

I want to render a single texture over all of a single type of tile. So if I had a large area of sand, a single texture would be displayed for all of it. However, if there was a small area of dirt within that sand, that would need its own texture as well. These areas wouldn't necessarily be square either.

I've seen this used in games such as RimWorld, but I have no idea how to accomplish it. Any ideas?

Edit: Added picture of what I am attempting. This is a screenshot from RimWorld. As you can see, the sand is made up of hundreds of tiles, but has only one texture over it.

This is all I have managed so far:

# Answer
Apparently the recommended StackExchange approach when two different questions can be solved by the same answer is to reproduce the relevant parts of the solution, along with a link. So:

---

I proposed worldspace texturing to solve an earlier question about adjusting the tiling of a texture when scaling geometry. As a helpful side effect, this also makes adjacent object tile seamlessly together (assuming an appropriate texture), so it can be used in this case too.

In this example you can see conventional texture mapping on the left, using four standard quads at different scales with one material. On the right are the same four quads textured in worldspace using a single material. (The brick texture is a free asset from Kenney)

To do this, create a new shader something like the following:

```
Shader "Unlit/WorldspaceTiling"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
    }
    SubShader
    {
        Tags { "RenderType"="Opaque" }
        LOD 100

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

            // Structure for input coming from the game to the vertex shader.
            struct appdata
            {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
            };

            // Structure to pass data from vertex to fragment shader.
            struct v2f
            {
                float2 uv : TEXCOORD0;
                float4 vertex : SV_POSITION;
            };

            // Variables to refer to the texture & transform parameters assigned in the Inspector.
            sampler2D _MainTex;
            float4 _MainTex_ST;

            // Vertex shader transforms each vertex & preps data for interpolation.
            v2f vert (appdata v)
            {
                // Prepare a structure to hold the output.
                v2f o;

                // Transform the vertex into screen space.
                o.vertex = mul(UNITY_MATRIX_MVP, v.vertex);

                // Get the xy position of the vertex in worldspace.
                // We'll use these instead of the object's own texture coordinates.
                float2 worldXY = mul(_Object2World, v.vertex).xy;

                // Apply the texture offset & scale parameters set in the material Inspector.
                o.uv = TRANSFORM_TEX(worldXY, _MainTex);

                return o;
            }

            // Fragment shader renders each pixel.
            fixed4 frag (v2f i) : SV_Target
            {
                // Look up the right colour from the texture and output it.
                fixed4 col = tex2D(_MainTex, i.uv);
                return col;
            }
            ENDCG
        }
    }
}

```

(Here I've used an unlit opaque shader without fog as a base, but other effects can be incorporated in a straightforward way if you need.)

Assign this shader to a new material, drop in your texture (make sure its wrap mode is set to repeat), and apply that material to your tiles. You can use the regular texture tiling & offset fields to fine-tune how many repeats you want per world unit and the alignment of the tiling.

---

As you've noted in the comments above, using this on a `SpriteRenderer` prevents us from changing the scale & offset of the tiling using the material's texture transform parameters. Switching to quads with `MeshRenderers` solves this issue. If you want the atlasing & layering features of a SpriteRenderer we can make an alternate version of the shader, but it's likely to be more complicated than what you need.

For additional optimizations, we could even get rid of the individual tile objects entirely, and just draw one big quad for your level, using a texture to mark which tile texture should be used for each square of the grid.
> 0 votes

---
Tags: unity, tiles
---


# Question
Title: How to calculate random new position base on original position on map
I am making a 2D game with HTML5 Canvas. The game has several shapes and I want them to move all over the map randomly.

> 1. However, if I just give them a constant angle to follow, they will all end up in a corner after a certain amount of time.
> 2. Also, I am building this game with client-server so I don't want to send a lot of data. For example, I don't want to constantly update the angle on the server side and send it to the client.

**That's why I want to generate a random position base on the shape's position on the big map.**

For example, it's angle of movement will be tangent of it's (x,y). (It obviously won't work because it will get stuck on the sides of the map).

So what's a good way of generating the new coordinates base on it's current one?

# Answer
> 2 votes
What you need then is a function in the format:

```
xy nextPosition(seed, x, y)

```

A function which takes a seed value, and a current x and y location, and returns a new x and y location based on noise functions which use the seed for randomness, so that no matter how many times the function is called, the result returned for any given set of input is always the same. All the server would need to do is sync the seed, x and y values initially of all objects in a scene across all clients and from that the client could correctly calculate every update the object position after that, as long as the clients all update at the same frame rate, eg: 60/sec.

As for the nextPosition() function itself, if you want to avoid walls you need to blend the result of two equations. One equation which will move the object away from the wall, and one equation which will move the object in a noise randomised direction based on the seed value. And you'd just blend between the results based on how close the object is to the wall. So that as the object approaches the wall, the desire to move away from it increasingly takes over until eventually it's the sole driving motivator. But in the middle of the arena, there'd be no urge to avoid walls at all and objects would roam freely.

Alternatively, the server could calculate target locations for objects to move towards, and sync those targets, and clients could just simulate those objects moving towards their targets with infrequent updates of target locations whenever an object is close to reaching it's target. That way you're not sending an update of direction at 60hz, just a new target location every second or so.

I hope either of those solutions help?

---
Tags: 2d, game-design, javascript, algorithm, client-server
---


title: 2d MMO world generation?

text:
# Question
Title: 2d MMO world generation?
I am developing a MMO, and i'll describe it as a 2d mine craft (it's a lot more complicated than that). There will be a multitude of blocks that will be in a world. I need them to be randomly placed. Im not quite sure how to do this, such as should I make a tile map with the items and place a random item in the tilemap when the world is loaded??? I am using python with pygame. Any answers will be appreciated.

# Answer
I couldn't tell from your question if your world is top down or side on. But I'm going to assume top down for my answer.

If you just want the blocks to be totally random, all you'd need to is go through each block in your 2D world, which is basically an image, and place a random block value. That would be "random", but it wouldn't look very nice.

I would recommend investigating procedural generation of environments, concepts such as biomes, noise functions, etc.

Ideally you'd define a set of Biomes like:

* Grass Field
* Forest
* Town
* Beach
* Lake
* Ocean

Each Biome would contain it's own rules for how to generate blocks for that type of Biome. Such as forest might contain a rule for frequently generating tree blocks. Beach could use 90% sand blocks and 10% shells/rocks/beachball blocks.

And then your procedural generation function would be somewhat like this: Biome pickBiome(int seed, int x, int y)

At each point on your map you could call that function, which would use noise functions and other calculations to pick a biome. This function would return a consistent result every time it's called if called with the same seed and at the same coordinate. Different worlds would be generated by using different seed values, not just a rand() function.

The function would also have to smoothly transition from one biome to another, so perhaps the function could return several biomes and a weight function to blend between biomes while generating the world.

I also recommend looking up how Minecraft itself generates terrain as it works on a similar basis to everything I just described.

Hopefully that gives you some ideas! Good luck!
> 3 votes

# Answer
To add on to Grady's answer. You also have some templates for creating dungeons. Obviously it will be a pain in the arse to find a RNG algorithm that will set up a very complex dungeon from scratch. So this is where a lot of games tend to cheat.

When you play a game that features fully featured RNG like minecraft, terraria, or Starbound, you will start to notice that there are some elements that are similar enough in appearance if you paid attention. If you were to take a snap shot of those pieces, and carry them with you and compare them to the next location. You will see that more complex structures are really just prefabs of rooms with rules set to how they should link up.

To get a mental picture of this... if you were to go out to the store, and buy a D&D tileset, you would notice that they are prefabricate slots of land. The dungeon master can put these together in any manner of way to achieve some insane number of dungeon set ups. The only rule is that there needs to be some form of consistency. Like a river under no circumstance should just end randomly as you transition from one prefab to the next without an outflow. So either you tell the RNG algorithm to link a prefab that safely continues that detail, OR you provide a way to just cut it off in a pleasing way.
> 1 votes

---
Tags: game-design, python, pygame
---


# Question
Title: Unity: Creating a panel that stretches using anchors
Relative newbie to Unity so please excuse any oversights. I have a component (canvas/panel) that I'm wanting to add a panel to, so that when the parent component's height changes, the child panel's height changes to match. I've achieved this manually using the inspector (see top half of attached pic) to set the anchor points at min(0.5, 0) and max(0.5, 1) (pivot is unchanged at (0.5,0.5)).

I want to create that stretching panel in scripting, and have the following code that results in the bottom half of the attached pic where the rect transform's anchors aren't set at all.

```
GameObject panel2 = GameObject.Find("Panel2");

GameObject divider = new GameObject("RunTimeLine");
divider.layer = LayerMask.NameToLayer("UI");
divider.transform.SetParent(panel2.transform);

CanvasRenderer c = divider.AddComponent<CanvasRenderer>();

RectTransform rt = (RectTransform)divider.AddComponent<RectTransform>();

Image img = divider.AddComponent<Image>();
img.color = Color.red;

rt.localPosition = new Vector2(0f, 0f);
rt.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, 20);
rt.anchorMin.Set(0.5f, 0);
rt.anchorMax.Set(0.5f, 1);

```

Any suggestions? I've also tried setting the min/max offsets and pivot but haven't been able to create what I've got manually in the inspector.

# Answer
Unsure if this is a bug, but setting the anchors has to be done with

rt.anchorMin = new Vector2(0.5f, 0);

and NOT

rt.anchorMin.Set(0.5f, 0);

IMO this is a bug, but will leave it up to others to inform me otherwise.
> 1 votes

---
Tags: unity
---


# Question
Title: Showing Google Play Game Leaderboard UI not working at all
Trying to figure out what went wrong with this GPG plugin. I followed the instructions and understand the document in order to test run the login and show leaderboard UI via this one. I did make the play games achievements + leaderboard via Google Play developer account, do the setup, copy-paste source, and done. Testing the ads via adding *Admob* Unity package and GPG Unity package and it worked perfectly. I even update some plugins for Android (etc. .aar files, firebase-common, manifest) in order to maximize compatibility and efficiency so that I could build APK without any issues that interfering the build-up.

However, there is one issue: after I logged in and trying to tap the "show leaderboard UI" button along with the button event that asks if the user is authenticated and it will allow you to record your latest highscore by updating it before showing the leaderboard UI. Here's how the code works:

First, at the Start() callback...

```
PlayGamesClientConfiguration config = new PlayGamesClientConfiguration.Builder()
        .Build();

    PlayGamesPlatform.InitializeInstance(config);
    PlayGamesPlatform.DebugLogEnabled = true;
    PlayGamesPlatform.Activate();

```

Next, here's the login/logout process...

```
public void LogInAccount() {
// Show dialog.
y = 0;
dialogPanel.SetActive (true);
dialogBackground.SetActive (true);

// You can logout if you're logged in.
if(Social.localUser.authenticated) {

    ((PlayGamesPlatform)Social.Active).SignOut ();

    y = 0;
    message.text = "Your account have been logged out.";
    logButtonLabel.text = "Log-in via Google";
    button.SetActive (true);
    confirmSound.Play();

    return;

}

// Check for status.
if (CheckNetwork.checkOnlineStatus ()) {

    Social.localUser.Authenticate ((bool success) => {

        if (success) {

            // LOG IN SUCCESS! (Check if the email is identified or not.)
            if((((PlayGamesLocalUser)Social.localUser).Email != null) || (((PlayGamesLocalUser)Social.localUser).Email != "")) {

                y = 0;
                message.text = "Login complete. However, email is not verified or unknown.";
                logButtonLabel.text = "Log-out";
                button.SetActive (true);
                errorSound.Play();

            } else {

                y = 0;
                message.text = "Login complete!\nYour email:" + ((PlayGamesLocalUser)Social.localUser).Email;
                logButtonLabel.text = "Log-out";
                button.SetActive (true);
                confirmSound.Play();

            }

        } else if (!success) {

            // LOG IN FAILED.
            if((((PlayGamesLocalUser)Social.localUser).Email != null) || (((PlayGamesLocalUser)Social.localUser).Email != "")) {

                message.text = "Login failed. Please try again later.\nYour email: ? ? ?";

            } else {

                message.text = "Login failed. Please try again later.\nYour email: " + ((PlayGamesLocalUser)Social.localUser).Email;

            }

            y = 0;
            button.SetActive (true);
            logButtonLabel.text = "Log-in via Google";
            errorSound.Play();

        }

    });

} else {

    message.text = "Connection is lost. Please enable online.";
    button.SetActive (true);

}

```

}

And then, the show leaderboard callback/button event.

```
    public void OpenLeaderboard() {

        // Show dialog.
        y = 0;
        dialogPanel.SetActive (true);
        dialogBackground.SetActive (true);

        // Check for status.
        if (Social.localUser.authenticated && CheckNetwork.checkOnlineStatus ()) {

            // Updating your highscore...
            Social.ReportScore ((long)Score.GetScore (),
                AchievementReference.leaderboard_best_intergalactic_chasers_top_score,
                (bool success) => {

                    if(success) {

                        // LEADERBOARD APPEARED!
                        dialogPanel.SetActive (false);
                        dialogBackground.SetActive (false);
                        confirmSound.Play();
                        Social.ShowLeaderboardUI();
//                      ((PlayGamesPlatform)Social.Active).ShowLeaderboardUI(AchievementReference.leaderboard_best_intergalactic_chasers_top_score);

                    } else {

                        y = 0;
                        message.text = "Load failed. Please try again later.";
                        button.SetActive (true);
                        errorSound.Play();

                    }

                });

        } else if (!Social.localUser.authenticated) {

            y = 0;
            confirmSound.Play();
            button.SetActive (true);

            if (!CheckNetwork.checkOnlineStatus ()) {

                message.text = "Connection not available at a moment.";

            } else if (CheckNetwork.checkOnlineStatus ()) {

                message.text = "You must login first in order to see the leaderboard.";

            }

        }

    }

```

At my first attempt, I do login (it shows the welcome sign sometimes) and tap the leaderboard button but nothing happens after 2 minutes. Second attempt, I do login-logout-login method and the GPG prompted me to select the Email address and the welcome username sign appeared on top. However, still...when I tapped the show leaderboard UI button and nothing happens after 3 minutes. I used this reference to gain more ideas on effective showing the leaderboardc UI and checked for the code sample. Final attempt, and I assumed that leaderboard UI won't show up until I publish the Game Services I've created (it was set for testing mode before) and see if the leaderboard UI is working or not. Then after a day or two, used the same method from first second attempt and still got no luck.

The question is: how come the leaderboard UI still won't show-up during test mode and even after published the game services via Google play Services developer section? The same thing happen in displaying in Achievements UI. What was the cause that preventing the leaderboard UI from showing up even if I did it correctly on the setup? I doubt it's the internet connection issues or wifi signal. The issues probably is the long load on a very simple game services I've made. I only created only two leaderboards (highscore and no. of ships destroyed) and five achievements on reaching certain score and no. of ships destroyed. Please help.

Also, aside from showing leaderboard UI issues, there is also an error that leaves the string value (actually, I'm retrieving with the email address selected) null or empty even if successfully logged in via Google account follow-up by the welcome username sign at the top of the screen.

**UPDATE (As of 2:46 PM via Philippines, 7/5/2016):** After I checked the bugs and offer some solution from *S. Tarik Cetin*, I checked on logcat about login. At first, I thought it's successful login. Then, I noticed this:

```
W/Unity   (32099): *** [Play Games Plugin DLL] 07/05/16 14:33:54 -07:00 ERROR: E
xception launching token request: java.lang.ClassNotFoundException: com.google.g
ames.bridge.TokenFragment
W/Unity   (32099):
W/Unity   (32099): (Filename: ./artifacts/generated/common/runtime/UnityEngineDe
bugBindings.gen.cpp Line: 37)
W/Unity   (32099):
W/Unity   (32099): *** [Play Games Plugin DLL] 07/05/16 14:33:54 -07:00 ERROR: U
nityEngine.AndroidJavaException: java.lang.ClassNotFoundException: com.google.ga
mes.bridge.TokenFragment
W/Unity   (32099): java.lang.ClassNotFoundException: com.google.games.bridge.Tok
enFragment
W/Unity   (32099):      at java.lang.Class.classForName(Native Method)
W/Unity   (32099):      at java.lang.Class.forName(Class.java:217)
W/Unity   (32099):      at java.lang.Class.forName(Class.java:172)
W/Unity   (32099):      at com.unity3d.player.UnityPlayer.nativeRender(Native Me
thod)
W/Unity   (32099):      at com.unity3d.player.UnityPlayer.a(Unknown Source)
W/Unity   (32099):      at com.unity3d.player.UnityPlayer$b.run(Unknown Source)
W/Unity   (32099): Caused by: java.lang.NoClassDefFoundError: com/google/games/b
ridge/TokenFragment
W/Unity   (32099):      ... 6 more
W/Unity   (32099): Caused by: java.lang.ClassNotFoundException: com.google.games
.bridge.TokenFragment
W/Unity   (32099):      at dalvik.system.BaseDexClassLoader.findClass(BaseDexCla
ssLoader.java:61)
W/Unity   (32099):      at java.lang.ClassLoader.loadClass(ClassLoader.java:501)

W/Unity   (32099):      at java.lang.ClassLoader.loadClass(ClassLoader.java:461)

W/Unity   (32099):      ... 6 more
W/Unity   (32099):   at UnityEngine.AndroidJNISafe.CheckException () [0x00000] i
n <filename unknown>:0
W/Unity   (32099):   at UnityEn

```

Also, I encountered the status form my logcat when I did sign-in and out once.

```
W/Unity   (32099):   at UnityEn
I/Unity   (32099):  [Play Games Plugin DLL] 07/05/16 14:38:07 -07:00 DEBUG: Star
ting Auth Transition. Op: SIGN_OUT status: ERROR_NOT_AUTHORIZED
I/Unity   (32099):
I/Unity   (32099): (Filename: ./artifacts/generated/common/runtime/UnityEngineDe
bugBindings.gen.cpp Line: 37)
I/Unity   (32099):

```

Finally, here's the issue found during attempt on opening leaderboard UI directly.

```
W/Unity   (32099): *** [Play Games Plugin DLL] 07/05/16 14:40:31 -07:00 ERROR: U
nityEngine.AndroidJavaException: java.lang.ClassNotFoundException: com.google.ga
mes.bridge.NativeBridgeActivity
W/Unity   (32099): java.lang.ClassNotFoundException: com.google.games.bridge.Nat
iveBridgeActivity
W/Unity   (32099):      at java.lang.Class.classForName(Native Method)
W/Unity   (32099):      at java.lang.Class.forName(Class.java:217)
W/Unity   (32099):      at java.lang.Class.forName(Class.java:172)
W/Unity   (32099):      at com.unity3d.player.UnityPlayer.nativeRender(Native Me
thod)
W/Unity   (32099):      at com.unity3d.player.UnityPlayer.a(Unknown Source)
W/Unity   (32099):      at com.unity3d.player.UnityPlayer$b.run(Unknown Source)
W/Unity   (32099): Caused by: java.lang.NoClassDefFoundError: com/google/games/b
ridge/NativeBridgeActivity
W/Unity   (32099):      ... 6 more
W/Unity   (32099): Caused by: java.lang.ClassNotFoundException: com.google.games
.bridge.NativeBridgeActivity
W/Unity   (32099):      at dalvik.system.BaseDexClassLoader.findClass(BaseDexCla
ssLoader.java:61)
W/Unity   (32099):      at java.lang.ClassLoader.loadClass(ClassLoader.java:501)

W/Unity   (32099):      at java.lang.ClassLoader.loadClass(ClassLoader.java:461)

W/Unity   (32099):      ... 6 more
W/Unity   (32099):   at UnityEngine.AndroidJNISafe.CheckException () [0x00000] i
n <filen

```

One thing, another case found during authenticating the username before entering leaderboard UI. This report from logcat found before attempting to open the leaderboard.

```
I/Unity   ( 6099):  [Play Games Plugin DLL] 07/05/16 14:57:45 -07:00 DEBUG: Foun
d User: [Player: 'DavidTredecies029' (id g09634522073000464528)]
I/Unity   ( 6099):
I/Unity   ( 6099): (Filename: ./artifacts/generated/common/runtime/UnityEngineDe
bugBindings.gen.cpp Line: 37)
I/Unity   ( 6099):
I/Unity   ( 6099):  [Play Games Plugin DLL] 07/05/16 14:57:45 -07:00 DEBUG: Mayb
e finish for User
I/Unity   ( 6099):
I/Unity   ( 6099): (Filename: ./artifacts/generated/common/runtime/UnityEngineDe
bugBindings.gen.cpp Line: 37)
I/Unity   ( 6099):
I/Unity   ( 6099):  [Play Games Plugin DLL] 07/05/16 14:57:45 -07:00 DEBUG: Auth
 not finished. User=[Player: 'DavidTredecies029' (id g09634522073000464528)] ach
ievements=
I/Unity   ( 6099):
I/Unity   ( 6099): (Filename: ./artifacts/generated/common/runtime/UnityEngineDe
bugBindings.gen.cpp Line: 37)
I/Unity   ( 6099):

```

**UPDATE (As of 5:29 PM via Philippines, 7/5/2016):** I made a mistake about checking if the email is empty or not. I made a reading wrong. Though, email address value still has issue and it should return with identified ones in string value and leaving with a blank when it reads not empty.

```
// LOG IN SUCCESS! (Check if the email is identified or not.)
if((((PlayGamesLocalUser)Social.localUser).Email != null) || (((PlayGamesLocalUser)Social.localUser).Email != "")) {

    y = 0;
    message.text = "Login complete!\nYour email:" + ((PlayGamesLocalUser)Social.localUser).Email;
    logButtonLabel.text = "Log-out";
    button.SetActive (true);
    confirmSound.Play();

} else {

    y = 0;
    message.text = "Login complete. However, email is not verified or unknown.";
    logButtonLabel.text = "Log-out";
    button.SetActive (true);
    errorSound.Play();

}

```

# Answer
> 0 votes
Since nobody helped me and my deadline is busted in total failure, my conclusion will provided nothing but myself. Okay, I checked and observe this tutorial from App Guruz and make the sample one. I observed how this game flow and use my package name to modify it. Luckily, the leaderboard UI finally showed up. I'm assumed that there are some certain particular problem or issues on plugins from Android (some library folders like *firebase* and .aar files) when I tried to compare mine from the sample roject form App Guruz website. Possibly compatibility issues. If you're came to make leaderboard UI's and stuff and relying on this Unity Plugin via GIT website, stay away from this crap. It's not worth to use it. Full of bugs, especially the Android plugins. Rely first on making your own GPG from scratch and observe the plugins and jars since I'm focused on Android only.

---
Tags: unity, leaderboards, google-play, plugin, authentication
---


# Question
Title: Unity Editor Script to instantiate a prefab
I want to instantiate a prefab within the context menu (Components). I got the code to create the entry in the context menu, but I can't figure out how to place my prefab in the scene. My current code is somehow like this :

```
using UnityEngine;
using UnityEditor;
using System.Collections;

public static class MenuItemGameobject {

    [MenuItem("GameObject/Create RedBlue GameObject", false, 12)]
    static void Init()
    {
        Debug.Log("here");
        //new GameObject("RedBlue GameObject"); // This adds an empty GO
        //new GameObject((GameObject.Find("UIPlane"))); //This duplicates the GO if it is already in the scene
        //PrefabUtility.InstantiatePrefab(); //This is the method which I guess is needed, but I don't know how to get the GO parameter
    }
}

```

So again, I want to add my prefab exactly like you add a cube within the context menu.

Edit : This is how a public variable looks like in the inspector :

# Answer
> 2 votes
## Create a central-control script to manage your prefabs

If you would prefer the "drag and drop" approach of being able to drag your prefabs in from the inspector, there is an easy work around to working with a script that is *not* inherited from MonoBehaviour; create a separate MonoBehaviour to work as the go-between. This script can also handle any other management functionality you might need, in regards to prefabs, now or in the future.

---

The first step is to set up a global controller script. I tend to favor the static self-reference approach, as I work in a very controlled environment.

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

public class PrefabManager: MonoBehaviour
{
    public static PrefabManager control;  // cheeky self-reference

    void Start ()
    {
        control = this;                   // linking the self-reference
    }
}

```

In this example, I can access my `PrefabManager` script from any other script, using the line `PrefabManager.control`. You have to ensure that you only have one instance running, for it to work correctly, but it can be a simple and helpful workaround. There are other, and far better, ways to approach creating a central 'control script'.

Though I am still fairly new to the concept, I am told that Singletons can be helpful in this area. In XNA, I have used services to the same effect, but can not comment on how they relate to or work in Unity. If you are working within a team, discuss other options with them. There will likely be a specific method used to create these static classes, throughout your project, as you will often find need to do so.

---

From here, all you need to do is create an interface to allow you to store your prefab references through the Unity interface. There are several approaches you can take for this, two of which I will mention:

### Arrays or Lists

You can create a simple `GameObject` array to store your references. You can do this with a list or array.

```
public List<GameObject> prefabList;

```

A list allows greater manipulation functionality, and are more suitable when you intend to add more items to the list past the initial instantiation. It sounds like all objects would be referenced before the game is run, so you will probably be better off with an array.

```
public GameObject[] prefabArray;

```

A more generic array has its limitations. As I have always been taught, C# is particularly troublesome with increasing the maximum size of an array, past the initial instantiation. There are always ways around that, but it sounds like you may not need to, in the first place. Most importantly, arrays store the elements in a more generic format. You can easily reference the elements in the array by their index, using `prefabArray[0]`, `prefabArray[1]` and `prefabArray[2]` to access the first, second and third prefabs listed in the array.

### Serialised Struct

You might prefer to create your own structure, in order to store extra values with your prefab reference. A text-based tag for easier searching, for example.

```
public PrefabElement[] prefabStruct;

[System.Serializable]           // Expose the struct inside the Unity Inspector
public struct PrefabElement
{
    public GameObject prefab;
    public string tag;
}

```

In this example, we have an array of elements that *each* store a `GameObject` reference and a `string`. **Note the use of `[System.Serializable]`.** This is important, as it tells Unity to serialise the `struct`, allowing it to display the fields in the inspector. Without it, you do not have the ability to drag items in, or edit it from the inspector, at all. This sort of implementation allows you to bind other variables to your prefab reference. If it would be helpful to search for a particular prefab using text-based naming conventions, for example, this would be the better option.

You can access the elements with `prefabStruct[i].prefab` and `prefabStructure[i].tag`. In the example implementation, where you only have two variables, it might be more beneficial to use `Dictionary<GameObject, string> prefabDictionary`. The `Dictionary` type is more suited to handling sets, in this case. I have not been able to determine a way to make it accessible via the inspector, however, and am unable to suggest a good method to implement a `Dictionary` for supplying prefabs via the inspector.

### What if I can not use public variables?

Of course, in the examples given so far, the variables need to be public in order to allow you to drop values and references in from the inspector. But you can enable variables from the inspector, without making them publicly accessible to everything else. Simply use `[SerializeField]`.

```
public float a;                      // shown in inspector
private float b;                     // not shown in inspector
[SerializeField] private float c;    // shown in inspector

```

You would also need to include some sort of `Get()` function in your prefab controller, to allow access to the prefab references from outside the controller.

### Loading resources with the Resources.Load() function

If you instead prefer to load in the prefabs using script, the `Resources.Load()` function will help you with that. I am not as familiar with it, but you can find documentation on it here.

`Resources.Load(string)` looks in your resources folder for any prefab matching the string. You can look directly for a prefab with `Resources.Load("prefabName")`, or look in a specific folder with `Resources.Load("folder/prefabName"`. **Note that we always use forward slashes**. This is important, as while you may be use interchanging the forward slash (`/`) with a backward slash (`\`) for use with alternate operating systems, Unity **always** accepts the forward slash (`/`), regardless of the operating system.

You can overload the function with a type, in order to narrow your selection down. `Resources.Load("prefabName", typeof(GameObject)` will only return GameObjects, even if you have a texture that is *also* named "prefabName".

---

Note that this does not immediately instantiate the prefab, although you can load the resource inline with an instantiation. You should also consider the possible return structure, as follows:

* If the search returns multiple prefabs, it will return an *array* of the prefabs. If your code is set up to only interpret a single instance, this can lead to errors. Unless you intend to load an array of like-named prefabs, I would recommend ensuring your prefabs each use different names. Regardless, this is generally a good idea for the purpose of keeping your project tidy. *50 tips for working with Unity (Best Practices)* offers some sound advice for naming conventions, as well as a plethora of other useful tips.
* If the search returns no prefab, it will instead return `null`. Obviously, this should not happen. It might still be a good idea to double check that your prefab reference `!= null` after your `Resources.Load()`, to prevent possible issues, later.

---

You would generally load and/or instantiate a prefab as so:

```
GameObject prefab

// Loading in the reference to your prefab
prefab = Resources.Load("prefabName", typeof(GameObject)) as GameObject;

// Loading in and instantiating an instance of your prefab
prefab = Instantiate(Resources.Load("prefabName", typeof(GameObject))) as GameObject;

```

Note the `as GameObject` at the end. Documentation infers that you must confirm that you wish to load it as the particular type you are setting it as. This concept is also new to me, but I am sure others can explain why you have to do this, if you are curious.

# Answer
> 1 votes
You need 2 scripts. One Editor-script and one MonoBehaviour-script.

1. Put the prefab "filenameXYZ.prefab" in your "\Assets\Resources" folder.
2. In your MonoBehaviour-Script copy this:

```
using UnityEngine;
using System.Collections;

public class myMonoScript : MonoBehaviour{

    public GameObject myPrefab;

    public void createObject()
    {
        if (myPrefab != null)
        {
            myPrefab = Resources.Load("filenameXYZ") as GameObject;
        }

    GameObject myInstance = (GameObject)Instantiate(myPrefab, new Vector3(0, 0, 0), new Quaternion(0, 0, 0, 0));

    myInstance.name = "new Instance";

    //... set other parameters
    }
}

```
3. In your inspector script copy this:

```
using UnityEngine;
using System.Collections;
using UnityEditor;

[CustomEditor(typeof(myMonoScript))]

public class myEditorScript : Editor
{

    void Update()
    {
        if (target != null)
        {
            myMonoScript myScript = (myMonoScript)target;
        }
    }

    public override void OnInspectorGUI()
    {
        DrawDefaultInspector();
        myMonoScript myScript = (myMonoScript)target;

        if (GUILayout.Button("Instantiate Object"))
        {
            myScript.createObject();
        }
    }
}

```
4. Adjust the code.

# Answer
> 0 votes
Both answers helped me a lot, but to solve the problem for my particular case, I will post the solution here :

You need a `MonoBehaviour` Script :

```
using UnityEngine;
using System.Collections;

public class mymonoscript : MonoBehaviour
{
    public void createObject()
    {
        GameObject instance = Instantiate(Resources.Load("UIPlane", typeof(GameObject))) as GameObject;
    }
}

```

And another static class for the CustomMenu stuff :

```
using UnityEngine;
using UnityEditor; // Dont forget to add this as we are extending the Editor
using System.Collections;

public static class MenuItemGameobject
{
    [MenuItem("GameObject/CustomUI/Element1", false, 12)]
    static void Init()
    {
        mymonoscript myScript = (mymonoscript)new mymonoscript();
        myScript.createObject();
    }
}

```

Not sure whether my script call is perfect, but it does the job in this case, maybe someone can edit it.

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


# Question
Title: GLSL: Issue replacing ternary operator with mix
I was expecting these two code snippets to do the same thing:

```
return  vec3(  1.0-b.r>=a.r ? 0.0 : 1.0-((1.0-b.r)/a.r),
               1.0-b.g>=a.g ? 0.0 : 1.0-((1.0-b.g)/a.g),
               1.0-b.b>=a.b ? 0.0 : 1.0-((1.0-b.b)/a.b)  );

```

and

```
return mix( ONE3 - ((ONE3-b)/a), ZERO3, vec3(greaterThanEqual(ONE3-b, a)) );
       // ONE3=vec3(1.0,1.0,1.0); ZERO3=vec3(0.0,0.0,0.0);

```

For some reason, they have different outputs. Do you know why? (`a` can have zeros sometimes)

# Answer
The main issue is that `(ONE3-b)/a` may cause a division by zero. This causes the result to be NaN (Not A Number). In that case mix will also return NaN because pretty much anything done to a NaN gives back an NaN and `mix(a, b, i)` internally does `a*(1-i) + b*i` or `a + (b-a)*i`.

try using `mix( ONE3 - ((ONE3-b)/max(a, vec3(0.001, 0.001, 0.001))), ZERO3, step(a, ONE3-b) );`

Using `max(a, tiny_value )` prevents a division by zero.

Using `?:` avoids the NaN case completely.

And instead of `greaterThanEqual` and a cast back to `vec3` you can use `step(edge, x)` which returns 0 if x \< edge and 1 otherwise without branching.

You should really profile your shaders on the target platform. Depending on the GPU and the operands used sometimes `?:` will be faster.

Some GPUs (especially mobile GPUs) don't mind branches too much and may benefit from them if the calculation skipped is quite long.
> 4 votes

# Answer
You do not actually need `mix`. Just realise that `1.0-(1.0-b)/(1.0-b)` is always zero (except in the case of a division by zero, we’ll come to that later).

So you can just forget the ternary operator and when `1.0-b>=a`, instead of dividing by `a` you just divide by `1-b` to get zero in the end. This means dividing by `max(1-b,a)`:

```
vec3 m = max(ONE3 - b, a);
return ONE3 - (ONE3 - b) / m;

```

This can be rewritten as:

```
vec3 m = max(ONE3 - b, a);
return (m + b - ONE3) / m;

```

Now you still have a division by zero when `b` is exactly `1` and `a` is exactly `0`. This can be prevented using a small correcting factor:

```
vec3 m = max(ONE3 - b, a);
return (m + b - ONE3) / max(m, vec3(1e-6));

```
> 0 votes

---
Tags: shaders, glsl, fragment-shader
---


# Question
Title: How to instantiate an object to a randomised Vector2
So I'm trying to make a little game where squares randomly spawn around a set area and you have to tap them. The game is 2D. I'm having trouble using my randomly generated x and y floats to instantiate a cube in the game. Here is my code:

```
#pragma strict

public var play = false;
public var xpos : float;
public var ypos : float;
public var cube : GameObject;

function Start () {

}

function Update () {
}

function Game () {
    xpos = Random.Range(-10f,10f);
    ypos = Random.Range(-4.45f,4.45f);
    Instantiate(cube, new Vector2(xpos, ypos));
}

```

And here's the error!

```
Assets/gameController.js(18,20): BCE0023: No appropriate version of 'UnityEngine.Object.Instantiate' for the argument list '(UnityEngine.Rigidbody, UnityEngine.Vector2)' was found.

```

Any help would be appreciated. Thanks! -Alex

# Answer
> -1 votes
After a bit of help from @Droopy I was able to figure out the solution. I was simply missing a few arguments from the Instantiate function.

---
Tags: unity, 2d, android, javascript
---


title: Unity Loading Image?

text:
# Question
Title: Unity Loading Image?
I have a quastion about loading screen in unity. I don't want to make a scene between to levels \[Main Menu \> Loading Scene \> Game level\]. I want to use Canvas "Image"that run at the start of the game level and then disappear after few seconds \[Main Menu \> Game level\]. Is this good idea ?

# Answer
If I understand correctly, you just want a Main Menu canvas to exist in your level and disable/destroy it when you're done with it. So just do exactly that in the OnClick handler of your button(s).

```
public void OnClick()
{
    gameObject.SetActive(false);
}

```

Have the above in a script attached to your menu canvas' object and select it as the method to call for your button's OnClick.

Now, if you want this to happen automatically after, say, 5 seconds...

```
float delay = 5f;
float timer = 0f;
private void Update()
{
    timer += Time.deltaTime;
    if (timer >= delay)
    {
        gameObject.SetActive(false);
    }
}

```

There are much better and more concise ways to handle delayed actions like this, but this should demonstrate things adequately.
> 1 votes

---
Tags: unity
---


# Question
Title: How to avoid an applied force from effecting one particular Rigidbody2D
I am creating a 2D side-scroller car race game with zombies. In this game, I set up a feature through which the player can shoot the zombies from the car, as well.

The problem is that when I apply force to shoot the bullet towards the right, the car also gets effected by that force, i.e it just moves a lot in reaction to the bullet shot. I don't want this behavior. I want the car to remain calm and just shoot.

Is there any way to exclude one particular rigidbody, i.e the rigidbody attached to the car, from applying the force the bullet rigidbody is using?

# Answer
the car should be affected. if you apply Newton's laws correctly, the force will be proportional to the mass. hence it appears that you have to increase the mass of the car in your model
> 1 votes

# Answer
As comments suggest that I should answer my own question, since I figured it out. If the bullet is been fired with much force, and its mass is more or less equal to the car, than the car shooting the bullet will be affected.

For the solution, I have ignored the collisions in the editor settings between car and bullet. This may not be the optimal solution, as you might need to have a slight impact on the car when you add force to your bullet rigidbody, in which case you need to decrease mass of your bullet and increase the mass of your car.

Thanks a lot to all who commented.
> 0 votes

---
Tags: unity, rigidbody
---


# Question
Title: Endless runner game: Dynamic world vs Static world
I've seen a lot of tutorials on how to build infinite runners and came up with a question about game optimization.

This types of games are built on two ways, according to my research; these are:

1. Set the player and camera static. Usually on the origin of the world space, and have all the environment assets created on the distance and move them towards the user.
2. The environment assets are created on a straight line to infinity and the player and the camera both move forward until the player loses. This means the environment's position will not be changed once they are created.

My question arises from here. Which of the two involves less calculations? Which one gives the player a better feel of movement? Is the difference actually significant (in terms of performance) or is it just a trivial question?

# Answer
> 3 votes
Although it may seem more intuitive to move the player object forward, it can lead to problems of numerical instability. If the runner is truly 'endless', then you can, at least in theory, end up with a player at a position with very large values. I'm basing this on experience with Unity specifically, and you can see this answer for more details:

http://answers.unity3d.com/questions/710798/infinite-runner-and-coordinates-limit.html

So finally, I would suggest that you either have the player and camera static and move the obstacles toward them like a conveyor belt, or that you move the player forward up to a certain limit before resetting. In both cases, you would generate your obstacles ahead of the player by either a fixed or random offset, before either moving them or the player closer, which allows you to limit your worries to just the player's position in the world.

# Answer
> 1 votes
I'd say to move the player/camera. It will probably be easier, and at the very least it's generally more intuitive to move the player rather than the world.

In terms of number of calculations, I'd say the effect would be minimal, but if not ( your scene has many, many objects) it would tend towards moving the player: Moving the player means moving one thing, moving the scene means moving everything that's part of the environment.

In terms of "feel of movement," the two should produce the exact same visuals if done correctly.

(Interesting piece of info: OpenGL's "camera" is locked in one position, so if using it you do at some point have to move the world around the camera. However, in my experience at least, it's pretty simple to have my own user-defined Camera object even so, as the OpenGl camera is only 1 matrix multiplication away.)

# Answer
> 0 votes
Think of flappy birds, the pipes move towards you. I know this is not exactly what you are making but just bear with me.

When you allow your player to be static, you can cheat a little (Nice right?) and have the player only use animations for running, sliding can be done using a "pixel perfect" collision, so again... a sprite just changes, and the sprite image is smaller (Neeto). Now jumping is just done like a platform jump, with an animation to make it look like you are keeping momentum.

Now i built a similar game in GameMaker, and at first the player moved. But think to yourself, why? why move the player etc. Just have the world around you move. Flappy bird did a good job of this by having the pipes spawn slightly off screen and delete themselves slightly off screen.

*To sum it up*

Have the player and camera stay still. I believe youl find it easier, have a nicer finish and less "mess" to worry about.

---
Tags: game-design
---


title: Create BoundingBoxes on a Model

text:
# Question
Title: Create BoundingBoxes on a Model
I am trying to create multiple `BoundingBoxes` on a `Model` by following this tutorial:

https://electronicmeteor.wordpress.com/2011/10/25/bounding-boxes-for-your-model-meshes/

However, I keep getting this error: `Requested range extends past the end of the array.` on this line:

```
part.VertexBuffer.GetData(part.VertexOffset * stride, vertexData, 0, part.NumVertices, stride);

```

I can't figure out why it is giving me that. I load my model and try to create the boxes like this:

```
Model model = this.Content.Load<Model>("Cube");
MeshModel box = new MeshModel(model);

```

Instead of passing a `String` path of the model, I just pass the `Model` itself (I changed the constructor to accept `Model model`).

Any help would be appreciated!

Here's what the debugger says (the `vertexStride` and `VertexBuffer` has `24` which is the same size as the `vertexData` so it should be ok):

# Answer
> 2 votes
In the tutorial you are using, `vertexData` is an array of a number of `VertexPositionNormalTexture`. But if your cube is made from a type of Vertex that is different (say `VertexPositionColor` for instance), then you have to adjust `vertexData` accordingly.

`VertexPositionColor[] vertexData = new VertexPositionColor[part.NumVertices];`

If you expand the Vertex Declaration line on your debugger output, we can see what type of Vertex Blender gave you and Xna probably has a Vertex that fits it.

# Answer
> 2 votes
That looks like an `ArgumentOutOfRangeException` message. If you're using XNA's `GetData` method, that can occur because:

* The vertex stride is larger than the vertex buffer, or
* The vertex stride is too small for the type of data requested.

It seems likely that you're `vertexData` array is too small to hold the requested amount of data, but you should attach a debugger and verify. It's also possible the calculations you're doing for the other parameters do not match the actual data you have available in the buffer.

---
Tags: xna, monogame, bounding-boxes
---


# Question
Title: Save variable and load between 2 scenes in Unity
I have variable that I need to save and load between 2 scenes.

So this is what I'm trying:

First script:

```
public class s1sc : MonoBehaviour
{
public string playername;

public static s1sc Instance;

void Awake ()
{
    if (Instance == null)
    {
        DontDestroyOnLoad(gameObject);
        Instance = this;
    }
    else if (Instance != this)
    {
        Destroy (gameObject);
    }
 }

```

Second script:

```
public class s2sc : MonoBehaviour
{
    public string pn;

    void Start ()
    {
        pn = s1sc.Instance.playername;
    }
}

```

And it doesn't work fine. What is the problem??

# Answer
> 3 votes
This is what I do to retain variables between scenes. Create a static class that is not derived by Monobehaviour:

```
public static class ApplicationData {
    public static string PlayerName;
}

```

Then use it in your Monobehaviour scrips like so:

```
ApplicationData.PlayerName = "Frank";

```

This PlayerName variable will persist until you close your application. It will be accessible from all MonoBehaviour scripts.

# Answer
> -1 votes
You can simply use an empty game object with your desired script and this code, at the least:

```
void Awake()
{
    Debug.Log("DontDestory Script's Awake");
    DontDestroyOnLoad(this);
}

```

The script with variable values will be maintain across different scenes. I just confirmed the below code with Scene1 and Scene2:

```
using UnityEngine;
using System.Collections;

public class DontDestroy : MonoBehaviour
{

    public int testingInt = 10;

    void Reset()
    {
        Debug.Log("DontDestroy Script's Reset");
    }

    void Awake()
    {
        Debug.Log("DontDestory Script's Awake");
        DontDestroyOnLoad(this);
    }

    void OnGUI()
    {
        if (GUI.Button(new Rect(10,10,100,50),"increment :"+ testingInt))
        {
            testingInt++;
        }
        if (GUI.Button(new Rect(10,60, 100, 50), "Load second "))
        {
            Application.LoadLevel("Scene2");
        }
    }
}

```

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


# Question
Title: access public variable in other script/scene
I have public variable `score` in script `scr_a` that attach to object `obj_a` in scene `sce_a`.

now I need to access the variable (score) in script `scr_b` that attach to object `obj_b` in scene `sce_b`.

I have try something but they did not work and I think that's because my scripts are in two different scene...

# Answer
> 0 votes
Use a Score managing object that doesn't destroy in scene load or destroy. Unity have have a method `DontDestroyOnLoad()` for doing that. Get this object from other script with tag like "ScoreManager" then access the public methods as you need.

Use some code like below:

```
private int score;

void Awake()
{
 DontDestroyOnLoad(this.gameObject);
}

public int GetCurrentScore()//call this method to get the current score
{
 return score;
}

public void UpdateScore()//call this method to update the score increment
{
 score++;
}

```

# Answer
> -1 votes
You have to maintain/retain/dontDestory **scr\_a** script when you switching from **sce\_a** to **sce\_b** and this can be acheiveable through this

```
public scr_a{
public int score;
 void Awake() {
        Debug.Log("DontDestory Script's Awake");
        DontDestroyOnLoad(this);
    }
///your logic update or blah blah functions

}

```

Adding DontDestoryOnLoad in your scr\_a script will maintain you scr\_a script object in sce\_b then you can get it in scr\_b using this

```
scr_a scr_aObj = GameObject.FindObjectOfType<scr_a>();
Debug.Log(scr_aObj.score);

```

---
Tags: unity
---


# Question
Title: problem on enable and disable GameObject
I'm trying to enable and disable GameObject (canvas) using this code:

```
public int canvaslevel = 1;
public GameObject one;
public GameObject two;
public GameObject three;

void Update(){
    if(canvaslevel=1){
        one.SetActive(true);
        two.SetActive(false);
        three.SetActive(false);
    }
    if(canvaslevel=2){
        one.SetActive(false);
        two.SetActive(true);
        three.SetActive(false);
    }
    if(canvaslevel=3){
        one.SetActive(false);
        two.SetActive(false);
        three.SetActive(true);
    }
}

```

but it doesn't work!!!

error:

> Cannot implicitly convert type `int' to`bool'

# Answer
Use `canvaslevel==1` instead of `canvaslevel=1`. Change to `canvaslevel==2` and `canvaslevel==3` as well.

You need to check equivalence not assign a value.
> 3 votes

---
Tags: unity
---


# Question
Title: What behaviors should go into making a "non-perfect" AI combatant?
When making an npc combatant, it's easy *obvious what to do* to get a robot deathmachine by optimizing combat tactics, timing and attack types, but harder (and more interesting in a fight) to get an idiosyncratic, inpredictable enemy. What behaviors (algorithms?) are useful for creating a more organic, unconventional enemy?

**Edit:** My specific use case is with MMO-like enemies, e.g. World of Warcraft, although with less graphics involved. Note that that means both human and inhuman enemies (animals, monsters, etc)

# Answer
> 14 votes
There is a very interesting article on the matter on Gamasutra: Intelligent Mistakes: How to Incorporate Stupidity Into Your AI Code, by Mick West.

This article talks about a Pool game AI. When implementing such an AI, it's quite easy to make it pot a ball at each shoot. A simplistic way to make the AI less "smart" is, as suggested on other answers, to add a random factor to the calculation, making the AI miss more.

But there is two major flaws with such an approach. First, it's unpredictable. For a player playing in "Easy" mode, it's unacceptable that the AI gets "lucky". What if your random factor makes the AI do an even better shot, hitting a more valuable ball, or doing a combo? You don't know what is going to happen, and being lucky shouldn't be an option for the AI on an easy mode.

The other flaw is that the player will try to identify a pattern in the AI behaviors. And with a simple random factor, there is no pattern. But that doesn't mean the player won't see any pattern, quite the opposite, in fact. As soon as the AI gets lucky, the player will see a strategy in its behavior. In the article, the players are complaining about the AI playing a position strategy. *When there's just a random factor in the angular precision*.

From my point of view, after reading this eye-opening article, a non-perfect AI should never use randomization as a simplification factor. It's quite the opposite. **An easier AI should be smarter, but trying to help the player.**

In the article Pool game example, the best option for implementing an "easy mode" AI was in fact to remove all random factor, and to add a positioning strategy. The AI would try to hit balls in order to prepare an easy and awesome shot *for the player*.

This way, the player will think *he* got lucky. And that's what you're expecting for a game when playing it easy.

# Answer
> 10 votes
The key concept is to avoid giving the NPC "perfect knowledge".

* Randomized margin of error on any decisions or actions that involve a calculation. obvious example being aiming (ie. stormtrooper snipers). If they don't always hit you, it's more realistic.
* Line of Sight ... if they can't see you, it can make an interesting game of cat and mouse.
* Team tactics, depending on your type of game, enemies that adapt to the situation can be way more interesting. For example, if you're getting shot at, you wouldn't charge in blindly, you'd take cover until incoming fire lets up. Or perhaps you would feel more comfortable with rushing in if you've got team-mates nearby ... you can simulate those behaviors to make the NPCs behave as if they were alive.

I'm sure there's a ton more examples that will be given, maybe you could tell us about your game and we can get more specific :-)

# Answer
> 4 votes
One quick way to render a perfect AI fightable is to have it make unperfect decisions by adding some 'noise' to either its inputs or its outputs. By noise I mean some random factors.

Here's a small example for output:

* Perfect algorithm yields three possible actions ranked with a score.
* Add a random value to each score.
* Pick best score.

Here are some ideas for input:

* If actions are based on opponent's health, add a random factor (say +/- 10 for a 0-100 health bar) to perceived state by AI.
* Same for rating of actions, if AI knows some attacks are stronger than others, randomly add/subtract some values there.

One obvious thing to take into consideration is the speed of the AI. In most games, AIs can react *MUCH* faster than humans (especially in fighting) and do apparent multitasking (very visible in RTS games). So you have to act on that, by keeping the AI a bit slow (maybe adaptively so), and limiting the amount of things it can do in a determined frame of time (ie one action each half-second).

Hope this helps, and good luck!

# Answer
> 3 votes
It's difficult to give a directly useful answer without knowing what exactly you're trying to do.

I have two things to say on the subject that might help you out.

First thing (and this is by far the most important one), if you're trying to make the enemy feel more interesting and human then your combat tactics are irrelevant. The trick to making players "believe" an enemy is alive is to use animation, sounds, and little details to imply human behavior. The perfect AI might walk around a corner, see a player, and shoot. A human AI might walk around a corner, see a player, have a surprised look on his face and shout out in alarm, and shoot. The first one seems robotic. The second one seems human. Both are using identical AI in every way, other than the insertion of the animation just before shooting (or, to keep the tactical behavior the same, *during* shooting).

Second, avoid randomizing. Players don't appreciate it as much as designers want to think they will. Players don't see "computer generated a 1 out of 100, followed by a 5, 3, and 4, so the error factors for the last four shots were only 1%, 5%, 3%, and 4%, and that's why you died in half a second this round." The players just see enemies that sometimes wildly miss and other times nail them repeatedly for no discernible reason, which is incredibly frustrating. Good game design is largely about building patterns that human players *can* observe, learn, and beat, and making the player's success based on his own judgement and skills and intuition rather than making it about whether the player got lucky. The urge to randomize comes from experience with table-top games and gambling games, both of which are incredibly different mediums than video games (and what works in one medium often does not make sense in another).

# Answer
> 1 votes
I remember at our AI course at college there was a topic about making AI more "human" and less perfect. That was many years ago so I just remember a few bullet points from the top of my mind.

* Use "libraries of moves". If you are fighting an orc, give him say 3 combat routines that they repeat every now and then. This makes combats easier by being more predictable, which seems to be the opposite of what you want, but still makes the AI less "perfect machine" and more "noob repeating the same move over and over".
* Suboptimize, if possible. If, as you say, your AI is based on calculating the best move, put an artificial limit on this calculation. Make the search shallower, or limit the number of steps. Instead of the best move ever, the AI will choose simply a good move instead. This may add a lot of variety to your enemies behaviour, since there are many more good than best moves.
* Make mistakes on purpose. Instead of the best move, choose the second or third best. Or even choose a move that has bad utility. This may address your "unpredictability" point.

Of course these are just general advice that should be studied and playtested for each case, and may indeed make your AI look even more artificial than intended. However I think they are a good starting point.

# Answer
> 0 votes
I just saw this pop up and wanted to share an idea that I've used in the past.

Let's say the character has three moves and each are scored, higher score is a better move. (Other answers talk about adding noise to creating this score.)

* Attack with a sword (30 points)
* Fire spell (50 points)
* Ice spell (20 points)

Sum up the total points (100)

Take the character's intelligence stat out of the max possible value for this stat (let's say 60 out of 100).

Generate a random number between 0 (or some other floor) and the intelligence ratio (0.6), multiply by the total points (100). In our example, let's say the result is 45.

Now you start subtracting the bad moves from this value until you hit zero. (Subtract in order.)

First, we consider the Ice spell, which scored a 20. 45 - 20 = 25. This is above zero, so we throw the Ice spell out.

Second, look at the Attack with a sword, worth 30 points. 25 - 30 = -5. We hit our threshold, so we choose the Attack with a sword action.

In this system, a character with low intelligence won't pick the best move. And a character with high intelligence will often pick the best move. (In this example, a character with perfect intelligence picks the best move 50% of the time.)

Adding a floor mechanism to the random number will increase the chance that better moves are selected.

---
Tags: ai, npc, combat
---


# Question
Title: Premake a texture in SDL (C++) and save it
I am new with SDL, and am making a Conway Game of Life.

I want to make a grid appear on the screen, so of course I could make one manually with SDL\_RenderDrawLine and two loops. But I don't want to create this grid every single time, once is enough, after I can just copy it to the screen.

So I want to create the grid once, and save it somewhere, like a texture.

The problem is, how do I draw to a texture ?

From what I understand, SDL\_RenderDrawLine will need a renderer (which is associated with a window) and so it won't work for my purpose as it will be drawing to that renderer buffer or something, and then to a window.

How can I do that ? You can load an image instead, but I'll lose the whole point of drawing it algorithmically (what if the tile size change, etc).

**EDIT :** So I'm trying to use SDL\_SetRenderTarget, as well as the correct flag to create the texture. However it simply doesn't show up.

Here is the code that create the whole texture, and should render to it :

```
// part of my init function for SDL

SDL_SetRenderDrawColor(d_renderer, 0xFF, 0xFF, 0xFF, 0xFF);
SDL_RenderClear(d_renderer);
// Create square grid once
d_grid = SDL_CreateTexture(d_renderer, SDL_GetWindowPixelFormat(d_window), SDL_TEXTUREACCESS_TARGET, WINDOW_WIDTH, WINDOW_HEIGHT);
if (d_grid == NULL){
    fprintf(stderr, "Error creating blank grid texture: %s\n", SDL_GetError());
    return false;
}
SDL_SetRenderTarget(d_renderer, d_grid);
for (x = 0; x < MAP_WIDTH; x++){
    SDL_RenderDrawLine(d_renderer, x * 10, 0, x * 10, WINDOW_HEIGHT);
}
for (y = 0; y < MAP_HEIGHT; y++){
    SDL_RenderDrawLine(d_renderer, 0, y * 10, WINDOW_WIDTH, y * 10);
}
// TODO: Draw the grid to the texture
 SDL_RenderPresent(d_renderer);
// Renderer will now draw to screen again
SDL_SetRenderTarget(d_renderer, NULL);

```

I've checked it, the two loops does create what I want.

Now when I update the screen:

```
// Reset display
SDL_RenderClear(d_renderer);
SDL_RenderCopy(d_renderer, d_grid, NULL, NULL);

SDL_SetRenderDrawColor(d_renderer, 0x00, 0x00, 0x00, 0xff);

/* Code used to render the game grid, removed for clarity */

SDL_RenderPresent(d_renderer);

```

I don't understand how I'm supposed to do. According to LazyFoo tutorial, I need to use the SDL\_RenderDraw\* function, which will render to the texture, but using SDL\_RenderPresent or not doesn't change anything. What am I doing wrong ?

# Answer
> 2 votes
The technology you are looking for is called "render textures". Basically you create a texture that the GPU can render to, and after that you can simply render that texture to the screen.

You can create a render texture with `SDL_CreateTexture(renderer, SDL_GetWindowPixelFormat(window), SDL_TEXTUREACCESS_TARGET, width, height);`, and render to it using `SDL_SetRenderTarget(renderer, texture);`. After that, all calls to `SDL_Render*` functions will draw to that texture. Call `SDL_SetRenderTarget(renderer, NULL);` to enable back drawing to the screen.

Once you are done with the texture, you can simply render the target texture to the screen with `SDL_RenderCopy` as usual, or even save it using a little code snippet that converts the texture to a surface.

---
Tags: sdl2, c++
---


# Question
Title: How to implement in-app-Billing in libgdx?
I'm trying to implement in-app-Billing in libgdx game. Does someone have a working example? There is some explanation on *developer.android* but it's not helpful for libgdx.

# Answer
There are a few standard extensions on the wiki - check out https://github.com/libgdx/libgdx/wiki/gdx-pay
> 1 votes

---
Tags: libgdx, google-play-services, in-app-purchase
---


title: GGX energy conservation

text:
# Question
Title: GGX energy conservation
I´m trying to implement a microfacet BDRF with GGX density function in my renderer. I have read almost all the papers out there in the last week, and I have a bunch of equations that should work fine, but I think they don´t. My problem is that the normalized functions of the BDRF are returning specular values way over 1:

I´m using Schlick's approximation for the fresnel term, the only one that is returning values in the range \[0-1\]:

```
F = oSpecular + ( 1.0 - oSpecular ) * ( 1.0 - L.H )^5 ;

```

The normalized GGX distribution function with a being the roughness:

```
D = a^2 / ( PI * N.H^2 * ( a^2 - 1.0 ) + 1.0 )^2

```

The Geometric factors I´m using:

```
G1 = 1.0 + sqrt( 1.0 + a^2 *( ( 1.0 - N.L^2 ) / ( N.L^2 ) ) ) ;
G2 = 1.0 + sqrt( 1.0 + a^2 *( ( 1.0 - N.V^2 ) / ( N.V^2 ) ) ) ;

```

And the full BDRF:

```
nSpecular = D * F * G1 * G2 / ( 4.0 * N.L * N.V )

```

I have seen this setup used widely. But even with the N.L factor it returns values over way 100.0 in the hotspot of the light reflection. I have tryed other Geometric terms with no luck. The BDRF is always overburned. It seems that I´m missing some important point here. Any idea?

Edit:

Thanks for the answer. So for area lights using representative points energy conservation is only an aproximation, wich explains why with low intensity lights the reflection can be still a lot brighter than the light source itself, wich is a pitty, and does not look right at all. I will try to look for another method. Any suggestion?

Returning to the original question about point lights with GGX and energy conservation, there is a thing I´m still missing. As the NDF returns a density probability function, wich can have values way over 1, that means that you can´t use the value as returned from the NDF directly in the shader, can you? As the specular component is later multiplied by the light source power, it should be really in the range 0-1, or you will have specular reflections 400 times brighter than the light source itself, with has no sense. Tell me only about one real life situation when a reflection in a dx returns 400 more energy than it receives and we can do business. The density probability function should be weighted or interpreted somehow to return it to a propper 0-1 range? If so, why nobody does that?

# Answer
(Based on the comments, the question is really about using BRDFs with area lights.)

This is a subtle issue. First of all, there's a difference between what the "color of a light source" means for point lights versus area lights: the color of a point light is an irradiance, while the color of an area light is a radiance.

So when using the representative-point method for rendering area lights, we actually need to convert the color (radiance) of the light source to an *irradiance*, so we can treat it as a point light. So we need to calculate (or approximate) the irradiance received the shaded point from the area light.

For uniform spherical area lights, a result that's quoted in Brian Karis' course notes is that the irradiance is the same as a point light of the same total power. So you can calculate the power of the spherical light `π * area * radiance`, then calculate the resulting irradiance at the shaded point `power / (4π * distance²)` (for physical 1/r² falloff, or substitute your own attenuation function if you like). For other shapes of area lights it will be more difficult, but you can hopefully work out some approximate irradiance formula.

Note that the irradiance will be numerically smaller than the radiance when the shaded point is far enough from the light, so this will help cut down the intensity of the reflection.

The other factor here is that the representative-point method isn't energy-conserving by itself. Karis recommends altering the GGX normalization factor to approximately fix this; see equations 10 and 14 in his course notes. This will also reduce the brightness of the reflection. Between these two factors, the intensity should be cut down to something more reasonable.
> 3 votes

# Answer
```
G1 = N.L + sqrt( 1.0 + a^2 * (( 1.0 - N.L^2 ) / ( N.L^2 )) );
G2 = N.V + sqrt( 1.0 + a^2 * (( 1.0 - N.V^2 ) / ( N.V^2 )) );

```

Full BDRF should be for Smith GGX:

```
nSpecular = D * F / (G1 * G2)

```
> 0 votes

---
Tags: shaders, rendering, pbr
---


# Question
Title: Asset Library Class or passing Asset's through constructors
I am at the point of designing UI-Logic and I was wondering what a good way to pass asset information to these objects would be.

What I was trying as of yet was passing assets to the objects representing UI-elements through their constructors, leading to code where I pass between 1 to 10 assets (like "button idle" "button being hovered" and "button active" etc.) to the objects or having to create "metaclasses" that define the "look and feel" of these objects that need to be passed to the ui-elements to handle the rendering.

A way I thought of handling this in a "dirty" way was to create a singleton "asset database" that is globally accessible. As every button need's it's own callback function on click it can also get it's own rendering function from where the button can pick it's assets from the accessible assets.

What is a common way to handle this?

# Answer
I'd wrap all those ten assets up into a type representing a "style." You can either do this generically, so that you have a single `Style` class that uses some kind of associative mapping from element keys to textures or other assets:

```
class Style {
  TextureReference getTextureAssetFor(String key);
  SoundReference getSoundAssetFor(String key);
};

```

Or you have specific style types for each widget, such as `ButtonStyle` and `SliderStyle` and so on, each of which just have a simple list of fields pointing to the various asset categories required by widgets of that type.

Then your widget constructors take one of those, either a generic `Style` or the type-specific style, depending on your preferences.

The type-specific style method requires more boilerplate work on your part, but means errors such as trying to access the wrong "kind" of asset by misspelling the key name or whatever are caught at compile time. The generic style approach requires a little more up-front engineering and has some runtime overhead, and also makes it easier to make errors that aren't detected until runtime, but it also is more extensible to future widget types and subclasses.
> 2 votes

---
Tags: graphics, software-engineering, ui-design
---


# Question
Title: Accessing an object from another scene in Unity
My game requires the changing of scenes. My game also requires the health to stay the same and not get destroyed in the transition of the scene. Which I did with the use of `DontDestroyOnload`. In the second scene, I want one of the game object's script to use the health bar(which is in the first scene and using `DontDestroyOnload`). how do I do that?

# Answer
There are a couple of ways you could obtain/retain reference to a game object between scenes. You could use `GameObject.Find` to find the game object in your new scene, or you could simply use `DontDestroyOnLoad()` to retain the original reference from the previous scene on a 'controller' script. Note that these methods work for all component types, but I will be using `Texture2D` as an example.

## Using `GameObject.Find` to find a game object in your scene

There are a couple of useful functions for finding game objects, in Unity. You can ideally use any of them to set up your reference prior to accessing the game object containing your health.

You will find that some are better for finding the specific game object, while others are more useful when trying to grab a reference to a component on the game object.

Keep in mind that **`GameObject.Find` functions will return `null` if nothing is found**. As a matter of good housekeeping, it might be worth double checking that your retrieved reference `!- null` before continuing to access it.

### Finding a game object by name or tag

By searching for an object by name or tag, you are specifically looking using a string identifier. That means that if you ensure your desired object has a unique name or tag, you ensure that you will grab the correct reference.

```
// You can find a GameObject by name
GameObject.Find("nameOfObject");               // single

// You can find GameObject(s) by tag
GameObject.FindWithTag("objectTag");           // single
GameObject.FindGameObjectByTag("objectTag");   // single
GameObject.FindGameObjectsByTag("objectTag");  // array

```

In the case where you have multiple objects that match the name or tag, but only call for a single game object, it will not necessarily return any particular instance. On multiple iterations, I had the function return the first instance, before defaulting to the very last instance. If you intend to retrieve a unique object, give it a unique name or tag.

If you intend to access a specific component, you can store the reference to the game object, or simply grab the component reference inline.

```
// Storing the GameObject reference to retrieve a component
GameObject gameObject = GameObject.Find("nameOfObject");
Texture2D texture = gameObject.GetComponenet<Texture2D>();

// Storing the Component reference, inline
Texture2D texture = GameObject.Find("nameOfObject").GetComponent<Texture2D>();

```

All of the `GameObject.Find` functions allow inline component retrieval in this way.

### Finding a component by type in your scene

By searching for an object of type, you specifically look for references to the internal components on a game object. You can do this with the `<type>` variation, or specify a `typeof()` in the function call. Keep in mind that these functions traditionally return an `Object`; you will have to cast them to the correct type you wish to retrieve. If you wish to use these functions to find a `GameObject`, for any reason, you can use the `(GameObject)` cast.

Once more, when looking for a single component there appears to be no real guarantee that any specific component will be retrieved. If you are looking for an individual reference, I would recommend only using this method if you are ensured there is only one instance of the component in your scene. *You can also use the type of a specific script, to directly grab reference to other scripts*. This might be the most useful approach for using this method in the described scenario.

```
// using type specifier
Texture2D texture = GameObject.FindObjectByType<Texture2D>();                     // single
Texture2D[] texture = GameObject.FindObjectsByType<Texture2D>();                  // array

// using typeof and casting
Texture2D texture = (Texture2D)GameObject.FindObjectByType(typeof(Texture2D));    // single
Texture2D[] texture = (Texture2D)GameObject.FindObjectsByType(typeof(Texture2D)); // array

// using typeof and casting to retrieve the GameObject reference
GameObject texture = (GameObject )GameObject.FindObjectByType(typeof(Texture2D));
GameObject [] texture = (GameObject )GameObject.FindObjectsByType(typeof(Texture2D));

```

## Retaining your reference with a persistent controller script

In some cases, it is a better idea to have a central controller script to manage the references and some of the functionality. In this way, you could also use `DontDestroyOnLoad()` to ensure that your controller persists, thus retaining your reference from the previous scene.

The first step is to set up a global controller script. I tend to favor the static self-reference approach, as I work in a very controlled environment.

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

public class ComponentManager : MonoBehaviour
{
    public static ComponentManager control;      // cheeky self-reference
    public Texture2D texture;                    // our component reference

    void Awake()
    {
        control = this;                          // linking the self-reference
        DontDestroyOnLoad(transform.gameObject); // set to dont destroy
    }
}

```

In this example, I can access my `ComponentManager` script from any other script, using the line `ComponentManager.control`. You have to ensure that you only have one instance running, for it to work correctly, but it can be a simple and helpful workaround. Whether you want to use the `GameObject.Find` methods to initially load the components in, or use the editor to drag and drop, its completely up to you.

There are other, and far better, ways to approach creating a central 'control script'. Though I am still fairly new to the concept, I am told that Singletons can be helpful in this area. In XNA, I have used services to the same effect, but can not comment on how they relate to or work in Unity. If you are working within a team, discuss other options with them. There will likely be a specific method used to create these static classes, throughout your project, as you will often find need to do so.
> 7 votes

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


# Question
Title: Why is my mouse disappearing at runtime?
I'm using Unity 5.3.5f1 and every time I play my game in the editor, my mouse disappears. I really need to test some of my parameters in the inspector but I can't because the mouse is gone. How can I fix this, and if possible, make it permanent?

# Answer
The problem was that I was using the First Person Controller from the standard assets. Just had to uncheck this: First Person Controller script \> Mouse Look \> Lock Mouse
> 0 votes

---
Tags: unity, mouse
---


# Question
Title: How to orbit an object around another object in an oval path in Unity?
I would like to create kind of planetary orbit structure for my game. I was used `transform.RotateAround(Vector3.zero, Vector3.forward, RotationAngle * Time.deltaTime);` and it rotates in a circular shape. But I would like to do it in an oval (Ellipse) shape.

# Answer
You may translate the orbiting object with the coordinates of an elliptical path. You can get the x and y values from the equations.

> x = centerX + (semi-major * sin T)
>
> y = centerY + (semi-minor * cos T)

Use some code like below:

```
float alpha = 0f;

void Update ()
{
    //transform.position = new Vector2(center.x + (semiMajor * Mathf.Sin(AngleX)),
    //                                 center.y + (semiMinor * Mathf.Cos(AngleY)));

    transform.position = new Vector2(0f + (10f * Mathf.Sin(Mathf.Deg2Rad * alpha)),
                                     0f + ( 5f * Mathf.Cos(Mathf.Deg2Rad * alpha)));
    alpha += 5f;//can be used as speed
}

```

Result with a trail renderer:

More generalized solution:

Formula used:

> x = centerX + {semi-major * cos(alpha)\*cos(tiltAngle) - semi-major * sin(alpha)\*sin(tiltAngle)}
>
> y = centerX + {semi-minor * cos(alpha)\*sin(tiltAngle) + semi-minor * sin(alpha)\*cos(tiltAngle)}

```
public float alpha = 0f;

public float tilt = 45f;

void Update ()
{
    transform.position = new Vector2(0f + (10f * MCos(alpha) * MCos(tilt)) - ( 5f * MSin(alpha) * MSin(tilt)),
                                     0f + (10f * MCos(alpha) * MSin(tilt)) + ( 5f * MSin(alpha) * MCos(tilt)));
    alpha += 5f;
}

float MCos(float value)
{
    return Mathf.Cos(Mathf.Deg2Rad * value);
}

float MSin(float value)
{
    return Mathf.Sin(Mathf.Deg2Rad * value);
}

```

You can control tilt of the eliptical path with the above code. Constants can be changed as you need.
> 3 votes

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


title: Free scripting in Construct 2?

text:
# Question
Title: Free scripting in Construct 2?
In Construct 2 example about creating an animated player, they used more than 8 events:

4 events to store movement direction into `Direction` variable from `Player.8Direction.MovingAngle`

4 events to select animation based on `Direction` value

1 event to stop animation

Apparently if would be much easier to do the same with simple if-else code with 4 or 5 cases. Is it possible in `Construct 2`?

**UPDATE**

I didn't find scripting, but was able to express the same example in more condensed way:

All names are from example.

# Answer
Construct 2 has no direct support for scripting, although it's possible to create modules with JavaScript. There's documentation on how to do this on Scirra's website. A link to the documentation can be found here: Official C2 SDK documentation

As for if-else statements, C2 *does* have them.
> 1 votes

---
Tags: scripting, construct-2
---


title: Unity Game Hang

text:
# Question
Title: Unity Game Hang
I've created a prefab for coin. The Scenario is like that : When player collides with coin, the coin will move towards coin image(coin image is one which is displayed in header for information purpose). In a prefab, there is random number of coins attached under one empty gameobject. and one script is attached with each coin to move towards static coin image. I am posting the snippet of that script.

```
public bool isMove;

void Update(){
    if(isMove){
        transform.position = Vector3.MoveTowards (transform.position, GameObject.FindGameObjectWithTag ("HeaderCoin").transform.position,Time.deltaTime*30);
    }
}
void OnTriggerEnter2D(Collider2D target){
    if (target.tag == "Player") {
        isMove = true;

        PlayerOfGame.instance.PlayCoins+=1;
        GamePlayController.instance.SetPlayCoins (PlayerOfGame.instance.PlayCoins);
        PlayerOfGame.instance.coins+=1;

        StartCoroutine (HideCoin ());
    }
}

IEnumerator HideCoin()
{
    yield return new WaitForSeconds (0.5f);
    transform.gameObject.SetActive (false);
}

```

when playing game, it gets hang after sometime. I think the problem is with prefab. So what should I change to make my game more smooth.

# Answer
You should use:

```
Destroy(gameobject, delay_time );

```

Instead of using a co-routine.

In this way you can obtain the same effect using less resources.
> 1 votes

---
Tags: unity
---


# Question
Title: How to create spaceship 'ion trails' that can be curved in Unity?
I'm working on a simple space combat game (single-player) with the goal of having 100+ fighters and capital ships in a single battle. To keep system requirements down I'm using a minimum of effects. One that I do wish to include, however, is that of 'ion trails' from the rocket engines of the spacecraft and missiles. Ideally it would look something like the images below. The trail won't have to be very long, but I do want it to curve to show the spaceship's path, acting as a visual aid in a dogfight.

My question is, how to implementing such trails efficiently?

# Answer
> 3 votes
Use trail renderer component with the object.

You can set time, width, color etc with it.

See for more.

---
Tags: unity, graphic-effects
---


# Question
Title: How to move rigidbody player to its facing direction with AddForce?
How can I move a rigidbody to its facing direction? I've already tried this:

```
rigidbody.AddForce (transform.forward * v, ForceMode.Acceleration);
// v is a public float which gets a new value in Update function:
v = Input.GetAxis ("Vertical") * Speed;

```

in FixedUpdate, but it doesn't move forward. It should go on that blue arrow, but it spins on the red arrow.

Hopefully u understood. Any suggestions?

# Answer
Instead of using AddForce use AddRelativeForce

```
    rigidbody.AddRelativeForce (transform.forward * v, ForceMode.Acceleration);

    v = Input.GetAxis ("Vertical") * Speed;

```
> 1 votes

# Answer
My code works good. For example:

```
using UnityEngine;
using System.Collections;

public class AddForce : MonoBehaviour {

public Rigidbody myBody;
public float ForcePower;
public Vector3 myDirection;

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

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

}

void FixedUpdate()
{
    myBody.AddForce(myDirection, ForceMode.Force);
}

```

}
> 0 votes

---
Tags: c#, unity, physics, movement
---


title: How to voxelize a height map?

text:
# Question
Title: How to voxelize a height map?
Lets say I make a height map and I want to make it out of CUBES to use in my game. I dont want to generate anything procedualy, I just want to cubify a height map. So I just want a static mesh. I also want to LOD it, so I have a 1024 version, a 512 version, and a 256 version. Btw I am using Blender and UE4.

# Answer
> 1 votes
The procedure goes something like this:

```
for(x = 0; x < worldSize; x += cubeSize)
  for(y = 0; y < worldSize; y += cubeSize)
      float mapX = (x/worldSize) * mapSize
      float mapY = (y/worldSize) * mapSize
      float height = heightMap.GetValue(mapX, mapY)
      for(z = 0; z < height; z+= cubeSize)
          PlaceCube(x,y,z)

```

Essentially, you iterate through your world, mapping a world location to a height map location. Then you create a column of cubes as high as the height map value at that location.

From there, things get complicated. If you want to hide cubes that are hidden by surrounding terrain (as most of the columns will be), you need to check their orthogonal surroundings before placing them. And there are optimizations. For example, the final loop can start at the terrain height, and once you reach a cube that's not visible, you stop processing cubes for that column. Being a height map, you can make a lot of useful assumptions about what's going to be visible later on. If one cube in a column is not visible, none of the cubes below it are going to be visible either.

---
Tags: blender, voxels, minecraft-modding, unreal
---


# Question
Title: Animations not working using scene2d and actor class in LibGDX
I have a problem making a simple animation using the Actor class.

```
public class fondoanima extends Actor {

protected TextureRegion currentFrame;
protected TextureRegion[] walkFrames;
protected Animation walkAnimation, idleAnimation, currentAnimation;
private Texture texture;
float stateTime;

public fondoanima() {

    texture = new Texture(Gdx.files.internal("image.png"));
    TextureRegion[][] tmp = TextureRegion.split(texture, texture.getWidth()/5, texture.getHeight() / 1);

    walkFrames = new TextureRegion[5];
    for (int j = 0; j < 5; j++) {
        walkFrames[j] = tmp[0][j];
    }

    walkAnimation = new Animation(0.4f, walkFrames);
    currentAnimation = walkAnimation;

    stateTime = 0f;

    }

@Override
public void draw(Batch batch, float parentAlpha) {
    // TODO Auto-generated method stub
    super.draw(batch, parentAlpha);

    Color col = getColor();
    batch.setColor(col.r, col.g, col.b, col.a*parentAlpha);
        batch.draw(currentFrame, 10, 10);

}

@Override
public void act(float delta) {
    // TODO Auto-generated method stub
    super.act(delta);

         stateTime += Gdx.graphics.getDeltaTime();
        currentFrame = currentAnimation.getKeyFrame(stateTime, true);
}

public void dispose(){}

```

I have been guided by different examples and the wiki, But I get not make it work. It is an animation that will be as the background. (image.png=\>1600x350=\>5 images are linked horizontally). Thanks.

**Solution:** initialize `currentFrame = tmp[0][0];`

# Answer
> -1 votes
**Solution:** initialize `currentFrame = tmp[0][0];`

---
Tags: libgdx, scene2d
---


title: Xcode Build Errors Unity 4.7.2

text:
# Question
Title: Xcode Build Errors Unity 4.7.2
These two errors are doing my head in. New to Xcode. So please advise thank you.

FYI

I did not touch or modify anything of the Xcode that was generated by Unity. Upon opening there is a warning that says to set to recommended settings. Other than that just set the provisional file. Set the simulator device then pressed play but these two errors keep showing!

# include "Unity/GlesHelper.h" file not found

# include "UI/Keyboard.h" file not found

# Answer
> -1 votes
There are 2 possibilities given what you've posted. Since I've not used Unity, I don't know which it is, but I'll explain both:

1. If Unity isn't a framework, then you need to just add the path to the Unity folder to your target's "Header Search Paths". Given how the `#include`s are written, my guess is that that's the case.
2. If Unity is a framework, then you haven't added the Unity.framework to your target. I don't know if Unity ships as a framework, but if it does, you need to add the framework to your target by going to the target's "Build Phases" and clicking the "+" button under "Link Binary With Libraries". From there, click the "Add Other…" button and navigate to wherever you put the Unity.framework. You also need to change the `#include "Unity/GlesHelper.h"` to `#include <Unity/GlesHelper.h>`. You may additionally need to add the Unity framework's headers path to your target's headers path. I have found instances where Xcode didn't automatically add the headers path of a framework after adding the framework to the target.

---
Tags: unity, ios, xcode
---


# Question
Title: How is Crytek going to make profit from making their tools free?
Middleware companies like Epic, Crytek, Unity are offering their tools, essentially, game engines, for free.

Crytek, for example, never had distributed their engine for free before, but started doing that too.

What are the reasons behind this decision, in case of Crytek?

Amazon with Lumberyard going to get profits from offering their network and cloud services, essential infrastructure for online and multi-player games.

But how is Crytek going to make a profit?

# Answer
> 3 votes
The typical business model for companies that offer a tool for free, whether it is open-source or not, is that they sell support services for customers.

Crytek does not seem to deviate much from that by looking at their website.

Additional ways Crytek can be making money out of their free tool:

* They have a 'pay what you want' feature
* They might have a deal with Amazon, and they get paid a royalty when a user use Amazon's services

Another strategy in this case is to gain enough momentum with their engine to eventually release a "Pro" version which has additional features and ask the users to pay for it, just like every other engines.

---
Tags: business, cryengine
---


title: Make models not see through

text:
# Question
Title: Make models not see through
All my models are see through and I can't figure out why. For example:

Here's what it looks like when you are not looking through them:

And when I look through one of them:

Why can I see the black cube through the other `Model`? It's the same the other way around. I can see the gray object through the black cube. I draw the models like this:

```
public void Draw(GraphicsDevice graphicsDevice)
{
    foreach (ModelMesh mesh in model.Meshes)
    {
        foreach (BasicEffect effect in mesh.Effects)
        {
            effect.View = camera.View;
            effect.World = worldMatrix;
            effect.Projection = camera.Projection;

            mesh.Draw();

            // Debug: Draw bounding boxes
            modelBox.Draw(effect, camera.View, camera.Projection, effect.World, graphicsDevice);
        }
    }
}

```

What am I doing wrong?

More screenshots: https://i.stack.imgur.com/cZYJT.jpg, https://i.stack.imgur.com/w84bL.jpg

# Answer
I think I figured it out. If anyone knows another way please do share.

I had to enable `DepthBuffer` in `DepthStencilState` in the `Draw()` method like so:

```
public void Draw(GraphicsDevice graphicsDevice)
{
    // Depth Buffer
    DepthStencilState dss = new DepthStencilState();
    dss.DepthBufferEnable = true;
    graphicsDevice.DepthStencilState = dss;

    // Draw model
    foreach (ModelMesh mesh in model.Meshes)
    {
        foreach (BasicEffect effect in mesh.Effects)
        {
            effect.View = camera.View;
            effect.World = worldMatrix;
            effect.Projection = camera.Projection;

            mesh.Draw();

            // Debug: Draw bounding boxes
            modelBox.Draw(effect, camera.View, camera.Projection, effect.World, graphicsDevice);
        }
    }
}

```

It ends up coming out exactly how you would expect:
> 2 votes

---
Tags: xna, monogame, models
---