# Question
Title: Determining which edge of a box was clicked in Unity
How would I go about figuring out which edge of a box is clicked in Unity?

Quick image I created, colored in boxes represent edges on a face I would like to check for.

The current solution I have is half working. I create a raycast, check if it collided with a box, get the normal from the hit (to determine which side it collided with) & check if the point meets the criteria for X, Y, or Z (in the buffer zone, as outlined in the image). For example, if the raycast intersects the forward face I check that the point is inside one of the X buffers and not in one of the y buffers.

Currently only 2 sides on the forward / backward face work, as shown below

Finally, the related code.

```
void forwardMethod(RaycastHit hit){
    if(intersectsX(hit.point, hit.transform) && !intersectsY(hit.point, hit.transform)){

    }
    else if(intersectsY(hit.point, hit.transform) && !intersectsX(hit.point, hit.transform)){

    }
}

bool intersectsX(Vector3 hit, Transform transform){
    float buffer = transform.localScale.x * edgeBufferPercent;
    return hit.x <= buffer || hit.x >= transform.localScale.x - buffer;
}

bool intersectsY(Vector3 hit, Transform transform){
    float buffer = transform.localScale.y * edgeBufferPercent;
    return hit.y <= buffer || hit.y >= transform.localScale.y - buffer;
}

bool intersectsZ(Vector3 hit, Transform transform){
    float buffer = transform.localScale.z * edgeBufferPercent;
    return hit.z <= buffer || hit.z >= transform.localScale.z - buffer;
}

```

The buffer is equal to .15 if anyone is interested in that as well.

Any ideas? Am I approaching this wrong or is there a bug in my code I'm not seeing?

# Answer
> 1 votes
As Twyla mentioned, RaycastHit.point returns the world-space position. In order to get the local position of the hit point on the box, you have to transform the hit point with the inverse transformation of the box. You can do this by using `hit.transform.InverseTransformPoint(hit.point)`, where *hit* is the RaycastHit object.

To determine what side the ray hit, you can transform hit.normal to the local normal using `hit.transform.InverseTransformDirection(hit.normal)`. Once you have the local normal it's easy to determine what side is hit by checking which absolute value of the three components is largest, then check whether it's positive or negative. E.g. if the local normal is (-1, 0, 0), the left side of the box is hit, if it's (0, 1, 0) it's the top side.

Once you have the local position and know the largest component in the local normal, check if the other two components in the local position are in range of the edges. If x is the largest component, you check for y and z. If y is the largest component you check for x and z, etc.

Note: the way your code looks now, it seems like your box has it's center at `localScale / 2`. If this is not the case, and the box is centered around (0, 0, 0), you have to check if the components lie between `-localScale.xyz / 2 + edgeWidth and localScale.xyz / 2 - edgeWidth`.

# Answer
> 1 votes
Kind of a shot-in-the-dark here, but......

hit.point returns the world-space position of where RaycastHit impacted the collider. Compare that against the cube's position in world-space to produce a Vector3 relative to the cube's origin, then refactor for the cube's current orientation.

Whichever component of the Vector3 has the greatest magnitude indicates which side of the cube was hit.

Edit: Misread the question

You could do as above then normalize the Vector3. Check for absolute values above the threshold (probably around 0.85) for the two non-face axes to see if it's a valid trigger (to determine top/bottom or left/right), then +/- to single it out.

Just my own feeble attempt at the code...

```
using UnityEngine;
using System.Collections;

public class BoxMenu : MonoBehaviour
{
    private float threshold = 0.8f;

    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            RaycastHit hitInfo = new RaycastHit();
            bool hit = Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hitInfo);
            if (hit)
            {
                //
                //  Did we click on the target cube?
                //
            if (hitInfo.transform.gameObject.tag == "ClickTarget")
                {
                    Vector3 clicked = (hitInfo.point - this.transform.position).normalized;
                    //
                    //  Assuming we want the positive X face
                    //
                    //  Was the click beyond the threshold?
                    //
                    if(Mathf.Abs(clicked.y) > (clicked.x * threshold))
                    {
                        if(clicked.y > 0)
                        {
                            Debug.Log( "Clicked on top" );
                        } else {
                            Debug.Log( "Clicked on bottom" );
                        }
                    } else if(Mathf.Abs(clicked.z) > (clicked.x * threshold)) {
                        if(clicked.z > 0)
                        {
                            Debug.Log( "Clicked on right" );
                        } else {
                            Debug.Log( "Clicked on left" );
                        }
                    }
                }
            }
        }
    }
}

```

(I'm sure someone more proficient could give better details, but that's how I would approach the problem.)

# Answer
> 0 votes
You can detect the side of the cube via the following algo

```
public enum MCFace
    {
        None,
        Up,
        Down,
        East,
        West,
        North,
        South
    }

public MCFace GetHitFace(RaycastHit hit)
    {
        Vector3 incomingVec = hit.normal - Vector3.up;

        if (incomingVec == new Vector3(0, -1, -1))
            return MCFace.South;

        if (incomingVec == new Vector3(0, -1, 1))
            return MCFace.North;

        if (incomingVec == new Vector3(0, 0, 0))
            return MCFace.Up;

        if (incomingVec == new Vector3(1, 1, 1))
            return MCFace.Down;

        if (incomingVec == new Vector3(-1, -1, 0))
            return MCFace.West;

        if (incomingVec == new Vector3(1, -1, 0))
            return MCFace.East;

        return MCFace.None;
    }

```

Demo Video Bellow: https://dl.dropboxusercontent.com/u/53593879/ShareX/2015/05/2015-05-26\_20-20-16.mp4

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


title: Object Composition in the Unity Editor

text:
# Question
Title: Object Composition in the Unity Editor
I'm trying to learn how to use Unity for my class composition, and I was wondering if you could help me.

I'm trying to create a simple game where the player is trying to pop a bunch of balloons. However, any given balloon can only be popped if all of its conditions are met. Example conditions are:

* The player color must match the balloon color
* The balloon must be popped in sequence (balloon A must be popped before balloon C)
* The balloon is only pop-able during a certain time window

And I'm sure you could think of more.

Balloons can have 0 to many conditions associated with them, but they follow the 80/20 principle where 80% will fall into a specific category (e.g. color-match-only, or color-and-sequence-only).

**My Initial Solution**

I created a "Balloon" class that contains a list of "ICondition" interfaces. When a collision occurs, the balloon loops through each condition to determine whether the balloon is pop-able or not. I populate this list within a "BalloonFactory" class. For 80% scenarios I can just pass in the name of the balloon type I want. For 20% scenarios I can pass a list of conditions. This solution works, except for each new combination I need to change the factory code to include the new condition.

**What I'd Like to Do**

Instead of storing the balloon definitions in code, I'd prefer to create prefabs in Unity and use the editor to assign condition implementations to each balloon. My problem so far is that the Unity editor doesn't seem to like displaying a list of interfaces or abstract classes.

Is there some way to do what I'm trying to do here? Or is there a third option which you would recommend?

# Answer
> 3 votes
Your balloons are gameobjects right? I find that in general, adapting your ideas to how Unity works yields better results than hacking around the limitations. I use this component-based approach to do pretty much everything involving composition, and it's especially handy to change the behavior of objects on the fly or in the editor, without ever touching the code, by just manipulating components.

```
abstract class PoppingCondition : MonoBehaviour
{
       public abstract bool IsMet();
}

class ColorMatchCondition : PoppingCondition
{
       //Can edit in the editor.
       public Color Color;

       public bool IsMet()
       {
           //Logic goes here. Can use GetComponent<Balloon> to get its owner
           //and compare its color to the one set in the editor.
           //Your condition also has access to the usual Start, Awake, Update etc.
       }
}

class PoppingSequenceCondition : PoppingCondition
{
       //Can edit in the editor.
       public List<Balloon> BallonsThatHaveToBePopped;

       public bool IsMet()
       {
           //logic goes here
       }
}

```

Then you attach how many conditions you want to some balloon, via Add Component, and edit their properties normally in the editor.

Inside your balloons:

```
//Balloon.cs
bool CanBePopped()
{
     //True if all conditions are met, otherwise false. Your logic goes here.
     PoppingCondition[] conditions = GetComponents<PoppingCondition>();
     foreach (var condition in conditions)
     {
          if (!condition.IsMet())
          {
               return false;
          }
     }
     return true;
}

```

Of course, you can store your balloons together with their conditions inside prefabs. Or do pretty much anything else that you're able to do with gameobjects and their components.

Sample editor:

# Answer
> 3 votes
Some facts:

* unity supports serialization of polymorphic types only when derived from `MonoBehaviour` or `ScriptableObject`
* reference to Interfaces won't be took in consideration by the serializer, even if the actual instance is of a serializable type

Now, I often prefer programming against interfaces, so I faced similar problem several times (unfortunately not found a particularly elegant solution).

What I would do:

First of all I'll use a ScriptableObject asset to describe your `ICondition`. This allow several nice usage that, as far as I understood your use case, would be usefule, such as:

* despite a `MonoBehaviour` , they don't need a `GameObject` instance to be attached to
* you can **serialize** reference to them
* they support polymorphism
* you can share the same `ScriptableObject` condition across several classes

For how to store reference you have 2 possibilities:

**Inheritance**

Make your concrete `Condition` classes extend a common base class derived from `ScriptableObject`.

