# Question
Title: I imported both the rig and baked animation seperatly from Maya, but it's not working correctly
I am using the animation controller to bind the "jump" animation I did onto the rig itself. I don't get any errors. The animation plays. Except it seems to only affect the root joint only. Basically the model moves but not the arms or legs. They stay static. So If i have a character jumping few feet away, the entire model rig will move in jump motion(X and Y axis), but nothing happens with legs and arms.

What's going on?

# Answer
> 1 votes
I have solved the problem. The issue was the binded rig/model itself. Every time I exported it as FBX in Maya, it unbinds the mesh and skeleton. That was why the animation was not properly working in Unity.

I solved it by importing the FBX file back in Maya and re-binding the mesh and skeleton and re-exporting it as FBX. That was it.

---
Tags: unity, animation, maya, fbx, import
---


# Question
Title: How to clip what is outside scroll view when using a custom UI element?
I have created a custom UI element (that use CanvasRenderer).

Here is code :

```
Mesh mesh = new Mesh();

Rect drawArea = GetComponent<RectTransform>().rect;

using (VertexHelper helper = new VertexHelper())
{
    helper.AddVert(new Vector3(drawArea.xMin, drawArea.yMin), Color.white, Vector2.zero);
    helper.AddVert(new Vector3(drawArea.xMin, drawArea.yMax), Color.white, Vector2.zero);
    helper.AddVert(new Vector3(drawArea.xMax, drawArea.yMax), Color.white, Vector2.zero);
    helper.AddVert(new Vector3(drawArea.xMax, drawArea.yMin), Color.white, Vector2.zero);
    helper.AddTriangle(0, 1, 2);
    helper.AddTriangle(2, 3, 0);

    helper.FillMesh(mesh);
}

var canvas = GetComponent<CanvasRenderer>();
canvas.SetMesh(mesh);
canvas.SetMaterial(Material, null);

```

It creates a simple rectangle that is same size as rect transform.

It works great. However if I put this inside a scroll view, everything that is outside scroll area / viewport is rendered (while it should be clipped).

The scrolling works as it should (rectangle get scrolled by changing position when scrollbar is used).

I have tried to call `canvas.EnableRectClipping(...);` but without success.

# Answer
I answer my own question :

Custom UI component should inherit from MaskableGraphic and method OnPopulateMesh() need to be overridden, like in this example.
> 0 votes

---
Tags: unity, gui, scrolling, clipping
---


# Question
Title: Glow effect shader for mesh generated at runtime
I'm using the leap motion-paint module and i would like the ribbons that are generated at runtime to have a glow effect, I tried editing the existing shader by adding a glow property but the colors did not change. I'm not experienced with shaders so any help would be much appreciated.

EDIT: I tried adding post-processing effects for bloom & glows, all the objects have a glow effect except the ones i'm generating at runtime..

```
 Shader "LeapMotion/TubeShader" {

Properties{
    _Color("Tint", Color) = (1,1,1,1)
    _Glossiness("Smoothness", Range(0,1)) = 0.5
    _Metallic("Metallic", Range(0,1)) = 0.0
     _Glow("Intensity", Range(0, 3)) = 1
  }
  SubShader{
    Tags { "RenderType" = "Opaque" "Glowable"="True"}
    LOD 200
CGPROGRAM
#pragma surface surf Standard fullforwardshadows
#pragma target 3.0

struct Input {
  float4 color : COLOR;
};

half _Glossiness;
half _Metallic;
fixed4 _Color;
half _Glow;

void surf(Input IN, inout SurfaceOutputStandard o) {
  o.Albedo = (_Color* _Glow * IN.color).rgb * ;
  o.Metallic = _Metallic;
  o.Smoothness = _Glossiness;
}
ENDCG

}
  FallBack "Diffuse"
}

```

# Answer
> 0 votes
After looking a bit further into it, i made some adjustments and it works, I needed to add some tags, edit the way i was changing the albedo and add post-processing effects for bloom. Here's the code if anyone's facing the same problem.

```
 Shader "LeapMotion/TubeShader" {
  Properties{
    _Color("Color", Color) = (1,1,1,1)
    _Glossiness("Smoothness", Range(0,1)) = 0.5
    _Metallic("Metallic", Range(0,1)) = 0.0
     _Glow("Intensity", Range(0, 3)) = 1
  }
  SubShader{
    Tags { "Queue" = "Transparent" "IgnoreProjector" = "True" "RenderType" = "Transparent" "Glowable"="True"}
    LOD 200

    CGPROGRAM
    #pragma surface surf Standard fullforwardshadows
    #pragma target 3.0

    struct Input {
      float4 color : COLOR;
    };

    half _Glossiness;
    half _Metallic;
    fixed4 _Color;
    half _Glow;

    void surf(Input IN, inout SurfaceOutputStandard o) {
     o.Albedo = (_Color + _Glow * IN.color).rgb;
      o.Metallic = _Metallic;
      o.Smoothness = _Glossiness;
    }
    ENDCG
  }
  FallBack "Diffuse"
}

```

---
Tags: unity, shaders, glsl
---


# Question
Title: How can I add velocity to the standard CharacterController?
I have FPS controller from standard asset. After a long trial and error I figured that `CharacterController` doesn't respond to `AddForce`.

So, I have this trigger in the scene which I would like to throw FPS controller upwards.

Now, I know that I need to replace `AddForce` with adding velocity to the player. How to do that?

I need to use FPS controller component for velocity and add `Vector3.up`. So, every game object *other* which will enter the trigger, will get upwards velocity.

```
void OnTriggerEnter(Collider other)
{
    other.attachedRigidbody.AddForce(Vector3.up * 100, ForceMode.Impulse);
}

```

# Answer
I think you don't have an understanding of Object-Oriented programming, AddForce is a method from Rigidbody class, FPSController is another class, so it is not a shared method. What both classes have, is a GetComponent function, which returns to you a component (base class of both Rigidbody and FPSController) of the type you provide. So what you can do is use GetComponent to get the Rigidbody's component of the object you collide with, and then call AddForce.

Other problem you have, is that you are calling other.AddForce, taking as granted that the objects you collide with will have Rigidbody, that is why you first check either the other object's tag or layer, to see if it is on the category of objects of a cerain type.

Example:

```
private void OnTriggerEnter(Collider obj)
{
    if(obj.CompareTag("DesiredTag"))
    {
        Rigidbody r = obj.GetComponent<Rigidbody>();
        if(r != null) r.Addforce(Vector3.up);
    }
}

```
> 1 votes

---
Tags: unity
---


# Question
Title: Baking lights causes weird seams on meshes. How to avoid it?
I'm trying to bake lightning in the simple scene with some imported geometry. The result is weird seams near the edges of the meshes even there is no free space between them. How to avoid it and just simply bake that lightning? This is just something that should not be.

# Answer
It's hard to tell without more information about your models, but my suspicion is that there is an issue with the normals. Normals are vectors that are used to describe to the lighting system what direction the the edge/vertex is pointed. You can think of it as an arrow that is pointing from the flat surface outwards. If the vertices/edges don't share a normal, even if they share a position, then as far as the lighting is concerned, those 2 adjoining faces are pointed in different directions.

Imagine you have a sphere that you've made out of triangles. Your "sphere" consists of a bunch of flat faces that are joined together. To make it look "round", where 2 of the those flat faces meet, they should share a normal, and that normal should point outwards from the sphere at roughly the average direction that the 2 flat surfaces are pointed (so if they are 90" apart, one at 0", or horizontal, and the other at 90", or vertical, where the faces meet, the normal should be pointed at 45" to generate a smooth looking surface. Clearly, if you're making a sphere, you wouldn't have 2 faces 90" apart, but it's easier to describe this way).

Now, let's say you wanted to make something out of flat faces, but you *didn't* want it to look like a sphere. Instead, you wanted it to look roughly like 100 sided dice, so it consists of a bunch of flat planes in a roughly circular fashion. In that case, you *wouldn't* want the edges to share a normal. You would want each vertex to have its own normal, so that you would get a hard edge between the faces.

In the picture you posted of the interior of the house, the vertical lines above the doorways are probably not sharing normals between the 2 flat wall surfaces. Instead, there might be some interior surfaces that the edge is sharing a normal with, but that's not the normal you want, since it won't point directly away from the face, but out at an angle.

On the other hand, your ceiling looks correct where it joins the wall. That's a hard edge. You wouldn't want the edges where the ceiling hits the wall to share a normal, if they did, you wouldn't have a hard edge anymore, but it would look smoothly colored between the ceiling and the floor, disguising the hard edge.

I'm not sure what modeling program you're using, but most modeling tools will have a setting to display the normals. Turn that on, and you'll see a bunch of arrows pointing out of each vertex in your model. Where you want a smooth edge, you'll want to make sure the normals between two joined vertices share a normal. Where you want a hard edge (such as the ceiling and the wall), you'll want them to have separate normals.
> 1 votes

---
Tags: unity, lighting, lightmap
---


title: Coherence between 2d tile maps

text:
# Question
Title: Coherence between 2d tile maps
In dwarf fortress, there are 3 levels of maps in the screen you pick your starting position, and they all coincide with each other perfectly. I am assuming that the top level tile accounts for lets say 36 smaller map blocks, and when the player spawns on the map, that is just a noise value at a different level or frequency of even more tiles.

The selection screen looks like this:

How is such a level of coherence achieved? It doesn't seem like simply adjusting noise frequency/octave values would work perfectly, or maybe it does, I am just not grasping the workflow properly?

# Answer
I believe, starting with the idea that Tarn wants the world to be as detailed as computationally possible, that the highest resolution is generated and the lower level details are then calculated; think of it like LOD in graphics; you can't add detail to an image, but you can easily shrink it and take out some details when those details need to be hidden.

Of course there is no real way to know the exact way that Dwarf Fortress does it as for the moment the game has not been open sourced yet, but that would seem to be the way that the game handles basically everything. Think about how the game models blood streams and the such so it's possible to chop someones leg off before poison reaches the rest of their body for example, but you are never shown that level of detail in game, as that detail can be safely hidden away from view.
> 2 votes

---
Tags: procedural-generation
---


# Question
Title: I need to keep music playing but still be able to mute it between games, how?
I have a game built in Unity. The game plays music continuously, which can be muted on button press on the scene. This works fine using the below code:

