# Question
Title: Unity3D [C#]: How do I use a custom inspector to expose an array of polymorphic objects to edit?
*\[EDIT: based on some feedback, I pruned the example down to the base functionality of the bug we are trying to solve. The description below remains accurate, but the repro has been shortened to:*

1. *Add the FXTriggerTimer component to an object*
2. *Hit the blue '+' button to add an AnimEvent and a SFXEvent*
3. *Save the scene, leave the scene and come back to the scene*
4. *Notice that the object has blank FXEvents instead of AnimEvents & SFXEvents*
5. *Hit space in a script file and save to trigger a script refresh in Unity*
6. *Notice that the object has had AnimEvents & SFXEvents restored*

*FINALLY: if anybody knows how to solve this problem without using scriptable or serializeable objects, that would be preferred. Thanks a million!\]*

# Preamble

I'm trying to hook up a way to synchronize animations & sfx (and potentially later particle fx, camera movement, etc) calls for our artists to use when placing art in our levels. The way I have come up with is to have a trigger that has an array of base class type `FXEvent`, with child classes of type `AnimEvent` and `SFXEvent`. C# in general handles polymorphism pretty well, but Unity's Inspector, alas, does not. and I fear that is the root of my problem.

I solved this problem 4 years ago, so I know it can be done; but, I do not have access to that code anymore. I'm trying to build a solution this time with `ScriptableObject` and `SerilizableObject`, and I have something that *almost* works.

# My problem is as follows:

I apply my `FXTriggerTimer` MonoBehavior (which inherits from `FXTriggerBase`) to a test object, and then hit the blue '+' button to add an `AnimEvent` and a `SFXEvent` to the trigger. I then save the scene, and reload the scene, and my test object has an array of two null elements that (obviously) don't draw in the inspector. **BUT**, if I edit a script, any script (e.g. hit space and save), the script refresh will magically repopulate with the correct items. So I know that all of the pieces are there under the hood, they just need to be restored on scene load.

NOTE: I am not wedded to my current solution with ScriptableObject and SerializableObject. It feels a bit over complicated to me, but it has brought me closest to a real solution.

# Code below.

Also, there's an example scene downloadable here, if anybody wants to look at the problem that way.

The base polymorphic stuff that I'm trying to get to work:

```
//Scripts/FXTriggerBase.cs
using UnityEngine;
using System.Collections;

public enum FXEventType {kNone, kAnim,  kSFX,}

/*-----------------------------------------------------------------------------
*///---------------------------------------------------------------------------
[System.Serializable]
public class FXEvent: UnityEngine.ScriptableObject
{
    [SerializeField]        public FXEventType  type;
    [SerializeField]        public GameObject   go;
    virtual public void Fire()  {   }
};

/*-----------------------------------------------------------------------------
*///---------------------------------------------------------------------------
[System.Serializable]
public class AnimEvent : FXEvent
{
    [SerializeField]    public string       animName = "";
    public AnimEvent()      {type = FXEventType.kAnim;}
    public void Fire()      {go.animation.Play(animName);   }
}

/*-----------------------------------------------------------------------------
*///---------------------------------------------------------------------------
[System.Serializable]
public class SFXEvent: FXEvent
{
    [SerializeField]    public AudioClip    clip;
    public SFXEvent()       {type = FXEventType.kSFX;}
    public void Fire()      {go.audio.PlayOneShot(clip);    }
}

/*-----------------------------------------------------------------------------
*///---------------------------------------------------------------------------
[AddComponentMenu("")]  // prevents users from using this directly
public class FXTriggerBase : MonoBehaviour
{
    [SerializeField]    public FXEvent[] events = new FXEvent[]{};

    public void Fire()
    {
        for( int e = 0; e < events.Length; e++)
        {
            events[e].go = gameObject;
            events[e].Fire();
        }
    }
}

```

A sample MonoBehavior that uses it:

```
//Scripts/FXTriggerTimer.cs
using UnityEngine;
using System.Collections;

/*-----------------------------------------------------------------------------
*///---------------------------------------------------------------------------
public class FXTriggerTimer: FXTriggerBase
{
    public void Start()
    {
        Fire();
    }
}

```

A custom inspector utility class to edit it with - the bug is in here:

```
//Editor/FXTriggerBaseUtil.cs
using UnityEngine;
using System.Collections;
using UnityEditor;

/*-----------------------------------------------------------------------------
*///---------------------------------------------------------------------------
public class FXEditorUtil
{
    SerializedObject[] serial;
    public bool dirtied = false;

    /*-------------------------------------------------------------------------
    *///-----------------------------------------------------------------------
    public void OnSubGUI(this FXEvent fx)
    {
        //having trouble getting polymorphism to work right in the inspector,
        // so this is what works.
        if(fx.type == FXEventType.kAnim)
        {
            AnimEvent anim = (AnimEvent)fx;
            string newAnimName = GUILayout.TextField(anim.animName);
            if(newAnimName != anim.animName)
            {
                anim.animName = newAnimName;
                dirtied = true;
            }
        }
        else if(fx.type == FXEventType.kSFX)
        {
            SFXEvent sfx = (SFXEvent)fx;
            AudioClip newSFX = (AudioClip)EditorGUILayout.ObjectField(sfx.clip, typeof(AudioClip));
            if(newSFX != sfx.clip)
            {
                sfx.clip =newSFX;
                dirtied = true;
            }
        }
    }

    /*-------------------------------------------------------------------------
    *///-----------------------------------------------------------------------
    public FXEvent OnGUI(FXEvent fx)
    {
        if(fx == null)
            return fx;

        GUILayout.BeginHorizontal();
        FXEvent ret = null;

        //display the enum type so we can see what we're editing
        GUILayout.Label(fx.type.ToString(), GUILayout.Width(60));

        //handle element GUI, if that applies
        if(fx.type != FXEventType.kNone)
            OnSubGUI(fx);
        else
            GUILayout.Label("");

        GUILayout.EndHorizontal();
        return ret;
    }

    /*-------------------------------------------------------------------------
    *///-----------------------------------------------------------------------
    public void OnGUI(FXTriggerBase trigger)
    {
        FXTriggerBase triggerBase = trigger as FXTriggerBase;
        if(triggerBase == null)
        {
            Debug.LogError("FXTriggerBaseInspector.OnGUI() : null item to inspect?");
            return;
        }

        //build an array of serialized versions of our array elements, so that they
        // save out properly
        int numEvents = triggerBase.events.Length;
        serial = new SerializedObject[numEvents];
        for(int e = 0; e < numEvents; e++)
        {
            serial[e] = new SerializedObject(triggerBase.events[e]);
        }

        dirtied = false;

        //Do inspector GUI of our array elements
        int ret = ArrayGUI("events", trigger.events, trigger.gameObject);

        //handle addition of elements
        if (ret >= 0)
            ArrayHandleAdd(ref trigger.events);

        //if any changes have been registered, save our serialized versions out
        if(dirtied)
        {
            numEvents = serial.Length;
            for(int e = 0; e < numEvents; e++)
            {
                serial[e].ApplyModifiedProperties();
            }

            EditorUtility.SetDirty(trigger);
        }
    }

    /*-------------------------------------------------------------------------
    *///-----------------------------------------------------------------------
    int ArrayGUI(string label, FXEvent[] arr, GameObject go)
    {
        int ret = -1;
        Color defColor = GUI.color;

        GUILayout.BeginVertical(GUILayout.Width(250));

        //blue plus button that populates some events for us
        GUILayout.Label("");
        GUI.color = Color.cyan;
        bool add = GUILayout.Button("+", GUILayout.Width(20));
        if (add)
            ret = arr.Length;
        GUI.color = defColor;

        GUILayout.Label(label);

        int numObjects = arr.Length;
        for (int o = 0; o < numObjects; o++)
        {
            GUILayout.BeginHorizontal();
            {
                //draw custom GUI for each of the polymorphic fx event types
                FXEvent fx = arr[o];
                FXEvent newFX = OnGUI(fx);
                if(newFX != null)
                {
                    arr[o] = newFX;
                    dirtied = true;

                    serial[o] = new SerializedObject(arr[o]);
                    ScriptableObject.DestroyImmediate(fx);
                }
            }
            GUILayout.EndHorizontal();
        }
        GUILayout.EndVertical();
        return ret;
    }

    /*-------------------------------------------------------------------------
    *///-----------------------------------------------------------------------
    void ArrayHandleAdd(ref FXEvent[]  arr)
    {
        int size = arr.Length;

        //add new element to the end
        System.Array.Resize(ref arr, size + 2);
        System.Array.Resize(ref serial, size + 2);

        arr[size] = ScriptableObject.CreateInstance<AnimEvent>();
        serial[size] = new SerializedObject(arr[size]);

        arr[size+1] = ScriptableObject.CreateInstance<SFXEvent>();
        serial[size+1] = new SerializedObject(arr[size+1]);

        dirtied = true;
    }
}

```

and sample custom inspector that uses that

```
//Editor/FXTriggerTimerInspector.cs
using UnityEngine;
using System.Collections;
using UnityEditor;

/*-----------------------------------------------------------------------------
*///---------------------------------------------------------------------------
[CustomEditor(typeof(FXTriggerTimer))]
public class FXTriggerTimerInspector : Editor
{
    FXEditorUtil util;

    public override void OnInspectorGUI()
    {
        FXTriggerTimer trigger = (FXTriggerTimer)target;
        if(util == null)
        {
            util = new FXEditorUtil();
        }

        util.OnGUI(trigger);

        if(util.dirtied)
        {
            EditorUtility.SetDirty(target);
            //serializedObject.ApplyModifiedProperties();
        }
    }
}

```

# Answer
Ok, as I said in my comment above, I have come to believe my problem is a genuine bug in Unity 4.x. \[EDIT\] It is still a bug in Unity 5.x. I couldn't wait anymore and I just hacked a non-polymorphic solution. **I'm going to not green-check this answer in case some hero out there magically comes up with the right solution**, but for the intrepid internet explorer who comes to this question with the exact same problem and needs a solution, stat, here's what I did.

I essentially ripped out my polymorphic solution and replaced it with a c-style union solution ... except C# doesn't really support unions. So it's a weird hack bloated union solution. I made the base class FXEvent into a container class for all of the specific types of events, and then used the enum type to determine which sub class to choose.

Besides the initial bloat of all the type-specific code that had to be written since polymorphism no longer hid the details, all of the event classes got further away from the mono behaviour that hosts them, so I had to write more stuff to make sure that GameObjects got passed all the way down to the leaf-events.

That said, in my real world case, this may require more maintenance than I'd like, but I actually think this solution is more kind on Unity3D; I think it ultimately runs better and is simpler under the hood and thus much less likely to go wrong in some bizarre way.

In the future, I might try to address the scalability problems using Generics or something like that; but for now this is how it stands.

```
//scripts.FXTriggerBase.cs
using UnityEngine;
using System.Collections;

public enum FXEventType {kNone, kAnim,  kSFX,}

/*-----------------------------------------------------------------------------
*///---------------------------------------------------------------------------
[System.Serializable]
public interface FXEventBase
{
    public virtual void  Awake(GameObject gobj);
    public virtual void  Fire();
}

/*-----------------------------------------------------------------------------
*///---------------------------------------------------------------------------
[System.Serializable]
public class AnimEvent : FXEventBase
{
    [System.NonSerialized]
    public GameObject go;

    [SerializeField]
    public string       animName = "";
    public AnimEvent() {}

    public void Awake(GameObject gobj)  {go = gobj;}
    public void Fire()                  {go.animation.Play(animName);   }
}

/*-----------------------------------------------------------------------------
*///---------------------------------------------------------------------------
[System.Serializable]
public class SFXEvent: FXEventBase
{
    [System.NonSerialized]
    public GameObject go;

    [SerializeField]
    public AudioClip    clip;
    public SFXEvent()   {}

    public void Awake(GameObject gobj)  {go = gobj;}
    public void Fire()                  {go.audio.PlayOneShot(clip);    }
}

/*-----------------------------------------------------------------------------
*///---------------------------------------------------------------------------
[System.Serializable]
public class FXEvent
{
    [SerializeField]
    public FXEventType  type = FXEventType.kNone;

    [SerializeField]
    public GameObject   go;

    public void Awake(GameObject gobj)
    {
        if(go == null)
            go = gobj;

        if(type == FXEventType.kAnim)
            anim.Awake(go);
        else if ( type == FXEventType.kSFX)
            sfx.Awake(go);
    }

    public void Fire()
    {
        if(type == FXEventType.kAnim)
            anim.Fire();
        else if ( type == FXEventType.kSFX)
            sfx.Fire();
    }

    [SerializeField] public AnimEvent anim;
    [SerializeField] public SFXEvent sfx;

#if NULL
    //other fx events implemented in the real world case, to show how poorly
    // this solution scales
    [SerializeField]  public PFXEvent pfx;
    [SerializeField]  public CamEvent cam;
#endif

    //---------------------------------------------------------------------------

    static public FXEvent CreateAnimEvent(GameObject gobj)
    {
        FXEvent fx = new FXEvent();
        fx.go = gobj;

        fx.anim = new AnimEvent();
        fx.anim.go = gobj;
        fx.type = FXEventType.kAnim;
        return fx;
    }

    static public  FXEvent CreateSFXEvent(GameObject gobj)
    {
        FXEvent fx = new FXEvent();
        fx.go = gobj;

        fx.sfx = new SFXEvent();
        fx.sfx.go = gobj;
        fx.type = FXEventType.kSFX;
        return fx;
    }

    static public  FXEvent CreateNullEvent(GameObject gobj)
    {
        FXEvent fx = new FXEvent();
        fx.go = gobj;

        return fx;
    }
};

/*-----------------------------------------------------------------------------
*///---------------------------------------------------------------------------
[AddComponentMenu("")]  // prevents users from using this directly
public class FXTriggerBase : MonoBehaviour
{
    [SerializeField]
    public FXEvent[] events = new FXEvent[]{};

    //if the GameObject parent in the FXEvent wasn't assigned prior, do it now
    void Awake()
    {
        for(int i = 0; i < events.Length; i++)
        {
            events[i].Awake(gameObject);
        }
    }

    public void Fire()
    {
        for( int e = 0; e < events.Length; e++)
        {
            events[e].Fire();
        }
    }
}

```

And for those keeping track, this is how my test inspector change to accommodate the changes; in contrast, minus all of the scriptable and serializeable object stuff, it is much simpler, though it will have the same scalability problems to come.

```
//editor/FXTriggerBaseInspector.cs
using UnityEngine;
using System.Collections;
using UnityEditor;

/*-----------------------------------------------------------------------------
*///---------------------------------------------------------------------------
public class FXEditorUtil
{
    public bool dirtied = false;

    /*-------------------------------------------------------------------------
    *///-----------------------------------------------------------------------
    public void OnSubGUI(this FXEvent fx)
    {
        //having trouble getting polymorphism to work right in the inspector,
        // so this is what works.
        if(fx.type == FXEventType.kAnim)
        {
            AnimEvent anim = fx.anim;
            string newAnimName = GUILayout.TextField(anim.animName);
            if(newAnimName != anim.animName)
            {
                anim.animName = newAnimName;
                dirtied = true;
            }
        }
        else if(fx.type == FXEventType.kSFX)
        {
            SFXEvent sfx = fx.sfx;
            AudioClip newSFX = (AudioClip)EditorGUILayout.ObjectField(sfx.clip, typeof(AudioClip));
            if(newSFX != sfx.clip)
            {
                sfx.clip =newSFX;
                dirtied = true;
            }
        }
    }

    /*-------------------------------------------------------------------------
    *///-----------------------------------------------------------------------
    public FXEvent OnGUI(FXEvent fx)
    {
        if(fx == null)
            return fx;

        GUILayout.BeginHorizontal();
        FXEvent ret = null;

        //if the enum changes, create new FXEvent sub type corresponding to the
        // new enum, and return it
        GUILayout.Label(fx.type.ToString(), GUILayout.Width(60));

        //handle element GUI, if that applies
        if(fx.type != FXEventType.kNone)
        {
            OnSubGUI(fx);
        }
        else
            GUILayout.Label("");

        GUILayout.EndHorizontal();
        return ret;
    }

    /*-------------------------------------------------------------------------
    *///-----------------------------------------------------------------------
    public void OnGUI(FXTriggerBase trigger)
    {
        FXTriggerBase triggerBase = trigger as FXTriggerBase;
        if(triggerBase == null)
        {
            Debug.LogError("FXTriggerBaseInspector.OnGUI() : null item to inspect?");
            return;
        }

        dirtied = false;

        //Do inspector GUI of our array elements
        int ret = ArrayGUI("events", trigger.events, trigger.gameObject);

        //handle addition of elements
        if (ret >= 0)
            ArrayHandleAdd(ref trigger.events, trigger.gameObject);
    }

    /*-------------------------------------------------------------------------
    *///-----------------------------------------------------------------------
    int ArrayGUI(string label, FXEvent[] arr, GameObject go)
    {
        int ret = -1;
        Color defColor = GUI.color;

        GUILayout.BeginVertical(GUILayout.Width(250));

        //blue plus button that populates some events for us
        GUILayout.Label("");
        GUI.color = Color.cyan;
        bool add = GUILayout.Button("+", GUILayout.Width(20));
        if (add)
            ret = arr.Length;
        GUI.color = defColor;

        GUILayout.Label(label);

        int numObjects = arr.Length;
        for (int o = 0; o < numObjects; o++)
        {
            GUILayout.BeginHorizontal();
            {
                //draw custom GUI for each of the polymorphic fx event types
                FXEvent fx = arr[o];
                FXEvent newFX = OnGUI(fx);
                if(newFX != null)
                {
                    arr[o] = newFX;
                    dirtied = true;
                }
            }
            GUILayout.EndHorizontal();
        }
        GUILayout.EndVertical();
        return ret;
    }

    /*-------------------------------------------------------------------------
    *///-----------------------------------------------------------------------
    void ArrayHandleAdd(ref FXEvent[]  arr, GameObject go)
    {
        int size = arr.Length;

        //add new element to the end
        System.Array.Resize(ref arr, size + 2);

        arr[size] = FXEvent.CreateAnimEvent(go);
        arr[size+1] = FXEvent.CreateSFXEvent(go);

        dirtied = true;
    }
}

```
> 1 votes

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


title: Making a ordered list iterator

text:
# Question
Title: Making a ordered list iterator
Noob here,

I am trying to display a list of a vector with ascending numbers. To display the list I iterate through the following code.

`cout << "\nYour games list is: \n";
 for (iter = gameTitle.begin(); iter != gameTitle.end(); ++iter)
 {
 cout << listNum << ".- " << *iter << endl;
 }`

So listNum is an integer that I initialized as "0" but this particular setup will give me a list with three elements as follows.
3.- userInput
3.- userInput
3.- userInput

"userInput" is a vector of string type that is declared yet not initialized.

**¿How do I get a list like follows?**
1.- userInput
2.- userInput
3.- userInput
etc.

Thanks

# Answer
> 0 votes
You could either: post increment listNum prior to outputting listNum, assign your iter to listNum prior to outputting listNum, or instead of outputting listNum, just replace it with iter.

The issue at hand is that your are not incrementing listNum.

---
Tags: c++, vector, input
---


# Question
Title: Sorting sprite's layers in isometric view
I'm making a strategy game with isometric view and I'm having some problems with deciding which sprite should be drawn first (I'm using SFML 2.2 as graphic library). I'm using `std::sort` to sort sprites in array by their Y position in a window (Floor and walls aren't sorted, they are stored in different arrays). This code works well in an RPG game where there aren't more than 100 sprites on the map at the same time, but this is going to be a strategy game and when there are 13000 or more sprites on the map, FPS is dropping below 30 and game is becoming unplayable. So, is there any faster way to sort these sprites?

# Answer
**Sorting**
Use a quad- or oct-tree. Basically, the single bucket (vector/array) you are using now represents the outer-most tree-node; it contains everything. In addition to containing all game objects, it will contain 4/8 child nodes (sub-buckets) that are exactly 1/4(quad) or 1/8(oct) the size of the orginal and fit entirely inside it with no "empty space" between any of them. Each of those also contains another 4/8 sub-buckets. The subdivision continues until the number of objects in a single node is manageable.

If you sort the nodes first, you have *already* sorted your objects. Draw the nodes in front-to-back (near-to-far) order.

As an example, visualize standing at the exact center point of a node. You can see that 2/4 of the 4/8 child nodes are behind you and there is no need to draw them or whatever is inside them.

Depth/distance sorting is certainly a popular use for trees, but they are not limited to only drawing. The nodes can represent any logical division that you want. Consider an InterfaceComponent that is also a container of InterfaceComponents. If you make an InterfaceComponent non-visible, there is no need to draw/check any of its' children or it's children's children. You cull the entire rest of the branch as soon as you reach Visible=False. That also represenets a tree structure (with variable dimensions).

**Drawing**
You are not specific about how you are drawing these, but it sounds like you may be rendering them individually, i.e. foreach(object-\>Render()). Please look into using instanced draw calls, if you are not already.

It implies taking the data needed for rendering out of your InterfaceComponent and storing it in a tightly packed buffer, ready to go to the GPU. When you move the InterfaceComponent around, you modify the vertex in the buffer and not the "object". In essence, InterfaceComponent has been abstracted to just the data in the buffer and, separately, the class implementation that uniquely manipulates it. To draw a quad, I need a position, size, and color; even with a complicated class inheritance structure, that's all an InterfaceComponent will ever be.

**Combining**
The leaf-nodes do not have to directly contain objects. You can subdivide each node into buckets for reusable geometry. i.e. a "trees bucket", "buildings bucket", etc. When you add a building instance to the tree, the usual node finding occurs, but the node adds the building to the building bucket instead of just one big master bucket for everything in the node. When you query the tree for buildings, the usual node finding occurs, but the node can easily return a list of just buildings; this is in addition to being already spatially sorted near-to-far.

This simplifies:
\[state change\]
Draw a TreeVariant1
\[state change\]
Draw a TreeVariant1
\[state change\]
Draw a TreeVariant2
\[state change\]
Draw a TreeVariant1
etc. etc. etc.

Down to:
\[state change\]
Draw terrain
\[state change\]
Draw all TreeVariant1's near-to-far
\[state change\]
Draw all TreeVariant2's near-to-far
\[state change\]
Draw all buildings near-to-far

**Neat:**
Using the new-ish geometry shader stage, you can render all of your sprites as individual vertices. Each sprite's position, size, UV/texture-atlas, time-factor, etc. are all crammed into a single vertex for each. The geometry shader spits out a properly-sized (and billboarded?) quad for each point it receives, calculating and filling in anything the pixel shader will need to color it.

This allows instancing, without instancing; each vertex *is* an instance.

**Iso:**
Since you are isometric, you have an advantage over normal 3D games in that you have 4 well-defined angles to work with. The difference in the near-to-far sorting algorithm between the SW and SE views will be something like checking node\[2\] first, rather than \[3\].

**LOD:**
Check the leaf-nodes' distances first and set the LOD for each node appropriately. Assign the highest leaf-LOD to each parent. Continue until you reach the top-level-node. With the LOD factor baked into the vertex, there are no additional states to set. The LOD factor would get consumed by the shaders to implement dynamic LOD; the LOD factor can be used to select a specific mip-level for pixel shader sampling and/or be the tessellation factor for the hull shader. The LOD factor can also, also, also be used CPU-side to determine update priorities; distant animations do not need to be updated as often as the nearer ones.
> 0 votes

---
Tags: c++, 2d, isometric, sfml
---


title: Is transform.forward mutable?

text:
# Question
Title: Is transform.forward mutable?
Suppose I have a `GameObject`, and I want it's `transform.forward` to be facing up. Is it possible to change it as seen below?

```
public class Main : MonoBehaviour
{
    void Start ()
    {
        Vector3 forward = transform.forward;
        forward = new Vector3 (0, 1, 0);
        transform.forward = forward;
    }
}

```

# Answer
Perhaps this is what you are looking for:

```
transform.forward = transform.up;

```
> 1 votes

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


# Question
Title: Make my Tower continously fire at enemy while inside collider?
So I've made a Tower script in c# that spawns a projectile that then fires at the enemy gameobject. However, because I'm using the OnTriggerEnter() function it will only fire as many times as gameObjects enters the collider.

How do I make sure that the tower will keep firing untill there is no more enemies within its collider?

```
public class Tower : MonoBehaviour {

// Public variables
public GameObject ammoPrefab;
public float reloadTime = 1f;

// Private variables
private Transform projectileTarget;
private GameObject projectile;
private float nextFireTime;
private float nextAnimTime;

void Update() {
    if (projectileTarget) {
        Debug.Log("We have target");
        if(Time.time >= nextFireTime){
            Debug.Log("nextFireTime has passed");
            FireProjectile();
        }
    }

}

void OnTriggerEnter(Collider co) {
    // Was it a Monster? Then Shoot it
    if (co.gameObject.tag == "Enemy") {
        Debug.Log("Enemy tag detected");
        nextFireTime = (float)(Time.time+(reloadTime*0.5));
        projectileTarget = FindClosestEnemy().gameObject.transform;
    }
}
void OnTriggerExit(Collider co) {
}
void FireProjectile()  {
    Debug.Log ("Shoot");
    nextFireTime = Time.time + reloadTime;
    projectile = (GameObject)Instantiate (ammoPrefab, transform.position, ammoPrefab.transform.rotation);
    projectile.GetComponent<Projectile> ().target = projectileTarget;
}
GameObject FindClosestEnemy() {
    GameObject[] gos;
    gos = GameObject.FindGameObjectsWithTag("Enemy");
    GameObject closest = null;
    float distance = Mathf.Infinity;
    Vector3 position = transform.position;
    foreach (GameObject go in gos) {
        Vector3 diff = go.transform.position - position;
        float curDistance = diff.sqrMagnitude;
        if (curDistance < distance) {
            closest = go;
            distance = curDistance;
        }
    }
    return closest;
}

```

}

# Answer
> 4 votes
you might try having the on enter adding the enemy to a 'target list', and on exit/killing enemy have that entry removed from the list.

```
using System.Collections.Generic; // lets use use the magical 'List' array

List<GameObject> targetedEnemies; // List arrays let us add and remove stuff later,
// that is, they do not have a maximum capacity and won't break from too many targets.

void OnTriggerEnter(Collider other)
{
    if(other.tag = "enemy")
    {
        targetedEnemies.Add (other.gameObject);
    }
}

void Update()
{
    foreach (GameObject target in targetedEnemies)
    {
        // take shot at target
        // check if target is still alive. If dead, remove from list
    }
}

void OnTriggerExit(Collider other)
{
    if(other.tag = "enemy")
    {
        targetedEnemies.Remove (other.gameObject);
    }
}

```

You could use a second gameObject placeholder to store the first target, and set the tower up in a way that it will focus on the first enemy that comes within range, and moves on to the next if the enemy dies.

You could also use OnTriggerStay() instead of OnTriggerEnter() to simply work every update function in which the target enemy is within the trigger collider, instead of the first.

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


title: Texture to Painted Vertex Algorithm

text:
# Question
Title: Texture to Painted Vertex Algorithm
I want to generate some game textures into coloured vertex arrays.

Is there a known algorithm to transform texture/bitmap data into an optimised vertex array. Much like how the Homeworld skyboxes were made.

*EDIT:* Don't need the dome part, would like todo these flat.

# Answer
I think what I need is a `vertex collapse` algorithm that is typically used with reducing excess polycount.

http://pomax.nihongoresources.com/downloads/PolygonReduction.pdf

but create a different cost formula.
> 0 votes

---
Tags: textures, algorithm, vertex-arrays
---


# Question
Title: Simple switch to instanced draws causes consistent, but incorrect, results
I have dumbed the following code down to "stupid simple" for DirectX and still cannot get any cooperation:

```
g_d3dContext->OMSetRenderTargets(1, g_renderTargetWorld->ColorRenderTargetView.GetAddressOf(), g_depthStencilView.Get());
g_d3dContext->OMSetDepthStencilState(g_States->DepthNone(), 0);
g_d3dContext->OMSetBlendState(g_States->AlphaBlend(), NULL, 0xffffffff);
g_d3dContext->IASetVertexBuffers(0, 2, m_segments->GetLineVertexBuffers(), s_strides, s_offsets);
g_d3dContext->IASetIndexBuffer(m_segments->GetLineIndexBuffer(), DXGI_FORMAT_R16_UINT, 0);
g_d3dContext->IASetInputLayout(s_IL_Polyline.Get());
g_d3dContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_LINELIST_ADJ);
g_d3dContext->VSSetShader(g_World_Polyline_VS_Segment.Get(), NULL, 0);
g_d3dContext->GSSetShader(g_World_Polyline_GS_Segment.Get(), NULL, 0);
g_d3dContext->PSSetShader(g_World_Polyline_PS_Segment.Get(), NULL, 0);
g_d3dContext->RSSetState(g_States->CullNone());
//g_d3dContext->DrawIndexed(4 * m_segments->LineCount, 0, 0);
g_d3dContext->DrawIndexedInstanced(4, m_segments->LineCount, 0, 0, 0);
g_d3dContext->GSSetShader(nullptr, NULL, 0);

```

-The DrawIndexed call draws all segments
-The DrawIndexedInstanced call draws only the first segment

Creating a second instance of this class, DrawIndexedInstanced draws only the first segment of each compound line. Although it is correctly created, filled, and set, I am not even using the per-instance data yet. Manually manipulating the StartIndexOffset parameter causes different, only-one, line segments to be drawn.

PIX is worthless, as usual, but, at least, allowed me to inspect the buffer contents. All of the data is correct and in-place but I cannot get the "gosh-darn" thing to work. After 18 hours of searching and getting nowhere, I'm livid, giving up, and going to bed.

Please help me explain why (4\*2) != 4\[0:1\]

**Edit**:
This, stupidly, works:

```
for (char i = 0; i < m_segments->LineCount; i++)
{
    g_d3dContext->DrawIndexedInstanced(4, 1, i * 4, 0, i * 4);
}

```

So, now: (4\[0\] + 4\[1\]) == (4\*2) != 4\[0:1\]

Verifying, again, that the data is all where it needs to be.. Stumped. It's got to be something so obvious, that it's not. I feel like I'm already over-kill on setting every possible state parameter there is and if I comment any one line, it would switch from *doesn't* work to *shouldn't* work and I can't debug it.

# Answer
> 0 votes
This was a newbie error. I RTFM, but didn't pay close enough attention and, apparently, hadn't used this draw call in this way before.

Specifically:

This draws 8 consecutively-indexed vertices starting at index 0:

```
g_d3dContext->DrawIndexed(4 * m_segments->LineCount, 0, 0);

```

This draws the same 4 consecutively-indexed vertices, starting at index 0, LineCount times:

```
g_d3dContext->DrawIndexedInstanced(4, m_segments->LineCount, 0, 0, 0);

```

Since my per-instance data doesn't offer a way to translate the pattern of vertices into place, it's drawing the same segment over and over.

To fix this, I will stuff the coordinates from the 4 separate vertices into a single vertex; each vertex will represent an entire segment.

---
Tags: directx11, instancing
---


# Question
Title: Cocos2dx+Chipmunk: Fully elastic collision between moving bodies
I'm using Cocos2dx and the built in Chipmunk physics engine, and currently I've got my PhysicsBodys' materials set up with:

```
Density=0
Restitution=1
Friction=0

```

in order to get fully elastic collision, and keep moving bodies moving at a constant speed. This works great if they collide against a static element, like a wall, not so much if they collide with other moving objects.

I'm moving these bodies by applying an initial force:

```
Vec2 velocity = moveDirection.getNormalized()*moveSpeed - myPhysicsBody->getVelocity();
Vec2 newForce = myPhysicsBody->getMass()*velocity / deltaTime;
myPhysicsBody->applyForce(newForce);

```

So I'm guessing that even though their materials would result in fully elastic collisions, the moving objects both carry an impact force, this modifies the resulting force into one with different magnitude? All these moving bodies have the same mass.

Currently I'm manually catching the impact start and manually generating the resulting force in the right directing, and using the object's speed to apply it with the same previous magnitude, effectively overriding Chipmunk's collision resolution.

Is this the best way to do this, or can I configure my bodies in a way that allows Chipmunk collision resolution to achieve the same effect? I'm a bit rusty on my physics.. heh..

# Answer
It is now quite some time after the original question was asked; Chipmunk shapes have a property called "elasticity" which is a number from 0 to 1. Setting it to 1 for both bodies you want to collide will ensure perfectly elastic collisions.

However, you mentioned that you want to "keep moving bodies moving at a constant speed". This is physically incorrect behaviour. Imagine billiard balls which are a close real-life approximation of elastic collision; depending on the collision angle, the resulting speeds can be very different. Or imagine Newton's cradle, where the collisions cause one ball to have some speed whilst the other to remain stationary.

Instead, you will have to override the physics engine after collisions occur. You could do this by using `cpBodySetVelocity`:

```
cpVect speed = cpBodyGetVelocity(mybody);
cpVect newspeed = cpvmult(cpvnormalize(speed), myspeed);
cpBodySetVelocity(mybody, newspeed);

```
> 0 votes

---
Tags: physics, collision-resolution, cocos2d-x, chipmunk
---


title: Missing Visual Studio 2013 Templates

text:
# Question
Title: Missing Visual Studio 2013 Templates
Visual Studio 2013 is missing the installed templates related to graphics, **SPECIFICALLY** the fbx scene template.. Why is this so? And where do I get them ?

# Answer
This should help: From MSDN: How to: Restore Default Project Templates:

> If you accidentally delete the default project templates that are included with Visual Studio, you can use this procedure to restore them without reinstalling Visual Studio.
>
> **To restore the default project templates** In the command prompt, navigate to the location of devenv.exe. This file is located in \Common7\IDE. Note:If you are running Windows Vista or Windows 7, you must open the command prompt as an administrator by right-clicking the command prompt and then clicking Run as administrator.
>
> Type "devenv /installvstemplates" and press Enter. Note:If you are using an Express Edition of Visual Studio, type "Express /installvstemplates" where is either VB or VCS for Visual Basic and Visual C#, respectively.
>
> If this procedure does not restore the default templates, reinstall Visual Studio.

In case you want to download it, from MSDN:How to: Find and Install Templates Located Online

> You can find and install online project templates from the New Project dialog box. Each project template represents a type of project that Visual Studio can create for you. You can find and install online item templates from the Add New Item dialog box. You can also install online project and item templates from Extension Manager.
>
> **To install project templates from the New Project dialog box** On the File menu, click New, and then click Project. The New Project \>dialog box opens. In the left pane, click Online Templates and expand the Templates list. In the Templates list, select the category of templates to search for -- OR -- Type one or more keywords in the Search box. A list of templates appears in the middle pane. Note:The search function ignores the selected category and returns results with the given keywords in their titles or descriptions. Partial words are included but all keywords must be present in the result. Select a template from the list. Information about the selected template appears in the right pane. Double-click the template to install -- OR -- Fill in the fields at the bottom of the window and click OK to install the template and create a new project.
>
> **To install item templates from the Add New Item dialog box** In Solution Explorer, right-click the current project, select Add, and New Item. The Add New Item dialog box opens. In the left pane, click Online Templates and expand the Templates list. In the Templates list, select the category of templates to search for -- OR -- Type one or more keywords in the Search box. A list of templates appears in the middle pane. Note:The search function ignores the selected category and returns results with the given keywords in their titles or descriptions. Partial words are included but all keywords must be present in the result. Select a template from the list. Information about the selected template appears in the right pane. Double-click the template to install
>
> **To install templates from Extension Manager** On the Tools menu, click Extension Manager…. In the left pane, click Online Gallery and expand the Templates list. In the Templates list, select the category of templates to search for. A list of templates appears in the middle pane. -- OR -- Type one or more keywords in the Search box. A list of extensions matching the search keywords appears in the middle pane. Note:The search function ignores the selected category and returns results with the given keywords in their titles or descriptions. Partial words are included but all keywords must be present in the result. Select a template from the list. Information about the selected template appears in the right pane. Double-click the template to install -- OR -- Click Download.

Or try going to **FILE-\>NEW-\>FILE**.
> 1 votes

---
Tags: c++, graphics, fbx, visual-studio
---


# Question
Title: Overlapping Vertex in DynamicVertexBuffer draw priority?
I am creating a voxel game, and I have recently run into an issue. My world is drawn by a DynamicVertexBuffer, which just consists of vertices for the blocks themselves. On top of that, I switch vertex buffers to my "Selected" vertex buffer which draws a white outline of a block for now. (This includes alpha but I have it turned off until I figure this glitch out).

This issue I run into is here:

Rather than the selected buffer overwriting my world block, it sort of does depending on the angle. Sometimes I see no overlap, sometimes weird glitches like shown above.

I was wondering, what can I do to prioritize the "Selected" buffer so that it is drawn on top of anything else sharing coordinates? Note that I did have this working, when everything used a basic effect. After switching to my own custom effect.fx (which supports fog and lighting, if that has anything to do with it), I run into this issue.

Any help is appreciated, thank you!

EDIT:

Just got the "flickering" of sorts to stop, I changed the DepthStencilState of the buffer to:

```
GraphicsDevice.DepthStencilState = DepthStencilState.None;

```

The only downside here is that it draws all 6 sides of the selected block now and it overlaps the world completely, again I don't know if this would be the right way to do it but any help would be appreciated:

The above picture is flat with the rest of the terrain around it, as you can see it draws the two sides that wouldn't actually be visible as well.

# Answer
You don't want to turn off depth stencil state. Leave that the way it was before.

## Giving the Problem a Name

The problem you're having is that two objects are being drawn in almost identical locations, but because of floating point precision errors, at the different pixels, sometimes one turns out to be barely closer to the camera/eye than the other, and on other pixels, it's reversed.

**This is what's called z-fighting** (or z-buffer fighting, or depth-buffer fighting). It's a very common problem when you're drawing objects on top of each other. Basically every 3D game will deal with it sooner or later.

## Solving the Problem

There are two solutions to this.

**1. You can find a way to only draw one object--the one that should be visible.** Based on the pictures, you're probably drawing the "normal" cubes in a large group, all at once. If you could skip the selected block and draw the selected version (immediately, or after the rest of the blocks are drawn) you wouldn't get z-fighting, because there wouldn't be two objects to contend with.

**2. You can adjust the depth bias that DirectX has.** (OpenGL's got a similar thing, though off the top of my head, I don't remember what it's called. It might also be depth bias.) It's a render pipeline setting, specifically on the rasterization step.

## Some Details on the Solution

Assuming you go with the second (which is probably more common) in XNA, you'd simply assign a new `RasterizerState` to your `GraphicsDevice` object that sets the `DepthBias` property to a non-zero value. (I'm not 100% sure how MonoGame handles this. I think it supports it, but if you're targeting non Microsoft platforms, and you're using MonoGame, you should try this out on one of those platforms.)

Setting a depth bias value essentially adjusts the computed depth value by a predetermined amount, which moves it a little closer to the camera or a little farther, depending on what you put in.

There are a few little details that make setting a depth bias on your rendering pipeline a little troublesome, but we can deal with this.

1. You can't just change `RasterizerState`'s `DepthBias` property. You have to create a whole new `RasterizerState` object. Once it has been used, it essentially becomes frozen, and can't change individual parts.
2. Creating new `RasterizerState` objects using the default constructor usually doesn't put them in a good state. (It sets everything to 0 values, which is rarely what you want.)

So the best way to set this is by creating a new `RasterizerState` with properties identical to the current one, and then just change the one you need (`DepthBias` in this case) to the appropriate value.

## Some Sample Code

I've opted to do this with an extension method that uses a "fluent" API to make a copy with the change:

```
public static class RasterizerStateExtensions
{
    private static RasterizerState Copy(RasterizerState state)
    {
        return new RasterizerState()
        {
            CullMode = state.CullMode,
            DepthBias = state.DepthBias,
            FillMode = state.FillMode,
            MultiSampleAntiAlias = state.MultiSampleAntiAlias,
            Name = state.Name,
            ScissorTestEnable = state.ScissorTestEnable,
            SlopeScaleDepthBias = state.SlopeScaleDepthBias,
            Tag = state.Tag,
        };
    }

    public static RasterizerState WithDepthBias(this RasterizerState state, float depthBias)
    {
        RasterizerState copy = Copy(state);
        copy.DepthBias = depthBias;
        return copy;
    }
}

```

Add the above to new file in your project.

Before you draw your selected object, do something like this:

```
GraphicsDevice.RasterizerState = GraphicsDevice.RasterizerState.WithDepthBias(-0.0001f);

```

After you draw your selected object, revert the depth bias back to the default of 0:

```
GraphicsDevice.RasterizerState = GraphicsDevice.RasterizerState.WithDepthBias(0);

```

You are, of course, free to get the depth bias set any way you want (you don't have to use my extension method) but that's the general idea.

## About Which Values to Use...

What I found interesting here is that all of the documentation seems to say, "Use a floating point value between 0 and 16, where the higher it is, the closer it is to the camera." Changing the depth bias here didn't seem to work that way for me.

It seems like the way I was taught, setting a depth bias adjusts the final depth value by that amount, assuming 0 is the near clipping plane and 1 is the far clipping plane. In this case, putting in a larger value will push the object farther from the screen, while putting in a smaller value will move it closer to the screen. And that means your reference range is really more like -1 to +1, where -1 will force it to the front no matter how far back it is.

(This also means there's a relationship between your near and far clipping planes and the depth bias you need. If you change your clipping planes, you'll probably also have to revisit your depth bias.)

That leads a person to want the smallest depth bias possible that gets rid of the problem, because otherwise it starts to also overlap adjacent objects. (Try using a value of -1 and you'll see the selected object pops on top of everything in the scene.)

I'm not sure what to make of the mismatch between my prior knowledge about depth bias and the way it seems to actually work (which match each other) vs. the official documentation (which suggests 0-16). Perhaps somebody else can shed some light on that.

Sorry for such a long answer. Hopefully it gets you back on track.
> 1 votes

---
Tags: xna, monogame, voxels, vertex
---


title: Scrolling is going too fast

text:
# Question
Title: Scrolling is going too fast
I used delta based off the LWJGL tutorials and it works (I get 16 or 17 delta) but everything is scrolling nonstop.

Here's how I render things:

```
public class Game {

    int camX;
    int camY;

    float dx = 0.35f;
    float dy = 0.35f;

    public void init()
    {
    }

    public void update(int delta)
    {
        getInput(delta);
    }

    public void render(int delta)
    {
        glTranslatef(-camX, -camY, 0);
        Artist.drawQuad(10, 10);        //draws at 0,0 with width and height of 10
    }

    ////////////////////////////////////////////////////
    public void getInput(int delta)
    {
        if(Keyboard.isKeyDown(Keyboard.KEY_A))
            camX-=1;

    }

}

```

EDIT: it seems when I `glTranslatef();` it moves fast.

# Answer
> 0 votes
```
public void getInput(int delta)
{
    if(Keyboard.isKeyDown(Keyboard.KEY_A))
        camX-=1;
}

```

Is usually:

```
float camX;
float speedPerWholeSecond = 1;
public void getInput(float fractionalElapsedSeconds)
{
    if(Keyboard.isKeyDown(Keyboard.KEY_A))
        camX -= (speedPerWholeSecond  * fractionalElapsedSeconds);
}

```

This calculation is made FrameRate times per second.
You can still snap to integer increments:

```
glTranslatef(int)-camX, (int)-camY, 0);

```

If Delta must be an int:

```
float camX;
float speedPerWholeSecond = 1;
public void getInput(int delta)
{
    //delta = 16(ms) (60 fps)
    float fDelta = (delta / 1000.0f);
    if(Keyboard.isKeyDown(Keyboard.KEY_A))
        camX -= (speedPerWholeSecond * fDelta);
}

```

Edit: Since this is your top-level Game object:

```
public void update(int delta)
{
    float fDelta = (delta / 1000.0f);
    getInput(fDelta);
    //Future stuff below
    //camera.update(fDelta);
    //terrain.update(fDelta);
    //player.update(fDelta);
}

```

(Render() also)

Edit2:

```
public void getInput(float delta)
{
  float deltaX = 0;
  float deltaY = 0;
  float amountX = (1 * delta / 1000.0f); //For separate X and Y speeds
  float amountY = (1 * delta / 1000.0f); //For separate X and Y speeds
  if(Keyboard.isKeyDown(Keyboard.KEY_A))
    deltaX -= amountX;
  if(Keyboard.isKeyDown(Keyboard.KEY_S))
    deltaY += amountY;
  if(Keyboard.isKeyDown(Keyboard.KEY_D))
    deltaX += amountX;
  if(Keyboard.isKeyDown(Keyboard.KEY_W))
    deltaY -= amountY;
  if(deltaX || deltaY)
  {
    camX = deltaX;
    camY = deltaY;
  }
  else
  {
    camX = 0;
    camY = 0;
  }
}

```

---
Tags: java, algorithm, lwjgl
---


title: FBX Importer - Vertex Color

text:
# Question
Title: FBX Importer - Vertex Color
I imported vertex positions, indices and normals successfully in OpenGL using fbx sdk, but I just can't figure out how to import vertex colors. I tried to fetch the pointer to array of colors trough mesh layer but it returns null. Can anyone help me with this one please?

# Answer
> 1 votes
they are stored in normalized *GL\_UNSIGNED\_BYTEs*, a single color is 4 bytes, and are held under the KFbxLayer class and KFbxLayerElement class is the base class for Layer Elements and describes how all is arranged in memory. example layers

```
KFbxLayerElementVertexColor KFbxLayerElementNormal KFbxLayerElementUV KFbxLayerElementTexture KFbxLayerElementMaterial KFbxLayerElementPolygonGroup

```

Create an instance of KFbxMesh object and a new KFbxNode object containing that mesh. Then access KFbxNodeAttribute or the KFbxLayerContainer also holds layers, maybe your vertex colors are in there

refer to the sdk documentation Autodesk

---
Tags: opengl, c++, fbx
---


# Question
Title: Parsing Blender exported collada file in c++
Since I could not find any libraries that can help me parse collada files in my c++/opengl project, I decided to write my own. (I did find assimp, but binaries for Visual Studio 2013 were't available, and I don't know enough to build it myself from the source; Can anyone build it and share it please? )

I read up a little about the structure of .dae files, figured I could do it, and exported Suzanne from Blender in a .dae file. Fine. Now I open up the .dae file in Notepad++ just to make sure I got the basic understanding right, and I found something weird.

So the tags \[float\_array id="Suzanne-mesh-positions-array" count="1521"\] and \[/float\_array\] contain the huge list of vertex positions right?

And the tags \[p\] and \[/p\] inside \[polylist count = "968"\] and \[/polylist\] should contain vertex indices in triangular order right? But that doesn't make sense, cause then the first triangle is going to be vertex\[46\], vertex\[0\] and vertex\[0\].. But how is that possible? Any help please? If I've got it wrong, can someone direct me to some place where i can learn how to parse collada files. Thanks a lot.

EDIT: I finally managed to build Assimp for VS 2013 (YAAYYYY!!)after getting awesome instructions at http://www.learnopengl.com/#!Model-Loading/Assimp

But my confusion regarding the vertex indices remain.

# Answer
> 3 votes
> So the tags \[float\_array id="Suzanne-mesh-positions-array" count="1521"\] and \[/float\_array\] contain the huge list of vertex positions right?

Yes.

> And the tags \[p\] and \[/p\] inside \[polylist count = "968"\] and \[/polylist\] should contain vertex indices in triangular order right? But that doesn't make sense, cause then the first triangle is going to be vertex\[46\], vertex\[0\] and vertex\[0\].. But how is that possible?

Your confusion is that collada uses a different set of indices for each `<input`, not for each vertex. So each vertex in the `<p>` array has indeed 2 indices: the first index is the vertex position (because of the offset="0"), and the second indice is the normal. Indeed the indices in the collada file are different than the indices than would be in an OpenGL index buffer.

In your file, the first primitive is a triangle (`3` in the `<vcount>` array), it uses the indices `46 0 0 0 2 0` and you must read its vertices as : {position\[46\] normal\[0\]}, {position\[0\] normal\[0\]}, {position\[2\] normal\[0\]}.

Building an OpenGL index buffer data from this format requires some postprocessing to find the duplicate vertices.

> can someone direct me to some place where i can learn how to parse collada files. Thanks a lot

If you want to learn the collada file you should have a look at the collada specification, but it is not the best way to understand the format. You should export a quad or triangle mesh from Blender to have simple example files that you could study.

---
Tags: opengl, c++, blender, file-format, collada
---


# Question
Title: Check if is object in camera field and not covered by other object
I know how to check if object is in camera view but how I can check if that object is cover by something elese? In my case I want to turn on or off some effect when I look at light. At this moment my code is straight forward, I have created interface for lightable object with method

```
public bool isVisibleByCam(Camera cam) {
    if (GeometryUtility.TestPlanesAABB(GeometryUtility.CalculateFrustumPlanes(cam), gameObject.GetComponent<Collider>().bounds)) {
        return true;
    }
    return false;
}

```

I hope there is better way than checking every object in camera view and comparing distnace between camera.

# Answer
> 1 votes
Hello I suggest you use Raycasting to test if the camera is directly pointing to the light source. The ray will go from the camera into the front vector direction, Once you get the RaycastHit, you can check the name, the tag or even use Layer Mask to selectively ignore colliders.

If you want to apply the effect even when the camera is not pointing directly to the light, you can combine the test you are already doing to determine if the light is in view, and then raycast using the transform.LookAt(target) method to get a vector from the camera in the direction of the light. Please note that LookAt will rotate the transform, so do it with a new object that has the same values, or use Quaternion.LookRotation if you prefer.

Lastly you can improve using Vector3.Angle and Vector3.Distance to fine tune when to trigger the effect. Here is how you get the angle and distance assuming you have an array of all the lights on the view:

```
    for( int i = 0; i < lightObjects.Length; i++)
    {
        Vector3 targetLine = lightObjects[i].transform.position - camera.transform.position; //Obtain the vector from camera to Target light
        float distance = targetLine.magnitude;
        float angle = Vector3.Angle (camera.transform.forward, targetLine); //Get the Angle between camera forwward and targetDir
        if ( (distance < shortDistance && angle < 30) ||
                    (distance < mediumDistance && angle < 15) || (distance < longDistance && angle < 5f) )
        {
            Debug.Log("Apply effect on light " + lightObjects[i].name);
            Debug.Log("Angle: " + angle.ToString () + " Distance: " + distance.ToString());
        }
    }

```

---
Tags: unity, camera, gameobject
---


# Question
Title: How do 3D games create the illusion of depth?
How do libraries like OpenGL convert three dimensional coordinates into the two dimensional pixels we see on our screens? I'm not talking about the 3DS or games that require 3D glasses, but rather the illusion of three dimensions.

I don't need any code to create this effect - I'm just curious about the concept.

# Answer
As the commenters on the opening post have already pointed out, this mechanism is called 'perspective correction' or in 3D terms 'perspective projection'.

The basic idea is that as things get further away, they get smaller. It's all about trigonometry (calculating triangles).

You can calculate this by assuming that your Field of View is like a pyramid with a square base, where the point is at your eye (or camera) and the pyramid is aligned to the direction you are looking.

If you know the shape of your Field of View and you know the size and location of a point on screen (Near plane), you can extrapolate what size the object should be at a given distance when you scale proportionally.

Remember that objects closer to the Near plane will take up more of the view space and objects further away will take up less space.

Notice how in the picture below, everything gets smaller the further away it is.

The vanishing point is another way to think about it. The vanishing point is the place in the distance where everything converges (the Far plane accommodates this). You can observe this in real-life when you look down a street. If the street were long enough, it would look like a triangle.

You could think of a 2D shape like a circle on the screen and apply the same principle as the view frustum to the object itself, but in reverse. When you extrapolate the circle into a 3D shape, it becomes a cone. The circular base is in your view and the cone points away extending to the vanishing point. If you want to know how big to draw the circle when it is X units away, then you calculate the diameter of the cone at that distance.
> 4 votes

---
Tags: 3d, projection
---


# Question
Title: Can .NET Core be used to make games on non-Windows platforms?
If I build a game that runs on a Windows phone, does that mean it will work on Android (and future ios) with .NET core or vNext? I do not wish to use XNA or C++.

# Answer
> 2 votes
Yes,it will. Microsoft is open-sourcing it, and making it available on different platforms.

From Wired:

> **MICROSOFT OPEN SOURCES .NET, SAYING IT WILL RUN ON LINUX AND MAC**
>
> SATYA NADELLA’S RAPID reinvention of Microsoft continues.
>
> In yet another bid to make up lost ground in the long march to the future of computing, Microsoft is now open sourcing the very foundation of .NET—the software that millions of developers use to build and operate websites and other large online applications—and it says this free code will eventually run not only on computer servers that use its own Windows operating system, but also atop machines equipped with Linux or Apple’s Mac OS, Microsoft’s two main operating system rivals.

Hope this helps (=

# Answer
> 1 votes
Yes is the answer, and Xamarin is a useful to create native apps for all three major OS platforms, you could install Xamarin for Visual Studio

---
Tags: .net
---


# Question
Title: Destroying Unity GameObject when it goes out of camera during runtime
I have this GameObject instanciated in unity -

```
void Start () {

         GameObject myRoadInstance =
            Instantiate(Resources.Load("car"),
                        new Vector3(5, 5, 5),
                        Quaternion.identity) as GameObject;

    }

```

On running the game, I want this instance removed when it is no longer visible.

How do I do this ?

# Answer
> 3 votes
You can use the `OnBecameInvisible` callback for that.

Just implement something like:

```
void OnBecameInvisible(){
    // disable or destroy gameobject
}

```

The method will get called when the object isn't being rendered by any camera anymore. This also includes cameras from the Unity-Editor. So if you're running your game and have the *Game* and the *Scene* view open, `OnBecameInvisible` won't trigger for any object that is still rendered by the *Scene-View* camera.

---
Tags: unity, camera, gameobject
---


# Question
Title: How do I implement a fixed delta time step with a SDL_Delay(15ms) precision
So I am using SDL2.0 for making a Game Engine. Where I am having a problem is using SDL\_Delay().

SDL\_Delay's minimum delay time is 15ms, I've tried everything, and my FPS is Stuck at 64 because of this. I have seen another post about this but it does not seem to answer the question with SDL\_Delay.

I can turn on VSYNC, and I Get a fixed 60FPS, Please explain what the SDL Library is doing that I cannot implement Myself?

This is very weird, I dont think I need to post my code for this, the code is not wrong, Its the SDL\_Delay(), wether it be SDL\_Delay(1) or SDL\_Delay(15) , it will always delay for 15ms, does anyone know a way of fixing this so I can still use SDL\_Delay.

I have seen on SDL Documentation they say this is expected, because of OS Scheduling.

Then I read OS Scheduling does this to save power consumption... I have High Performance turned on my computer, not Power Saver.

Does anyone know a workaround for this? I am very hardheaded and do not want to use VSYNC.

Or I might just have to. LOL Thanks in advance!!

Edit: https://wiki.libsdl.org/SDL\_Delay

# Answer
You can't reliably control the FPS with functions like SDL\_Delay, they call the operating sleep function, which tells the operating system "Please don't give me any CPU time for at least N miliseconds", the operating system is then free to decide:

1. At what granularity (i.e., as you said you specify 1ms and it waits for 15ms, it has a granularity of 15ms) it controls sleeping.
2. Whether it wants to run other programs before bringing your program back up.

This combines to making SDL\_Delay not useful for any reliable timing.

What VSYNC is doing is something different, with VSYNC enabled, when you send a new frame to the monitor it will wait for a Vertical SYNC signal to return control to the program so it can start with the next frame.

What you want to do, if you don't want to use VSYNC, is something more like this:

```
TIME_PER_TICK = 20;

int lastTickTime = now();
int lastFrameTime = now();
while ( gameIsRunning ) {
    while ( now() > lastTickTime + TIME_PER_TICK ) {
        //Not included, logic to detect when we're *way* behind so we can just drop some ticks
        doTick();
        lastTickTime += TIME_PER_TICK;
    }
    runFrame( now() - lastFrameTime );
    lastFrameTime = now();
}

```

This separates the rendering (runFrame) from when physics and such is updated, this allows you to have smooth graphical effects while your game logic runs at a fixed delta time.
> 6 votes

---
Tags: sdl, game-loop, frame-rate
---


# Question
Title: How can I manually call/fire OnTriggerExit() for colliders a trigger is inside of in Unity?
In Unity, the OnTriggerExit() method is not called/fired (not sure if it's an event or not) when an object is disabled or destroyed within it's collider. In comparison to it being fired is an active object that was within it's collider no longer being inside the bounds of that collider on the next frame. I want to be able to call OnTriggerExit() on my triggers OnDisable() method as a workaround.

How would I go about calling/firing OnTriggerExit() manually?

# Answer
If you want the code in your `OnTriggerExit` to be called inside the `OnDisable` method as well, simply encapsulate the code into a function of its own, and call the function from both methods.

```
void OnTriggerExit(Collider other) {
    CommonTriggerExitCode();
}

void OnDisable() {
    CommonTriggerExitCode();
}

void CommonTriggerExitCode() {
    //Code to be called when trigger exits or object is disabled
}

```

As far as I know, there's no way to manually trigger these events, and this strategy is far less of a work-around than manually triggering events.
> 2 votes

# Answer
Here is a simple solution:

Instead of calling `Destroy(yourObject)` everywhere , replace that with a `CustomDestroy` function what has the following code:

```
public static void CustomDestroy(GameObject o)
{
    o.transform.position = new Vector3(100000000.0f,10000000.0f,10000000.0f);
    Destroy(o);
}

```

Setting the position before you destroy an to 'infinity' will handle all the appropriate collisions calls.
> 0 votes

---
Tags: unity
---


# Question
Title: Instantiating on a random node, provided the node is walkable, but what if it isn't walkable?
In my demo I have a GUI where the user determines the number of AI that will spawn. I would like these AI to spawn onto the walkable area of my Grid. So I choose a random position then get the node from that, then check to see if the node is walkable, if it is then instantiate the game object at that position, however my problem here is that if it is not walkable I would like a new random position to be chosen and then checked again to see if it is walkable all the while looping until the number of game objects specified have been created. How do I go about the last part of this? I can't get my head around the logic.

```
        for(int i = 0; i < intBlinkyCount; i++)
                {

                    Vector3 pos = new Vector3(Random.Range(-(floatGroundScaleX/2*10), floatGroundScaleX/2*10), 0.5f, Random.Range(-(floatGroundScaleZ/2*10), floatGroundScaleZ/2*10));
                    Node randomNode = grid.NodeFromWorldPoint(pos);

                    if(randomNode.walkable)
                        {
                            Instantiate(blinky, pos, Quaternion.identity);
                            blinky.name = "blinky"+i;

                        }
                    else
                        {

                        }

                }

```

# Answer
That seems like a very basic task, if I understood correctly. Obviously, if one node can fit only one blinky, then your function has to satisfy the following condition: Amount of blinkies \<= amount of nodes.

And there're several ways to loop until you have placed a blinky. One would be just decrementing the iterating variable:

```
if(randomNode.walkable)
{ ... }
else {
  i--
}

```

Another one would be having a while loop instead of an if-conditional:

```
while(!randomNode.walkable) {
  //Choose a new random node here
}
//Instantiate your blinky here

```

Originally I had the second example as while-else, but I guess that statement doesn't work in C#.
> 1 votes

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


title: How to rotate (YAW) aircraft in XNA?

text:
# Question
Title: How to rotate (YAW) aircraft in XNA?
I'm developing a flight simulator based on Riemer's Blog tutorial (XNA C#). To control the aircraft, I use the following code:

```
Quaternion additionalRotation = Quaternion.Identity;
additionalRotation *= Quaternion.CreateFromAxisAngle(Vector3.Forward, roll);
additionalRotation *= Quaternion.CreateFromAxisAngle(Vector3.Right, pitch);
model_ROTATION *= additionalRotation;

```

This only executes pitch and roll. I wanted to add code so that if the aircraft is rolling, then it should rotate to right or left (yaw) so I changed the code to the following:

```
Quaternion additionalRotation = Quaternion.Identity;
additionalRotation *= Quaternion.CreateFromAxisAngle(Vector3.Forward,roll);
additionalRotation *= Quaternion.CreateFromAxisAngle(Vector3.Up, yaw);
additionalRotation *= Quaternion.CreateFromAxisAngle(Vector3.Right, pitch);
model_ROTATION *= additionalRotation;

```

This behaviour is not so realistic; when I roll the aircraft rotates to right/left (yaws), but at the same time it loses altitude and I must pitch up (pull handle) to avoid crashing.

Is there any solution to make slew rotation (yaw) without losing altitude.

# Answer
I avoid Euler angles in aircraft pitch, roll, yaw orientations because aircraft rotate about thier local axis and trying to resolve this to Euler angles about the world (or global) axis adds uneccesary complication to the code. Instead of 3 Euler angles, I store the current orientation as a matrix or quat and simply modify the matrix/quat depending on input since last frame. A matrix or a quat is equally sufficient but the matrix has the advantage of being in the same format that you need to send to the shader anyway and it has properties that are the exact axes you need to do the rotations about. A quat is useful if you want steady slerp rates. Gimbal lock is absolutly NOT an issue when working with matrices this way.

```
//class scope variables
Matrix aircraftOrientationMatrix = Matrix.Identity;
float pitchChangeThisFrame, yawChangeThisFrame, rollChangeThisFrame;

//in the Update method
pitchChangeThisFrame = ?.f;//actual value based on player input
yawChangeThisFrame = ?.f;
rollChangeThisFrame = ?.f;

Vector3 pitch = aircraftOrientationMatrix.Right * pitchChangeThisFrame;//local pitch axis * amount of pitch change to apply this frame
Vector3 yaw = aircraftOrientationMatrix.Up * yawChangeThisFrame;
Vector3 roll = aircraftOrientationMatrix.Forward * rollChangeThisFrame;

Vector3 overallOrientationChangeThisFrame = pitch + yaw + roll;//
float overallAngularChangeThisFrame = overallOrientationChangeThisFrame.Length();//magnitude of all changes added together
Vector3 overallRotationAxis = Vector3.Normalize(overallOrientationChangeThisFrame);

Matrix orientationChangeThisFrame = Matrix.CreateFromAxisAngle(overallRotationAxis, overallAngularChangeThisFrame);

aircraftOrientationMatrix *= orientationChangeThisFrame;

```
> 1 votes

# Answer
You're using vector3.up, vector3.forward and vector3.right to calculate the needed rotations. These axes don't move along with your plane. What you need to do is rotate the plane around its very own up, forward and right vectors. You could do that like this:

```
Matrix rotMat = Matrix.CreateFromQuaternion(model_ROTATION);
Quaternion additionalRotation = Quaternion.Identity;
additionalRotation *= Quaternion.CreateFromAxisAngle(rotMat.Forward,roll);
additionalRotation *= Quaternion.CreateFromAxisAngle(rotMat.Up, yaw);
additionalRotation *= Quaternion.CreateFromAxisAngle(rotMat.Right, pitch);
model_ROTATION *= additionalRotation;

```
> 1 votes

---
Tags: xna, rotation, quaternion
---


# Question
Title: How to use an A* Pathfinding System across uneven environments?
I am developing a game in Unity3D. I want an enemy character to follow the player around. The problem is, my surface is uneven and full of mountains. I am using aarongranberg's pathfinding project. Every time that a player climbs a hill or a mountain, the enemy stops because the grid is flat and it considers the mountain to be an obstacle. How do I solve this problem ?

# Answer
Essentialy A\* needs to be configured with what is not an accessible tile , so you can configure that by making an algorithm using gameObjects 'surface taken on the terrain then calculate the tiles to avoid at runtime .Then add it to the closed list (if there is not something for that already )
> 1 votes

# Answer
Within this project, you are able to define what is passable and impassable terrain. If you recast the graph and alter the maximum slope that's walkable to the gradient of your mountains, they should be included in the navmesh, albeit at a higher cost to use.

There may be other ways, but ultimately, what you want to be looking to do is include the mountain in the mesh as a highly weighted path. I'd recommend reading through the documentation for your A\* project
> 0 votes

---
Tags: c#, unity, path-finding
---


title: Updating object position

text:
# Question
Title: Updating object position
An object - a player or npc or whatever - has a position, direction and speed and such.

Before drawing each frame, we want to compute the current position of each object.

How do you do this?

If you take the elapsed time since last frame, you run the very real risk of the game running at the wrong speed if the frame-rate is very fast and the clock precision poor (as it often is on some platforms).

And how can you incorporate player controls such as the player wanting to go left or right (e.g. in a simple asteroids clone without ship inertia)?

# Answer
> 1 votes
First of all, the method of just using the elapsed time since the last frame should absolutely work just fine in 99% of all cases. If you're having problems, there's probably a bug in your implementation.

That said, this problem is generally referred to as numerical integration. Given a set of system dynamics (rules that define the next state of the system given the current state and a change in time), you have to compute the *trajectory* of the system over time.

The simplest method of doing this is called Newton-Euler. That method basically boils down to:

```
position[t + 1] = position[t] + velocity[t] * dt
velocity[t + 1] = velocity[t] + acceleration[t] * dt

```

It works as long as `dt` is sufficiently small. If Newton-Euler doesn't work for you, you generally move straight on to Runge-Kutta 4. RK4 is a little bit more complex. You will have to store not just the previous and next states of the system, but 4 more intermediate points between the previous and next. Essentially, RK4 tries to predit the next state of the system given the previous state and its derivatives. However, it requires you to be able to say what the position, velocity and acceleration of the object will be in the *future* as well as the present. This is easy in some systems (like orbiting bodies or falling characters), but is nigh-but-impossible when you've got stuff like collisions involved -- but otherwise it will give you nearly perfect results even when your timestep is quite large.

---
Tags: movement
---


title: Rotate Object Towards Direction in 2D

text:
# Question
Title: Rotate Object Towards Direction in 2D
For my RTS game's physics engine, I'm trying to find out a clever way to make a unit face the direction it's moving in. Given a Vector2d direction of movement (its normalized velocity), how can I calculate the unit's rotation? If possible, I'd rather not use inverse trig functions because I only have a lookup table for Sine.

# Answer
> 3 votes
You shouldn't use a rotation angles if you can avoid it.\* They are a bad representation of directions. If you choose to use them, you will need an inverse trig function.

Instead of storing `theta`, store the pair `(cos(theta), sin(theta))`. You can combine rotations and directions using the multiplication rules of complex numbers, i.e.

```
(a,b) * (c,d) = (ac - bd, ad + bc)

```

The 2D rotation matrix is easily constructed, because cos and sin of the angle are immediately available. Be sure to re-normalize the directions sufficiently often or they will inadvertently scale your points.

Finally, the angle between two vectors can be compared to a reference angle `theta_0` using the dot product between the two direction vectors, as when the smaller angle between A and B is less than `theta_0` iff `cos(theta_0) < dot(A,B)`.

* Except for input/output to humans or as a compact way to store a direction if every byte counts.

---
Tags: 2d, mathematics, rotation, geometry, rts
---


# Question
Title: How to add a callback to addAction in scene2d
Sorry if this is a newbie question, I'm still learning libgdx. I'm using scene2d and I am trying to fade a tooltip into my scene and fade it out after 4.5 seconds.

Everything is working in my code except that `tooltip.setVisible()` always overrides the fading animation. I'm wondering if there's a way to set up a callback function or if there's any way to tell when an action has completed so I can trigger `setVisible` after the fade animation has completed. I thought about setting up a second timer that triggers after 5 seconds, but that seems like a hacky way to do things.

**Here's my TooltipListener class:**

```
public class TooltipListener extends InputListener {

private Actor tooltip;
private InputListener inputListener;
private Timer timer = new Timer();

public TooltipListener(Actor tooltip) {
    this.tooltip = tooltip;
}

@Override
public boolean touchDown(
    InputEvent event,
    float x,
    float y,
    int pointer,
    int button
){
    tooltip.setVisible(true);
    tooltip.addAction(fadeIn(1f));
    tooltip.toFront();

    timer.scheduleTask(new Timer.Task() {
        @Override
        public void run() {
            tooltip.addAction(fadeOut(1f));
            tooltip.setVisible(false);
        }
     }, 4.5f);

    return true;
}

}

```

# Answer
A nice way to implement what you are trying to achieve would be to use a SequenceAction and built in libgdx actions :

```
tooltip.addAction(Actions.sequence(
    Actions.show(),
    Actions.fadeIn(1f),
    Actions.delay(4.5f),
    Actions.fadeOut(1f),
    Actions.hide())
)

```

Actions.show() basically call setVisible(true) on your actor and Action.hide() call setVisible(false).

Be aware that you can also implement your own custom actions, by subclassing the libgdx Action class. For example, to call toFront as you do in your code in an action :

```
public class ToFrontAction extends Action {

    public boolean act (float delta) {
        target.toFront();
        return true; // An action returns true when it's completed
    }

}

```

So that you will be able to do :

```
tooltip.addAction(Actions.sequence(
    Actions.show(),
    new ToFrontAction(),
    Actions.fadeIn(1f),
    Actions.delay(4.5f),
    Actions.fadeOut(1f),
    Actions.hide())
)

```
> 3 votes

---
Tags: java, libgdx, scene2d
---


# Question
Title: Is WWW reliable for downloading a large AssetBundle?
I have a very large AssetBundle. More than 200MB.

Is `WWW` reasonable for downloading it from my server? I heard that you can't tell the timeout it has. I intend to use it for iOS and Android.

Since clearly the download will last more than 5 minutes for a lot of people, is it reliable or will it time out? Should I instead make my own application in my server to transfer the bundle's bytes using sockets?

# Answer
> 1 votes
Breaking your assets into smaller bundles holds many advantages and only 2 disadvantages.

The advantages are that if you update some of the assets, users only have to download a portion of the asset data instead of the entire bundle.(unless you roll a decent updater) This also means if some of the assets don't download properly, you again don't have to re download all of the assets. Finally, if you time out, you again, don't have to re download all of the assets, only the ones you missed.

There are 2 main disadvantages I can think of with this method but they are small enough that they aren't unreasonable. Making many assets will increase the download time but your talking about seconds. The other disadvantage is that since you have multiple asset bundles, you need to keep track of which asset bundle has what content.

# Answer
> 0 votes
I using this code for downloading some pictures in my apps you can use it with some changes i never had any problem with this code

```
string uri; //Source Path
string fileName; //Destination Path

HttpWebRequest request_ = (HttpWebRequest)WebRequest.Create (uri);
HttpWebResponse response_ = (HttpWebResponse)request_.GetResponse ();

if ((response_.StatusCode == HttpStatusCode.OK ||
     response_.StatusCode == HttpStatusCode.Moved ||
     response_.StatusCode == HttpStatusCode.Redirect) &&
    response_.ContentType.StartsWith ("image", StringComparison.OrdinalIgnoreCase)) {
    using (Stream inputStream = response_.GetResponseStream())
    using (Stream outputStream = File.OpenWrite(fileName)) {
        byte[] buffer = new byte[4096];
        int bytesRead;
        do {
            bytesRead = inputStream.Read (buffer, 0, buffer.Length);
            outputStream.Write (buffer, 0, bytesRead);
        } while (bytesRead != 0);
    }
}

```

---
Tags: unity
---


# Question
Title: Button image on game menu is updating too slow
I'm using **SDL2** and i'm facing a problem with my game menu buttons.

Every time i detect that the mouse pointer is over a button of the menu i update the image of the button (from `MOUSE_OUT to MOUSE_OVER`).When i move **several times and fast** the pointer over the button and then i stop pointing at it the button image keeps updating. Like if the updating of the screen were not synchronize with the update of the events.

My guest is that because i'm polling the events by using `SDL_PollEvent()` there still events on the queue to poll and that causes the update of the images.

How can i avoid this problem of latency between the polling of events from the poll and the update of the image?

This is the method i use to check if the pointer is over the button. The `input` object keeps the type of event and the event itself.

```
int MenuState::update(GameEngine g)
{
    state_play = MOUSE_OUT;
    state_exit = MOUSE_OUT;

    switch(input->get_type()) {
        case MOUSE_PRESSED_EVENT:
            if((input->get_x_pos() > POS_X_PLAY_BUTTON) && (input->get_x_pos() < (POS_X_PLAY_BUTTON + 400)) &&
                (input->get_y_pos() > POS_Y_PLAY_BUTTON) && ( input->get_y_pos() < (POS_Y_PLAY_BUTTON + 100))) {
                state_play = MOUSE_CLICKED;
                next_state = Game;
            }

            if((input->get_x_pos() > POS_X_EXIT_BUTTON) && (input->get_x_pos() < (POS_X_EXIT_BUTTON + 400)) &&
                (input->get_y_pos() > POS_Y_EXIT_BUTTON) && ( input->get_y_pos() < (POS_Y_EXIT_BUTTON + 100))) {
                state_exit = MOUSE_CLICKED;
                next_state = Game_Over;
            }
            break;
        case MOUSE_MOVED_EVENT:
            if((input->get_x_pos() > POS_X_PLAY_BUTTON) && (input->get_x_pos() < (POS_X_PLAY_BUTTON + 400)) &&
                (input->get_y_pos() > POS_Y_PLAY_BUTTON) && ( input->get_y_pos() < (POS_Y_PLAY_BUTTON + 100))) {
                state_play = MOUSE_OVER;
            }
            if((input->get_x_pos() > POS_X_EXIT_BUTTON) && (input->get_x_pos() < (POS_X_EXIT_BUTTON + 400)) &&
                (input->get_y_pos() > POS_Y_EXIT_BUTTON) && ( input->get_y_pos() < (POS_Y_EXIT_BUTTON + 100))) {
                state_exit = MOUSE_OVER;
            }

            break;
        default:
            break;
    }
}

```

This is where i poll the events.

```
TypeEvent InputManager::poll_event()
{
    TypeEvent t;

     if(SDL_PollEvent(e)) {
        switch (e->type) {
            case SDL_QUIT:
                input = new QuitInput(QUIT_BUTTON);
                t = QUIT_BUTTON;
                break;
            case SDL_KEYDOWN:
                input = new KeyboardInput(KEYBOARD_EVENT);
                t = KEYBOARD_EVENT;
                break;
            case SDL_KEYUP:
                input = new NoneInput(NONE_EVENT);
                t = NONE_EVENT;
                break;
            case SDL_MOUSEMOTION:
                input = new MouseInput(MOUSE_MOVED_EVENT);
                t = MOUSE_MOVED_EVENT;
                break;
            case SDL_MOUSEBUTTONDOWN:
                input = new MouseInput(MOUSE_PRESSED_EVENT);
                t = MOUSE_PRESSED_EVENT;
                break;
            default:
                input = new NoneInput(NONE_EVENT);
                t = NONE_EVENT;
                break;
        }
        input->set_input(e);
        return t;
    }
    return NONE_EVENT;
}

```

This is my first try in order to make an input system and is not complete or totally optimal.

Thanks in advance!

# Answer
```
if(SDL_PollEvent(e)) {

```

should be

```
while(SDL_PollEvent(e)) {

```

With "if", you're only processing one event per rendered frame. You need to use a 'while' loop so that every event which occurred during the frame gets processed before the next frame gets drawn.
> 3 votes

---
Tags: c++, input, sdl2, menu
---


# Question
Title: How to store variable inside an array unity?
I was wondering how I can store these `anims` inside an array, because, the start function will be fired one time. I would like to be able to call these `Animators` more then one time.

```
    public Animator anim0;
    public Animator anim25;
    public Animator anim50;
    public Animator anim75;
    public Animator anim100;

void Start () {

        anim0 = GameObject.FindGameObjectWithTag("Campfire0").GetComponent<Animator>();
        anim25 = GameObject.FindGameObjectWithTag("Campfire25").GetComponent<Animator>();
        anim50 = GameObject.FindGameObjectWithTag("Campfire50").GetComponent<Animator>();
        anim75 = GameObject.FindGameObjectWithTag("Campfire75").GetComponent<Animator>();
        anim100 = GameObject.FindGameObjectWithTag("Campfire100").GetComponent<Animator>();

    }

```

# Answer
what about:

```
Animator[] anims = new Animator[number_of_animators];

anims[0] = anim0;
...

```

if you mean to have an array editable inside the editor you can declare it as public and you will specify inside the editor its size and you will be able to drag and drop elements into it

just like this:

```
public Animator[] anims;

```

this is to be declared just as variable. No need to initialize inside Start()

then to check which animation is being played just declare

```
AnimationInfo[] animPlayed;

```

and when it is needed call

```
animPlayed = you_animator.GetCurrentAnimationClipState (0);

```

which returns the first animation clip being played (because you may have more concurrent animation)
> 1 votes

---
Tags: unity
---


# Question
Title: Adding some recoil to the Camera so that the crosshair is pushing to the sky (FPS game)
I just want to add some recoil to the camera, but I can't find a working script. It's an fps, so I take my mouse axis to rotate the camera. And now I want a pushback to the top, so that the camera looks into the sky after shooting a whole clip. It should be pretty easy, just add some amount to the axis, but it isn't working for me.

I've got something like this from another post, but it just does nothing for me... I got a feeling that my axis is locked in some way, I'm using the "MouseLook" from the standart assets.

```
transform.Rotate( recoil * Time.deltaTime, 0, 0 ) ;

```

---

Update:

This Script is working partially, but I think I reactivate the MouseLook too fast after the Rotate, so that the Mouse just jumps back to the starting position.

```
 mouseLook.enabled = false;
 transform.Rotate (-5, 0, 0);
 mouseLook.enabled = true;

```

# Answer
you can disable MouseLook for a small amount of time?

using invoke to reactivate after "disableTime"

```
float disableTime = 0.5f;//0.5 second disable

void reactivateML() {
mouseLook.enabled = true;
}

    ...
     mouseLook.enabled = false;
     transform.Rotate (-5, 0, 0);
     Invoke("reactivateML", disableTime);
    ...

```
> 0 votes

---
Tags: unity, camera, first-person-shooter
---


# Question
Title: How can I write my scoring system and add a score multiplier?
I am new to the scripting world and I am currently trying to add a score multiplier to the game code I am working on.

Right now the score is set to increase as the player runs across the level however I want to set it up so that the players gains X amount of score for every Y amount of distance traveled. I also want to add a multiplier for when they come into contact with certain objects X amount of time. Any help would be greatly appreciated.

# Answer
I'll use pseudocode examples here.

Rather than setting score based on current position

```
score = distance;

```

*increment* their score based on a change in position over time. Depending on your code this should be fairly easy. If the character is moving then you're changing it's distance over time already. Somewhere in your game loop you've got something that looks like this:

```
position_x = position_x + speed;

```

or maybe

```
position_x += 5;

```

(I recommend the first case, by the way. Using a variable means it should be easy to make a pick up item that increases or decreases speed)

Once you've found this, you can add a line right there to increment your score

```
position_x = position_x + speed;
score = score + 1;

```

Now for a multiplier. Normally you don't want to multiply the score by anything, and sometimes you want to double or triple the gains made. So, add a new variable called "multiplier", set it to one, and use that everywhere you add to the score:

```
integer variable "multiplier" = 1;

(in main game loop){
    position_x = position_x + speed;
    score = score + 1*multiplier;
}

```

and

```
(on item pickup){
     score = score + itemScoreValue*multiplier;
}

```
> 3 votes

---
Tags: algorithm
---


title: PHP battle script

text:
# Question
Title: PHP battle script
I have custom built as a little personal project a website coded in php that is a MMORPG.

It is at the minute just a personal private project but I am stuck as what to do when it comes to users battling each others' accounts!

I have four stats for each user which they can train at a gym if they wish too, so the differences in stats could be huge or not so much.

The stats are:

Speed - How fast they can hit

Strength - How hard they hit

Agility - How well they can dodge attacks

Endurance - How long they can fight for / How good their defence is

All these numbers are floats with upto 6 decimals, I was wondering if anyone on gamedev SO could point me into a good direction of how writing a script so each player could battle each other with all these factors involved.

At the minute I am just working out percentage differences of the two and using that, but it is isn't very consistent!

Thanks

# Answer
> 1 votes
I think the same algorithm as used in warcraft could help you in your way. in warcraft there are these parameters:

* hitpoint : which means how much can one take damages without dying!
* armor : which is basically telling you how much can damage is taken from attack (the higher armor means less damage).
* damage : which means how much damage can player deal in one attack
* attack speed : means how many attacks can one deal in one second
* life regen : which means how much hitpoint will player regain every second
* strength : which directly affects health and life regen
* agility : which directly affects armor

knowing these parameters there are two variables which will determine battle results

1. dps (which is damage per second) is equal to `attackspeed*damage`
2. ehp (which means effective hitpoint) is equal to `hitpoint * (1+constant*armor)`

while in warcraft engine the battle takes place in real time, you can directly compute results in your game, as a note every variable with number 1 is related to player 1 and every thing I assume `1/(1+constant * armor) * dps > liferegen`:

* t1 = hitpoint2 * (1 + constant * armor2) / (dps1 - liferegen2 * (1 + constant * armor2));
* t2 = hitpoint1 * (1 + constant * armor1) / (dps2 - liferegen1 * (1 + constant * armor1));

t1 and t2 will represent how much time does it take for player1 to kill player2 and time needed for player2 to kill player1. you can easily check if t1\>t2 or t2\>t1 and declare results.

# Answer
> 0 votes
Don't create an algorithm!

Determine what you *want to happen*, first.

Do you want player skill to trump stats? How much of a level difference should a skillful player be able to overcome? How much benefit should high level/experience/age in a character make? Does strength trump armor, or agility trump strength?

Set the parameters of exactly what you -want- to happen, and then create tests of the behavior that you expect. Then when you create the actual algorithm, you won't just be shooting in the dark, you'll know whether it's doing what you want.

---
Tags: php
---


# Question
Title: What is the cause of these WaitForFPS spikes and dips?
In Unity, moving the player causes the camera to jitter. I went to the Profiler, and I saw these spikes: On further inspection, all the yellow spikes were WaitForFPS(). I've tried every VSync setting in quality options, but none of them seem to fix this issue.

# Answer
> 1 votes
`WaitForFPS` isn't really an issue (it has a specific purpose in attaining the target frame-rate of your game).

Is your camera getting moved in the `LateUpdate` Callback? The most common reason for camera jitter in camera movement scripts is using Update, which is causes the target's movement to happen after the camera's movement is updated, leaving it always "catching up".

---
Tags: unity, profiler
---


# Question
Title: With a Texture Atlas that has 128x128 tiles, how can I use that in Unity3D?
So I've got a working texture atlas that has tiles fitting 128x128. However, I can't quite figure out how to use them. I know it's probably got something to do with

```
    TileRenderer.material.SetTextureScale("_MainTex", new Vector2(0.25f, 0.25f));
    TileRenderer.material.SetTextureOffset("_MainTex", new Vector2(0 * 0.25f,0));

```

but I'm not sure where to take it from there. Can anyone offer some advice? The size of the image is 1024x128 if that helps, which I think it might.

# Answer
You are creating a rectangular "viewport".
The first line sets the width and height of the rectangle.
The second line translates it to the correct tile.

If all of your tiles are 128 wide and the texture is 1024 wide then each tile is 128/1024=0.125=12.5% of the overall width and 128/128=1.00=100% of the overall height.

You can think of this as applying a "world matrix" to a unit square. You scale it down to the size of an individual tile, then move it to the correct tile.

(0,0):(1,1) * (0.125, 1) = (0,0):(0.125, 1) -Scale to tile-sized
(0,0):(0.125, 1) + (x * 0.125, 0) -Move to correct tile

The counter-intuitive part is that 1,1 is always the lower-left corner of the texture, regardless of it's dimensions. That means you can modify the texture any way you'd like without having to mess with the UV's again, as long as the new texture is divided into the same number of tiles. Increasing the input texture's resolution increases the resolution of the final tile rendering by cramming more pixels into the same "viewport" (0,0):(0.125,1).
In other words, an 1/8th of twice as many pixels is twice as many pixels

Adding a second dimension:

(0,0):(1,1) * (0.125, 0.5) = (0,0):(0.125, 0.5) -Scale to tile-sized
(0,0):(0.125, 0.5) + (x * 0.125, y * 0.5) -Move to correct tile
> 2 votes

---
Tags: unity, textures, texture-atlas
---