You can serialize the reference to the required assets. (I'd go this way in your case)

**Interfaces**

You can implement the ICondition interface from your ScriptableObject derived class, but to show them in the inspector, and allow a proper serialization and display you need to do some work:

* Somewhere in the referencing class you need a reference to ScriptableObject (or a serializable derived base class reference)
* You eventually need a custom inspector for checking assigned reference actually implements the required interface

I do something similar in my code, it looks like:

```
[SerializeField]
[IFace("IMyInterface", typeof(MonoBehaviour), typeof(IMyInterface))]
private MonoBehaviour m_refTo;

```

The attribute allow me to:

* writing a custom `PropertyDrawer` which enforce some costraints (es. when a drag&drop operation is performed it checks if the referenced component actually implements the interface)
* object is correctly serialized because serializer will take into consideration `m_refTo` (and supports polymorphic type, so every derived class will be displayed correctly)

You still need to cast `m_refTo` at some point (either on Start or during a SerializationCallback).

Hope this help

---
Tags: unity
---


title: Level Data with JSON

text:
# Question
Title: Level Data with JSON
I am doing level data for a game in Unity with C#

I have it in my game as

```
int[,] data = {
            {0,1,1,0,0,0,1,1,0},
            {1,1,1,1,1,1,1,1,1},
            {1,1,1,1,1,1,1,1,1},
            {1,1,1,1,1,1,1,1,1},
            {0,0,1,1,1,1,1,0,0},
            {1,1,1,1,1,1,1,1,1},
            {1,1,1,1,1,1,1,1,1},
            {1,1,1,1,1,1,1,1,1},
            {0,1,1,0,0,0,1,1,0}
        };

```

The *1s* draw the shape of the board.

I then have JSON like this:

```
{
    "level_01":
    {
        "tiles" : {
            {0,1,1,0,0,0,1,1,0},
            {1,1,1,1,1,1,1,1,1},
            {1,1,1,1,1,1,1,1,1},
            {1,1,1,1,1,1,1,1,1},
            {0,0,1,1,1,1,1,0,0},
            {1,1,1,1,1,1,1,1,1},
            {1,1,1,1,1,1,1,1,1},
            {1,1,1,1,1,1,1,1,1},
            {0,1,1,0,0,0,1,1,0}
        },
        "target_score": 1000,

    },
    "level_02":
    {
        "tiles" :
        {
            {0,1,1,0,0,0,1,1,0},
            {1,1,1,1,1,1,1,1,1},
            {1,1,1,1,1,1,1,1,1},
            {1,1,1,1,1,1,1,1,1},
            {0,0,1,1,1,1,1,0,0},
            {1,1,1,1,1,1,1,1,1},
            {1,1,1,1,1,1,1,1,1},
            {1,1,1,1,1,1,1,1,1},
            {0,1,1,0,0,0,1,1,0}
        },
        "target_score": 1000,
    }
}

```

I am aware that the JSON format is broken but lost on what to do to correct it.

Aside from that bit... how would I go about translating the properly formatted JSON to an int\[,\] in C#?

# Answer
> 2 votes
In "tiles" value, you should change all the curly braces to brackets. In JSON, curly braces mean an object, while brackets mean arrays.

Also about parsing JSON, once you actually have the content of JSON file (via reading the file for example!), there are lots of pure CS libraries to help you parse it. Json.Net for example.

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


title: Unified Aesthetics

text:
# Question
Title: Unified Aesthetics
I've been watching Extra Credits videos to learn concepts about designing video games and this one especially impacted me. It made me realize that the aesthetics of a game might have even more influence on players than the mechanics.

Basically, the video explains how a visual theme that immerses a player is better than any graphically superior one that does not - and how many successful games have visuals which work together to create the same world, while less successful games fall short there.

I've just prototyped a game for iOS based on 2048 and I'm not sure how to unify the aesthetics to make it more immersive for the player. In 2048, a plain board with tiles of interesting colors work well because the game is relaxing and simple but the one I'm making is fast-paced and twitchy.

Here are the webplayer link and some screenshots which show the gist of it.

I opted for a sci-fi theme because I think it suited the fast-paced feeling of the game. I'm not so sure about the progressive colors or the cube shapes though. *Sigh*, I already see this question getting too broad - sorry I'm not very experienced with this subject.

What I'm asking specifically is for feedback concerning the visual synergy between the number cubes, obstacles, and vector grid. With these 3 elements, how can I modify, add, or remove pieces to make the world of the game seem consistent?

If you have any in mind, recommended articles or other resources about game aesthetics would be very helpful as well.

# Answer
Panda Pajama is definitely correct about having to take the time and possibly money to learn a depth knowledge of art. But, it really can depend on the complexity of your game. You will have to oversimplify things if you don't have the art skills. Many games do this.

Here is a VERY brief and general article on some things to know when designing for aesthetics in games. http://www.gamasutra.com/view/feature/185676/the\_aesthetics\_of\_game\_art\_and\_.php?print=1

This may be obvious, but another good way to learn is to just take a few art classes, specifically at a well rated technical game development and design school. I feel every developer should take a few art classes, it makes you a better developer because you think of these things in the back of your mind while you are programming/developing. It promotes creativity. It also saves headaches in the long run.

Good luck!
> 1 votes

---
Tags: user-experience
---


# Question
Title: Android Density Independent Pixel Drawables Resource Folder
I'm trying to get to grips with DIP in Android (using Eclipse). I'm writing a little game with OpenGL ES 2.0. Could I get some guidance and tips on what I'm not understanding/doing right.

From what I understand I need to make different sizes of the same image so that they appear correctly on different devices. This is because each device has a different aspect ratio and a 1cm by 1cm sprite on one screen might not be 1cm by cm on another screen.

I read here that I need to place my sprite images in the res/drawables folders. I did this, but when I try to reference the resource using:

```
    mySpriteTexture = new Texture(context, R.mysprite);

```

the R class fails to find the .png. I have tried cleaning, rebuilding etc., and tried variations like R.res.mysprite. Although I don't see the point in trying R.res.drawables-XXX as according to the article Android is meant to pick the correct images on running...

I think it must be something to do with the XML manifest? But I have no clue. Any help would be welcome.

# Answer
> 0 votes
Use `R.drawable.myprite`. Android will choose the correct size image from those available in the drawable-XXX drawers.

---
Tags: android, opengl-es2
---


# Question
Title: Ways I can identify fraudulent customers / users for an upcoming game?
I'm trying to figure out ways I can identify potential fraudulent customers and users for an upcoming project. Similar to how major game publishes track and detect users who "hack" or "bot".

The only thing I could find regarding ways to track someone is by: Cookies IP Mac Address

Any information is greatly appreciated.

# Answer
> 2 votes
You can enact some things locally on the client, and it might fend off those that don't want to spend the time to get around it, but there is no way to truly stop people from breaking apart your game (creating and sharing cracks or serials, etc.).

The best that you can hope is that you create a system that deters common skiddies.

With that said, the best way that I would think to get around this is to have a server authenticate the client; So when the game is played, the client needs to check in with a server. Much like anything else, this can be bypassed by a multitude of ways (ranging from sending a phony authentication, or even bypass the server altogether). If you have the client 'phone home' when it is run, you can also make note of characteristics of the computer that is running it (ip, mac, computer name,... whatever); However, as with anything... these too can be forged or emulated. --- also be careful about storing PII like someones IP, the legality and practices behind that vary from place to place.

In the case of using an authentication server, if two players with the same game serial number (or account/cd key/etc.) logs in, then you can respond to such an event (banning that serial for instance, or showing a warning).

If I had any parting words, they would be to say that piracy is a huge issue (in quantity and magnitude) for a reason --- it is nearly impossible to eliminate, the best that anyone can hope for is to mitigate it.

---
Tags: security
---


# Question
Title: What is an acceptable receive rate for a client?
I've noticed that syncing a transform( in Unity, so a Vector3, and a Quaternion ) ends up being close to 1000 byes per second received on a client( send rate of 20hz ). Multiply this by a generous 20 entities a single match might have and that's about 15k-20k bytes per second.

Is this too much? What should I be aiming for? What data rates do games typically have?

# Answer
Shawn Hargreaves wrote few slides for Xbox live gaming, concerning latencies, you can check the full presentation from here

> Bandwidth - How much is available? Assume 64 kilobits (8 kilobytes) per second

0.5 Mbit/s ADSL has theoretical limit of 64kbs
> 2 votes

---
Tags: unity, networking
---


# Question
Title: What is a good way to code dialogue creation?
I'm thinking of making a single method/class/something that will handle my dialogue in the game. AKA, something like:

Main text:

Choice 1
Choice 2

So I want a method that will able to put different strings into the main text section and also different strings into the Choice options. I've been thinking about solutions, and so far I've come up with just a simple method that accepts parameters for main text, choice1 and choice2 -- problem being that the strings called will be quite long and I think it looks a little clumsy? Also I won't want to have 2 choices every time, OR I want to have multiple "pages" of dialogue show up before you need to take an action. This would require me to overload methods which may turn out quite ugly?

So yeah I don't have a lot of experience with this and method overloading is all I've thought about for now. I've given thought to interfaces/abstract classes but I'm not entirely sure if they're even relevant for what I want to do. Any thoughts?

# Answer
> 2 votes
I suggest to use a tree (graph) class aproach. Place Main text into nodes and choise text into arcs (arrows)

Multi page Text can placed into sequential nodes with only one choice arc ("Next page")

Rough c# implementation:

```
public class DialogueArc {
    public String Text { get; set; }
    public DialogueTreeNode outgoingNode;
    public DialogueArc(String text, DialogueTreeNode N)
    {
        Text = text;
        outgoingNode = N;
    }

}
public class DialogueTreeNode
{
    public String Text { get; set; }
    public List<DialogueArc> Choiches = new List<DialogueArc>();
    public DialogueTreeNode(String text)
    {
        Text = text;
    }
    public void AddArc(string T, DialogueTreeNode N) {
        Choiches.Add(new DialogueArc(T, N));
    }
}

```

Dialogue creation example:

```
    //define nodes
    DialogueTreeNode Root = new DialogueTreeNode("First Page dialogue....");
    DialogueTreeNode RootPg2 = new DialogueTreeNode("Second page dialogue....");
    DialogueTreeNode RootPg3 = new DialogueTreeNode("third page page...");
    DialogueTreeNode afterCh1 = new DialogueTreeNode("After choice 1..");
    DialogueTreeNode afterCh2 = new DialogueTreeNode("After choice 2..");
    DialogueTreeNode afterCh1Ch1 = new DialogueTreeNode("After choice 1_1..");
    DialogueTreeNode afterCh2Ch1 = new DialogueTreeNode("After choice 2_1..");
    //define choices
    Root.AddArc("Next page", RootPg2);
    RootPg2.AddArc("Next page", RootPg3);
    RootPg3.AddArc("Choice 1 txt", afterCh1);
    RootPg3.AddArc("Choice 2 txt", afterCh2);
    afterCh1.AddArc("Chise 1_1 txt", afterCh1Ch1);
    afterCh2.AddArc("Chise 2_1 txt", afterCh2Ch1);

```

---
Tags: unity
---


# Question
Title: UnityException: Unable to install APK! Installation failed. See the Console for details
I got this error message when trying to build and run on Android actual device.

```
UnityException: Unable to install APK!
Installation failed. See the Console for details.
UnityEditor.Android.PostProcessAndroidPlayer.ShowErrDlgAndThrow (System.String title, System.String message, System.Exception ex)
UnityEditor.Android.PostProcessAndroidPlayer.ShowErrDlgAndThrow (System.String title, System.String message)
UnityEditor.Android.PostProcessAndroidPlayer.UploadAndStartPlayer (System.String manifestName, System.String stagingArea, UnityEditor.Android.AndroidDevice device, System.String packageName, Boolean devPlayer, Boolean retryUpload)
UnityEditor.Android.PostProcessAndroidPlayer.PostProcessInternal (BuildTarget target, System.String stagingAreaData, System.String stagingArea, System.String playerPackage, System.String installPath, System.String companyName, System.String productName, BuildOptions options)
UnityEditor.Android.PostProcessAndroidPlayer.PostProcess (BuildTarget target, System.String stagingAreaData, System.String stagingArea, System.String playerPackage, System.String installPath, System.String companyName, System.String productName, BuildOptions options)
UnityEditor.Android.AndroidBuildPostprocessor.PostProcess (BuildPostProcessArgs args)
UnityEditor.PostprocessBuildPlayer.Postprocess (BuildTarget target, System.String installPath, System.String companyName, System.String productName, Int32 width, Int32 height, System.String downloadWebplayerUrl, System.String manualDownloadWebplayerUrl, BuildOptions options, UnityEditor.RuntimeClassRegistry usedClassRegistry) (at /Users/builduser/buildslave/unity/build/Editor/Mono/BuildPipeline/PostprocessBuildPlayer.cs:316)
UnityEditor.HostView:OnGUI()

```

Why it happens? Please advice. Thank you.

# Answer
Presumably you hit "Build and Run"; that will cause Unity to first generate the APK, and then attempt to automatically install that on the connected device. Personally I recommend "Build" to just generate the APK and save it somewhere; then you can install it yourself after the APK is generated.
> 1 votes

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


# Question
Title: Is it possible to run GLFW eventhough my graphic card(Nvidia) supports Direct3d API?
I have Nvidia 820M GPU installed in my windows 7 machine. In nvidia control panel it is showing it supports Direct3d API version 11. Am I able to run OpenGL applications(using GLUT,GLFW) on my machine with this configuration? see the below screenshot for configuration details.

# Answer
Yes, you can easily do it. Modern video drivers (almost) always come with OpenGL support.

DirectX 11 requires same hardware as OpenGL 4, so you will probably get at least OpenGL 4.3.

---

Based on these statistics, and this information about equivalence of hardware requirements between different OpenGL and DirectX versions, we have approximately these numbers:

`OpenGL 1 works everywhere,`
`OpenGL 2 works on ~99.5% PCs,` (I've recently seen an old PC without OpenGL 2 support, but they are rare.)
`OpenGL 3 works on ~85% PCs,`
`OpenGL 4 works on ~40% PCs.`
> 2 votes

# Answer
You can use glviewer to see which version of OpenGL your graphics card supports and which extensions are available to use.
> 0 votes

---
Tags: opengl, directx, graphics, graphics-programming
---


title: Drawing text with Slick

text:
# Question
Title: Drawing text with Slick
I've been trying to draw a text to the display using **Slick**. However, when ever I draw the `TrueTypeFont` to the screen, it draws it reversed upside down and also, it makes the whole display turn black.

This is only a piece of the entire game code, I think this is enough to explain the problem though. I'm new to LWJGL and Slick so this is probably a stupid question.

```
public Game(String name, int width, int height)
{
    this.name = name;
    this.width = width;
    this.height = height;

    try {
        Display.setDisplayMode(new DisplayMode(width, height));
        Display.setTitle(name + " " + version);
        Display.setResizable(true);

        Display.create();
    } catch (LWJGLException e) {
        e.printStackTrace();

        Display.destroy();
        return;
    }

    TrueTypeFont font;
    Font awtFont = new Font("Arial", Font.PLAIN, 24);
    font = new TrueTypeFont(awtFont, false);

    Player player = new Player(this, 32, 32);
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    while(!Display.isCloseRequested())
    {
        glClear(GL_COLOR_BUFFER_BIT);
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        glOrtho(0, width, 0, height, -1, 1);
        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();

        drawBackground();

        player.update();
        player.draw();
        font.drawString(50, 50, "Platform");

        Display.update();
        Display.sync(60);
    }

    Display.destroy();
}

```

**Edit:** After doing what @Katu said, I changed `glOrtho(0, width, 0, height, -1, 1);` to `glOrtho(0, width, height, 0, -1, 1);`. The text is not reversed upside down, but the black screen is still there.

The screen should look something like this. (**NOTE:** It's an edited image)

# Answer
> 1 votes
Change

```
glOrtho(0, width, 0, height, -1, 1);

```

To this:

```
glOrtho(0, width, height, 0, -1, 1);

```

> A quick little understanding about why your font wasn't working (if you don't already know), glOrtho is called like this:

```
glOrtho(double left, double right, double bottom, double top, double zNear, double zFar).

```

> This being said, you had the bottom set to 0 where it should have been set to the display's height or a custom bottom if necessary and that is the reason why the text was facing the top of the screen or rather, being drawn up-side down.

I collected this answer from these:

---
Tags: java, lwjgl, slick
---


# Question
Title: how to rotate a sphere around centre (x y z)
I have centre of sphere at x y z. now I want to rotate any point (a b c) on the sphere about centre. how can I do it in c++.

# Answer
You need to first translate the center of the sphere to the origin, then rotate it, then translate it back to its original position. You can do all 3 of those by constructing a single matrix.

The glm library has several classes that make this easy to do, and it has reasonably good documentation. If you're using OpenGL, it's very similar to glsl's data types.

You could do something like this:

```
glm::mat4 transform = glm::mat4(1.0);
transform = translate(transform, glm::vec3(-center.x, -center.y, -center.z));
transform = rotate(transform, angle, glm::vec3(0.0, 1.0, 0.0)); // Assumes up is y-direction
transform = translate(transform, glm::vec3(center.x, center.y, center.z));

```

Then pass each vertex or coordinate of your sphere model through the `transform` matrix, like so:

```
rotatedVertex = transform * vertex;

```

If you're using OpenGL, you can use the matrix as your modelView matrix for the sphere, for example.
> 0 votes

---
Tags: c++, sphere, rotate
---


# Question
Title: Overriding all object inspectors in Unity
How can this be done? I want to add a single label to every component( including non-misbehavior ones ) in the inspector. I've tried:

```
[CustomEditor( typeof( Object ) )]

```

And:

```
[CustomEditor( typeof( Component ) )]

```

This seems to work for all components that don't seem to have a custom editor already( like BoxCollider, and Transform ). It seems if a component has a custom editor already, it ignores the one I've defined. Even if I change the attribute to this:

```
[CustomEditor( typeof( Transform ) )]

```

There is still no change to the Transform inspector. How can I define my own custom editor for these components?

# Answer
> 1 votes
Using the CustomEditor attribute should certainly work for the Transform component.

I have my own custom editor for transforms to make resetting them a bit easier.

By creating the following CustomEditor you will notice that the localRotation changes from displaying three values that represent the Euler angles (x, y, z) of the rotation quaternion to the 4 values (x, y, z, w) of the underlying rotation quaternion. This is because Unity is now using the CustomEditor which is empty and just shows the raw transform data structures.

```
[CustomEditor(typeof(Transform))]
public class TransformEditor : Editor
{
}

```

To implement your own custom inspector make sure you override OnInspectorGUI() and place the relevant code there.

As you ahve said you will need to follow this approach for each component that already has a default Custom Inspector set up.

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


# Question
Title: How can I make backtracking interesting?
When a player navigates a space for the first time, it is very interesting: the content is new, the dangers are unknown, paths need to be found. However, various situations force the player to backtrack, or navigate the same space multiple times. Perhaps the level designers are being economical, or trying to build familiarity with a space. Perhaps the game itself is open-ended, or like a sandbox, where navigating the same spaces is part of the game itself. These can make the same spaces seem tedious and sparse.

Given that backtracking (or navigating the same space multiple times) is unavoidable, what are some effective, economical ways of making it interesting? Please keep in mind:

* We are reusing levels deliberately, either for effect or to save on cost. Therefore modifying the levels beyond recognition would be against our intent.
* We also cannot modify the gameplay too much; if we were attempting to save cost by reusing levels, incurring more costs by adding gameplay would be counterproductive.

One quick-fix I had in mind was to give the player some sort of powerup or vehicle so that they could backtrack faster. I'm sure there are better methods, and examples of games where they were used.

# Answer
> 28 votes
One thing I liked about the backtracking in Super Metroid is how your new powers allowed you to get through the areas faster, but in a more challenging way. Another way is to place items such as health upgrades (or obvious switches/breakable blocks) in plain sight but out of reach until you come back in possession of another item. The best example of this is the first part of the lower area of Brinstar, where at first you have to take your time carefully jumping through waist-high water and avoiding invincible enemies. When you come back to that area, you have the Ice Beam which allows you to freeze the enemies and use them as stepping stones to quickly traverse the water, and of course you eventually get the Gravity Suit.

A different game that makes backtracking interesting is Dark Souls. The difference with Dark Souls of course is that you aren't usually locked off from areas, it's simply that the enemies are too high-level and thus will be hard to kill. When you first come to Anor Londo, there are a bunch of Sentinels standing around that don't get easily aggro'd, although some guard chests. At that point, most players won't be able to really take them on, so they are ignored. When you come back to go to the Duke's Archives, you can take on the Sentinels and claim the treasure. The same goes for Blighttown when you need to go to the Demon Ruins: it becomes much easier to explore the rest of the swampy area and you can find the Great Hollow. At the same time, power players (like me) will have already explored these areas and removed the need for backtracking by enabling warping to the areas that are weren't opened yet. There is of course also the optional revisit to the Asylum, in which the area is repopulated with tougher enemies and a heinous trap is placed.

# Answer
> 14 votes
You said that modifying the level beyond recognition is out of the question, but what about only small, randomized modifications to levels?

This can be in form of events which only have a certain chance of happening whenever the player traverses the area. When there are multiple such events which also interact with each other, it will result in a slightly different experience everytime the player passes through the area.

One game which does this with an interesting effect is The Stanley Parable. The gameplay of this game is based on lots and lots of branching paths, and after trying one path through the game, the game resets and the player can make different choices and see what happens. That means that the starting area of the game is traversed many, many times. To make this a more interesting experience (and to confuse the player even more), this starting area has a certain probability to have some random but meaningless changes. Corridors change their length, sections are added, removed or replaced, or rooms suddenly have papers all over them.

Such completely unexpected and unexplainable changes would of course not work in a game which isn't as abstract, meta-referential and intentionally confusing as TSP, but there are other, more plausible things you can have to make your game world feel more alive.

In a hostile area, you could have enemies which only spawn with a certain probability or have different positions in which they can spawn. That way the combat experience will be a bit different each time the player passes through the area.

In a friendly area, you could have background events happen or not happen with a certain probability or spawn NPCs which approach the player with a certain probability during each pass-through and say something which might or might not be important.

# Answer
> 11 votes
One thing I hated about backtracking in Metroid Prime was how when I first came across something new and interesting, *I couldn't tell if I had the tools to interact with it or not*.

I'd leave, hoping I'd get the tools later. But then I'd hit a dead end. Then I'd wonder if I had the tools to navigate the dead end, if I was missing something, or if I had to go back to the previous place I was unsure about. This led to lots of aimless wandering; so I quit playing.

Personally, I find it wrong to show the player something before he can do it (unless it's painfully obvious they can't do it, like what's that little hole at the bottom of the drain pipe in Banjo Kazooie? Braid only made this mistake once, and I thought it made a huge difference to its flow. It meant that if I couldn't figure something out, it was because I had more thinking to do, not more wandering (or trying to figure out if I had to wander or think)).

If you're going to reuse level geometry by making the player traverse it multiple times, it is my opinion that this should not be done in such a frustrating way. Halo did this well in certain places. Like when you were going back through a bunch of levels you already traversed, but this time by flying. There was no presentation of something that you thought you could do but couldn't, but they still found something interesting to do when going back through.

# Answer
> 7 votes
In Portal, the developers intentionally introduced back tracking into the game.

They did this for a couple of reasons:

* Player Immersion: It happens after you have broken out of the initial portion of the game and have been running around 'behind the scenes'. Bringing you back reminds you that you are still stuck in the facility, still 'in' the game. It also allows the recognition of the area for the player and crucially, prevents the player from feeling like they are just following a long linear corridor.
* Show the effect the player is having on the environment: Due to the players actions when entering the room, the player can't progress in the same way that they did before, and so they intact more with the space.
* showing the player that they have changed and how it opens up more opportunities for them. In this case by subverting the previously established rules for the area.
* it allows the player to feel smart: it's a great example of fridge brilliance. How? Well the player exits the room by descending am empty lift shaft. How is that brilliant? Well the astute will have remembered that unlike every other lift in the game, the first time the encounters this lift, it was not already there but was arriving late as you arrived. The second time around our doesn't make it all!
* Forshadowing: By having the lift arrive later, it gives a glimpse at the world outside of the whitewashed walls of the test centre (sorry: Aperture Science Computer Aided Enrichment Centre,hinting that you will soon be running around outside the trading environment. That it is also Forshadowing an actual escape route that you actually take later in the game is just an added bonus.
* Added collectables. A patch of the game shortly before the release of the sequel added radios hidden in most of the areas of the game, including that room. This led to players voluntarily backtracking through the entire game to collect them.

Wow. That's quite a lot for one simple room. How does it help you?

* Backtracking can make your world feel more real. A comfortable area (Say an NPC town could act as a 'home' for the player and/or a hub that connects you to different areas of the game.) lets the player become familiar with the area, and thus more connected to the game. Having it as a hub lets you reduce the time taken to backtrack between different areas, and so also reduces player frustration.
* Have hints in areas that only become more apparent or meaningful when passing through an area again. That first time through, the castle on the hill looks like a nice bit of scenery. Coming back through, you know that it is the home of the "big bad" and you will have to make your way there in the future - possibly by returning to the area again!
* Change your area over time, either by player or npc actions. This can be purely visual; town attacked = some buildings with burn marks/missing thatched roofing etc, or you can take the opportunity to totally change how the player interacts with the environment; same town, but after more attacks, makeshift barriers have been constructed from the scenery (maybe from a cart / street furniture that was already there, but have now been moved). Bonus points for having the player *help* with the change.
Another alternative is to have NPCs introduce items to the game: The first time on a coastline for example, you see a beach from a cliff. The next time you go down to the beach. The third time *(yawn, again?)*, a ship suddenly appears and offloads warriors for you to fight. You pass through again and the ship is still there - it is persistent. you can explore it etc. Later on, you find you need a ship to enable you to progress - Oh look, there was that one on the beach a while back. Lets go back (again) and commandeer it.
* Use the changes to introduce new things for the player to *do*, be it finding bonus collectables, opening up new routes or discovering new ways to interact with the environment. You don't need to make big changes, keep it subtle.
* If all else fails:
Massive changes. You've crossed the plain and navigated through the temple to get to the tower of Babel. Going into the tower, you have an epic quest and end up with it coming down around your ears. What now? you need to go back through all that space to get back to somewhere meaningful. Wouldn't it be nice if there was a new area you could pass through to progress? Well, there can be. What happened to the tower? Introduce it to your environment, it blocks off routes that were there before, can crush obstacles that blocked you and open new routes. It can even be a new route itself; introduce familiar rooms from the tower, only in a new orientation that provides a new challenge to traverse. or use the outside of the tower - get up on and run along it to access new areas / shortcuts that didn't exist before.
One key thing to note is that the changes don't actually have to be massive in terms of added content, but they should be in your face and provide new ways of using what is already there - design your original levels with the changes in mind.

Good luck! I don't know your genre, so I tried to keep this *fairly* generic.

# Answer
> 4 votes
There has been a lot of suggestions in terms of powerups, time decay and ETC. My opinion is a mixture of all of these elements to form a living breathing world that can be both cheap and expensive for development depending on the level of complexity and scale.

However, there has been too much emphasis on going backwards. It's not just about going back, but actually going forward too. Let me explain.

**Living Breathing World**

Depending on the game, having a living breathing world is a key feature to consider. That's because no matter what direction you are going as a player, living and breathing worlds are always changing.

Instead of thinking of a solution to solve going backwards through a static dimension, think about how life flows in both directions. Dynamic changing events enhance both directions, which fill a game with events that can enrich a gameplay session.

This can start with simple dynamic gameplay events or triggers. That no matter the direction, provide a dynamic event for the player under certain conditions.

For example, if a player is traveling through a world zone that is outside, a trigger based on time could include elements of new music, new sound effects and a sunset that sets the mood of the zone during that particular time (i.e.: World of Warcraft).

Another example, if a player completes a certain quest, dialogs in both towns that have been visited and new towns that have to be visited include new dialog (i.e.: Skyrim).

One more example, visiting certain areas during world changing events provides a sense of player driven change such as what you expect when conquering a new universe. NPC guards now hail to a new faction, security statuses have changed and wars have begun (i.e.: Eve Online).

**Dynamic**

I focus on dynamic events because so much can be designed around them. It doesn't matter if you're doing a simple side scrolling game or a robust online game. Dynamic events breathe life into a game that is unexpected and diverse for all players that experience them. Particular focus can be applied to both new and old encounters. That means going forward and backwards can entail a set of dynamic events that really add a unique touch to the game.

I for one, enjoy change as I progress through a game. As time goes on, age and even seasons of the world make the game that much immersive. Seeing a house that was once standing during my first visit, then it burnt to the ground in my next visit is rewarding (i.e.: Fable).

Seeing the seasons change as the game time changes is also equally rewarding, even during revisits. Seeing a christmas tree erected in the main square or simply experiencing snow or fall is equally rewarding in both new and existing visits (i.e.: Guild Wars).

**Solution**

Therefore, I think to key to all the suggestion is a living breathing world that is built off dynamic events or triggers.

# Answer
> 3 votes
What you are talking about is not easy to do.

If you are going to send the player back through an area then you can still make a lot more game experience there by making new things happen on their journey back. Consider the original Halo where the second half of the game was effectively a fight back through the locations of the first half, but confronted by new enemies. This approach makes effective reuse of the environments *but* it was not without it's critics in Halo and doing it well is certainly difficult. You should be able to up the difficulty on the return journey so that players benefit from knowing the terrain somewhat. On a two-way trip you could also make certain rooms and power ups available on the way back that were not available on the first journey true, as mentioned in other answers.

If you are thinking of having more of a sandbox setting, then giving the players ways of jumping to the general area they are aiming for is helpful- the various Zelda games do this in fairly useful ways, giving the player a horse or a bird for faster travel at a certain point. You still move through the same areas often, but you can at least get to them quickly. The Elder Scrolls games do something similar with Fast Travel, allowing you to quickly return to a location you have previously visited. In both cases dropping you in the right area does not stop you from having to revisit places you previously passed through once you get there, so the content is re-used effectively.

# Answer
> 3 votes
There are several techniques that can help improve player experience.

**Rule 1 - Inaccessible areas:** Make it impossible for the player to explore all of the area first time round. If backtracking is an intentional part of the game, making sub-areas of a location inaccessible first time round is an excellent way to stretch out the interest in the area. When the player then has to backtrack, the newly accessible area makes the familiar location seem new. It's like moving out of your house while an extension is built and then coming back home to enjoy it.

**Rule 2 - Character scripting:** One of the most underused techniques for revamping old areas is to change what the characters say. When the player returns and speaks to an NPC, only to find that NPC's former throwaway dialogue has been replaced with new, interesting lines.

One good way to revamp dialogue is to make the NPC comment on recent events that have happened within the game world - maybe an evil organisation was overthrown, maybe there was a dragon attack in some far off town, maybe the town mayor celebrated his birthday, maybe the weather has changed. Not only does this add interest, but it has the secondary effect of fleshing out NPCs by making them seem aware of what's going on around them. This in turn makes the game feel more immersive because it reflects reality - humans are constantly talking about current events. Now is the best place to be.

To take this slightly further, if an NPC knows the player by name, they should absolutely express how much they have missed the player (or even their displeasure that the player is back). A friendly NPC would also ask questions about where the player has been and what they've seen on their travels, particularly things relating to that NPC's interests.

**Rule 3 - Expansion of shops:** In many games (RPGs in particular) items are constantly won, bought and sold. Coming back to a location and finding that the variety of a shop's goods has been increased is always nice, particularly if the items are new to the player or even if they just weren't available from that shop before.

**Rule 4 - The effects of time** If the player has been away for any significant length of time, it's a good idea to show the effects of time on the world and the characters within it. Characters age, they grow, they get new clothes, they injure themselves, they get diagnosed with poor eyesight and now require glasses. Buildings age, ivy and vines grow on them, the exterior tarnishes and gets weathered, glass gets broken, tiles fall off. Trees grow, flowers grow, graves are dug, rivers dry up, rivers expand, bridges are built. Life does not stop because the player leaves, the rhythm of life is a powerful beat.

# Answer
> 2 votes
The best approach to backtracking to make the player feel like the area they are backtracking through has progressed slightly timewise. Were there two NPCs arguing in the village? Have them in a fistfight when the player backtracks. Did the player destroy a wall? Crumble some of the infrastructure around to show the damage they did. Did they summon a blizzard? Add snow to the ground.

These little tidbits keep a players interest in already familiar territory while saving you the need to remake a fourth forest area when they just went through a third. It also gives the player the impression that time is occurring around them, something a lot of games fail to convey.

Other fun ideas:

* Use a filter to make it night, twilight or dawn.
* Change the location of enemies to keep the player guessing
* Put a repair man NPC in the level trying to scrub the laser burns off the wall.
* Add 'battle damage' to certain location where tough battles would have occurred.

# Answer
> 2 votes
Time! Let the environment develop over time. Time is a resource that's missed by pretty much all games throughout time and genres. Small, random, changes to the environment, over time, can lead to massive changes. Letting time and some randomness guide the development of the games environment also increases replay value and it can do so quite a lot, depending on the type of game.

Allows NPCs to change the environment or react to changes imposed by any character -- then provide rumors to the player and tell them about (some of) the changes. Introduce grudges between characters, let characters die (and be sure to pass on any game functions from the character to someone else -- maybe in a different area) or just move them about.

Only having small, static, changes tend to make it seem like the developers have done a half-arsed job about it.

Suggesting that it's possible to do anything to keep backtracking interesting without spending resources on it is naive. Any change to a game will require some resources and making backtracking interesting is going to require that you either redo maps or introduce new features (or both). Being able to traverse an area you have already been in faster than the last time doesn't make it more interesting. It just shows the player that they where forced into an area for no really good reason; if you're not adding anything to the environment, you should just let the players skip it entirely.

# Answer
> 1 votes
If you have design space for platformer elements, you could create topology that makes moving backwards a different problem than forwards. For example, lots of jumps and tricks to get to the top of a cliff such that getting back down without falling to death is distinctly different. You might try doing this passively via gravity (ex. jumping to platform slightly lower, creating a one-way gate), or more actively by changing the actual state of obstacles. (ex. oh no, the elevator is out of order now, because a dinosaur attacked it.)

Basically, the space is the same, but spatial navigation problems are different because the objective has changed.

# Answer
> 1 votes
Two approaches I think help were used in 1996's Duke Nukem 3D.

1. Provide multiple routes to get to a key location. In the first level of the shareware episode, you need to get into the projection room of the cinema to get the red keycard. You can get there either by going up the stairs from a door in the lobby, or by going through the air vent in the toilets, which also lets you find a secret room, the door of which opens into the projection room. You can use either route to get in or out of there.
2. Spawn enemies when the player does something vital, so they have something to do on the way back. Quite a few levels have enemy spawning tied to either flicking a necessary switch (such as one to disable a forcefield) or by an invisible touchplate floor in a key area. Either way, the level designer includes enemy spawners linked to those switches, so areas you cleared out the first time won't be clear on your return.

Similar to number 2, you could also trigger one-time phenomena which cause changes to the level architecture. E1L5 is a good example of this with the game's earthquake mechanism being used to open up new paths and change the slope or height of existing ones.

Secret places can also make things interesting. The player might miss them on the first trip, but spot them on the second. This is particularly likely if they were on walls which would have been facing in the same direction as the player's movement on the first trip, but which they'll get a better look at on the second.

# Answer
> 0 votes
You don't necessarily have to change the rooms themselves if you can change what objects are *in* the room when the player backtracks.

As a quick example, one of the lairs in Neverwinter Online has a room that's basically empty (although it has two locked doors). As you advance through the lair, you encounter a boss that drops a key, and the door behind the boss was one of the locked doors in the empty room... but now the room is full of enemies! And, of course, the key dropped by the boss grants access to the remaining locked door once you dispatch them.

Because you enter the room from a different entrance than you have before and because the room has enemies where it had none before (especially since the game has already trained you that the rooms you've passed are going to necessarily be clear of enemies), it took me a little while to realize I had backtracked at all!

# Answer
> 0 votes
After reading Philipp's post about changing environments in The Stanley Parable, I am reminded of Quake II.

While Q2 is very linear (age of Duke Nukem 3D, Shadow Warrior, etc... style FPS), at one point the player passes through the Pumping Station, only to revisit it after the next level. When the player is revisiting the level, they enter through an area not seen before (nor accessible their first time through), briefly passes through a familiar part of the level, and exits through another inaccessible area.

A couple interesting things to note:

* The part of the level the player passes through - that they *are* familiar with - has some new decoration. There are barriers set up, and there are new enemies present to hinder the player's progress.
* The part of the level the player ultimately exits through is somewhat visitable (though locked) their first time through. It gives a sense of a future possibility to revisit and interact with later.

These are things that can give a game a bit more "life" - it gives the illusion that the Strogg - the enemies the player faces - are sentient and aware of the player, and their progress through their facilities. E.g.:

"Curse this human invader! They've torn through \[levels a, b, c, ...\], decimated our warriors, and destroyed our factories! They must be stopped! Recently, we noticed they passed through \[zone N\] to get to \[zone M\] - too bad for them! \[Zone M\] is a dead end, and they'll have to come back through \[zone N\] eventually! We'll set up an ambush for them as they make their return."

Giving players something to see - but not reach or interact with *(yet!)* \- can add to the excitement and immersion as they make their way through the game. They know they'll come back to it later, and be able to do something about the obstacle, or say "Hey! This is that pathway I saw from the cliff two levels ago! I know where I am *now* relative to where I was *then*!" - and reminisce about their adventure(s) between the *then* and the *now*.

---
Tags: game-design, level-design
---


# Question
Title: How to Render and Blend Multiple Frames to a Buffer in Unity?
I was wondering if anyone knew how to render multiple frames from a camera or texture to a buffer in Unity and to then blend them together? Is this possible? If so how would I go about doing so in Unity?

# Answer
> 1 votes
The Image Effects source code should give you a good idea how to render into a render target. You can import the package and look through the source code to get an idea of how they happen.

The basics are:

* render a quad that covers the full size of the render target
* the shader does the blending you're talking about by using the previous render target texture(s) as input
* the output goes into a new render target, which can then be used as input for the next

---
Tags: unity, frame-buffer
---


# Question
Title: Unity3D: collider performances on mobile iOS devices
I'm experimenting with `Unity3D` and colliders. Unfortunately I still don't have `Unity Pro` version and I can't use the profiler.

Consider the following situation:

* mobile devices (ios, iphone 3GS).
* an infinite runner game (consider something like agent dash or temple run). The player run along its path collecting bonuses and possibly hurting obstacles.
* the number of objects along player's path is very high.

The first simple approach is to use a rigidbody with a collider attached to the player (let's say it could be even a shere collider) and use a collider for each object in the scene (coins, obstacles, bonuses,...) .

AFAIK, using hundreds of colliders could have a serious impact on performances,specially on mobile devices, am I right?

So here's some questions:

* In the situation described above, is that feasible use collider to detect objects collectable by a player running along a path?
* Could be a better idea to store the location of the collectables objects inside some kind of data structure and completely avoid to use Unity collision detection?
* What's a reasonable average number of RigidBody/Sphere Collider that can be used in a single scene on a mobile device?

Does anyone has implemented something similar? Could you suggest me the right way to go?

# Answer
> 0 votes
Before I answer this question here's a quick idea of how I would go about implementing an infinite or endless runner.

I have worked on a couple of endless runners and they have both worked in the same way. This isn't necessarily the only way to do it but it is a way that has been proven to work.

You can create generic sections of a level that contain geometry (such as the ground, maybe some buildings and so on). These sections will also contain a spline (path) fragment. In Unity these would probably be saved out as prefabs and placed in Asset Bundles or under the Resources directory.

At runtime you would then create a number of these sections and stitch them together. (Some pieces might not fit with each other so you will need some way of recording which pieces can fit with whichother pieces - this would be some sort of offline process in the editor). Once your character has cleared a section that section will be destroyed and a new one will be created at the end of the currently loaded sections.

Now to answer your question about colliding objects:

> In the situation described above, is that feasible use collider to detect objects collectable by a player running along a path?

It would be perfectly feasible to do this yes, provided the number of objects is not stupidly high. If you have followed the previous setup then objects the player can interact with can be placed randomly in each of the sections that gets generated on the fly. Usually these sections would have some predefined areas marked up for where to spawn these objects so they do not get spawned in silly places. As there are only going to be a few sections loaded at any one time and only I would imagine 10s of object at the most in each section this should perform just fine and in fact this approach has been used on a couple of games I have worked on for mobile devices.

> Could be a better idea to store the location of the collectables objects inside some kind of data structure and completely avoid to use Unity collision detection?

You certainly could do this. You could store a data structure containing a position and a radius for the circle/sphere collision or some other appropriate data if you wanted to use another kind of collider. My guess though would be that its not really going to perform any quicker than the Unity collision system. So long as you don't have a silly number of objects and you know that it's not causing you any bottlenecks I'd stick with that.

> What's a reasonable average number of RigidBody/Sphere Collider that can be used in a single scene on a mobile device?

Well this number is going to change wildly depending on which platform you are talking about and how much other stuff you have going on in your game. In an empty scene on a low end device you could probably chuck in a few hundred colliders and keep a nice framerate.

On iOS iPhone4 is the lowest device most developers target these days and that device is pretty poor. At the studio I work we haven't targeted the iPhone 3GS at all in any project over the last 2 years or so so I cna't comment on that particular device but needless to say its capabilities will be less than the iPhone4.

I would suggest that your bigger problem would be rendering the geometry for all of these items the player can interact with. But under a 'normal' level I guess you could probably have a good 30 odd colliders. This is a bit of a guesstimate based on working with the platforms before so don't read too much into these numbers. It will depend very much on how much stuff your game is rendering to screen and how complex your game logic is.

On Android you're going to have to deal with devices that perform even worse than that though and Windows Phone also has some really low end devices so its hard to give an exact number with so many unknown variables.

---
Tags: collision-detection, physics, unity, ios, mobile
---


# Question
Title: Best way of writing pixel manipuliting-intensive applications with OpenGL/Direct3D
Recently I have been making little experiments with engines similar to old Wolfenstein 3D, Doom and Build, engines where the 3D rendering is entirely done in software and therefore you need full access to the screen buffers at pixel level.

In the days of DOS and before we had current GPUs it was relatively straightforward to get a surface to plot pixels. You had to devise the fastest way to do your calculations and the fastest way of updating the framebuffer. In fact, it is still possible by using libraries like SDL, which still give you a reasonable speed when you manipulate surfaces at pixel level.

So I wonder which would be the best way of dealing with pixel-intensive applications like the ones I suggest using current GPUs, by using OpenGL or Direct3D.

I understand this sounds absurd, but I have been looking at API documentation and it seems that it is a feature that we have somewhat lost in current hardware. I see suggestions as using glDrawPixels or using pixel shaders, but no solid explanation or theory which can help me to make the right decisions.

# Answer
> 5 votes
I understand that you are at a loss. I also liked to hack pixels when I was young, and did some games on calculator devices, or dos era this way.

This can still be done today, but, because of various hardware history of evolutions, it has become more involved.

## CPU pixel pushing

Notably, we can still push pixels one by one, but it would be incredibly slow because the frontbuffer is a memory that is very far away nowadays. In current PC architectures we can't just write to some memory zone and get pixels displayed, because of hardware reasons. We have double buffering, we have write combining buffers, we have synchronization issues between chips, we have bus frequency and width issues, driver interposition...

What you need to do to push pixels today is accept that fact or hardware life, and draw into your own personal surface in the general heap memory of your process, make it a new texture every frame and upload it to the graphic card. This is how movie playing works and it works well enough.

If you use OpenGL 3+ core, or Direct3D 10+, you will be forced to use a technique that is hardware happy, which means, write combining safe, and pipelinable.
It takes the form of multiple buffering, your surface in RAM will get copied to a "shared" surface on some special VRAM location that the CPU can lock to access without disturbing the rendering by the GPU (`D3D10_USAGE_DYNAMIC`), of the current or previous frame (`glMap/glUnmap`). In the next frame, the data copy hopefully will be finished and the gpu will flush the new frame command buffer, inside of which will be contained the instruction to copy the shared zone to a hard zone in order to use as a texture (`d3dcontext::CopyResource` or `glCopyTexSubImage2D`). Which will be streamed on GPU by the texture units into a screen quad (`tex2d` in a pixel shader.).

some link to consider carefully: http://eatplayhate.me/2013/09/29/d3d11-texture-update-costs/.

This is how you can create a texture streaming pipeline that will not take much resource, and your CPU power can be used to push the pixels. Actually it will be limited by RAM bus speed, which is about 20/30 GiB/s nowadays, so you can push 4k\*3k res at about 670 FPS.

There are wonderful articles about how to optimize the creation of software renderers, particularly rasterizers, its fascinating. With the history of scanline techniques and perspective correction issues (division was a slow hardware operation, and still is to some extent). Get the whole story here, after reading it all you will be a much better graphics engineer: https://fgiesen.wordpress.com/2013/02/17/optimizing-sw-occlusion-culling-index/
The man is Fabian Giesen, the guy from Farbrausch, a big name.

## GPU pixel pulling

The second big paradigm that you can apply here, is forget totally about the Amiga500 way of drawing things, and use the GPUs to their full processing power, and code everything as part of a pixel shader. If you don't use unordered access writes, you will be forced into the mold of "parallel gather" collective operation. (MPI terminology)

This is a much more powerful paradigm because of the non-dependency on your neighbors, which means the hardware can be parallel, and schedule units to pixels freely how it sees fit. (of course there are some contrived details when going deeper (like inter-fragment-quad approximate communication using `ddx` `ddy`). But basically you are given a `main` function into which you can decide the color of the pixel that is given to you, but you don't decide where to write this pixel, it has fixed coordinate. So you gather data around you to decide this color. Its the other way around. You cannot make an iterating Bresenham algorithm for instance. Rather, to draw a line, you'd have to determine if your pixel is on the line and write black it yes, `discard` if no.)

This has its constraints but its a happy playground up shaderland. I recommend :)

## Compute

Finally you can use compute, in computeland you can use the GPU as a multi core CPU and write where you want, to the cost of interlocking operations, this can get quite difficult to understand without serious experience in concurrent computations. This is why doing shaders first is a good idea to get used to it progressively.

The freedom you'll gain compared to shader is access to non filtered memory, and more hardware control on the low level. Where you put data, registers, unit, global...

# Answer
> 3 votes
I'm also from a pixel-banging background. PEEK and POKE anyone?

Using a GPU is a different mind-set entirely. (Well, it's still code, so just "more of the same...)

The GPU is really good at certain things: Processing individual pixels (through textures and fragment shaders), and filling triangles with pixels.

Much effort (on the programmer's part) is needed to get things set up. Much of the code involves creating buffers and textures to send to the GPU.

A trivial starting step would be to continue drawing your pixels, and pushing it to the GPU as one big textured rectangle, or rather, two triangles.

As you wrap your head around fragment shaders (which push individual pixels) and vertex shaders (which transform triangles mathematically around the screen) you'll begin to see opportunities to move some of your rendering work into these shaders.

There's plenty of example code around for open GL; here's one set of tutorials:

http://www.opengl-tutorial.org

To get your first rectangle of pixels on the screen through OpenGL, you'll use a combination of "Drawing a triangle" and "Drawing a textured cube".

OpenGL has a sort-of long runway, but it's pretty fun and powerful once you're airborne.

Hope that helps a little!

---
Tags: opengl, directx, fragment-shader, raycasting, software-rendering
---


# Question
Title: How to move sprite mimicking mouse/touch position on some part of the screen?
I am having a difficulty and I am been doing it wrong, I think. I want to move sprite relatively to touch. Just like when you are playing space shooter like 1943. I just learning some math and try to mimic those control by myself but I have no luck doing so far.

I have snippet of code, its far from perfect, I was able to move the sprite relatively but keeps jumping off when I first touch and moved.

Here is what I got so far:

When the touch move:

```
void Trooper::onTouchMoved(cocos2d::Touch * touch, cocos2d::Event * event)
{
    mPreviousTouchPosition = mTouchMovePosition;
    mTouchMovePosition = touch->getLocation();

    cocos2d::Vec2 delta = utility::Object::getPosition() + (mTouchMovePosition - mPreviousTouchPosition);
    delta = utility::Object::getContainingScene()->convertToNodeSpace(delta);

    utility::Object::setPositionTo(delta);

    CCLOG("Coordinates when moved : %f , %f" , delta.x , delta.y);
}

```

Here is the data I logged and the first line for coordinates when moved seem anomalous to me:

```
Coordinates on touch : 633.746338 , 395.874329
Coordinates when moved : 883.746338 , 644.876404
Coordinates when moved : 882.747925 , 644.876404
Coordinates when moved : 880.752136 , 642.879517
Coordinates when moved : 878.755249 , 641.881104
Coordinates when moved : 876.758423 , 640.882690
Coordinates when moved : 874.761536 , 637.887939

```

I shouldn't be seeing this kind of huge number when my actual sprite is on 250 , 250. The difference of previous touch position and the current touch position should be added to the sprite position. I wanted to achieve relativeness regardless I touch and move. The sprite should mimic that. Did I missed something or anything wrong with my math?

Thank you!

# Answer
My actual code actually works. I only forgot to initialize the mTouchMovedPosition initially to the mOnTouchPosition.

Here is what I have:

```
void Trooper::onTouchMoved(cocos2d::Touch * touch, cocos2d::Event * event)
{
    mPreviousTouchPosition = mTouchMovePosition;
    mTouchMovePosition = touch->getLocation();

    cocos2d::Vec2 delta = (mTouchMovePosition - mPreviousTouchPosition);
    delta = utility::Object::getContainingScene()->convertToNodeSpace(delta);
    mNewPosition = utility::Object::getPosition() + delta;

    utility::Object::setPositionTo(mNewPosition);
}

```

Notice I set the mTouchMovePosition to equal the area of the screen that has been touched.

```
bool Trooper::onTouchBegan(cocos2d::Touch * touch, cocos2d::Event * event)
{
    mTouchMovePosition = mTouchPosition = utility::Object::getContainingScene()->convertTouchToNodeSpace(touch);
    return true;
}

```

It works! I hoped it help somebody who is trying to achieve similar thing.
> 1 votes

---
Tags: mathematics, physics, cocos2d
---


title: Good design for skills (heal,dmg etc)

text:
# Question
Title: Good design for skills (heal,dmg etc)
I'm trying to create a good designed "skill system" for my game, but curious if anybody knows a good design?

Skills can Heal,Damage ofc, they can be single target,multiple(chain), AOE. Instant dmg/heal or overtime. some skills can do damage and heal together and so on.

Maybe a little bit to complex for me to start, but can anybody help me?

Update:

lets say i have a Character class, and each character ofc has hitpoints and also a method TakeDamage(float amountOfDmg,Character damage\_causer);

should this TakeDamage(..) method be used inside each Skill class e.g.?:

```
class AnySkill
{
 public:
 void Execute()
 {
   *(somehow get the character who takes damage)*->TakeDamage(damage, *(somehow get the causer)*)
 }

 private:
 float damage;
}

```

Would this be a good design?

```
class Character
{
 public:
 void SetTarget(Character* target)
  {
    target_ = target;
  }
 void TakeDamage(float damage, Character* causer)
 {
   hit_points_ -= damage;
 }
  void UseSkill1()
  {
    skill1->Execute(this,target);
  }

private:
 Character* target_;
 AnySkill* skill1;
 float hit_points_
}

class AnySkill
{
 public:
 void Execute(Character* causer,Character* taker)
{
  taker->TakeDamage(damage_value,causer);
}

 private:
 float damage_value_;
 Character* target_;
}

```

And somewhere:

```
player->SetTarget(enemy);

if(skill1_key_pressed)
{
  player->UseSkill1();
}

```

# Answer
> 3 votes
I think you are looking in what's called the "Strategy pattern" in OOP. Your skill has something like the following signature(in pseudocode)

```
interface TargetBehaviour{
 list<targets> getTargets();
}
class TargetAOA implements TargetBehaviour{
  list<targets> getTargets(){...{
}
class TargetSingle implements TargetBehaviour{
  list<targets> getTargets(){...}
}
interface SkillEffectBehaviour...

class skill{
    TargetBehaviour targetBehaviour;
    SkillEffectBehaviour effect;
    void use(){
        list<targets> targets = targetBehaviour.getTargets();
        foreach(target in targets){
             effect.use(target);
        }
    }
}

```

that way you can create new skills by swapping out effects targets and whatever else you want to swap (class,graphical effect ext.) by just swapping out which class you assign to the variables.

# Answer
> 1 votes
OOP is your friend here! Many skills will have similar traits and you can categorize them so you don't have to recode every aspect of every skill.

For example, skills will all be attachable to a character. An abstract class can be used for this. This class can also include several features that all skills have, like a call to simulate the skill or the tier of the skill.

Next, are passive and active skills. That's 2 more abstract classes to derive from. Active skills will accept input and be cast while passive skills aren't cast.

Under active skills, can be damaging skills, yet another abstract class to derive from which derives from the active skills class. Damaging skills can also include an abstract variable called "DamageType" that describes the skill as lightning/fire/pineapple/whatever.

For example, Lighting Blast is a class deriving from DamageSkill which has a damage and damage type variable. Its damage is 50 and its type is Lightning. DamageSkill derives from ActiveSkill, which has an input variable. Its input to cast is "Input.One". ActiveSkill derives from Skill, which has a tier and an abstract Simulate () method. Its tier is 3 and its Simulate () method consists of checking if the ability is cooled down. If it is, check for input and if the corresponding input registers, shoot lightning that does 50 damage of Lightning type. AOE and whatnot gets simulated here just as healing would, and Simulate () is called every simulation frame on the abilities. You can also throw in a Visualize () for the skills to show cool effects independent of simulation.

Come to think of it, DamageSkill should be an interface but this is the gist of an ability system where you have the root of a tree that branches out to accommodate a vast number of leaves where your leaves are the abilities and the branches are the abstract classes/interfaces that define the shared properties of the abilities. It might actually be easier and faster (debug-wise) to copy-paste a bunch but having an OOP setup allows you to do cool things like storing all your abilities in a convenient array and in the long run, OOP can support many more abilities than hardcoding everything.

By the way, if required, you can even screw the branches and grow a leaf at the root of the tree. Sorry for the bad metaphor but this was honestly the way best I could think of to visualize OOP.

---
Tags: c++, architecture, oop
---


# Question
Title: How to prevent bullets from passing right through entities?
(sorry for bad english)

I'm making 2D arcade game. I write all of physics stuff myself. The problem involves bullet behaviour. Imagine bullet flying towards some entity. If the bullet's velocity is relatively high and the entity is small, the bullet passes right through the entity which is obviously not what it's meant to do. Here's the gif that shows why that happens (values are exaggerated to better show the process):
As you can see bullet's velocity is simply bigger than the size of the entity. Then I came up with this:
Getting point of impact coordinates means I can check if the distance between the point of impact is smaller than the bullet's velocity. If the distance is smaller then bullet should collide with the entity at the point of impact. But I don't know how to calculate the coordinates of the point of impact. Pls help.

# Answer
First calculate the line equation (the laser direction)

```
<x,y,z> = <x0,y0,z0> + t*V  (1)

```

where V is the direction Vector, and is the a known position of your bullet.

Second calculate the equations of each side of your entity,

the intersection would be the point that satisfies (1) and one of the rectangle sides equations
> 2 votes

---
Tags: physics, vector
---


# Question
Title: What makes Minecraft so CPU intensive, and what could be done to improve it?
Recently I've been searching for VPSes that allow Minecraft servers to be hosted, and surprisingly very few do. Most allow for games - but Minecraft in specific is disallowed by many.

Now it's fairly obvious why this is - it's very CPU intensive, and fairly ram hungry... But **why**? The answer I've gotten a lot through googling is "It's written in Java", or "Java's memory management is bad", but those aren't really answers - they're cheap cop outs.

What I really want to know, what I want to track down - is what exactly is eating up so much processing power? And given the desire to do so, what could be done to fix those issues.

I'm not looking to start a discussion on the merits of Java, or how well written Minecraft is - I'm curious if there's an actual answer, actual sections of code or ways things are done that are causing such high CPU usage, and ideally what could, theoretically, be done to fix them.

# Answer
> 2 votes
> I'm not looking to start a discussion on the merits of Java

Neither do I, but Fact is that Java uses all the objects by reference, nothing is used by value, the memory management is Java is good, but with puting everything in the heap, performance is low, and the program uses a lot more memory.

# Answer
> 1 votes
Just think about it, what the server has to do. In Singleplayer needs to know and simulate the world around the player. The world is made out of voxels, which naturally needs a lot more memory than just working with heights. Doing stuff procedurally also needs more CPU power, because you can't optimize and precalculate some stuff (like culling, pathfinding etc). In Multiplayer the server should simulate the world around a lot of players who can be anywhere. In worst case you need to simulate 32 times as much on a 32 player server than in Singleplayer

---
Tags: java, algorithm, minecraft-modding, lag
---


# Question
Title: In Unity3D, how do I create an efficient scratch card effect?
I want to create a scratch-card-like effect in new Unity UI's new Image tag. I know it's possible with `setPixels`, but that's prohibitively expensive on mobile devices.

Something like this:

I'd like the user to be able to drag on any part of the image to "scratch off" the top layer and reveal the content underneath it.

How can I do this?

# Answer
I have done something similar to this in the past.

My solution to this would be to make use of Unity's new UI Mask and a Render Texture.

When the player touches the screen you would draw a circular sprite at that location and render it to a texture. You would then use this texture for the mask. Over time these sprites will reveal more and more of the image giving you the effect you are after without having to go down the SetPixels route.

This is a similar question that was asked which has a load of good links on it if you don't mind that it's XNA/C# but the concepts are the same.
> 1 votes

# Answer
Assuming no setPixel,

make a "single dirt bitmap"(1). Place a bunch of texture2d objects(2) (using image(1)) over the "card" and make them disappear when you move over them.

You can define properties on each (2) , so that one Texture object may take two (or more) scratch to disappear.
> 1 votes

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


title: Collision in different layer

text:
# Question
Title: Collision in different layer
I have a game object called gameObject1 on the screen. It holds an image called red. When I drag an image called "animal" on gameObject1 the collision happens correctly and destroys the "animal" in the same layer. Then I increment the score, but when I drag an image called "animal" on gameObject2 I want to decrement my score (with out collision). I know the collision on a different is not happening.

```
 void OnCollisionEnter2D(Collision2D col)
    {

            if(Input.GetMouseButtonUp(0))
            {
        if (col.gameObject.name == "Semi arid" )
        {
            //obj1.rigidbody.isKinematic = false;
                scoreCalculate.currentScore+=10 ;

                Destroy(gameObject);
                //Debug.Log ("Scored1............"+scoreCalculate.currentScore);
                Instantiate(obj1, ObjectSpawnPosition1, Quaternion.identity);
                Instantiate(green, ObjectSpawnPosition1, Quaternion.identity);
                obj1.renderer.enabled = true;
                green.renderer.enabled = true;}

```

# Answer
To disable collision between specific layers you should go to in

Edit-\>Project Settings-\>Physics

and customize the collision matrix, which specifies for each layer combination if they can collide or not.

See documentation, hope it helps.

If it isn't happening yet, then reasons could be just because you use OnCollisionEnter2D instead of OnTriggerEnter2D() or because you move the transform instead of the Rigidbody2d.
> 1 votes

# Answer
Instead of collision detection, you can use raycasting. When an object starts to be dragged, perform raytest inside the Update by filtering unwanted objects.

```
RaycastHit info;
int layerMask = (1 << LayerMask.NameToLayer("GO1Layer") | 1<<LayerMask.NameToLayer("GO2Layer"));
if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out info, 100f, layerMask))
{
    if (info.collider.name == "GO1")
        //statements
    else if (info.collider.name == "GO2")
        //statements
    else
        //statements
 }

```

Put this into a mouse listener script. Check whether an object is getting dragged and set the layermask to ignore the dragged object.
> 0 votes

---
Tags: unity, collision-detection, gameobject
---


title: Unity - Text not properly align

text:
# Question
Title: Unity - Text not properly align
My text doesn't seem properly align to top left even I already set it in `Rect Transform`.

Please advice. Thank you.

# Answer
Seem to me that you only changed the pivot point of the text, not the position. You can see the location of the text is relative to the pivot point which is X: 430, y: -223.

You need to hold shift & alt when align the text to top left to also change the position and pivot point of the text.

Alternatively, you can set your x, y, z coordinate of the text to 0, 0, 0 to move it to the pivot point.
> 1 votes

# Answer
When changing the alignment press ALT before clicking the top left corner, else you'll just set the pivot point.
> 1 votes

---
Tags: unity
---


# Question
Title: Is there a way of moving the transform of an object relative to it's geometry
I have a number of objects (mostly prefabs) that have their transform origin in inconvienient places such as about 1 unit to the left of the actual geometry or somewhere inside an object where it's hard to see. Is there any way to move these transforms without actually moving the object itself? This is in 3D.

# Answer
The easiest way is to create a new empty game object at the location & orientation you want for the origin. Then re-parent the game object containing the geometry (and anything that goes with it) to your new empty game object. Finally, name the game object appropriately and drag it into your Project window to save a prefab with the corrected origin.

If the current parent object has some content that needs to stay at the top transform level, you can either duplicate it to the new object, or move its child objects within it by:

* reparenting its child objects to the scene root
* moving the parent object to the location where you want the origin
* reparenting the former child objects back to the parent

Of course, the most robust method is as @Leggy7 says in a comment above: re-export your geometry from your 3D package so that the origin is exactly where you want it. I mention these other options in case you just need a quick fix, or don't have access to the source asset or 3D software to edit it.

If you only need the origin to *appear* somewhere different in the scene editor, you can use the Gizmo Display Toggles to display the transform gizmo at the center of the object's bounding box, rather than at the origin of its local coordinate space.
> 1 votes

---
Tags: unity, geometry, workflow
---


# Question
Title: Access different vertices of a Mesh Unity 3d
I have a mesh and I want to color each group of vertices with a certain color. If anyone could please advise how this can be done in Unity using coding?

# Answer
> 1 votes
Read up on the Mesh class. You can use this to read & modify any information you want about mesh assets in your project, or even create whole new meshes procedurally.

You can access and iterate over mesh information like this:

```
void AssignBoneColors(Mesh mesh)
{
   Color32[] colors = mesh.colors32;
   // Ready an array large enough for all vertices if the mesh didn't already have one.
   if(colors.Length == 0)
       colors = new Color32[mesh.vertexCount];

   BoneWeight[] weights = mesh.boneWeights;

   // If the mesh has no skinning weights, this will be zero,
   // which skips the loop below.
   int numVertices = weights.Length;

   for(int i = 0; i < numVertices; i++)
   {
       colors[i] = GetColorForBoneWeights(weights[i]);
   }

   mesh.colors32 = colors;
}

```

GetColorForBoneWeights() is where you'll implement your colour selection based on which limb the vertex is skinned to. Note that boneWeight.boneIndex0 should contain the index of the bone with the highest weight for each vertex, so you could colour based on that bone alone, or navigate to its first parent to which you've assigned a color, or write a colour-weighting function that considers multiple bones. These implementation details are up to you.

Note that the colours will only be visible if you render the mesh with a shader that uses vertex colours, or use additional editor extensions/gizmos to help visualize vertices.

---
Tags: unity, unityscript
---


# Question
Title: Shadow map depth error makes all light be covered and hidden
I've been following the tutorials listed below:

http://www.riemers.net/eng/Tutorials/XNA/Csharp/Series3/Shadow\_map.php

http://xbox.create.msdn.com/en-US/education/catalog/sample/shadow\_mapping\_1

And I made my shadow map creator effect:

```
float4x4 WorldViewProjection;

float4x4 LightingWorld;
float4x4 LightingViewProjection;

struct VertexToPixel {
    float4 Position : POSITION;
    float Depth : TEXCOORD0;
};

VertexToPixel ShadowMapVertexShader(float4 position : POSITION) {
    VertexToPixel output = (VertexToPixel)0;

    output.Position = mul(position, mul(LightingWorld, LightingViewProjection));
    output.Depth = output.Position.z / output.Position.w;

    return output;
}

float4 ShadowMapPixelShader(VertexToPixel input) : COLOR0 {
    float4 color = input.Depth;
    color.a = 1;

    return color;
}

```

I use the following flashlight (which has a cone angle: coneAngleHalfRad * 2) View and Projection matrices for the shadow map (and for checking the depths later):

```
        lightProjection = Matrix.CreatePerspectiveFieldOfView(
            coneAngleHalfRad * 2,
            1,
            1, //0.25f,
            range);

        //Helper.Message(this, "draw shadow maps: " + needsShadows);
        //Helper.Message(this, "rotation up: " + rotation.Up);
        lightView = Matrix.CreateLookAt(position, position + (direction * range), rotation.Up);
        lightViewProjection = lightView * lightProjection;
        DepthMapMakerEffect.Parameters["LightingWorld"].SetValue(Matrix.Identity);
        DepthMapMakerEffect.Parameters["LightingViewProjection"].SetValue(lightViewProjection);
        DepthMapMakerEffect.Techniques[0].Passes[0].Apply();

        device.SetRenderTarget(RenderDirectional);
        device.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.Black, 1.0f, 0);

        drawAction(this, DepthMapMakerEffect);

        device.SetRenderTarget(null);
        ShadowMapDirectional = (Texture2D)RenderDirectional;

```

I set my shadow map to the effect:

```
TextureManager.DynamicTexturingEffect.Parameters["Flashlight" + numFlashlightsPP + "Map"].SetValue(((Flashlight)lights[lightIndex]).ShadowMapDirectional);

```

And when I am drawing the light with additive blend state, I use the following code to get the depths from the shadow map and from the camera (is it from the camera? I didn't understand yet):

```
shared float DepthBias = 0.001f;

//  [...]

shared Texture Flashlight0Map;
shared sampler Flashlight0MapSampler = sampler_state {
    texture = <Flashlight0Map>;
    magfilter = LINEAR;
    minfilter = LINEAR;
    mipfilter = LINEAR;
    AddressU = clamp;
    AddressV = clamp;
};

//  [...]

//  Find the position of this pixel in light space.
float4 lightingPosition = mul(worldPosition, flashlight.LightingViewProjection);

//  Find the position in the shadow map for this pixel.
float2 shadowTexCoord = 0.5 * lightingPosition.xy /
                        lightingPosition.w + float2(0.5, 0.5);
shadowTexCoord.y = 1.0f - shadowTexCoord.y;

//  Get the current depth stored in the shadow map.
float shadowDepth = tex2D(Flashlight0MapSampler, shadowTexCoord).r;

//  Calculate the current pixel depth.
// The bias is used to prevent folating point errors that occur when
// the pixel of the occluder is being drawn.
float ourDepth = (lightingPosition.z / lightingPosition.w) - DepthBias;

//  [...]

float intensity = 0;
if (ourDepth <= shadowDepth) {
    if (atten > 0) {
        intensity = saturate((flashlight.Range - dist) / flashlight.Range) * (dot(vertexNormal, perVertexNormal) * fog) * atten;
    }
}

```

But what happens is that the result is ALWAYS "ourDepth \> shadowDepth", which makes the entire light always hidden so it's always shadowed no matter if there's an object in front of it or not.

What could I possible be doing wrong? I think I used wrong values in the flashlight's View and Projection. But I can't find the error. What might be the problem?

Any suggestion may help!

EDIT: I'm not using the same aspect ratio of the screen and of the camera for the shadow map. Do I need to?

# Answer
So, I found out I was multiplying the positions by an empty World matrix somewhere in the effect file, and the values went wrong or null.

I'm not sure about what really happened, but that was one of the causes. 'Cause it started working after cleaning the code of unused variables.

I had to adjust DepthBias to 0.01f too. Oh, and I had to multiply the Input Position by the World Matrix in the Vertex Shader to get the World Position and not in the Pixel Shader as I was doing before.

EDIT: I had to clean my shadow map renderer to black, too, and not to white.
> 1 votes

---
Tags: xna, c#, graphic-effects
---


title: Deferred Rendering with SFML

text:
# Question
Title: Deferred Rendering with SFML
I've been looking to implement a deferred rendering system in SFML.

I've read the tutorials on OGLdev for it, and I was wondering how to draw a scene built in SFML (sprites, text, etc) to the multiple render targets needed for the deferred shading process.

Basically, I need to be able to get SFML to draw every object to the GBuffer's MRTs, so I can have the parameters needed to do what I want.

Is this possible, or will I have to build my own rendering backend from scratch?

# Answer
Something you could try using only SFML is to use a sf::RenderTexture. It allows you to render sf::Drawables offscreen.

So you could define multiple RenderTexture and mix them together before rendering on screen.

Be aware that by directly using SFML you cannot achieve 3D rendering.

Here's a link to the documentation : http://www.sfml-dev.org/documentation/2.3-fr/classsf\_1\_1RenderTexture.php

EDIT: Since I can't comment, here is my suggestion. You create 3 (or more) RenderTextures to hold the informations about the positions, the colors and the normals of your final image. You can then pass these textures to a shader computing your final image by using the informations stored in your textures. I have no clues about the performance of this approach since I never tried it.
> 1 votes

---
Tags: opengl, sfml
---


title: Creating a Collision Detection system

text:
# Question
Title: Creating a Collision Detection system
I'm currently working on 3D project (C++) and I have now come to writing the collision detection systems.

Basically my question is regarding how to architect it.

All the collisions are either between AABB-AABB or AABB-circle. I'm perfectly aware how to detect whether any two objects are colliding, but I don't know where to do the checks.

Currently I am trying to make a CollisioManager class that contains a list of all the AABBs in the level and then the player object makes a call to the CollisionManager to ask whether it is currently colliding with any (then acts accordingly).

I think I can do it this way but are there any other ways of organizing it as it feels a bit messy and not the cleanest of solutions.

# Answer
> 0 votes
If you have an array of all objects in the simulation, you can do something like this:

```
Collider[] Colliders = new Collider[]{col1, col2, col3, col4...};

void Simulate ()
{
    for (int i = 0; i < Colliders.Length; i++)
    {
        Collider ColA = Colliders[i];
        if (ColA == null) continue;
        for (int j = i + 1; j < Colliders.Length; j++)
        {
            Collider ColB = Colliders[j];
            if (ColB == null) continue;
            CheckCollision (ColA, ColB);
        }
    }
}

```

These loops will iterate over all possible combinations once, skipping combinations of the same object and any objects that don't exist.

If you're doing spatial partitioning, you can use the same loops for iterating over the partitioned collection or you can include the indicator that the pair of objects are in the same partition in the CheckCollision() call (which is generally easier and more centralized).

Note that you can still do this for HashSets and other collections that don't use indexers but you have to store 'i' and 'j' somewhere else. I.e.

```
int i = 0;
foreach (Collider ColA in Colliders)
{
    int j = 1;
    foreach (Collider ColB in Colliders)
    {
        if (j > i)
        {
            SetCollisionPossible (ColA, ColB);
        }
        j++
    }
    i++;
}

```

---
Tags: c++, collision-detection, aabb
---