`MuteButton.cs`

```
using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class MuteButton : MonoBehaviour {
    public GameObject audioObject;
    private AudioSource audioSource;

    void Start()
    {
        Button b = gameObject.GetComponent<Button>();
        b.onClick.AddListener(Pause);
    }

    void Pause() {
        Debug.Log("mute toggle");

        audioSource = audioObject.GetComponent<AudioSource>();
        if(!audioSource.isPlaying) {
            audioSource.Play();
        } else {
            audioSource.Pause();
        }
    }
}

```

However, when the player loses the game restarts by reloading the scene, using this code:

```
public void Restart()
{
    SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}

```

In order to keep the music running I have attached the following script to my music game object:

```
using UnityEngine;
using System.Collections;

public class Music : MonoBehaviour {
    static Music instance;
    void Start() {
        if(instance == null)
        {
            instance = this;
            DontDestroyOnLoad(gameObject);
        }
        else if (instance != this)
        {
            Destroy(gameObject);
        }
    }
}

```

All working fine up until now. Once the scene is reloaded when the user tries to mute the music I get the following:

`MissingReferenceException: The object of type 'GameObject' 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.`

I understand that the error is that I'm trying to mute a now non-existent game object, but how can I pause the music if this is the case?

# Answer
> 4 votes
Add to your music class a method like this:

```
public static Music GetInstance() {
    // Optionally, you can create an instance here
    // if one isn't already present in the scene.
    return instance;
}

```

Then when you want to toggle the music, instead of referencing an object saved in a member variable, ask the music class which instance is current:

```
var currentMusic = Music.GetInstance();

```

Now you can play/pause this active instance.

# Answer
> 4 votes
The solution by DMGregory is a quick and dirty solution which works well for a single audio source. But in a more complex game you might have multiple audio sources which function as background music. You might also have other groups of audio sources you want to mute together. In that case you might want to use the cleaner solution using the Audio Mixer system and Audio Mixer Snapshots.

1. Create a second audio mixer "Music".
2. Assign that master audio group of that mixer to the Output of your background music Audio Source. It should now still work as normal.
3. Create two snapshots in the Music audio mixer. One with the master volume on normal volume and one with the master volume off.
4. Create two variables in your MuteButton script, `public AudioMixerSnapshot musicOn;` and `public AudioMixerSnapshot musicOff;`.
5. Assign the two snapshots to these variables.
6. You can now switch between the muted and the unmuted state with `musicOff.TransitionTo(0.0f)` and `musicOn.TransitionTo(0.0f)` respectively (`0.0f` is the time in seconds the transition should take. You can smoothly fade the music in and out by using a larger value).

---
Tags: unity, gameobject, music
---


# Question
Title: How can I return the class as a Transform in the array instead of each property?
```
public class TransformInfo
    {
        public string sceneName;
        public string name;
        public Transform parent;
        public Vector3 pos;
        public Quaternion rot;
        public Vector3 scale;
    }

```

Then the method:

```
public static TransformInfo[]  LoadTransformInfo()
    {
        string jsonTransform = File.ReadAllText(@"d:\json\json.txt");
        if (jsonTransform == null)
        {
            return null;
        }

        TransformInfo[] savedTransforms = JsonHelper.FromJson<TransformInfo>(jsonTransform);

        return savedTransforms;
    }

```

The return is:

But then when using it:

```
var test = TransformSaver.LoadTransformInfo();

```

Each item in the array contain the the TransfomInfo but instead I want it to return a Transform with already the info.

So I can do for example:

```
Transform test1 = test[0];

```

Instead make a loop and assign each property from the Test to the new Transform test1.

# Answer
As I said in the comments, I personally see no reason why you are making a class that stores Transform's data, like parent, rotation, position and scale, that a Transform already has by itself. What a transform does not have by itself is the scene name. So, the idea of having a wrapper class is okay, but there is redundancy of information, in my opinion. What I would do is a wrapper struct or class, just containing a reference to a transform, and a scene name. Like this:

```
public struct SceneTransformInfo
{
    public string sceneName;
    public Transform transform;
}

```

So to access all the data you declared in your class would be accessed like this:

```
SceneTransformData data;

Scene Name = data.sceneName;
Name = data.transform.name;
Parent = data.transform.parent;
Position = data.transform.position;
Rotation = data.transform.rotation;
Scale = data.transform.localScale;

```

If you are lazy, like me, and you would like for the user to be easier to access the data, then make functions or **C#'s properties**. Like this:

```
public struct SceneTransformInfo
{
    public string sceneName;
    public Transform transform;

    public string name { get { return transform.name; } }

    public string parent { get { return transform.parent; } }

    public string position { get { return transform.position; } }

    public string rotation { get { return transform.rotation; } }

    public string scale { get { return transform.localScale; } }
}

```

**So, at the end, the way of obtaining a Transform of an array of this struct/class, is just by getting its transform property.**

**NOTE:** Just be careful though, if you intend to have this data to persist between scenes, you may lose the Transform reference if that Transform does not persist, for that, you would need to make a custom data type to store the transform's information, this time similarly to what you did. But instead your parent reference should also be of the type of the custom data, and not Transform (due to the aforementioned problem). I have made myself some time ago a data type for that, in case you are interested on it.

**ABOUT THE DATA TYPE I WAS PROPOSING:**

I had a problem like yours a while ago, where I wanted to store Transform's Data, without having to rely on a Transform's instance, so I did a struct like the one I wrote. But my previous structure didn't have a reference to the parent's transform data. So this is my proposal, have it a class, and have inside the class another variable of the same type, referring to its father. Now, here I am using **implicit operators**, just syntactic sugar to avoid writing the new keyword (it is implicitly done anyway). Here on this class, I also made an IEnumerator to iterate all the parent's parent recursively in a foreach, but you can omit that function, and the class would be good to go for you, if you liked that idea, you could add the implementation for the children.

Of course, I didn't put the scene name's string on that data type, since I wanted to separate the logic. So it is up to you if you want to make a struct/class to store both a string (scene's name) and the TransformData, or have the string in this same class, that is more up to your design decisions.

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

[System.Serializable]
public class TransformData
{
    [SerializeField] private string _name;              /// <summary>Transform's Name.</summary>
    [SerializeField] private TransformData _parent;     /// <summary>Transform's Parent.</summary>
    [SerializeField] private Vector3 _position;         /// <summary>Transform's Position.</summary>
    [SerializeField] private Quaternion _rotation;      /// <summary>Transform's Rotation.</summary>
    [SerializeField] private Vector3 _eulerRotation;    /// <summary>Transfrom's Euler Rotation.</summary>
    [SerializeField] private Vector3 _scale;            /// <summary>Transform's Scale.</summary>

    /// <summary>Gets and Sets name property.</summary>
    public string name
    {
        get { return _name; }
        set { _name = value; }
    }

    /// <summary>Gets and Sets parent property.</summary>
    public TransformData parent
    {
        get { return _parent; }
        set { _parent = value; }
    }

    /// <summary>Gets and Sets position property.</summary>
    public Vector3 position
    {
        get { return _position; }
        set { _position = value; }
    }

    /// <summary>Gets and Sets rotation property.</summary>
    public Quaternion rotation
    {
        get { return _rotation; }
        set
        {
            _rotation = value;
            _eulerRotation = rotation.eulerAngles;
        }
    }

    /// <summary>Gets and Sets eulerRotation property.</summary>
    public Vector3 eulerRotation
    {
        get { return _eulerRotation; }
        set
        {
            _eulerRotation = value;
            _rotation = Quaternion.Euler(_eulerRotation);
        }
    }

    /// <summary>Gets and Sets scale property.</summary>
    public Vector3 scale
    {
        get { return _scale; }
        set { _scale = value; }
    }

    /// <summary>Transform to TransformData's implicit operator.</summary>
    public static implicit operator TransformData(Transform _transform) { return new TransformData(_transform); }

    /// <summary>TransformData's Constructor.</summary>
    /// <param name="_transform">Transform's Data.</param>
    public TransformData(Transform _transform)
    {
        name = _transform.name;
        parent = _transform.parent;
        position = _transform.position;
        rotation = _transform.rotation;
        scale = _transform.localScale;
    }

    /// <summary>Iterates through all parents recursively, starting from this Transform Data's parent.</summary>
    public IEnumerator<TransformData> GetParents()
    {
        TransformData currrentParent = parent;

        while(currrentParent != null)
        {
            yield return currrentParent;
            currrentParent = currrentParent.parent;
        }
    }
}

```

Hope it helps.
> 1 votes

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


title: 2D Sidescroller Gravity

text:
# Question
Title: 2D Sidescroller Gravity
Ive looked up implementing gravity on several sites. Subtract a constant gravity (9.8 * DeltaTime) from the velocity each frame. My problem is, when implementing it as they say, when walking off a ledge the player will float off, not vertically, just accelerates too slowly as he falls.

```
World->Gravity = -9.8 * PixelsToMeters;   // PixelsToMeters = 32
CurrentAcceleration = Vector2(0.0f, World->Gravity);
CurrentVelocity = (CurrentAcceleration * DeltaTime) + PrevVelocity;
Vector2 halfATSq = currentAcceleration * 0.5f * Square(DeltaTime);
Vector2 vt = CurrentVelocity * DeltaTime;
CurrentDelta = halfATSq + vt;
CurrentPosition += CurrentDelta;

```

Now the thing is, with the 1/2at^2 + vt + p calculation, the character does fall about 20 meters in 2 seconds, (I think those are the numbers I used, that was a couple hours ago), so it seems the calculations are right. Ive played quite a few side scrollers and none of them have this floating feel.

So, I tried calculating the gravity based on a TimeInAir variable that multiplies the World-\>Gravity on the third line, instead of DeltaTime.

```
CurrentVelocity = Vector2(currentAcceleration.X * DeltaTime, currentAcceleration.Y * TimeInAir) + PrevVelocity;

```

He no longer floats, he falls as expected. Even jumping looks better. However, now he falls 20 meters in 1 second. Ill deal with this, it is only a game and not reality.

Question is, why is it that this works instead of the original code? Or do I have an error somewhere? Because I have to rework the physics code to get it to look right for everything, instead of just using the basic equations. Is it because its all calculated in pixels? Im wondering if I need to add a full gravity to the velocity on the first frame instead of gravity * DeltaTime? This works for falling off a ledge, but not for jumping.

Im testing these questions as I think of them in my code, and still not getting it. These ideas dont seem to work. Thanks for looking and whatever help or ideas you can give!

# Answer
> Subtract a constant gravity (9.8 * DeltaTime)

Just FYI, 9.81 m/s^2 is not "Gravity". It's acceleration due to Gravity (on Earth).

--

Also, it looks like you are mixing up the kinematic equations. The equation you are using is:

```
0.5*a*t*t + v*t + p

```

This equation calculates the position based on initial velocity and initial position with constant acceleration, so you shouldn't be recalculating your velocity, and then feeding it back into the equation to calculate the distance. The equation already accounts for change in velocity with the 1/2at^2 term. Instead use prevVelocity here, and recalculate currentVelocity for use in the next frame.

I would recommend just using:

```
v += a * deltaT
p += v * deltaT

```

--

Also, sidescroller games don't always use 9.81m/s^2 as their acceleration due to gravity. Maybe this is just because it isn't snappy enough. If your game takes place in a different world, then you can use whatever acceleration you want and still be correct :)
> 0 votes

---
Tags: 2d, physics, side-scroller
---


# Question
Title: Having trouble initializing jagged array ('Object reference not set to an instance of an object' error)
As per https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/arrays/jagged-arrays
I have initialized my jagged array as follows:

```
private float[][] bulletBehaviour;

void Start()
{
    float[][] bulletBehaviour = new float[1][]
    {
        new float[4] {12.0f, 0.3f, 0.5f, 0.5f} // [typeSelected][speed, size, lifeTime, fireRate, damage]
    };
}

```

Then any time I try to use bulletBehaviour elsewhere it gives the error in the title.
Note: There will be more arrays eventually (if I can get them working)

Thanks!

# Answer
> 2 votes
Inside your `Start()` method, delete the `float[][]` before assigning a value to the variable, like so:

```
private float[][] bulletBehaviour;

void Start()
{
     /* Before:
    float[][] bulletBehaviour = new float[1][]
    After: */
    bulletBehaviour = new float[1][]
    {
        new float[4] {12.0f, 0.3f, 0.5f, 0.5f} // [typeSelected][speed, size, lifeTime, fireRate, damage]
    };
}

```

Why?

When you start a line with a variable type, you're telling the compiler "I'm defining a *new* variable of this type."

So you were creating a new local variable called `bulletBehaviour`, and everything that followed assigned a value to this local variable, not the member variable that you defined in the body of the class itself. So the member variable stayed unassigned (null).

If for some reason you need to have a local variable or argument of the same name inside a method, you can still refer to the member variable by qualifying it with `this.` like so:

```
string greeting = "Hello";

public void MyMethod() {
    string greeting = "Yo";

    Debug.Log(greeting);  // Refers to the local variable - outputs "Yo"
    Debug.Log(this.greeting); // Refers to the member variable - outputs "Hello"
}

```

---
Tags: c#
---


# Question
Title: Positioning items / clothes on character
I'm aware that in Unity, when you want to add (e.g.) a weapon to a character, you parent it to the "hand" bone of the character etc...

Well I'm trying to add a hat to a character in unity when it's clicked (and the head of the character is moving around beforehand), and I want the hat to always be in the same position on the characters head, no matter what position the (animated) head happens to be in when it's clicked.

I tried making a reference mesh in blender (just a cube), and then setting the hat mesh to the same position of that mesh in unity, and to do that I tried parenting it to the head bone and then positioning it on the exact spot of the head in the blender model, but I did this by using the "Child Of" restraints and apparently blender restraints don't render to unity.

SO I'm not sure if making a reference item in blender was the perfect solution, but how can I set the position of the hat to the same position on the characters head?

EDIT:

I'm using a basic CharacterController for the character, and basically my character starts as a capsule object with the CharacterController and then I hide the capsule mesh and make my .fbx model a child of the capsule, and when moving I only rotate the model, not the capsule (if that's relevant), but I (also) want to be able to place objects on NPCs that are moving around, and so far the way I'm making those is just adding a capsule collider to the .fbx and adding click events to it with event triggers... anyways here's the the node structure of the NPC model if that helps:

:

the "teffilinBox" is the placeholder that I manually added after it imported to Unity, and it's what I was trying to get automatically by parenting with Blender, which didn't work.

BTW, I found another way to make meshes children of bones in blender, by going into pose mode and manually parenting the mesh to the bone, which WORKS in blener and it APPEARS to work in unity, although; the problem:

In blender, when you parent to a bone, it doesn't actually parent to the bone itself, it just weights it 100%, and it's actually a child of the armature only, with 100% weighting, so when I import it to unity, it doesn't recognize the parent-child relationship at all, but it still moves with the head so I guess it recognizes the weighting...

When I tried to make the hat object a child of the placeholder, it wasn't affected by the head at all, since in unity the placeholder itself isn't an actual child of the head, it just looks that way. And when I tried to parent the hat to the head, then just adjust the world position to that of the cube, it was always way off.

SO I just found a workaround that works, in case anyone else is having this problem: in Blender, when making the placeholder, just move to the first frame of the animation and position it but DON'T parent it to anything, then give it some unique name like "placeholder\_Head" and then in Unity, on one of the start functions, find that gameobject (or ALL of the game objects that start with "placeholder" and then extract the other part of the name with Regex or something) and THEN parent it to the correct bone, in unity script, and afterwards, you can attach the hat object as a child of THAT, since now the placeholder is a real child of the bone. That worked for me, if anyone knows of how else to do it, I would like to know :) 'cause the main problem with this method is I'm not sure how to programmatically add all of the placeholders as children to the respective bone, because you can't just get a gameobject name with regex (Finding Game Object with Regular Expressions), without literally looping through all of the gameobjects or something like that... So does anyone know another way to do this (pretty basic) thing?

PS: to try to duplicate my issue to see what I mean, just get a rigged character in blender and try to make a placeholder cube or something then select the armature, go to pose mode and select the cube and shift-select the specific bone you want to parent it to, then make the animation and see how it moves with the bone in blender, but then import it to unity and try setting another object to the child of the placeholder with script any localPosition at 0, you'll see it doesn't work at all.

# Answer
> 0 votes
I ran into a similar problem, and I solved it this way: Every frame, take the bone's (in your case, the head bone's) transform, define an offset (from the center of the head, per se, to the top of the skull), and transform the *bone*'s facing direction\* with the offset applied (first). So:

```
public Vector3 boneToHat;    // from the start point of the bone to the origin of the hat

```

And in your update method:

```
Vector3 headTop = headBone.TransformPoint(boneToHat);
hat.position = headTop;

```

Then, you'll want to rotate the hat to be perpendicular to the head:

```
hat.up = headBone.forward;  // for instance, if the hat is oriented with *up* actually being up in Blender and the bone's forward is facing up

```

* My computer isn't booting right now, so I can't test, but using the `forward` property should work, if not that, click on the bone in the inspector and observe the colored line it's direction is aligned with, and use that axis (Blender can mess things up; this worked for me).

# Answer
> 0 votes
Seems like the easiest approach would be to just put an empty game object at each spot you want to be able to attach stuff (eg top of the head), then set that game object as parent of the equipment at runtime. This way you're less reliant on the actual world position of the head, for example, when placing the hat.

---
Tags: unity, blender
---


# Question
Title: Sprite/Object/Room limits in GameMaker 8.1?
I know about GameMaker Studio’s limitations for sprites, objects, rooms, and other assets (https://help.yoyogames.com/hc/en-us/articles/230407528-GameMaker-Studio-2-Trial-Limitations), but I can’t find anything about if there are similar limitations in GameMaker 8.1, which I also have on my computer. What are the limits for sprite, object, background, and room count in the Lite and Standard versions of GameMaker 8.1, if there are any?

# Answer
GM 8.1 Lite has a lot of limitations. And there is no any reason to use it.

Documentation says:

> Standard Edition contains considerably more functionality and does not display any logos or popup messages. More precisely, Standard Edition has the following additional functionality:
>
> * No GameMaker logo is shown when running a game.
> * No GameMaker TV logo in the corner of a game.
> * No GameMaker advert screen on exit.
> * No regular popups remind you of upgrading.
> * You can use color blended sprites, which can be used for many special effects and easy shadows.
> * There are additional options in the sprite and image editors.
> * There are additional actions for e.g. CD music, rotated text, and colorized shapes.
> * You can use special sound effects and positional sound.
> * You can create splash screens with movies, images, webpages, texts, etc.
> * There is a particle system to create explosions, fireworks, flames, rain, and other effects.
> * A number of advanced drawing functions are available, for example colorized text and textured polygons.
> * It is possible to create 3D games using functions for 3D graphics.
> * It is possible to create multiplayer games that can be played over a network.
> * You can define your own room transitions.
> * You can use functions to create, load, and modify resources (sprites, backgrounds, etc.) while the game is running.
> * There is a collection of functions to create and use data structures.
> * There are functions for motion planning.
> * You get the possibility to include additional files in the game executables that can be used when the game is run.
> * Standard Edition can be easily extended using extension package. These can be made by everybody and will in general be provided free of charge.
> * Three such extension packages are included adding many room transitions, windows dialogs, and printing facilities.
> * You can define your own trigger events.
> * You can export and import resources, which makes it easier to collaborate on games.
> 1 votes

---
Tags: sprites, game-maker, objects
---


# Question
Title: How to display all the previous strings except the current strings from the list?
I would like to create some sort of log to display previous strings for my game, but I still cannot figure out how to properly displaying them. I am using a button to run this method every time player clicks it.

```
public void AddLog()
{
    foreach (string logEvent in DisplayDialogueList)
    {
        logTextList.text = logText;
        logText += logEvent;
        logText += "\n\n";
    }
}

```

This method supposed to be displaying all the previous strings that has been displayed before inside `DisplayDialogueList` but I can't limit the displays only for the previous strings, and it will always display all the strings from the list.

I have tried the .Skip method to detect the current index of the list that are currently being displayed but it does not refresh the list, meaning if I loop to skip the first index from the list, it will always skips the first index even the current index to be displayed is second index and so on.

I also having trouble to skip the last index on the list since C# Unity does not support .SkipLast.

Any help would be appreciated.

EDIT: Sorry for the confusion, this is how I managed to distinguish which is the current string to be displayed, it runs on button click

```
public void Display()
{
    //Checks to see which element from the list has the same index number as the current index
    if((index == textIndex) && !(DisplayDialogueList.Count <= index))
    {
        //Displays the string from the list that has passed the argument above
        textList.text = DisplayDialogueList[textIndex];
        index +=1;
        textIndex = index;
    }
}

```

Everytime the button is clicked, the index number will be increased, so it will matches with the string with the same index from the list and displays it.

UPDATE: Ok I managed to skip the current displayed index and last index (thanks to the answer below) but this happens apparently

The **Hello, my name is Mira** text is in the first index of the list. How do I make sure that text won't be displayed again after the back button is clicked, which run the **AddLog()**?

The updated code is below:

```
if(!(index > DisplayDialogueList.Count))
    {
        firstIndex = DisplayDialogueList.First();
        lastIndex = DisplayDialogueList.Last();
        foreach (string logEvent in DisplayDialogueList)
        {
            if(logEvent != lastIndex && !(firstIndex == currentIndex))
            {
                logTextList.text = logText;
                logText += logEvent;
                logText += "\n\n";
            }
        }
    }

```

# Answer
Alright, after cramming for the whole night, I finally managed to solved this, I just add the displayed string to temporary list called **Logs** and just loop the **Logs** list and displays the added strings inside it before I clear them up, so it won't be any duplicates.

```
public void AddLog()
{
    if(!(index > DisplayDialogueList.Count))
    {
        //Iterate through the recorded logs
        for (int i = 0; i < Logs.Count; i++)
        {
            var log = Logs[i];
            var messageSameAsPrevious = i > 0 && log == Logs.Last();
            if(messageSameAsPrevious)
            {
                continue;
            }
            logTextList.text = logText;
            logText += log;
            logText += "\n\n";
        }
        //Clear the temp list
        Logs.Clear();
    }
}

```

Much simpler than my previous methods, and since for loop is much more efficient than foreach loop in terms of performance. Thanks to everyone here who gave me the ideas and insights, much appreciated :)
> 0 votes

# Answer
You can get the last item in your list by something like this :

lastElement = DisplayDialogueList.get(size - 1) Where size is the list size.

Then in the for each loop you simply add a if statement :

If(logEvent != lastElement) { You log it.. }

Hope to understand your need
> 1 votes

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


# Question
Title: libgdx - how to make enemies not overlap
I'm currently making a roguelike shooter in libgdx to get a better understanding of the library but I recently just stumped onto a problem where enemies would overlap each other while tracking the player's movements. The code I use to calculate the angle for the enemy to take is simple trigonometry. After moving the player around the screen a for a little bit, the enemies' paths intersect to the point where it just looks like a single mesh of textures following the player. Here's the code:

```
// track player
radians = MathUtils.atan2((player.getY() + player.getHeight() / 2) - (y + enemy.getRegionHeight() / 2),
        (player.getX() + player.getWidth() / 2) - (x + enemy.getRegionWidth() / 2));
dx = MathUtils.cos(radians) * speed;
dy = MathUtils.sin(radians) * speed;

```

An solution that allows the enemies to recalculate their angle would be much appreciated.

# Answer
> 1 votes
Two fairly straightforward approaches come to mind:

1. A simple anti-overlap mechanic.
2. A separation force which grows stronger the closer your enemies are. (This is in the "swarming behavior" or "steering behavior" space, if you want to learn more.)

**Anti-overlap**

The gist of this is that you test for your enemies actually overlapping, after computing movement, and you de-conflict them in some way. Two approaches you might consider:

1. Push them apart enough to prevent overlap (can cause rippling effects),
2. Give one higher priority (closest to player?) and have the other move as far as possible without colliding.

**Separation Force**

Your "track player" implementation above is often called a 'seek' behavior, essentially a force or vector that moves an agent (your enemies) towards a target (your player).

To avoid collision, you need to add some other force/vector.

The classic 'Boids' system may offer some intuition, here. Of the three rules in that link, the one you'd be implementing is called 'separation'. Generally, it means that when calculating the path an enemy takes, you check the locations of other nearby enemies, and then you calculate a force (a separate direction vector, in your case) that makes them move away from those enemies. That vector can usually be simply summed with the 'seek' vector.

I've had the most success when the force is inversely proportional to the distance they are apart - you only want enough separation force to keep them from actually running into each other.

This can be somewhat tricky to tune correctly, but it can also look a bit more believable. The main risk here is that you get two enemies trying to fit into a narrow space, preventing either from getting to the target.

---
Tags: java, libgdx, mathematics, ai, roguelikes
---


# Question
Title: i need suggestion animation technique for 3d?
firstly you need to now i am beginner :)

i am using opengl and for display vertex buffer object(vbo).

i made 2000 frames animation model with blender and i export with (.obj) files and i upload all these 2000 obj files to my opengl project.

But upload process is taking too much time. like 7-8min and this method use too much vram around 2-3gb.

Despite all this i'm glad draw performance because when i draw 100 animation(same model) at the same time my pc using %1-2 cpu and %70-80gpu.

Now i want to learn is there another method of good draw performance and low system consumption ? (i want to draw 100 and much more animation model at the same time)

# Answer
> 1 votes
What you're showing looks like it can be accomplished with conventional "skeletal' or "skinned mesh" animation.

To do this, we do *not* export a completely separate model file for every animation frame, analogous to rendering out individual sprites of a spritesheet animation.

Instead, our outputs are:

* the vertex positions/normals/etc & triangle indices for the model in a *single pose*, often called a "bind pose" or "T-pose."
* a hierarchy of *bones* corresponding to this pose. Each bone has a local position & orientation and a parent, establishing the structure of the moving parts.
* *skinning weights* for each vertex, identifying a set of bones that influence that vertex's position, and how much effect each of those bones should have.
* animation data, in the form of position & orientation *keyframes* for each bone.

When we want to show a particular frame of the animation in-game, we transform the bone hierarchy according to the skeletal animation for that frame, then transform each vertex position/normal according to the skinning weights that link it to those bones. The model is reshaped into a new pose on the fly.

Because we store the animation of just the bones, not every vertex, we get a massive savings in the amount of data that needs to be stored, and we can continue re-using the same triangle mesh for every frame.

We can even re-use this same animation data for other models that use the same bone skeleton but different triangle mesh & skinning data, or to animate swappable equipment & attachments on characters so it follows their movements without each piece needing its own custom animations.

We get further data savings by storing just the keyframes rather than every frame of the sequence. When displaying a frame that lands between two keyframes, their poses can be interpolated at runtime, allowing us to play animations at different speeds, or even blend & layer multiple animations.

These animation sampling and skinning calculations can be performed very efficiently, even offloaded to the GPU, so you can still render a large number of animated models despite more calculations happening at runtime.

I hope this clarifies the high-level strategy. As I'm not an animator or animation programmer myself, I'll have to defer to other answers to provide more specific direction in how to export skeletal animation data from the particular tools you're using, and how to implement sampling, skinning, & rendering the animation in-game.

You should find lots of existing resources to get you started if you search for the terms laid out above. This is probably the most common way to do animations in 3D games, so there are lots of guides.

---
Tags: opengl, animation, vbo
---


# Question
Title: Efficiently calculate 2d world position based on parent(s) recursively
I am writing a small 2d html5 game engine in javascript that relies on the concept of a hierarchy. The scene is the root node or *entity*, and its children make up the game objects. These children can have other children, recursively. Every entity has a *relative position* and an *absolute position*. By *relative*, I mean in object space, and by *absolute*, I mean in world space - based on its own and its parents' transformations.

To calculate the world position of an entity, all I have to do is apply its transformations (translation, rotation and scale), and that of its parent, and of its parent's parent, to its local/relative position up until the root entity of the hierarchy.

The problem I'm having is **when** to calculate this the most efficient way. Should I calculate the world position every time I **`get`** its `worldX` or `worldY` properties? What about every time the position, scale or rotation properties of the entity or any of its parents are **`set`**? Or is there a completely different way?

Note: along with knowing an entity's world *location*, I also need to know its world *bounding box*.

# Answer
> 4 votes
The way this is typically handled is with a dirty flag.

Each object stores both its current local transformation/bounds, and a net transformation/bounds according to its whole parent hierarchy (eg. a single composed local-to-world matrix and worldspace bounding box).

To avoid updating all of this transformation/bounds data more often than we need to, we allow it to go out of date, and mark stale data with a flag.

When we change an aspect of an object's transformation, we mark its transformation/bounds data "dirty" (and propagate this down to any child objects not already marked dirty).

If we change it again and it's already dirty, we're done, and don't need to do any extra calculations.

When we want to use an object's transformation/bounds data (eg. to check its final position in the world), we check if it's been marked "dirty."

* If so, we go up the hierarchy to the last dirty parent, and re-calculate the transformation & bounds data down the chain from there, clearing the dirty flags as we go.
* If not, we can use the object's net transformation & bounds data as-is, without extra computation or walking of the parent hierarchy.

This approach saves repeated calculations when we mix changes to the transformations and use of those transformations/bounds, walking the hierarchy and re-computing net transforms & bounds just once between a set of changes and the next use of that data.

---
Tags: 2d, javascript, transformation, recursion, hierarchy
---


# Question
Title: Handling exact collisions on character controller and/or other objects in unity? (eg. head shot, chest , leg,etc)
Hello all I have been working on games in Unity for a long while (making slow progress as I do it purely on my own , and of course you helpful people here on gamedev.stackexchange!)

I've made lots of capsule characters of my own using Rigidbody and without Rigidbody and on a basic level they work fine. But i now want to detect exact points of collisions (for example if a bullet hits his head, or hand or knee etc etc)

I've been trying to read as much as I can find about this, but honestly can't find the answer i need. I believe I would achieve it by making several colliders on the character. But I don't know exactly how this would work , also I have seen some guides saying that I should use OverlapSphere but again there wasn't exact instructions and I can't figure out how to do it.

Also, when I add some sphere colliders to my character, they dont stay in the correct position in relation to the model once it is animated (eg. Crouching, or running, the leg spheres pop out of his legs for example).

Could anyone here provide an explanation of how I can do it?

# Answer
Attach your body part colliders to the transforms representing the animated character's bones.

Set each one's "Is Trigger" property to true, so you can use them for checking collisions with projectiles, without altering the movement or physics simulation of your characters and their surroundings.

Add a Rigidbody component to each one, set to Kinematic, so they're driven solely by the animation of those bones.

Set them up on a new physics layer that doesn't collide with your character controller's capsule or the environment, only with projectiles / weapon raycasts, to reduce redundant collision checks & messages.

You can then check for hits on these body part triggers in a number of ways:

* Fire a raycast (or spherecast, etc) masked to the environment & body part layers. This is useful for instantaneous effects like a laser, or high-speed bullets that don't take an appreciable amount of time to travel from the barrel.
* Fire projectile Rigidbodies and detect collisions with an OnTriggerEnter method, on either the body part or the projectile object. This is good for low-speed or lobbed projectiles. You can also do this with persistent objects to represent things like tripwires or energy fields the player could walk into.
* Use volume queries like OverlapSphere to check for body parts within an area of effect. This is good for instantaneous blasts (like finding everything in the radius of a grenade at the moment of detonation)

Make sure to pass the argument `QueryTriggerInteraction.Collide` to ensure your raycasts/volume queries don't ignore triggers.
> 2 votes

---
Tags: unity, collision-detection, character
---


title: Draw text in OpenGL ES 3D game?

text:
# Question
Title: Draw text in OpenGL ES 3D game?
I am making a game using OpenGL ES 1.0 and I want to keep player score. So I need to draw text dinamically. What is the best approach? Some library, textures, bitmaps? I tried to use TextView but when I want to update text I need to do that from main thread, and there is an obvious lag in the game.

# Answer
> 1 votes
One common, easy way to do it is to simply make a texture atlas with the characters you'll need (probably lowercase letters, uppercase letters, numbers, and maybe some punctuation). Then simply pull out the section you need to draw each letter.

# Answer
> 1 votes
The typical way is to use a texture atlas with glyphs.

Personally, I am a fan of vector text, where you actually define the shape of the character with geometry, not with texels.

The advantage of this is that your text is completely resolution independent. You can zoom in on your text as far as you like, without every seeing aliasing or jaggies.

Now granted, the curves in text means that they will look best with curve primitives, or high poly counts.

But if you are OK with crude shapes, and want a simple approach, may I suggest Dutch Blunt?

DISCLAIMER: I am the author.

For a more professional solution (paid) you can look into Slug.

---
Tags: 3d, opengl-es
---


# Question
Title: What is the easiest way to make an online high scores table?
I made an 2d Android game with using Libgdx library. This game like Flappy Bird. And every user have a highscore. I want to store this highscores respectively to an online database and return the rank of the user in the world ranking.

How to do this? In backend ,which architecture should I use? Is there a tutorial for this?

# Answer
First you need a web site which gives you cgi access. I don't think any of the "free" sites will do that, but a minimal web server is pretty cheap; or perhaps you can find a friendly site to host your database and associated scripts.

Second, design a simple web interface to view and update the high scores table, using a mysql database and cgi scripts written in perl, php, python, or whatever back end you want. The public interface to add new high scores need not be left up permanantly, it's just for development.

Third, access those same scripts, or simple variants, from your android game using https requests.

And as Pete Taylor says, you must add some authentication to prevent the transactions being hacked. The minimal version of this would be to add a checksum of all the relevant data elements, plus the device id, plus some secret keystring.

If you look around, you will probably find open sources that have already done all that for you, except of course adding the https access to your app.
> -1 votes

---
Tags: libgdx, android, databases
---


# Question
Title: Why does my terrain texture fail to load? (OpenGL)
I'm currently using a vertex shader and a fragment shader for loading my texture onto the terrain I made.

Here is my vertex shader

```
#version 330 core
layout (location = 0) in vec3 aPos;
layout (location = 1) in vec3 aNormal;

uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;

float scale = 0.5;

out vec2 TexX;
out vec2 TexY;
out vec2 TexZ;
out vec3 blend_weights;

void main()
{
    vec3 blend_weights = abs(aNormal.xyz);
    blend_weights = (blend_weights - 0.2) * 0.7;
    blend_weights = max(blend_weights, 0);
    blend_weights /= (blend_weights.x + blend_weights.y + blend_weights.z);

    TexX = aPos.yz * scale;
    TexY = aPos.zx * scale;
    TexZ = aPos.xy * scale;

    gl_Position = projection * view * model * vec4(aPos, 1.0);
}

```

And here is my fragment shader.

```
#version 330 core
out vec4 FragColor;

uniform sampler2D terrainTexture;

in vec2 TexX;
in vec2 TexY;
in vec2 TexZ;

in vec3 blend_weights;

void main()
{
    FragColor = texture(terrainTexture, TexX)*blend_weights.x + texture(terrainTexture, TexY)*blend_weights.y + texture(terrainTexture, TexZ)*blend_weights.z;
}

```

I was trying to implement 3D texture planar projections, based on section 1.5 of this link https://developer.nvidia.com/gpugems/GPUGems3/gpugems3\_ch01.html

If I just try to implement the texture in a very simple way, it works (which looks terribly stretched on the mountanous terrains, of course). But if I implement it this way, the texture does not load. What could be the possible reason?

---

Just in case anyone is wondering, the following is my VAO, VBO, EBO configuration

```
// VAO, VBO configuration
    unsigned int VAO, VBO, EBO;
    glGenVertexArrays(1, &VAO);
    glGenBuffers(1, &VBO);
    glGenBuffers(1, &EBO);

    glBindVertexArray(VAO);
    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    glBufferData(GL_ARRAY_BUFFER, positions.size()*sizeof(glm::vec3) + normals.size() * sizeof(glm::vec3) , NULL, GL_STATIC_DRAW);
    glBufferSubData(GL_ARRAY_BUFFER, 0, positions.size() * sizeof(glm::vec3), &positions[0]);
    glBufferSubData(GL_ARRAY_BUFFER, positions.size() * sizeof(glm::vec3), normals.size() * sizeof(glm::vec3), &normals[0]);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(int), &indices[0], GL_STATIC_DRAW);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), 0);
    glEnableVertexAttribArray(1);
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)(positions.size() * sizeof(glm::vec3)));

```

This is my draw function

```
// Inside the render loop
void drawScene(Shader &shader, unsigned int VAO, unsigned int numIndices, unsigned int texture1)    //draw the scene with the parameter data.
{
    glm::mat4 model;
    model = glm::translate(model, glm::vec3(-(int)(gridXNum)/2, 0.0f, -(int)(gridZNum)/2));
    glm::mat4 view = camera.GetViewMatrix();
    glm::mat4 projection = glm::perspective(glm::radians(camera.Zoom), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f);

    shader.use();
    shader.setMat4("model", model);
    shader.setMat4("view", view);
    shader.setMat4("projection", projection);
    shader.setFloat("TERRAIN_WIDTH",gridXNum);

    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, texture1);

    glBindVertexArray(VAO);
    glDrawElements(GL_TRIANGLE_STRIP, numIndices, GL_UNSIGNED_INT, 0);
    glBindVertexArray(0);
}

```

However, I really don't think this is the problem because as I said, if I change the shader codes into a really basic one, the texture successfully loads. There is definitely something wrong with my shader program. Any help would be appreciated. Thanks in advance!

# Answer
> 2 votes
I found the answer. It was just a stupid mistake.

```
out vec3 blend_weights;

void main()
{
    vec3 blend_weights = abs(aNormal.xyz); ...

```

After I declared an output vec3, I declared another vec3 inside the main() with the same name. That's why the information disappeared as soon as the program exited the main() function. Sorry for the trouble!

---
Tags: opengl, shaders, textures, glsl
---


# Question
Title: How to know if one game idea is more worth pursuing than another?
Right now I'm stuck between multiple projects (I don't have shiny object syndrome) I have several game ideas and I'm trying to figure out how to pick between them. I was thinking maybe hearing someones else's idea on how to handle a situation like this would help me.

How can I pick between game project ideas?

# Answer
> 44 votes
Your first test should be to pitch individual ideas to a few random people from your offline or online social circle or to a few interested online communities. See how they react to it. This can provide a first sanity check which doesn't cost you a lot of time and effort.

However, it is difficult to really judge how a game *feels* just from a description of the game. So if the reaction is not completely negative, then your next step should be to build a rough, throw-away prototype.

Do not waste any effort on any bells and whistles like graphics, user experience or on the extensibility of your software architecture. Only get that core mechanic you have envisioned to a playable state so you can see how it feels to play it. Cut every corner you can. Only make what you can't fake or borrow and don't occupy yourself too much with fixing any bugs which do not completely prevent you from experiencing the core mechanic.

For more advise about rapid game prototyping, check out the Extra Credits videos Fail Faster and Minimum Viable Prototype.

If you find a prototype where you feel that you would like to do it properly, then it is time for a little business analysis:

* Can you realistically complete this project with the resources you have available? Be pessimistic here. Software development always gets far more expensive than you think at first.
* Is there a market niche for your game?
* Can you outperform the other games in that niche with the resources you are able and willing to invest? (If people call your game a rip-off, they should at least call it a rip-off which improves on the original)
* Do you see a way to effectively market your game?

If you answer yes to all of these questions, you might want to give it a try.

Whatever game idea you eventually decide upon, I am looking forward to playing it.

# Answer
> 28 votes
Everyone is different so take this advice with a grain of salt.

If you care about each of the projects equally, I would recommend going with whichever project has the smallest scope. That way, you'll have a greater chance of completing the project and you'll minimize the amount of time thinking about the other projects you want to do instead. You can start a list of 'future projects' and write the other ideas down there. Putting your ideas into writing will help put them to bed for now.

If you think you might me more passionate about a particular project, but aren't sure which project that is, you could try making small prototypes of each idea. Create a quick paper prototype, or something similar, and play-test each idea with a group of friends. The keyword here is quick. You want to spend as little time as possible on each idea while still getting the feel for what it would be like to work on that project.

# Answer
> 3 votes
Whether a personal project, android app or fully publisher funded release - the key aim is to **create as much value as possible for the resources you invest.**

---

If you were releasing this as a commercial game, some factors you may consider to be valuable could be:

* How much income you expect from sales
* How much this title will build your reputation, and increase future revenue

These can be measured in a number of ways - such as looking at similar and previous titles, asking your customer base, and many other aspects of market research.

---

But even a personal project, that never sees an audience, will still have value:

* How much you will develop your skills for future development
* How valuable the opportunities are that this project may open up to you
* How much value this project will add to your portfolio

---

*And of course, in both situations - how much personal satisfaction you'll gain from seeing this idea brought to life.*

---

The values you attribute will range from super fuzzy (personal satisfaction) to concrete (earning $x income). Some will have higher or lower priority for you, and there is no way for anybody except yourself to decide "how valuable" a project is to you overall.

However, once you've made a case for each project - and how valuable you expect it to realistically be - you can set that against the cost to make it.

Again the costs may be fuzzy (additional stress) or concrete (monetary cost of tools and your time *which isn't $0 - even if you're unemployed*).

*You can (and should) also weigh up the risk of not achieving each project. That is, the chance of the project ending up with no value gained for the given cost.*

---

Once you've properly planned out the projects, and have made decisions on what is or isn't valuable in each one - you can more objectively decide which project gives you the most value for your investment.

For personal projects, this is often the value vs the time investment (which should not be undervalued). But the same skills will apply even if you do decide to make a commercial title.

Importantly, if you have multiple projects that you've deduced to be equally valuable, and equally risk-free; choosing any of them will have the same result and so you can just pick one at random - they are all equally good options.

# Answer
> 0 votes
> one game being more fun/engaging than another.

More fun/engaging, for which players? It's tricky, because different people rank game-fun differently. And how do you contact them? How do you know how much fun it was to them? This is all too hard! So instead, we consider just one player, who we have great access to: *you*

(Alternative: some writers, to have a target audience in mind, think of a single individual, and what would be entertaining to them - several children's books have been written with some specific child in mind.)

Now, how domwe tell which game *you* find the most fun/engaging, when it doesn't exist?

1. The first thing is to ask yourself: which do you think you'd find the most fun/engaging?
2. The next approach is to perforrm an experiment to help you tell. The purpose of an experiment is to not be a result in itself, but to give you information. The lowest-cost experiment, that gives you the best information, is the way to go. We can consider what is really easy to try (low cost), and the start again, considering what will answer your question (high information).

This is the MVP concept others have mentioned, but more extreme. If you can try out part of an idea, without coding at all, that's a better experiment. For example, can it be done with pen and paper? A board game? A card game to represent the choices? A map drawn on paper? You can combine your imagination with the prop, as part of your prototype. There's no difficulty with getting the answer out of someone, or if they are imagini g it wrong, because it's you. Plus, imagination is even lower-cost than pen and paper!

Some non-game examples: a guy wanted to test the idea of selling cars online. So he made a webpage that emailed the form to him, and did everything else manually. He wasn't trying to build a business, but get informatiin aboit whether people would actually buy cars online.
The Wright Brothers realized control of an aircraft was the tricky bit, but it took 6 months to build a test aircraft (and risk life and limb to try it). So they built a wind-tunnel (perhaps the first?), and could try out ideas on models, sometimes several a day.

Note that the task here is *not* to make a prototype of your game, but to see if a game idea is fun, how much fun and which one is the most fun. It's about information, not to build your game. It should feel easy to throw out a failed experiment.

3. A problem with this approach is that a game idea might not be that much fun in the first version. This is a problem for you question only if it might change the fun-ranking: if one game idea is the least fun... but with some tweaks, becomes the most fun. You might need to change the idea, maybe a lot, to get the fun out of it. The experiment/prototyping aproach here can also be adapted to that - it's easier to tweak an idea in your mind, or on paper, than in code.

But if you consider all these variations, there are too many game ideas to compare. So, you shouldn't do this until you've choosen an idea (or, if you have a brilliant idez to make it better, and you can't help yourself but explore it).

Finally... through this process, as yo learn more about your game ideas, you may get a sense that *this is the one to do!* *This would be awesome fun!* That game is the one to do.

---
Tags: game-design, project-management
---


# Question
Title: libgdx - creating static HUD/widgets on screen
I'm having problems with creating static HUD/buttons on the game screen. Currently my game has a character moving on the tiled map, with OrthographicCamera put on, everything works fine. I wanted to add button on the screen:

```
...
Stage stage;
ImageButton imageButton;

@Override
public void create() {
        stage = new Stage(viewport);
        Texture texture = new Texture("bagbutton.png");
        Drawable drawable = new TextureRegionDrawable(new TextureRegion(texture));
        imageButton = new ImageButton(drawable);
        imageButton.setPosition(200, 200);
        imageButton.addListener(new ClickListener() {
            @Override
            public void clicked(InputEvent inputEvent, float x, float y) {
                System.out.println("clicked");
            }
        });

        Gdx.input.setInputProcessor(stage);
        stage.addActor(imageButton);
}
...

```

And then in render() method I got

```
stage.draw();

```

button appears, indeed, and it's even clickable. However, my player image (drawn by spritebatch.draw with texture) disappeared. Moreover, button is in the same position on map, and I'd like it to be somewhere on the bottom of the screen. It should be there statically, too, always in the same place, so when players moves, the button is always in the same place on screen. Next I'd like to make the same thing with some text and image, let's say on the top of screen. **How to make it so?**

# Answer
> 0 votes
You should use different viewports for your hud and your player.
Make a Hud class for your Head-up display with the stage and the viewport:

```
public class Hud {

    private Stage stage;
    private FitViewport stageViewport;

    public Hud(SpriteBatch spriteBatch) {
        stageViewport = new FitViewport(500,500);
        stage = new Stage(stageViewport, spriteBatch); //create stage with the stageViewport and the SpriteBatch given in Constructor

        Table table = new Table();
        ...
        ... //add the Buttons etc.

        stage.addActor(table);
    }

    public Stage getStage() { return stage; }

    public void dispose(){
        stage.dispose();
    }
}

```

And then in your GameScreen, you can create an instance of Hud:

```
public class GameScreen implements Screen {

    private Hud hud;
    private SpriteBatch spriteBatch;
    private OrthographicCamera camera;
    private FitViewport playerViewport;

    public GameScreen() {
        spriteBatch = new SpriteBatch();
        hud = a new Hud(spriteBatch); //SpriteBatch eats a lot of memory so you can use the spriteBatch for both drawing the hud and the player

        //our camera and viewport for the player
        camera = new OrthographicCamera();
        playerViewport = new FitViewport(WORLD_WIDTH, WORLD_HEIGHT, camera);

        ... //other stuff like create the player etc.
    }

    @Override
    public void render(float delta) {

        Gdx.gl.glClearColor(0,0,0,1); //clear the screen
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        camera.update(); //update camera

        //First draw the player
        spriteBatch.setProjectionMatrix(camera.combined); //set the spriteBatch to draw what our playerViewport sees
        spriteBatch.begin();
        ... //draw player and game objects
        spriteBatch.end();

        //Secondly draw the Hud
        spriteBatch.setProjectionMatrix(hud.getStage().getCamera().combined); //set the spriteBatch to draw what our stageViewport sees
        hud.getStage().act(delta); //act the Hud
        hud.getStage().draw(); //draw the Hud
    }

    @Override
    public void resize(int width, int height) {
        playerViewport.update(width, height); //update our viewports
        hud.getStage().getViewport().update(width, height);
    }

    @Override
    public void dispose() {
        hud.dispose(); //dispose our hud
        spriteBatch.dispose(); //dispose the spriteBatch
    }

    ... //other methods for Screen pause(), resume(), hide()
}

```

---
Tags: java, libgdx, screen, hud
---


title: Rotate billboard towards camera

text:
# Question
Title: Rotate billboard towards camera
I'm trying to create a particle system in OpenGL, and as such I need to use billboards.

I need these billboards to face the **camera at all times.**

The tutorials I've been following only rotated the billboard on 1 axis, such as billboards being used as grass or plants, but I need a method of rotating the quad to always face the camera, even when looking down on it.

---

**The Original Scene:**

**Desired Scene:**

While searching for an answer, I only really found the technique of turning the mat3 component of the camera's view/model matrix back to an identity matrix. This isn't quite what I need, as the point's location in space never change then.

**Incorrect Scene:**

---

How can I calculate a new rotation matrix that will successfully rotate a quad always towards the camera, or modify an existing matrix?

In the geometry shader I have access to the camera's position, the perspective matrix, and the view/model matrix.

I didn't include any shader code because it is really trivial; I create vertices that are an offset of the desired point's position based on the desired size. So if the quad should be 50 x 50, the vertex is the position offset by 25 on X and Y, multiplied by the Camera's Perspective x View matrix.

---

## Solution:

```
mat4 VP = pMatrix * vMatrix;
vec3 CameraRight = vec3(vMatrix[0][0], vMatrix[1][0], vMatrix[2][0]);
vec3 CameraUp = vec3(vMatrix[0][1], vMatrix[1][1], vMatrix[2][1]);

vec3 Pos = gl_in[0].gl_Position.xyz;  // The desired point for the billboard

vec4 v1 = VP * vec4(Pos + CameraRight * 0.5 * Size + CameraUp * -0.5 * Size, 1.0);
vec4 v2 = VP * vec4(Pos + CameraRight * 0.5 * Size + CameraUp * 0.5 * Size, 1.0);
vec4 v3 = VP * vec4(Pos + CameraRight * -0.5 * Size + CameraUp * -0.5 * Size, 1.0);
vec4 v4 = VP * vec4(Pos + CameraRight * -0.5 * Size + CameraUp * 0.5 * Size, 1.0);

```

# Answer
I think this article is what you are looking for.

Article from opengl tutorials

Basically, you'll have to find the matrix camera rotation and apply a derived form to your mesh.

Hope it helps!
> 3 votes

# Answer
I'm just leaving this here for a more general solution to the problem. What you want to do is retain the "global" translate/rotate/scale of the object/billboard so it is in the correct world position, but locally rotate it back so it faces the camera. That is, you want the parent model-view matrix, but apply the inverse of its rotation part to the object/billboard. This is what I did (pseudo-code for Qt math classes, but you'll get the idea):

```
// Calculate object->world tranform with inverse parent->world rotation
QMatrix4x4 objectTransform;
objectTransform.setToIdentity();
objectTransform.translate(objectPosition);
// Get length of first row as scale factor. See: https://stackoverflow.com/questions/27655885/get-position-rotation-and-scale-from-matrix-in-opengl
float scaleFactor = parentModelView.row(0).toVector3D().length();
// get upper left 3x3 sub-matrix and unscale
QMatrix3x3 parentRotation = parentModelView.toGenericMatrix<3,3>();
parentRotation *= 1.0f / scaleFactor;
// convert to quaternion and invert
QQuaternion inverseParentRotation = QQuaternion::fromRotationMatrix(parentRotation).inverted();
// set as rotation
objectTransform.rotate(inverseParentRotation);
objectTransform.scale(objectScaleFactor);

// Now for drawing calculate the combined object->world transform:
QMatrix4x4 objectModelView = parentModelView * objectTransform;

```

Caveat: Works only for uniform scaling and without shear transforms, as stated here.
> 3 votes

---
Tags: opengl, glsl, rotation, billboarding
---


# Question
Title: How do I move many "static relative to each other" objects around?
I'm currently building an Elevator Bank simulator in Unity3d and I'm stuck on how to reduce the amount of objects it's going to generate when it's done. The simulator will consist of one player (for now) walking into a building, calling an elevator, picking a floor, going up/down and getting out of the elevator again.

To illustrate the problem, I'll sketch 2 scenario's. One where there's no problem whatsoever. One where I simply scale upwards and create a mess. But first, a list of what's inside the simulator (excluding the player).

* One hull of elevator shafts (3D .obj model).
* One elevator car per shaft (3D .obj model).
* One group of hall buttons per shaft per floor (one button for the top & bottom floor, two for the rest).
* One group of control buttons per elevator car (door open, door closed, etc.). At least 3 buttons.
* One floor call button per elevator car per floor.
* Two doors per elevator car.
* Two doors per shaft per floor.

A simple set-up of 3 shafts and 4 floors will already create 75 objects of which 30 are moving. Take 20 floors, 2 rows of elevators, 3 cars per row and I'm over 600 objects already.

Now. The Empire State building has 102 floors and 73 elevators. Which means multiple banks, a whole lot of floors, a whole lot of buttons and a whole lot of cars. Scaling my current set-up to support that *will* create a mess at best and simply won't work at worst.

Since this is an elevator simulator, the whole point of it is to make sure every elevator is active from starting the scene to ending the scene. So no tricks like only spawning what's in range of a camera, hibernating objects, object pooling and what not are out.

Now, objects in the same elevator car are static relative to each other. If the car moves up, everything moves up the same amount. So I hope I can move them as a group. Except I have no clue how to do such a thing in Unity. Prefabs may be part of the solution, but that still won't link their movements together. I've considered linking them together like a Snake game, but the amount of objects involved is orders of magnitude more. Luckily, all moving objects (except for the player) will only move on one axis. Doors only slide open/closed, elevator cars and their buttons go up and down. All rotations are fixed.

How do I move so many objects around in a single scene without creating a mess of variables in a performance-wise good way?

# Answer
> 2 votes
The way this is typically solved is with a transform hierarchy.

Compound objects which need to be multiple separate pieces for a variety of reasons but move together as a unit (eg. the trigger colliders for each elevator button) are grouped under a common "parent" object (the elevator).

Only the outermost moving object (the elevator car) needs a Rigidbody, and the physics engine can simulate the whole assembly as one object. Any travel by the parent object is automatically inherited by all of its child objects. (So you don't need to manually compute the movement of each button on the panel individually)

In Unity, you can set up your transform hierarchy by dragging one object into another one in the Hierarchy window, creating a nested folder structure, or by using the `transform.parent` property or `transform.SetParent()` methods in code.

Layers of hierarchy are reasonably cheap to process, especially when they're not moving, so you can use a few otherwise empty GameObjects as folders this way to help you organize your scene.

When you have a temporary attachment between two otherwise separate & independent physics bodies (eg a passenger stepping onto an elevator), rather than re-parenting them, it can be better to create a Joint between them. That way their relationship is visible to the physics engine, and it can reduce jitter that can arise from the two objects trying to move independently, interpenetrating, and correcting.

---
Tags: unity, architecture, movement, gameobject, simulations
---


# Question
Title: What is the relationship between clipping and the fog of war concept?
I'm currently developing a 2D top down game and recently implemented clipping.

I understand clipping in a 2D top down game as rectangle or any other geometrical form which defines a viewport for the player of what exactly he sees and what is technically rendered from the engine. As I'm centering the clipping area around the player I recognized that it is similiar to the fog of war concept. So the player has a limited view perspective depending on his current position.

My questen is what is the concrete difference to the fog of war concept? Is this concept usually using clipping? I often recognized that for example the map is rendered but simply not the objects which are on that map. Are these objects rendered and simply invisible or are they not rendered at all because of the clipping? Could clipping be defined as a way to achieve fog of war?

Would be cool if anyone could shed some light on this topic.

# Answer
Clipping and fog of war are not very related.

In a fog of war system, we track which objects or portions of the map the player has *knowledge of*. They might gain this knowledge by directly observing the object in their current camera view (ie. an object that passes the clipping test), but in many games it's collected in other ways too/instead:

* Knowledge can be accumulated from many perspectives (eg. each unit/building reports knowledge of units and terrain visible to it). Clipping is specific to one viewpoint.
* Gaining knowledge may depend on line of sight: if a solid wall blocks sight from a given viewpoint, many games won't confer knowledge of the objects/terrain on the other side of that wall. Clipping has no knowledge of obstacles, so this is closer to a related rendering optimization called occlusion culling.
* Knowledge may be persistent. In a game with fog of war, I might gain knowledge of a particular area of the map and units/buildings there, then travel elsewhere so they're no longer in my current vision zone. But the terrain and stationary objects like buildings will often remain visible on my map (often greyed/darkened to show they're not currently in sight), because fog of war system has memory of the knowledge there. Clipping shows no such memory over time. It's just a method to exclude objects/geometry outside the current bounds.
* Fog of war is sometimes even "chunked, " where the map reveals a whole room or province at a time, based on whether the player has crossed a threshold/trigger. In cases like this, the fog can be completely separated from visibility bounds checks, revealing an object that never passed a clip check for any viewpoint.
> 2 votes

---
Tags: rendering, clipping, fog-of-war
---


title: CCD IK Pole Target Contraint

text:
# Question
Title: CCD IK Pole Target Contraint
I am writing my own CCD IK solver. The version I have currently works perfectly fine, however, I need a way to make it use a pole target constraint.

What I want is for the elbow of my characters arm to point towards a pole target, similar to how Blender allows you to add a pole target.

I would love if someone could point me in the right direction of how this can be implemented.

# Answer
I've never wrote CCD solver with pole targets but I've played quite a lot with FABRIK algorithm and I may have some idea to try.

Just before you run your solver try to rotate entire IK chain towards you pole target and then run the CCD. This should move you IK computations to the plane containing chain start, chain target and pole target.

As I've said I don't know if this will work so please let me know if you try it :).
> 2 votes

---
Tags: inverse-kinematics
---


# Question
Title: libgdx - getButtonTable() missing Window method
I'm following some tutorial to create my own Inventory for my game. I have met with an insidious problem:

```
public class InventoryActor extends Window {
    public InventoryActor(Inventory inventory, DragAndDrop dragAndDrop, Skin skin) {
        super("Inventory", skin);

        // add an "X" button to the top right of the window, and make it hide the inventory
        TextButton closeButton = new TextButton("X", skin);
        closeButton.addListener(new HidingClickListener(this));
        getButtonTable().add(closeButton).height(getPadTop());

        // basic layout
        setPosition(400, 100);
        defaults().space(8);
        row().fill().expandX();
...
}

```

Everything in this code is neat and nice. There's one BUT -

```
getButtonTable().add(closeButton).height(getPadTop());

```

This method isn't implemented anywhere. Tutorial I'm following comes from 2014. Therefore I assume that it may be some deprecated/old method from Window class or something like that. My question is - is there any way I could repair it, and how can I add this 'X' close button to the window then? Should I use some other method? Regards and thanks in advance!

# Answer
You're extending from the wrong class; extend from `Dialog` instead of `Window`. Dialog is a subclass of Window with much more functionality.

Dialog also has a few convenience methods such as `Dialog button(String text)` and `Dialog text(String text)` that automatically separates text and buttons appropriately and makes creating simple popups really easy.

The entire documentation can be found here.
> 0 votes

---
Tags: java, libgdx
---


# Question
Title: What can cause shadow slicing while moving camera?
Can't explain better than with video: https://youtu.be/4nIMIL6w-0M

The effect I'm trying to achive is a simple **fog of war**.

See, I have a **point light** casting shadows on a plane. The plane has a shader which takes light attenuation and either draws a black pixel if there is no light, or discards a pixel to draw background if the light touches that pixel.

After hours spent on this, I came up with a thought that I cannot do anything more.

### A problem as I see it:

> Light successefully casts a shadow of shadow casters on a plane, however, with camera at a distance from the shadow, the shadow it self gets splitted and sliced, like it would've been, if some of the shadow casters' faces are suddenly removed from their meshes.

### What I have tried:

1. Changing Z coordinate of a light.
2. Changing Z height of obstacles (shadow casters).
3. Changing vertices on the obstacles so that every face would have its own vertices so no faces could share a vertex.
4. Changing shadow quality in the settings.
5. Changing camera rendering mode, all four of them.
6. Changing point light to a spot light with wide cone radius.
7. Using nice and simple standart unity's shader for a shadow receiver (a plane) - Standart Diffuse.
8. Switching between hard and soft shadow types.
9. Changing light's shadow's resolution, shadow strength and biases
10. Trying out the compiled EXE on another machine.
11. Changing light's baking type, rage and intensity.
12. You name it.

### None of those had any improvementes on an issue.

I would like to hear **authoritive replies** (best option would be from the developers) as well as **any information** you guys think I can try out (so I can do that).

# Answer
> 0 votes
In case someone stumbles on the same rare and weird issue, I would like to recommend a solution:

## Decrease your total overall world size.

I have figuratively multiplied my whole unity world by **1 / 100** and the issue vanished.

# Answer
> -1 votes
I just solved it.. Go to Edit -\> ProjectSettings -\> Quality and then ShadowCascades set to No Cascades

---
Tags: unity, camera, shadow-mapping
---


title: Low fps on Arm Mali GPU

text:
# Question
Title: Low fps on Arm Mali GPU
I was trying to google and understand my problem in two weeks but i am defeated, so i am asking for help.

The main problem is that my custom unlit frag shader after certain amount of time on devices with mali gpu starts to drop fps - i see it via fps counter in the cpu section. I dont know why in that section and not in render section, but with out this fps counter i can still feel the drop of fps.

**So on Samsung S4, Samsung sm-t 380, xiaomi redmi note 5, samsung tab s2 is all ok, the drop was only on samsung s6 - to solve the problem i just half the resolution by Screen.SetResolution function.**

I was thinking that drawing the full screen sprite on such a high res device is the point. Then i can test app on samsung sm-t580 - and the drop was there - this device has low resolution than S6.

I assume that the problem in arm mali gpu - or i am sure in my hands.

**So again, i am rendering full-screen with draw-mode = tile(countinuous) sprite with 3 textures, just changing theirs uvs in vert func and apply in fragment. This makes distorting effect.** The shader show that i have 10 maths and 4 textures, yes 3 textures but i am making 4 sampling.

The textures are 256x256 with repeat mode. I was trying diferrent textures compressions, dxt5, etc1-2, alpha8, R5 - no effect.

I was trying to different precisions half and float in different parts in shader - no effect.

I was thinking in alpha, so i took textures without alpha and not getting it from tex2D. Even the size of textures is doesnt matter, even if they 64x64.

The dance with ZTest, ZWrite, Blend, Queue RenderType, other params - no effect.

My guess was that maybe on mali uv : TEXCOORD0 must be only float2, not float3 or float4 - no effect.

I am applying \_Time.y and replace it with float from script - no effect.

Only reducing amount of tex2d in shader - is working. Why?

What i\`m doing wrong?

# Answer
To summarise the symptoms:

* New phone loses FPS
* Takes a while for FPS to drop
* Profiler says **CPU** usage increases, not GPU usage.
* Older, slower phones don't lose FPS

My guess is your new faster phone is **overheating** and the CPU **throttles down**, increasing the relative CPU usage per frame.

You can verify this by cooling the phone down and see if the FPS goes back up and/or CPU usage goes down. Watch out for thermal shock breaking the screen's glass and water condensation if you try cooling the phone with an ice pack or a freezer.

Older, slower phones don't heat up as much. It takes time for the new phone to hit its thermal limit after which it has to slow down to not crash and take damage due to the heat.

By reducing the resolution the GPU (and CPU waiting on the GPU) produce less heat which allows the game to run without throttling.
> 1 votes

---
Tags: unity, shaders, fragment-shader
---


# Question
Title: Why does Input.GetKey("enter") never return true?
I want to modify an int variable on one script by having another script subtract 1 from it. But when I try to trigger this on an "enter" key press, nothing happens.

1st script:

```
public class spawnenemy : MonoBehaviour {

    public int enems = 1;

```

2nd script:

```
public class collisions : MonoBehaviour {

private spawnenemy enems;

void Start () {
    enems = gameObject.GetComponent<spawnenemy> ();

  }

void FixedUpdate(){
  if (Input.GetKey("enter")){
   enems.enems--;
 }
}

```

Thanks.

# Answer
"enter" is not a key name that Unity recognizes.

I recommend using the KeyCode enumeration instead of raw strings, so your IDE's autocompletion and the compiler will tell you when you're trying to use an unknown key identifier. In this case you'd use...

```
if(Input.GetKey(KeyCode.Return)) ...

```

If you prefer to use strings, refer to the Unity docs for the string names of each key:

**Keys**

The names of keys follow this convention:

* Normal keys: “a”, “b”, “c” …
* Number keys: “1”, “2”, “3”, …
* Arrow keys: “up”, “down”, “left”, “right”
* Keypad keys: “\[1\]”, “\[2\]”, “\[3\]”, “\[+\]”, “\[equals\]”
* Modifier keys: “right shift”, “left shift”, “right ctrl”, “left ctrl”, “right alt”, “left alt”, “right cmd”, “left cmd”
* Mouse Buttons: “mouse 0”, “mouse 1”, “mouse 2”, …
* Joystick Buttons (from any joystick): “joystick button 0”, “joystick button 1”, “joystick button 2”, …
* Joystick Buttons (from a specific joystick): “joystick 1 button 0”, “joystick 1 button 1”, “joystick 2 button 0”, …
* Special keys: “backspace”, “tab”, **“return”**, “escape”, “space”, “delete”, “enter”, “insert”, “home”, “end”, “page up”, “page down”
* Function keys: “f1”, “f2”, “f3”, …
> 3 votes

# Answer
Input.GetKeyDown("enter") uses the enter key on the number pad.
> 1 votes

# Answer
```
    //player propertie
    public float speed;
    public int health;
    public int score;
    //bullet
    public Bullet bulletPrefab;
    public Transform fireposition;
    //Sounds
    public AudioClip fxFire;
    //Boundaries
    [SerializeField] private float maxX;
    [SerializeField] private float minX;
    // Use this for initialization

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
            FireBullet();

        if (Input.GetKey(KeyCode.RightArrow))
            transform.position += Vector3.right * speed * Time.deltaTime;
        else if (Input.GetKey(KeyCode.LeftArrow))
            transform.position += Vector3.left * speed * Time.deltaTime;

        //Calculate
        float newX = Mathf.Clamp(transform.position.x, minX, maxX);
        transform.position = new Vector3(newX, transform.position.y, transform.position.z);
    }

    void FireBullet()
    {
        AudioSource.PlayClipAtPoint(fxFire, transform.position);
        Instantiate(bulletPrefab, fireposition.transform.position, Quaternion.identity);
    }
}

```
> 0 votes

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


# Question
Title: How do I avoid fetching duplicate tetromino shapes from a Shape array in Unity/C#?
I'm working in C# in Unity on a tetrominoes game. I have seven basic shapes (I, J, L, O, S, T, Z) but each of the four component squares on each shape is labelled with an identifier unique to the shape set. So the shapes include, e.g., an S-1,2,3,4, S-5,6,7,8, S-9,10,11,12, J-13,14,15,16, J-17,18,19,20, Z-21,22,23,24....

Currently, in my Spawner class, I have the following to fetch a shape randomly from the shape array, m\_shapeSet1:

```
public class Spawner : MonoBehaviour {

public Shape[] m_shapeSet1;

Shape GetRandomShape()
{
    int i = Random.Range(0, m_shapeSet1.Length);
    if(m_shapeSet1[i])
    {
        return m_shapeSet1[i];
    }
    else
    {
        return null;
    }
}

```

I thought it would be simple to use m\_shapeSet1.RemoveAt(i) before the final closing brace after each fetch to avoid fetching, and later spawning (there is another function to spawn shapes), a duplicate shape. BUT, Visual Studio responds with: (1) the RemoveAt request is unreachable and (2) Shape\[\] has no definition for RemoveAt and no extension for it.

(I'll have to add a Do While or another control to this as I cannot retrieve a shape from the empty array I hope to create once I'm able to get only a unique shape.)

Anyway, how do I get a shape without duplication?

# Answer
> 2 votes
> (1) the RemoveAt request is unreachable and (2) Shape\[\] has no definition for RemoveAt and no extension for it.

These are simple syntax & logic errors.

The first one points out that if you `return` in both branches of the `if` statement, there's no way to get to code after the end of the `if`. `return` means you're done with this function and you pass control back to the calling code right away (with the exception of `finally` type blocks, that is)

eg...

```
var headsOrTails = FlipCoin();

if(headsOrTails == "heads") {
    // Half of the time, we'll stop here and report my victory.
    return "I win.";
} else {
    // The other half of the time, we'll stop here and report your victory.
    return "You win.";
}

// There's no way to reach this line of code.
// If we chose "heads" we exit inside the first branch.
// Otherwise we exit in the second branch.
// So either way, we've stopped executing the function before we get here.
return "the coin explodes?";

```

If you want to decide on a value to return, then do something else before you return it, you should save it to a variable like so:

```
string returnValue;
if(headsOrTails == "heads") {
    returnValue = "I win";
} else {
    returnValue = "You win";
}

DoSomethingElse();
return returnValue;

```

(2) points out that the array type doesn't have a `RemoveAt` method defined as one of the built-in things it can do. You can check its documentation to confirm. You might be thinking of the type `List`, which does have a `RemoveAt` method?

Basic C# syntax questions like this are things you can answer for yourself with a search through the language reference or our general programming sister site StackOverflow. Questions that are just about syntax with no game-specific requirements can be closed as off-topic here on GameDev.StackExchange, so please keep this in mind in future.

---

In any case, to select an item from a deck and then exclude that selection from future picks (until the deck is reshuffled), I'd do it like this:

```
public class ShuffledDeck<T> {

    // Local copy of the list of items.
    T[] items;
    // Count how many remain in the deck, not yet dealt.
    int remaining;

    // Create a new shuffled deck from an array of items.
    public ShuffledDeck(T[] items) {
        // Clone the array since we'll be re-ordering our copy.
        this.items = items.Clone();
        remaining = items.Length;
    }

    // Deal a random item from the ones not yet drawn.
    public T Draw() {

        // If we're out of items, draw nothing.
        // (Or, we can reshuffle our discards here instead)
        if(remaining == 0);
            return default(T);

        // Choose a random item from the bottom indices remaining.
        int chosenIndex = Random.Range(0, remaining);
        T chosen = items[chosenIndex];

        // Reduce the number of items we have left to draw from.
        remaining--;

        // Swap the item we chose with the last item not yet dealt.
        // (Might be itself, in which case this is a No-Op)
        items[chosenIndex] = items[remaining];
        items[remaining] = chosen;

        // Return the item we chose.
        return chosen;
    }

    // Reshuffle our discards so we can deal from a fresh deck.
    public void Reshuffle() {
        remaining = items.Length;
    }
}

```

This works like a Knuth or Fisher-Yates shuffle, partitioning our items array into two parts: the low indices are the ones we haven't yet dealt, and the high indices are the ones we've already dealt. By only selecting from the low indices, and swapping whatever we choose into the high indices, we maintain this partition after each draw.

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