title: Game versions update?

text:
# Question
Title: Game versions update?
When does a game version change

from x.x.x.x to x.x.x.x+1 like from 1.0.0.0 to 1.0.0.1

or from x.x.x.x to x.x.x+1.x ?

or from x.x.x.x to x.x+1.x.x ?

or from x.x.x.x to x+1.x.x.x ?

Should the first game version be 1.0.0.0 or 0.0.0.1?

# Answer
What the accepted answer describes is called semantic versioning. It's a versioning scheme that describes how to version APIs, but it gives no guidelines on how to version applications (like video games). You can kind of hack it in, like this:

> Increment MAJOR version for "major" changes
> Increment MINOR version for "minor" changes
> Increment PATCH version for bugfixes

But in general, there is no widely-adopted standard for application-versioning - everyone just plays it by ear.

So if you feel your update is big enough to warrant calling this "2.0", then do it; otherwise, increment one of the other numbers.
> 2 votes

# Answer
Pretty clearly this depends on the industry standard, but in web development, there is a move towards **semantic versioning** as a standard, which you can read about here:

http://semver.org/

> MAJOR version when you make incompatible API changes,
>
> MINOR version when you add functionality in a backwards-compatible manner, and
>
> PATCH version when you make backwards-compatible bug fixes.

This isn't especially different from what Lolums is saying, but I wanted to give you a name for the process that will allow you to search for it in the future: **semantic versioning**
> 1 votes

# Answer
While there is no hard rules for software versions, the accepted (unofficial) standard these days is Semantic Versioning. Although the general meaning of the different version numbers has been used for a long time, how/when they are each incremented has been more of an art than a science. Semantic versioning is an attempt to make it more science and less art.

***When does a game version change? (External Versioning)***

The meaning of each version number is **Major.minor.patch.critical**

* **Major:** Significant changes have been made. If the changes break compatibility with the previous version, you should certainly increment the Major version. Modifying the external API does not in itself demand a Major version change. If you add new classes/functions to the public API for example, it does not break compatibility so is not a Major version change. This is just a rule of thumb though. There are other good reasons to increment the Major version. You might increment the Major version number if there has been a large number of changes even though it remains backward compatible.
* **minor:** Some changes have been made that affect the functionality of the software but do not warrant a Major increment. minor changes are always backward compatible.
* **patch:** Non-critical bug fixes. Fixes which do not directly affect the functionality of the software. Eg. cosmetic changes, documentation updates, performance improvements
* **critical:** Critical bug-fixes. These should be few but allows users to know when a version update is important. Critical bug-fixes would include fixing security issues, internal algorithms, broken installer, etc

To put it into more perspective: as an end-user when semantic versioning is used, one can tell when and if they should update to the latest version. If there is a critical update, then all users should update since it includes fixes for something that is fundamentally wrong with the software. Patch updates are less important fixes but should not break anything, so can (generally) be considered safe to update. Minor updates are less safe due to the amount of changes and introduction of new functionality but should be backward compatible. Each of these types of updates could introduce new bugs, which is why updating should be discretionary and not taken for granted. A major update should signify to the end-user that if they proceed with the update, they should expect to have some type of problems. Either having to migrate to the new version or changing something about how they use the software.

As to when to change version numbers (opposed to what version number to change): Only increment the version numbers when an update is **released**.

***Internal Versioning***

Internally, you should be using *revision numbers* that correspond to your version control software (svn, git, hg, etc), otherwise if you aren't using a VCS, you should increment the *build number* each time you build a new binary.

What this means is that if it takes you 500 revisions before you have something ready for release, your v1.0.0.0 package will be at rev500. Why, is because internally you need to keep track of every change but externally/publicly the end-user only cares about what has changed since the last release. As well, if you were to increment the version number internally, when you do release there could be large gaps in the version numbers which causes confusion.

***What version number should you start at?***

Prior to your first official public release, you will probably be releasing packages for testing purposes. These will start at v0.1.0.0 and will increment the same way as described above except you will not increment the Major version yet. The first major version (v1.0.0.0) will be the official, final release. Eg, when it's ready for sale.

Concerning games particularly, if you use semantic versioning then a sequel to the game is not a major update, it is an entirely new release and should start at v1.0.0.0 again, even if it's the 7th game in a series. Many games (and other software) do not follow this convention.

Whatever you do, I suggest you document how your version scheme works so that your end-users (and other developers) can understand what the numbers mean and utilize them appropriately.
> 1 votes

---
Tags: version-control
---


title: C# XNA - Can't Deserialize Element

text:
# Question
Title: C# XNA - Can't Deserialize Element
So This is my XML file:

```
<?xml version="1.0" encoding="utf-8" ?>
<XnaContent xmlns:ns="Microsoft.Xna.Framework">
  <!-- TODO: replace this Asset with your own XML asset data. -->
  <Asset Type="ScreenLoader.DataLoader">
    <Path>Graphics/Backgrounds/background_0</Path>
  </Asset>
</XnaContent>

```

And my XmlManager class:

```
public class XmlManager<T>
{
    public Type Type { get; private set; }
    public T Load(string path)
    {
        T instance;
        using (TextReader reader = new StreamReader(path))
        {
            XmlSerializer xml = new XmlSerializer(Type);
            instance = (T)xml.Deserialize(reader);
        }
        return instance;
    }
}

```

And my DataLoader class:

```
namespace ScreenLoader
{
    public class DataLoader
    {
        public static string Path;
    }
}

```

The compiler error:

> Severity Code Description Project File Line Error There was an error while deserializing intermediate XML. 'Element' is an invalid XmlNodeType. Line 5, position 6.

So that's what I did: Added XNA Game Library `ScreenLoader` to my project. Added the DataLoader class in it. Then I added reference to it in both my Content project and my Game project. Then I changed the game project to depend on the library. Then I adjusted the build order of the game project so that the library is built first. And I STILL CANNOT comprehend why the compiler complains like this. I just want to load content from XML files and have them compiled to XNB when I ship the game but I really need to know what I am missing. Thanks in advance!

# Answer
You are trying to write code to deserialize your xml file. The Xml deserialization in Xna is automatic so you do not need your XmlManager class at all.

Add your Xml file (myXmlFile.xml) to your content project just like you would a texture or model. This will allow the build process to convert it from xml to serialized xnb. Now your project is aware of myXmlFile.xnb and when you load it using the Content Manager, it will automatically deserialize it for you. It was one of the really cool things about Xna so stick with it.

```
//In your Game1 class scope variables:

ScreenLoader.DataLoader myDataLoader;

//then in your LoadContent Method:

myDataLoader = Content.Load<ScreenLoader.DataLoader>("myXmlFile");// it knows what a DataLoader is because you built that project first. the ("myXmlFile") refers to the myXmlFile.xnb, not the myXmlFile.xml.

```

Viola! myDataLoader.Path now holds "Graphics/Backgrounds/background\_0"

here's a link: http://blogs.msdn.com/b/shawnhar/archive/2008/08/12/everything-you-ever-wanted-to-know-about-intermediateserializer.aspx
> 2 votes

---
Tags: c#, xna, xml, serialization
---


# Question
Title: Change the color of GL.wireframe in Unity
Need to render something with GL.wireframe, this is what I have at the moment.

```
void OnPreRender() {
    GL.wireframe = true;
}
void OnPostRender() {
    GL.wireframe = false;
}

```

However the wireframe rendered is black and this will not work for my game. I've tried adding the following to OnPreRender()

```
GL.Color (Color.red);

```

Unfortunately the wireframe remains black. Does anyone know the proper way of changing this color?

# Answer
Here is a MonoBehaviour written for the express purpose by Benjamin Kiesewetter. It exposes some properties for line colour and thickness and the like.

Relatively speaking quite old now, so not 100% sure it'll work in Unity5 out the box, but it shouldn't be far out if not!

It might be worth adding a `[RequireComponent(typeof(MeshFilter))]`, as it absolutely does require one to work.

```
/*
wireframe update benjamin kiesewetter 2013
faster
normals
vertex extensions
*/

using UnityEngine;
using System.Collections;

public class wireframe : MonoBehaviour {

    public bool render_mesh = true;
    public bool render_wiresframe = true;
    public float normal_length = 1f;
    public float vertext_extention_length = 1f;
    public float lineWidth = 1;
    public Color lineColor = new Color (0.0f, 1.0f, 1.0f);
    public Color backgroundColor = new Color (0.0f, 0.5f, 0.5f);
    public bool ZWrite = true;
    public bool AWrite = true;
    public bool blend = true;

    public int size = 0;
    public int ignored =0;

    private Vector3[] points_a;
    private Vector3[] points_b;
    private Vector3[] vertices;
    private Vector3[] vertex_extensions;
    private Vector3[] normals_center;
    private Vector3[] normals;
    public Material lineMaterial ;

    /*
    ████████       ▄▀▀■  ▀▀█▀▀  ▄▀▀▄  █▀▀▄  ▀▀█▀▀
    ████████       ▀■■▄    █    █■■█  █▀▀▄    █
    ████████       ■▄▄▀    █    █  █  █  █    █
    */

    void Start () {
        if (lineMaterial == null ) {
            lineMaterial = new Material ("Shader \"Lines/Colored Blended\" {" +
                                        "SubShader { Pass {" +
                                        "   BindChannels { Bind \"Color\",color }" +
                                        "   Blend SrcAlpha OneMinusSrcAlpha" +
                                        "   ZWrite on Cull Off Fog { Mode Off }" +
                                        "} } }");
        }

        lineMaterial.hideFlags = HideFlags.HideAndDontSave;
        lineMaterial.shader.hideFlags = HideFlags.HideAndDontSave;

        // find vertices
        MeshFilter filter  = gameObject.GetComponent<MeshFilter>();
        vertices = filter.mesh.vertices;
        vertex_extensions = new Vector3[vertices.Length];

        // find wire lines and normals by triangles
        int[] triangles = filter.mesh.triangles;
        ArrayList points_a_List = new ArrayList(); //first points of wireframe lines
        ArrayList points_b_List = new ArrayList(); //second points of wireframe lines
        ArrayList normals_center_List = new ArrayList();
        ArrayList normals_List = new ArrayList();

        for (int i = 0; i+2 < triangles.Length; i+=3)
        {
            //for rEaDaBiLiTy
            Vector3 a = vertices[triangles[i]];
            Vector3 b = vertices[triangles[i + 1]];
            Vector3 c = vertices[triangles[i + 2]];

            /* Make the Lines:
                evry line may border two triangles
                so to not render evry line twice
                compare new lines to existing*/
            bool[] line_exists = new bool[]{false,false,false};
            for (int j=0; j<size; j++){
                if (points_a_List[j].Equals(a)){
                    if      (points_b_List[j].Equals(b)){
                        line_exists[0]= true;
                    }else if(points_b_List[j].Equals(c)){
                        line_exists[2]= true;
                    }
                }else if (points_a_List[j].Equals(b)){
                    if      (points_b_List[j].Equals(a)){
                        line_exists[0]= true;
                    }else if(points_b_List[j].Equals(c)){
                        line_exists[1]= true;
                    }
                }else  if (points_a_List[j].Equals(c)){
                    if      (points_b_List[j].Equals(a)){
                        line_exists[2]= true;
                    }else if(points_b_List[j].Equals(b)){
                        line_exists[1]= true;
                    }
                }
            }
            // only add lines if they dont yet exist
            if(!line_exists[0]){
                points_a_List.Add(a);
                points_b_List.Add(b);
                size++;
            } else {
                ignored++;
            }
            if(!line_exists[1]){
                points_a_List.Add(b);
                points_b_List.Add(c);
                size++;
            } else {
                ignored++;
            }
            if(!line_exists[2]){
                points_a_List.Add(c);
                points_b_List.Add(a);
                size++;
            }
            else {
                ignored++;
            }

            // Make the Normals

            //center of triangle
            normals_center_List.Add((a+b+c)*(1f/3f));
            //normal of triangle
            normals_List.Add(Vector3.Cross(b - a, c - a).normalized);
        }

        //arrays are faster than array lists
        points_a = (Vector3[]) points_a_List.ToArray(typeof(Vector3));
        points_a_List.Clear();//free memory from the arraylist
        points_b = (Vector3[]) points_b_List.ToArray(typeof(Vector3));
        points_b_List.Clear();//free memory from the arraylist

        normals_center = (Vector3[]) normals_center_List.ToArray(typeof(Vector3));
        normals_center_List.Clear();//free memory from the arraylist
        normals = (Vector3[]) normals_List.ToArray(typeof(Vector3));
        normals_List.Clear();//free memory from the arraylist
    }

    /*
    ████████       █▄ ▄█  █▀▀▀  ▀▀█▀▀  █  █  ▄▀▀▄  █▀▀▄  ▄▀▀■
    ████████       █▀▄▀█  █■■     █    █■■█  █  █  █  █  ▀■■▄
    ████████       █ █ █  █▄▄▄    █    █  █  ▀▄▄▀  █▄▄▀  ■▄▄▀
    */

    private float vertext_extention_length_old = 0;

    void update_vertex_extension_length(){
        /* asuming the length of the vertex extensions to barely change
         * only calculate this if really nessecairy,
         * increases memory but should speed up*/
        if(vertext_extention_length_old != vertext_extention_length){
            vertext_extention_length_old = vertext_extention_length;
            for(int i = 0; i<vertices.Length; i++){
                vertex_extensions[i]=vertices[i].normalized*vertext_extention_length;
            }
        }
    }

    private float normal_length_old = 0;

    void update_normal_length(){

        /* asuming the length of the normals to barely change
         * only calculate this if really nessecairy,
         * increases memory but should speed up*/
        if(normal_length_old != normal_length){
            normal_length_old = normal_length;
            for(int i = 0; i<normals.Length; i++){
                normals[i]=normals[i].normalized*normal_length;
            }
        }
    }

    // to simulate thickness, draw line as a quad scaled along the camera's vertical axis.
    void DrawQuad(Vector3 p1,Vector3 p2 ){
        float thisWidth = 1.0f/Screen.width * lineWidth * 0.5f;
        Vector3 edge1 = Camera.main.transform.position - (p2+p1)/2.0f;  //vector from line center to camera
        Vector3 edge2 = p2-p1;  //vector from point to point
        Vector3 perpendicular = Vector3.Cross(edge1,edge2).normalized * thisWidth;

        GL.Vertex(p1 - perpendicular);
        GL.Vertex(p1 + perpendicular);
        GL.Vertex(p2 + perpendicular);
        GL.Vertex(p2 - perpendicular);
    }

    Vector3 to_world(Vector3 vec)
    {
        return gameObject.transform.TransformPoint(vec);
    }

    /*
    ████████       █▀▀▄  █▀▀▀  █▄ █  █▀▀▄  █▀▀▀  █▀▀▄
    ████████       █▀▀▄  █■■   █▀▄█  █  █  █■■   █▀▀▄
    ████████       █  █  █▄▄▄  █ ▀█  █▄▄▀  █▄▄▄  █  █
    */

    void OnRenderObject () {
        gameObject.renderer.enabled=render_mesh;
        if (size >  3){
            lineMaterial.SetPass(0);
            GL.Color(lineColor);

            if (lineWidth == 1) {
                GL.Begin(GL.LINES);
                if(render_wiresframe){
                    for(int i = 0; i<size; i++)
                    {
                        GL.Vertex(to_world(points_a[i]));
                        GL.Vertex(to_world(points_b[i]));
                    }
                }
                if(normal_length>0){
                    update_normal_length();
                    for(int i = 0; i<normals.Length; i++){
                        Vector3 center = to_world(normals_center[i]);
                        GL.Vertex(center);
                        GL.Vertex(center+normals[i]);
                    }
                }
                if(vertext_extention_length > 0){
                    update_vertex_extension_length();
                    for(int i = 0; i<vertices.Length; i++){
                        Vector3 vertex = to_world(vertices[i]);
                        GL.Vertex(vertex);
                        GL.Vertex(vertex+vertex_extensions[i]);
                    }
                }
            } else {
                GL.Begin(GL.QUADS);
                for(int i = 0; i <size; i++) {
                    DrawQuad(to_world(points_a[i]),to_world(points_b[i]));
                }
                if(vertext_extention_length > 0){
                    update_vertex_extension_length();
                    for(int i = 0; i<vertices.Length; i++){
                        Vector3 vertex = to_world(vertices[i]);
                        DrawQuad(vertex,vertex+vertex_extensions[i]);
                    }
                }
                if(normal_length>0){
                    update_normal_length();
                    for(int i = 0; i<normals.Length; i++){
                        Vector3 center = to_world(normals_center[i]);
                        DrawQuad(center,center+normals[i]);
                    }
                }
            }
            GL.End();
        }else{
            print("No lines");
        }
    }
}

```
> 3 votes

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


# Question
Title: C# Refence or instance ( For List and assignment )
**First question :**

Does List holds the refence to an object or the instance itself ?

**Second question :**

When I assign an object to another, are they the same instance or two different ones ?

```
MyObjectType tempObject = realObject;

```

**Third question :**

When I assign a List to another List, are they same Lists or different ones ?

```
List<MyObjectType> tempList = realList;
tempList.Remove(someObject);

```

Thanks.

# Answer
> 0 votes
1. A List holds a bunch of references. In regards to C# from C++, basically every Reference-type (i.e. derived from class, NOT struct) is a "reference."
2. If they're classes, they are TWO REFERENCES to the same instance.
3. Again -- reference to the same List -- so the update you do will happen on both. (realList will lose the item in it).

To give you a better understanding C#'s garbage collector looks to find when things are no longer referenced... i.e. you have a reference type that is no longer having a scope (i.e. it was declared and used in a method, but that method has exited the call stack) -- and if so, it marks it for garbage collection. Now, if you return that reference type from a method, the method no longer has access to the local (so it would normally be marked for garbage collection), but the call stack one level down now has a reference to that object, so it will not be marked for collection.

I highly recommend looking at the GC for C# -- it might give you more perspective on what's going on under the covers. It really cemented my understanding of these things.

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


# Question
Title: Unity 2D, do Touch event must happen in the update() function?
***(Unity 5.1)***

My Issue is when attaching a script to a gameObject, all the examples I've found are based with the update() function and it's pretty wierd for me, as a desktop games developer.

**Is there anything like "OnMouseDown()" or other functions for a Touch platform game? Or do I must figure it out with Touch.GetInput from the update() function and that's it?**

Sorry in advance if my question is a bit cliche, it's just driving me nuts because I can't find anything with the Unity API or code examples, and I just can't believe there is no some "OnTap()" function...

# Answer
> 1 votes
There is no event handlers for touch inputs. You can make them if you want. It's not very difficult but I don't recommend doing it like you have described anyway.

Input events should map to the actions to take, rather than the specific input method used to implement that action. Consider if you are making a game for both desktop and mobile. *OnTouch* doesn't make sense on the desktop and *OnClick* doesn't make sense on mobile. It's better to have something like an *OnSelect* event that is called when either a touch or a mouseclick occurs.

Also consider if you might want to allow the user to remap the inputs or even if you decide to change the input mapping yourself during development. *OnTouch* or *OnClick* events would create complications and require reworking lots of code, rather than just having OnSelect and changing how it's triggered.

To make your own event handlers, investigate the GameObject.SendMessage() method.

Basically, what you would do is perform your tests for touch or left-click in the `Update()` method and trigger your *OnSelect* event when one or the other is detected by using SendMessage.

---
Tags: unityscript, unity
---


# Question
Title: How to keep my Quaternion-using FPS camera from tilting and messing up?
I am using an FPS-like camera, and it uses quaternions. But, whenever I try looking up and then sideways, it tilts, and sometimes it can turn upside down. How can I fix this?

# Answer
> 20 votes
You could decompose your quaternion into a yaw/pitch/roll set of angles, but that's overkill usually.

Instead of composing your quaternions like this:

```
cameraOrientation = cameraOrientation * framePitch * frameYaw;

```

Try this:

```
cameraOrientation = framePitch * cameraOrientation * frameYaw;

```

It will then never generate tilt/roll and is equivalent to storing yaw and pitch separately

# Answer
> 9 votes
This is a problem I had for a while, and I couldn't find any answers for, so I thought I would post it here.

It is actually quite simple. How you are most likely doing the rotations is like this:

```
currentDirection * newRotation;

```

But, doing it like this doesn't work either.

```
newRotation * currentDirection;

```

What you have to do, is do it in the first order for the up and down rotations, and in the second order for the sideways rotations.

For me, it was like this:

```
        if (keyboard.IsKeyDown(Keys.Up))
            Direction = Direction * Quaternion.CreateFromAxisAngle(new Vector3(1, 0, 0), TurnSpeed);
        if (keyboard.IsKeyDown(Keys.Down))
            Direction = Direction * Quaternion.CreateFromAxisAngle(new Vector3(-1, 0, 0), TurnSpeed);
        if (keyboard.IsKeyDown(Keys.Left))
            Direction = Quaternion.CreateFromAxisAngle(new Vector3(0, 0, 1), TurnSpeed) * Direction;
        if (keyboard.IsKeyDown(Keys.Right))
            Direction = Quaternion.CreateFromAxisAngle(new Vector3(0, 0, -1), TurnSpeed) * Direction;

```

For a reason why, the first way has the rotation relative to the current sideways direction, which you want for up and down, but you don't want that for the sideways rotations, which is why the second order is needed.

# Answer
> 5 votes
For an FPS camera you usually don't want roll and are limited to +/- 90 degrees pitch, so I'd just keep track of the current state using yaw and pitch angles. The full power of quaternions isn't really helpful for this.

You can still convert the yaw/pitch angles to and from quaternions in case you want to transition between the FPS camera and animated cameras using quaternion keyframe interpolation, or something like that.

# Answer
> 0 votes
Another simple trick is to put the camera in a GameObject, and have the Yaw rotation control the game object, while the child camera is configured with the Pitch coordinates:

```
playerCameraHolder.transform.Rotate(0, rotationYaw, 0);
playerCamera.transform.Rotate(rotationPitch, 0, 0);

```

---
Tags: camera, rotation, first-person-shooter, quaternion
---


# Question
Title: Box2d java contact point reference changes after collision
I am trying to hold the contacts made during a collision in an array list. After I add n amount of contacts, when I try to retrieve them later on, they point to the last contact made in the world.

How can I save the contact that was there initially?

I am using Box2d and Libgdx with Java.

```
public void beginContact(Contact contact) {
    Fixture fa = contact.getFixtureA();
    Fixture fb = contact.getFixtureB();

    if (isFixtureCheckpoint(fa) || isFixtureCheckpoint(fb)) {
        checkpointContact.add(contact);
    }
}

```

and when I am trying to retrieve in the update method, any contact that i get back is from the last contact made in the world:

```
public void update(float delta) {
    Fixture fa;
    Fixture fb;

    if (checkpointContact.size > 0) {
        fa = checkpointContact.first().getFixtureA();
        fb = checkpointContact.first().getFixtureB();

        if (isAnyFixtureRearWheel(fa, fb)) {
            // <--- This returns true. Why?
        }

        if (isFixtureCheckpoint(fa)) {
            context.progressHandler.checkpointPassed(fa.getBody().getWorldCenter());
        }
        if (isFixtureCheckpoint(fb)) {
            context.progressHandler.checkpointPassed(fb.getBody().getWorldCenter());
        }
    }
}

```

The comparison functions are comparing to different unrelated classes:

```
/* Check if ANY fixture is a rear wheel */
private boolean isAnyFixtureRearWheel(Fixture fa, Fixture fb) {
    if (((fa.getUserData() instanceof VehicleRearWheel) || (fb.getUserData() instanceof VehicleRearWheel))) {
            return true;
    }
    return false;
}

/* Check if fixture is contacting the flag */
private boolean isFixtureCheckpoint(Fixture f) {
    return f.getUserData() instanceof ProgressHandler;
}

```

EDIT: Last time I checked Java was considered a pass by value language?

# Answer
> 0 votes
It seems like Box2D is not creating a new instance of Contact everytime, but instead it is changing the most recent contact object's variables. So when you reference the contact object, you get the "updated" one (same object, but with updated variables).

You could simply save whatever information you need from the contact object to an object of your own custom class and add that to your list instead.

---
Tags: java, android, libgdx, box2d, jbox2d
---


title: How do I store an FBO'S as a cube map?

text:
# Question
Title: How do I store an FBO'S as a cube map?
As of late I've been trying to implement Cubemaps in my engine, and have managed to get the rendering side of them working. Currently, I'm trying to implement a function for *creating them*, but I somehow hit a road block.

The way I'm trying to implement this is by rendering my scene once into an FBO from the perspective of the cubemap node (x6 times, one in each direction), and cycle the format of the texture bound to the color attachment as:

> GL\_TEXTURE\_CUBE\_MAP\_POSITIVE\_X, GL\_TEXTURE\_CUBE\_MAP\_NEGATIVE\_X, etc

For whatever reason, I haven't been getting any expected results.

## All I want to do is take snapshots from the camera's perspective, but I need them in texture units I can use multiple frames over.

I've tried so many ways that I couldn't possibly recount them all here, but the general gist of how I've been trying to go about doing this, is this:

```
DTextureCubemapComponent *cubemap = getTexture(); // My Texture Component
GLuint target = cubemap->textureObj();            // CUBEMAP texture handle
glBindTexture(GL_TEXTURE_CUBE_MAP, target);       // Make cubemap active

for (int x = 0; x < 6; x++)                       // Render from 6 different angles
{
    gbuffercube->swapFinalFormat(GL_TEXTURE_CUBE_MAP_POSITIVE_X + x);
    gbuffercube->StartFrame();                    // my FBO Class, binds itself, etc

    /*... RENDER SCENE ...*/                      // Draw into my FBO, etc

    gbuffercube->BindForFinalPass();              // Read buffer == my FBO
}
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);

```

Where "SwapFinalFormat()" is:

```
void GBuffer::swapFinalFormat(GLuint format)
{
    format = fmt;
    glTexImage2D(format, 0, GL_RGBA32F, size.width(), size.height(), 0, GL_RGBA,     GL_UNSIGNED_BYTE, NULL);
    glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT6, format, m_finalTexture, 0);
}

```

I know that my FBO class works (labeld GBufferCube above) , as it is the same class I use normally for my deferred shading system.

# Answer
First of all don't use `glCopyTexImage2D` with FBOs, the whole point of using FBO is to avoid copying, and have multirender target support on the GPU side without copying.

FBO acts as a container of buffers and redirect rendering output to those buffers, without copying anything.

For instance you can attach a texture object or pixel buffer object to the FBO and all the rendering will be automatically redirected to the attached buffer. You can attach a texture to Color attachement 0 and then bind that texture to the current texture unit and use it as ordinary texture, the whole point is to avoid copying, everything happens on the GPU side. The steps roughly are:

1. Create an FBO
2. Create a texture object.
3. Attach the texture object to the FBO using glFramebufferTexture
4. Before rendering bind the FBO, rendering will be redirected to the FBO attachements.
5. Bind your created texture object, and use it in shaders like an ordinary texture in a different pass.

Oh, and before drawing anything to the FBO don't forget to clear it.

Finally this is just a rough guideline, for more details see this tutorial.
> 1 votes

---
Tags: opengl, textures, rendering, cubemap, frame-buffer
---


title: Where to save game data?

text:
# Question
Title: Where to save game data?
For my game, I'm currently considering where I should save the player's information (configuration files, state saves, player generated content). 'Where' refers to the physical location on disk. I have seen these approaches (there are probably more):

* (A subfolder in) the game's install dir (\Program Files\somegame\save\config.sav)
* A subfolder in My Documents (\Users\someuser\My Documents\gamename\config.sav)
* A subfolder in My Games (\Users\someuser\My Documents\My Games\gamename\config.sav)

Are there any important advantages to / reasons for using one over the other?

# Answer
As player, I prefer to have my saved games along with other game files. The reason for this is that when I need to reinstall my system, the save is still there and I don't have to remember to backup some, more or less, arbitrary location. I've lost saves for several games just because they were stored in some locations you mentioned. Sometimes they were even worse.

Despite that, the main reason for sending it to, e.g. "Users\someuser\My Documents\My Games\gamename\\", is that every user has control over his own files, not all the users in the system.

If the game is relatively small, I suggest storing save files within game folder. If not, decouple them and store in user-specific folders for safety reasons. The "My Games" folder is becoming more popular, so I place my bet on it.
> 2 votes

# Answer
The place to save application specific data like savegames is `%APPDATA%`, or possibly `%LOCALAPPDATA%`. The documents folder is a folder that's managed by the user.

`Program Files` is very wrong, because first you need admin rights to access this folder, second you will access the wrong folder on 64 bit machines, and third you will access the wrong folder on non english machines.

`\Users\someuser\My Documents` is wrong because this folder should be managed by the user, the name of the folder changes in different Windows versions, and the name of the folder changes on non english machines.
> 2 votes

---
Tags: xna, windows, .net
---


title: How to render portals in OpenGL?

text:
# Question
Title: How to render portals in OpenGL?
I am making RPG in OpenGl and I need to make some portals. How should I render it if I want to see through the portal on the other side?

# Answer
> 5 votes
You have two scenes rendered from two camera perspectives: one in local space and one in portal space. You need to superimpose part of the latter onto the former. You need a working knowledge of G-buffers (deferred shading) to achieve this, so I suggest you begin your research there.

**First** shader pass: Construct a G-buffer for your local scene. In your specific case, you'll have a colour buffer dedicated to masking out the silhouette of the portal from a local perspective; it will contain a colour (say white) denoting where your portal surface is, with everything else in local space being rendered black. This mask is used so that you know which pixels of your rendered local scene should be considered as a window into "portal space".

**Second** shader pass: Render your portal space scene with same camera orientation, but camera position shifted by the same vector that describes the camera's offset from the portal in local space.

**Third/final** shader pass: Use mask to cut out the section of the portal scene that you need to super-impose over the portal surface in the local scene, and super-impose in the fragment shader.

**DISCLAIMER** This is all easier said than done - getting into multi-pass rendering and g-buffers is a considerable amount of work if you've never done it before - expect several long days to several weeks depending on your level of skill, available time and general luck during implementation. Also, understand that deferred shading has a high cost and may be unsuitable for certain mobiles.

---
Tags: opengl, c++, glut
---


# Question
Title: Translating an object in the rotation direction
I am creating a graphical scene with OpenGL and SDL, and I'm running into a problem in regards to translating an object in its rotation direction.

Each of the graphical objects in the scene has a `Transform` object, which contains the object position, rotation, and scale. The following code in the `Transform` calculate the model for the object:

```
    inline glm::mat4 GetModel() const
    {
        glm::mat4 matx;
        matx = glm::translate(matx, m_translateV);
        matx = glm::rotate(matx, m_rotateV.x, glm::vec3(1.0, 0.0, 0.0));
        matx = glm::rotate(matx, m_rotateV.y, glm::vec3(0.0, 1.0, 0.0));
        matx = glm::rotate(matx, m_rotateV.z, glm::vec3(0.0, 0.0, 1.0));
        matx = glm::scale(matx, m_scaleV);

        return matx;
    }

```

Additionally it has getters which return a pointer to each `vec3`, so that I can modify it when I request it (not too important for my issue, just giving you a background).

```
    inline glm::vec3* GetPos() { return &m_translateV; }
    inline glm::vec3* GetRot() { return &m_rotateV; }
    inline glm::vec3* GetScale() { return &m_scaleV; }

```

The following code is called from my main game loop to process key inputs:

```
SDL_Event event;
std::shared_ptr<ENGINE::RenderObject> ro = m_renderer.GetRenderObject(0);
ENGINE::Transform t = ro->GetTransform();

if (SDL_PollEvent(&event))
{
    if (event.type == SDL_KEYDOWN)
    {
        if (event.key.keysym.sym == SDLK_ESCAPE)
        {
            m_gameState = GameState::EXIT;
        }
        if (event.key.keysym.sym == SDLK_w)
        {
            t.GetPos()->x -= glm::sin(glm::radians(t.GetRot()->y)) * 0.5;
            t.GetPos()->z -= glm::cos(glm::radians(t.GetRot()->y)) * 0.5;
        }
        if (event.key.keysym.sym == SDLK_s)
        {
            t.GetPos()->x += glm::sin(glm::radians(t.GetRot()->y)) * 0.5;
            t.GetPos()->z += glm::cos(glm::radians(t.GetRot()->y)) * 0.5;
        }
        if (event.key.keysym.sym == SDLK_a)
        {
            t.GetRot()->y += 0.1;
        }
        if (event.key.keysym.sym == SDLK_d)
        {
            t.GetRot()->y -= 0.1;
        }
    }
}

ro->SetTransform(t);

```

The problem I'm having is that even if I rotate my object, it keeps translating in the same direction (forward on the z-axis). The following two images should explain what I mean (the object of interest is the rotated one):

Image 1 : With rotation before translation (before pressing w):

Image 2 : With rotation and translation:

As you can see, even though I have rotated the object using `a and d`, when I press `w or s` to translate the object, it keeps translating in the same direction.

I have tried another case, where I create some rotation values, but I don't actually rotate the object. What happens in this case is that even though when I press `a or d` the object doesn't actually appear to rotate, however it will translate in the correct direction when I press `w or s`. The following is the code change that I tried:

```
if (SDL_PollEvent(&event))
{
    if (event.type == SDL_KEYDOWN)
    {
        if (event.key.keysym.sym == SDLK_ESCAPE)
        {
            m_gameState = GameState::EXIT;
        }
        if (event.key.keysym.sym == SDLK_w)
        {
            t.GetPos()->x -= glm::sin(glm::radians((float)direction)) * 0.5;
            t.GetPos()->z -= glm::cos(glm::radians((float)direction)) * 0.5;
        }
        if (event.key.keysym.sym == SDLK_s)
        {
            t.GetPos()->x += glm::sin(glm::radians((float)direction)) * 0.5;
            t.GetPos()->z += glm::cos(glm::radians((float)direction)) * 0.5;
        }
        if (event.key.keysym.sym == SDLK_a)
        {
            direction += 5; // new line
        }
        if (event.key.keysym.sym == SDLK_d)
        {
            direction -= 5; // new line
        }
    }
}

ro->SetTransform(t);

```

I can't seem to figure out why exactly the object doesn't translate in the correct direction when I apply rotation to it, but it does when I don't apply rotation and instead use some other value in the calculation for the `x and z` values. I am uploading the model matrix normally to the vertex shader.

Hope the question/issue is clear. I will provide any additional code if needed.

Thanks

# Answer
What are the effects of this:

```
inline glm::mat4 GetModel() const
{
    glm::mat4 matx;
    matx = glm::scale(matx, m_scaleV);
    matx = glm::rotate(matx, m_rotateV.x, glm::vec3(1.0, 0.0, 0.0));
    matx = glm::rotate(matx, m_rotateV.y, glm::vec3(0.0, 1.0, 0.0));
    matx = glm::rotate(matx, m_rotateV.z, glm::vec3(0.0, 0.0, 1.0));
    matx = glm::translate(matx, m_translateV);
    return matx;
}

```

(A little confused by the graphics; I may need to revise this when you reply)

I use XNA primarily and am not quite familiar enough to provide 100% code yet. That being said, to calculate character-forward, I would do something like this.

```
W:  t.GetPos() += ((0, 0, -1) * t.GetRot()); //Vector3.Forward * t.Rotation
S:  t.GetPos() += ((0, 0, +1) * t.GetRot()); //Vector3.Backward * t.Rotation

```
> 2 votes

# Answer
I am working on similar project right now and I think that you have two problems. First is that you compute direction in a wrong way. Try changing signs before **sin** and **cos**. For example:

```
if (event.key.keysym.sym == SDLK_w)
{
    t.GetPos()->x += glm::sin(glm::radians(t.GetRot()->y)) * 0.5;
    t.GetPos()->z -= glm::cos(glm::radians(t.GetRot()->y)) * 0.5;
    // or:
    // t.GetPos()->x -= glm::sin(glm::radians(t.GetRot()->y)) * 0.5;
    // t.GetPos()->z += glm::cos(glm::radians(t.GetRot()->y)) * 0.5;
}
if (event.key.keysym.sym == SDLK_s)
{
    t.GetPos()->x -= glm::sin(glm::radians(t.GetRot()->y)) * 0.5;
    t.GetPos()->z += glm::cos(glm::radians(t.GetRot()->y)) * 0.5;
    // or:
    // t.GetPos()->x += glm::sin(glm::radians(t.GetRot()->y)) * 0.5;
    // t.GetPos()->z -= glm::cos(glm::radians(t.GetRot()->y)) * 0.5;
}

```

Secondly, change the order of a model matrix rotation to

```
inline glm::mat4 GetModel() const
{
    glm::mat4 matx(1.0);
    matx = glm::translate(matx, m_translateV);
    matx = glm::rotate(matx, m_rotateV.z, glm::vec3(0.0, 0.0, 1.0));
    matx = glm::rotate(matx, m_rotateV.y, glm::vec3(0.0, 1.0, 0.0));
    matx = glm::rotate(matx, m_rotateV.x, glm::vec3(1.0, 0.0, 0.0));
    matx = glm::scale(matx, m_scaleV);

    return matx;
}

```

You can find here a good explanation of the order of matrices rotation.
> 0 votes

# Answer
In 3d programming, the sooner you stop using angles to represent rotations, the easier 3d programming becomes. It's ok to use angles to rotate something, it just muddys the water when you use them to represent something's overall rotation.

So instead of resolving the direction to move something through rotation angles, try it through your transform's columns which represent the exact directions you want the object to go anyway.

Currently you can get position, rotation, and scale. It is easy to also get forward, backward, right, left, up, down too. These are the directions you are trying to calculate with your angles.

psuedo code:

```
//assuming you have a Y-up system:
Vec3 forward = (transform[2][0],transform[2][1],transform[2][2]);//column 3 of your transform. Possibly m8,m9,m10 of the transform in openGL
forward.Normalize();
Vec3 backwards = forwards * -1f;
//for right, it is column 1 of your transform
//for up, it is column 2 of your transform

//then simply update position using these vectors:
pos += forward * speed;//when w is keyed
pos += right * speed;//when d is keyed
Pos += backward * speed;//when s is keyed
//etc.

```

If you are trying to do this to a camera's view matrix, you must invert the view matrix and use that.
> 0 votes

---
Tags: opengl, rotation, sdl, transformation
---


# Question
Title: How do I know what button was clicked? (Unity)
I have a prefabbed button (UI.Button) which I'm instantiating ten times:

```
public void LayoutButtons() {

    GameObject newCanvas = Instantiate (canvas) as GameObject;

    for (int i = 0; i < 10; i++) {
        buttons[i] = Instantiate(button, new Vector2((i * 100.0F)-500, -100), Quaternion.identity) as GameObject;
        buttons[i].transform.SetParent(newCanvas.transform, false);
        buttons[i].GetComponentInChildren<Text>().text = "Button " + i;
    }
}

```

However, I'm now stuck when trying to figure out which button was clicked. The Unity `onClick` seems to only allow zero or one parameters. I've tried using `public void onClick(Button button)` with `button.getComponentInChildren<Text>().text` but I get `ArgumentException: failed to convert parameters`

*All I want to do is print out the clicked button's text. How can I do this?*

# Answer
Instead of using the built-in `onClick` in the Editor, make your own and add the listener yourself.

```
public void PrintText(string buttonText) {
    Debug.Log("Clicked " + buttonText);
}

```

Add a listener in to your `LayoutButtons` function (you don't need to keep track of the buttons using the array so just use `tmp` or something):

```
tmp.GetComponentInChildren<Button>().onClick.AddListener( () => { PrintText(tmp.GetComponentInChildren<Text>().text); });

```
> 2 votes

---
Tags: c#, gui, events, unity
---


title: Animations with Model View Controller

text:
# Question
Title: Animations with Model View Controller
I'm currently wondering how to properly structure game code.

I have come across MVC (Model View Controller) method/approach, which seams to be a decent way to get a good extendable structure.

However, I'm wondering how one should put in animations and visual transitions into this model?

The simples example I can think of is Tetris.

In many newer Tetris clones, if a line is cleared, before it's removed from the screen, it sometimes flashes in different colors for visual effect. Where does this fit in the model?

The way I understand is that MVC has a controller that should update the board state, and if one line is full, it should be removed, yet the model would do this in a single frame? The view should not interact with the model, so what would be a good way to make these visual effects appear without loosing the benefits of decoupled logic and rendering?

Sorry if this is an ill posed question.

Thanks in advance : )

# Answer
Lately I've been wasting my spare time on an MVC/MVVM Monogame framework. I am writing a Roguelike as I go along.

Animations aren't easy. As you noticed, merely updating the model is not enough, since the animation lasts longer than the simple "remove a line" instruction in your code.

Moreover, the flashing animation wouldn't even belong in the model, as the animation state and duration aren't model values per se (model is our tetris block, for instance), but artifacts of a specific event (such as line removal).

You could have a viewmodel wrapping your model. A viewmodel's contents do not have to mirror its underlying model properties 1:1. A viewmodel is another abstraction layer. Something that includes view-specific properties that would otherwise pollute your model.

Now, such a system without observable properties (think WPF's Dependency Properties or Knockout.js observables) is somewhat of a pain to maintain and error prone due to its specular nature.

(By the way, this is the MVVM approach, model, view, view-model, if you want to look it up).

It's not easy. Development complexity increases in exchange for a potential long-term benefit you might not reap because you end up scrapping everything before completion.

Please let me know if this helps.
> 1 votes

---
Tags: architecture
---


# Question
Title: How to configure A* for large 2D Grid based pathfinding, where paths could be long or short?
I thought A\* was Optimal, meaning I'd always get the quickest path.

I have written a generic Pathfinding implementation here: https://github.com/mGuv/mGuv/blob/PathPerformanceExperiment/mGuv/mGuv/Pathfinding/Pathfinder.cs

It's a bit messy/weird as I've branched off my original to fix some issues and experiment.

I wrote a testing class that can read in an image file that uses Black for Obstacles, Blue for start, Green for goal. It too is a little messy but I'm just debugging again.

http://hastebin.com/wikejexige.avrasm

So it uses Euclidean Distance and Orthogonal movement to attempt to path.

It then generates an output image, with Black for Obstacles, Blue for the Path found, Orange for the Nodes Expanded, and Cyan for the Open Set.

Given the input image:

It outputs:

Which is less than Optimal?

I've tried tweaking the cost/heuristic functions and their weighting.

Eventually I can get something like:

But now look at that open set, it's essentially turned in to Dijkstra's Algorithm.

I also believe I have the "Breaking the tie" problem, as an input like:

Will expand way more nodes that necessary:

I've tried to follow the Wikipedia article on A\* to come up with better cost handling but most of those assume you know the estimated path length. Which is difficult for me as I will be using this to path find on giant (1024x1024+) grids that are dynamic. From tiny (\<10 step paths) to huge (\> 10000 step paths).

I'm a little lost now as to where I'm going wrong. I don't know if there's a bug or a misunderstanding. I apologise for the tiny images, it was just easier to work a pixel basis.

# Answer
> 0 votes
Someone on Reddit sussed it. The issue was on line 136. When it updates a node's position in the Open Set, it never replaced the Parent node. Meaning, yes, the node was correctly reordered and used in the path finding but when it came to reverse traversing to build the path, it used the out dated, more expensive parent.

The fix was to simply update that nodes parent at the same time as updating its cost.

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


title: GLFW Fullscreen OS X in LWJGL 3

text:
# Question
Title: GLFW Fullscreen OS X in LWJGL 3
How does one create a fullscreen window properly in OS X from the code, instead of just expanding into the current desktop?

I am referring to the sort of fullscreen window that one gets when the top-left-most green button is pressed.

*Is this actually possible?*

# Answer
After some research, This post caught my eye, where they said this property was added to the nightly build

```
System.setProperty("org.lwjgl.opengl.Display.enableOSXFullscreenModeAPI", "true");

```

Although you can always do it manually, see Here for a whole tutorial on creating a full screen display.
> 0 votes

---
Tags: lwjgl, macos, glfw
---


title: Difference between terrain and plane

text:
# Question
Title: Difference between terrain and plane
I'm going to make an environment with trees, walls, rocks, mountains and bushes in Unity 3D 5.1 . I don't know what game object suitable for the ground. I have used both terrain and plane in earlier simple projects.

My question is,

> What is the difference between terrain and plane?
>
> Which game object is suitable for my requirement?

# Answer
You need Terrain as it allows you to add vegetation (Trees & Details), make adjustments to the relief like rise land to form mountains and also it gives you ability to paint textures on it. A plane is a simple game object that can only be scaled on two axes and none of the above can be done with it.

They are both rendered only on one side of the object. By default the terrain object is scaled much larger than a plane.
> 6 votes

---
Tags: terrain, unity
---


title: characterController reference issue

text:
# Question
Title: characterController reference issue
I am trying to move my character to point that taken from mouse position.

here is my code:

```
private Vector3 hittedPoint=Vector3.zero;

 if (Input.GetMouseButtonDown (0)) {
             Ray ray = GameObject.FindGameObjectWithTag("MainCamera").GetComponent<Camera>().ScreenPointToRay(Input.mousePosition);
             RaycastHit hit;

         if (Physics.Raycast(ray, out hit)) {
             //get object
             GameObject hittedObject=hit.transform.gameObject;

             if(hittedObject==GameObject.FindGameObjectsWithTag("Ground")[0]){

                 hittedPoint= new Vector3(hit.point.x,transform.position.y,hit.point.z);
                 //hittedPoint = transform.TransformDirection (hittedPoint);

             }
         }
     }

             if (hittedPoint != Vector3.zero) {
                 float delta = (transform.position - hittedPoint).magnitude;
                 if (delta > 5) {
             controller.Move (hittedPoint*Time.deltaTime);
             Debug.Log (transform.position);
                 } else {
                     hittedPoint = Vector3.zero;
                     }
             }

```

The problem is that my object moves according to its first position at the scence. For example if I move character towards right then towards forward; at second movement it goes diagonal. It is like it makes its movements according the first position of it in scence.

The second problem is; i couldn't find efficient method for stopping movement when character reaches the point. If I decrease delta; character skips the point and if I increase it, character stops to early.

# Answer
> 0 votes
use

`controller.Move(( hittedPoint - transform.position)*speed*Time.deltaTime);`

to solve the two problems. Speed is for second problem. Decrese it as you get closer to target.

---
Tags: movement, raycasting, unity
---


title: How to decompose sprite sheet

text:
# Question
Title: How to decompose sprite sheet
I have a lot of spritesheets that are poorly formatted that I want to decompose, or split out into many small images, one for each sprite. If I can do that, I can use my custom texture packer tool to build my game assets with.

My development tools are XNA and C# targetting Windows. How can I decompose the images?

# Answer
> 6 votes
Try Sprite Decomposer or Sprite Vortex, I believe both of them have automatic sprite cutting based on alpha.

# Answer
> 0 votes
Two methods come to mind, depending on the number of fragments that you want to create:

Either Paint, as noted in the comments. Easily faster than coding something up if you have a small-ish number of spritesheets and/or if you are missing most of the mappings.

Or you could write a little XNA program that goes something like this:

# Answer
> 0 votes
You need to ether go to Adobe fireworks or Paint

But if your doing paint your also going to need paint.net! becuase if you use paint its going to have a background so once you open that sprite in paint.net you can take the background away its really simple but if your worryed about textures like in games you have to make your own.

---
Tags: xna, c#, algorithm, sprites, spritesheet
---


title: AS3 - Increase tint as health decreases

text:
# Question
Title: AS3 - Increase tint as health decreases
I'm working on a game where enemies continually spawn with more and more health based on how long you've been playing. As the enemies take damage, I'd like their sprite to get darker and darker, until they die.

Here's what I've got so far:

```
    enemy_array[i].health -= damage;
    healthcolor.setTint(0x000000, enemy_array[i].health*0.1);
    enemy_array[i].transform.colorTransform = healthcolor;

```

Predictably, this is making enemies get less black as they take damage. What I need is to convert the *decreasing* enemies' health into an *increasing* number between 0 and 1.

I have absolutely no idea where to begin. It's entirely possible I have tunnel vision, but I'm hoping someone here might have an idea for how to accomplish this.

Thanks for your time.

# Answer
A friend of mine actually provided a great solution on Facebook.

```
Healthratio = currentHealth/MaxHealth
tintRatio = 1.0 - healthratio

```

Anyway, I wanted to share that in the off chance anyone ever has a similar problem and wants a quick solution. Shout out to @keirmiron for that.
> 1 votes

---
Tags: flash, actionscript-3
---


# Question
Title: Issue creating a dynamic seemless cube map
I have a function for building a cube map, given a location in space. I also have a system for displaying cubemaps (either loaded from images or given as a texture handle), and **they work fine** and are used for displaying things such as a skybox as well as are used for reflections.

The issue is, when trying to create a cube map on the fly, I can't get it to be seemless, and it ends up looking like it is zoomed in, thus the right side of the image isn't complete.

This is what my scene looks like at an FOV of 90:

The left pillar isn't fully visible on the front side of the cube map, as well as the right pillar isn't even on that texture at all. The texture appears "zoomed in" so the last part of the image on the right side isn't even visible. This pattern occurs for each side of the cubemap.

If I increase the camera's FOV to 100, the pattern becomes even more clearer:

The way I'm trying to capture a cubemap is like this:

```
// Create camera, position at 0,0,0, rotate 0,0,0, 90 FOV
DCamera camera(QVector3D(0,0,0), QVector3D(0,0,0), 90.0f, 0x0004, 1.0f );
camera.setPerspective(512,512);

glBindTexture(GL_TEXTURE_CUBE_MAP, cubeTextureTarget);
for (int x = 0; x < 6; x++)
{
    QQuaternion q;
    switch (x) {
    case 0:
        q = QQuaternion::fromAxisAndAngle(0,1,0,90);
        break;
    case 1:
        q = QQuaternion::fromAxisAndAngle(0,1,0,-90);
        break;
    case 2:
        q = QQuaternion::fromAxisAndAngle(1,0,0,90);
        break;
    case 3:
        q = QQuaternion::fromAxisAndAngle(1,0,0,-90);
        break;
    case 4:
        q = QQuaternion::fromAxisAndAngle(0,1,0,0);
        break;
    case 5:
        q = QQuaternion::fromAxisAndAngle(0,1,0,180);
        break;
    }

    QMatrix4x4 mat;
    mat.rotate(q);
    mat.translate(camera.getPosition());
    camera.setModelMatrix(mat);

    /*... RENDERING LOGIC ...*/
}

```

When I set the camera's perspective projection, I do this:

```
void DCamera::setPerspective(int w, int h)
{
    projection = QMatrix4x4();
    projection.perspective( (fov), (float)w/(float)h, 1.0f, 1000000.0f );
}

```

In case it matters, my cubemap texture is formatted like this:

```
glBindTexture(ftype, cubeTextureTarget);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
for (int x = 0; x < 6; x++)
    glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X+x, 0, GL_RGBA32F, WindowWidth, WindowHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT6, GL_TEXTURE_CUBE_MAP_POSITIVE_X, cubeTextureTarget, 0);

```

Of course, I increment the texture target within the actual loop for rendering into the cubemap

---

I'm having trouble finding the proper resources for creating a cubemap. 99% of the hits I'm getting is for rendering a cubemap, not generating one...

# Answer
> 1 votes
I made a very stupid mistake: I forgot to make the call to glViewport(), as the texture is a different size then the screen. I forgot I had to do that.

---
Tags: opengl, textures, camera, projection, cubemap
---


# Question
Title: Unity - SetActive() on GameObject dont works on child's objects
I have the following line of code:

```
GameObject.Find("_obstacles").SetActive(false);

```

It serves to leave an inactive object, but the children of this object are not getting with the same status.

***My result is:***

> The objects children do not inherit the parent object state (as stated in the \> documentation of Unity)!

But the obsolete method "`SetActiveRecursively()`" works for me! O.o The Very strange, no?

# Answer
Have you tested if the child objects really are active in game? The behavior has changed from Unity3 when SetActiveRecursively was needed. Since Unity4, setting the parent to inactive should also deactivate the child objects (in game) even though it still shows them as active in the inspector.

See the documentation for GameObject.SetActive()

> **Note that a GameObject may be inactive because a parent is not active. In that case, calling SetActive() will not activate it, but only set the local state of the GameObject**, which can be checked using GameObject.activeSelf. This state will then be used once all parents are active.

If you really do want to deactivate the child objects, even when the parent is reactivated, then you will need your own function. Unity doesn't provide it anymore.

Here is a link to a solution that you can copy-paste to your own code.
> 1 votes

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


# Question
Title: Rotation of rectangles offsets render position
I have an unknown number "Bricks" that must follow a straight, but not always level, path. Each brick is rotated around one central point properly to form a shape of intersecting paths. My problem arises when rendering an image for a rotated brick. By rotating an image the width and height are changed thus altering the relative render point (top left, x/y). I need to find out what render offset would be necessary to make sure each brick is an equal relative distance from the center rotation point. I am using MonoGame (XNA) if that matters, but I don't currently have any code worth sharing (I need to understand this concept before anything else is worth coding). I hope the following image helps to visualize my problem. The example uses 3 bricks but that won't always be the case. https://i.stack.imgur.com/rO4IT.png

# Answer
> 0 votes
I haven't tried monogame yet, and mostly work in XNA. However, I'm still pretty sure this also applies to monogame.

Consider the following function (It's built into XNA and monogame):

```
public void Draw (
     Texture2D texture,
     Vector2 position,
     Nullable<Rectangle> sourceRectangle,
     Color color,
     float rotation,
     Vector2 origin,
     float scale,
     SpriteEffects effects,
     float layerDepth
)

```

As you can see, this function takes a float for rotation (in radians) and a vector2 for origin, as well as a texture2D and position. Of course, some other things like potential effects, but those are not important right now.

Using this function you can draw a texture2D. Let's say this texture2D of a brick is 20 pixels wide and 10 pixels high. You want to rotate your brick 60 degrees (or 1/3 * Pi), so that's what you fill in for "rotation". The vector2 "Origin" determins the point around which you'll rotate your texture. If you fill in `new Vector2(10,10)`, the rotation point will be the bottom center of the brick. The fun thing about a vector2 for position is that the ORIGIN of the texture2D will be drawn at this position. So you won't have to worry about finding the topleft coordinate.

You can find this function in the spritebatch class.

---
Tags: mathematics, graphics, rotation, monogame, trigonometry
---


# Question
Title: Generating objects randomly from prefabs in Unity2D
I am developing an infinite runner using Unity. I have already figured out how to loop a set of backgrounds randomly but I am having problems doing the same for the objects.

So, I have a few objects or obstacles in my prefabs. I want them to generate randomly in the game, not everything at once though.

How do I do that? Can I please get a well-explained piece of code for the purpose?

EDIT : I want the objects to be destroyed as soon as they move out of camera's view (The cam which is following the player).

Thank you.

# Answer
Load an array with all your prefabs (In the examples the prefabs are all into the same folder)

```
public List<GameObject> items;
void Start()
     {
         // If you store all your items that you want to load in the same folder (Assets/Resources/MyItemsToLoad).
         items = Resources.LoadAll("MyItemsToLoad") as GameObject[];
     }

```

When you need to random instantiate them

```
...
    int prefabIndex = UnityEngine.Random.Range(0,items.Count-1);
        Instantiate(items[prefabIndex], _position, _rotation);
...

```

Then put an empty gameobject with a "isTrigger" collider past camera view (i think you can make it child of camera):

Each obstacle object needs a script attached like this

```
 void OnCollisionEnter( Collision collision ) {

         if( collision.trasform.tag = 'DestroyTriggerCollider' ) {
         Destroy(gameObject);
         }
     }

```
> 1 votes

---
Tags: c#, 2d, random, unity
---


# Question
Title: Do I require a game engine  when I want to make a game?
I started making a 2D game in C# and realized that I could also use a game engine or XNA. For the moment everything works fine but I'm afraid I will have problems in the future.

So do I actually need a game engine or XNA? Or will it also works without.

PS: I don't know anything of XNA so I would learn it.

# Answer
Game engines are not required! However, since you seem to be new to game development, game engines are highly recommended. XNA will help you by abstracting away a large amount of complex tasks into easy ones. Think of the engine like a set of tools and code that covers all the "standard" game development tasks, so you don't have to re-write something that needs to be written for every game.

Obligatory game/engine advice: **Make games, not engines.**
> 12 votes

# Answer
It seems to be a slight misunderstanding here what a engine actually is. The foundation of a game is always called a engine. Can you build a car without a engine? No. But you can build your own, you don't have to depend on any premade engine. Your engine can be a tiny 100 lines of code or it can be a big beast of hundred thousands lines of code. Either way its a engine. Building big reusable engines is something rather new, ten/fifteen years ago every engine was a very specialized one, specifically build for the one game it was used in.

Building your game from scratch can teach you a lot about the implications of design decisions and I think every game developer should have gone through that process at least once for a small game.

However using a already existing engine will make a game require a lot less work, and why do the work again if it was done once already?

I tend to interpret the slogan "*Make games, not engines*" as "*Make your engine as small as possible*" because many programmers tend to work years on the engine for their game, implementing many things they don't really need, rather than the game itself. That way they never finish it.
> 7 votes

# Answer
Game engines make's it easier to create video games.But its not really 100% required to create.You can also use programming skills to create video games (Minecraft is created with Java)
> 0 votes

---
Tags: xna, c#
---


# Question
Title: Create a custom shape from a basic shape
Is it possible to create a custom shape by modifying one of the regular 3D objects in Unity3D 5.1?

For an example:
Make a cone from cylinder.

# Answer
> 2 votes
Yes, you can modify the default 3D objects but it's not as simple as you might hope. There are no controls in the editor to modify shapes, if that is what you mean. You can modify the mesh however you want using code though. Although, how to do that is too much to explain here.

You will need to investigate the Mesh component and it's functions. Check out some examples of how to build your own mesh and figure out from there how you would modify or create the shape you want.

Here is an example that shows how to create a plane (flat square) mesh.

# Answer
> 0 votes
Im pretty sure its possible on professional modeling tools like 3Ds Max or Blender.But it requires skills to make lets say a sword from bunch of blocks

---
Tags: unity, gameobject
---


# Question
Title: Batching texture to texture rendering in Unity on the gpu
I'm working on a 2D sidescroller within Unity 5.1. The terrain is intended to be semi-infinite in all 4 directions, procedurally generated using a noise algorithm.

I'm using a 3x3 grid of quads as "chunks" that I shift/update as the camera pans around. The issue I'm having is related to the dynamic texture I have tied to each chunk. When they need to be created rather than just shifted around, I'm not quite sure how to render individual tiles from a single texture to specific locations on another texture without using system memory.

Using setpixels, I believe it is passing color data each apply to the gpu side. Using gui/graphics with a rendertexture to drawtexture or any variants seems to be doing individual draws per call rather than giving me the opportunity to batch them. Using the native gameobjects has FAR too much overhead considering I'm trying to make tiles only be 8x8 pixels in size (meaning higher screen res = more on-screen tiles).

So, is it possible within Unity to do a low level texture to texture render/blit/draw/whatever without pulling texture data into system memory AND still batching same material/texture calls together without having to buy some toolkit from the asset store?

If any of this doesn't make sense, please ask anything you need to be able to help me and I'll update as needed.

Thanks!

# Answer
> 1 votes
It seems to me your best bet would be a dynamic mesh, whose material texture is the source texture, and which is drawn onto the target RenderTexture. The mesh's UV coordinates correspond to read position, and vertex coordinates correspond to write position. It'd be one draw call, although you'd need to create the mesh as well.

Still, for a simple mesh, creating the mesh would be very quick. Here are some performance tips if you do want to go down this route:

If your mesh can be of a fixed size (or you have an upper bound on how big it'll be), you can set it up once and then just update what's already there through `mesh.vertices = changedVertices;`. By using a fixed size mesh you avoid having to call Clear(), which can really hurt performance but is only necessary if mesh.triangles changes. For example, if you know you'll always need less than or equal to 1000 quads to do this batched blit, you'd have a mesh of 1000 quads, some of which may be degenerate (all vertices in the same position) depending on how many quads you actually want to draw. There's nothing wrong with a few degenerate quads at this scale -- in fact it'll be better than regularly having to use Clear() (which isn't cheap, apparently) every time the mesh changes.

If you're updating the mesh very regularly, you can MarkDynamic. This just tells the GPU it should keep the data somewhere it can quickly and regularly update it.

Avoid getting the mesh vertices from the mesh (`var x = mesh.vertices` actually has to build the array for you, even though it's disguised as a simple assignment). Instead you'll want to store your own copy of the vertices array, uvs array, and whatever else you'll be using.

If you're on mobile you can optimise this even more by double-buffering the changes to the mesh, so the CPU doesn't have to wait for the GPU to catch up with the changes you're making to the mesh:

```
void Update (){
  // flip between meshes
  bufferMesh = on ? meshA : meshB;
  on = !on;
  bufferMesh.vertices = vertices; // modification to mesh
  meshFilter.sharedMesh = bufferMesh;
}

```

*(...according to the manual under Mobile Optimisations; desktop doesn't seem to need this)*

If you're worried about the performance implications of updating a small mesh every frame, perhaps it'll be of comfort that I use a similar technique to have thousands of GPU-simulated particles and decals.

Also, while it might seem like a kind of hacky way to do things, this is probably how I'd do it in OpenGL, too, though I'd look into instancing or perhaps a geometry shader. One way or another, using a mesh to map from space on one texture to space on another is the best way to do this I can think of, assuming I understood your question.

---
Tags: unity, spritebatch, texture-atlas
---


title: Limit the boundary of Touch

text:
# Question
Title: Limit the boundary of Touch
a game that I currently working on is in a way that player should actually draw a rainbow on the screen by tap and drag gesture in order to make a hills for the car.

but the issue that i currently facing on is if the player wants to pause the game by touching the right most button on the screen above, the game will stop but the hill that he was drawn will remove. I actually not have any idea how can i put exception for that button on the screen because everytime i calculate the whole pixels on the screen for drawing hills. do you have any idea how can i solve this issue ?

btw, this is my code if it's required : http://pastebin.com/VnLAQbzW

# Answer
Hey the game is coming along nice :)

Ok so here is the simplest way to solve this problem. Check if the touch is inside a particular rectangular area on the screen and then only execute the rest of the Update function. Also you can add an additional boolean as Exerion has mentioned in his answer to check whether the menu screen is on.

```
Rect rect = new Rect(10, 10, 120, 120);

void Update()
{
   if ( !rect.Contains(Input.mousePosition) || inMenu)
      return;

   //Rest of the code

}

```
> 1 votes

# Answer
In your LineFreeDraw class create a public boolean variable:

```
public bool inMenu = false;

```

In Update() method check for this variable before anything else:

```
void Update()
{
    if(inMenu) return;
    // the rest of code here
}

```

Lastly, you should set this variable from the code of your button (that is not provided at the moment). Something like this: public LineFreeDraw lineFD;

```
public void OnButtonSettingsClick()
{
    lineFD.inMenu = true;
}

```
> 1 votes

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


title: Top view physics engine

text:
# Question
Title: Top view physics engine
For my first game i want to create a topview game in c++ where you can drive a car (like in gta2). As far as i know i dont need any gravity. While doing a bit of research about games they often advice a physics engine. What are the benefits of a physics engine on a topview game?

# Answer
Using ready-made components which are widely tested and professionally optimized instead of rolling your own can save you hundreds of man-hours of developing, testing and bugfixing...

...if they solve the problems you would otherwise have to solve yourself.

What any 2d physics engine should provide and what you definitely will have use for is collision detection. Finding out if and where two shapes collide is a problem almost every game needs to solve and which is easy to get wrong or unnecessarily slow when developed from scratch. So why reinvent the wheel when you can use collision detection algorithms already developed by someone else?

What might or might not be useful for you is managing movement. Acceleration and friction are usually not hard to do yourself, but what might be more challenging for you is calculating velocity vectors after impacts (how two cars push each other when they collide). Delegating this to a physics engine will give you a solid implementation with minimal work. Just make sure that the physics engine allows bodies to have different frictions for movement in different directions relative to their current rotation. This is necessary to account for the fact that cars are easier to push forward and backward than sideways. Otherwise your cars will behave like hovercrafts.
> 2 votes

---
Tags: physics-engine
---


title: Cube goes through objects

text:
# Question
Title: Cube goes through objects
I have Unity Pro 4.6.1 and I am trying to make a cube move with the arrow keys. Here are the barriers before I move the cube:

And here's when I move the cube (the problem):

I don't want the cube to go through the blocks, just inside them. Here is my moving code:

```
#pragma strict

static var selectedId : int;

static var speed : int = 5;

function Update () {

     if (Input.GetKey (KeyCode.UpArrow)) transform.Translate (Vector3(0,0,1) * Time.deltaTime*speed);
     if (Input.GetKey (KeyCode.DownArrow)) transform.Translate (Vector3(0,0,-1) * Time.deltaTime*speed);
     if (Input.GetKey (KeyCode.LeftArrow)) transform.Translate (Vector3(-1,0,0) * Time.deltaTime*speed);
     if (Input.GetKey (KeyCode.RightArrow)) transform.Translate (Vector3(1,0,0) * Time.deltaTime*speed);
}

```

How do I fix this?

**EDIT:** I modified my move code but it still goes through things:

```
#pragma strict

var speed : float = 10.0;

function Update () {
    var horMovement = Input.GetAxis("Horizontal");
    var forwardMovement = Input.GetAxis("Vertical");

    if (horMovement) {
        transform.Translate(transform.right * horMovement * Time.deltaTime * speed);
    }
    if (forwardMovement) {
        transform.Translate(transform.forward * forwardMovement * Time.deltaTime * speed);
    }
}

```

# Answer
> 1 votes
Collision detection is not applied when you Translate() a transform directly. In order to apply collision detection while moving, you must Move() a Rigidbody or CharacterController.

# Answer
> 0 votes
You must add a Rigidbody component to the cube's GameObject; this will allow it to get pushed back by other objects. The cube and all the barriers must have Collider components. You don't need rigidbodies on the barriers. Then, if you do not want the cube to rotate, turn on Freeze Rotation for all axes under the Rigidbody's Constraints.

While it is possible to use transform.Translate, you will get better results if you use rigidbody.MovePosition. This is because Translate attempts to teleport your object to the new position, and then during the next physics step, the colliders will interact. MovePosition will try to check collisions during the move.

You must call rigidbody.MovePosition during FixedUpdate. Notice that instead of a direction, it takes a destination point as argument. Calculate this accordingly. Also, try setting the Rigidbody component to use Interpolate for smoother motion.

As a performance tip, I suggest caching your Transform and Rigidbody as member variables during Awake, because the built-in properties will use GetComponent internally.

# Answer
> 0 votes
Rigid body collision using the cube mesh may cause you another issue as to get your cube between the gaps requires you to position it exactly. This may turn out to be quite frustrating, especially if you are colliding by one pixel and you cant see it.

I see that your map is created using a minimum of one cube in dimensions ( IE, there is no half cube steps ). If the cube is say 10 units in size, you could make the movement routine always move that amount. So pressing left would move 10 units ( or even better, move 1 unit 10 times for smoothness ). This way you will always be on a cube size boundary.

---
Tags: unity, javascript, transformation
---


# Question
Title: Most efficient way to mass render tiles in java slick2D
So I am trying to make a tile based game, it is rendering about 40 tiles on the screen at once. I get about 40 FPS on an okay computer. When I tell it to not render the FPS jumps to around 400 so I know its something with the rendering. I was wondering if there is a more efficient way to render a lot of tiles. Here is the code for my Tile class :

public class Tile { public static Tile empty; public static Tile rock; public static Tile flower; public static Tile grass;

```
public static Tile[] tiles;

protected boolean solid,breakable;

public static final int TILE_SIZE = 32;

public static final int VOID_TILE = 0, ROCK_TILE = 1,GRASS_TILE = 2,FLOWER_TILE = 3;

private int width = 16,height = 16;

private SpriteSheet image;
private int xCrop,yCrop;
private String path;
private boolean toRender = true;
private int ID;

public Tile(int ID) {
    this.ID = ID;
    path = ("res/spritesheet.png");
    if(ID == VOID_TILE) {
        solid = true;
        toRender = false;
        width = height = 16;
    }

    if(ID == ROCK_TILE) {
        solid = true;
        breakable = true;

        xCrop = yCrop = 1;
        width = height = 16;

        path = ("res/spritesheet.png");
    }

    if(ID == GRASS_TILE) {
        xCrop = yCrop = 0;
        width = height = 16;

        path = ("res/spritesheet.png");
    }

    if(ID == FLOWER_TILE) {
        xCrop = 1;
        yCrop = 0;
        width = height = 16;

        path = ("res/spritesheet.png");
    }
    if(toRender) {
        try {
            image = new SpriteSheet(path,width,height);
        } catch (SlickException e) {
            System.out.println("Error Loading File : " + path);
            e.printStackTrace();
        }
    }

}

public static void initTiles() {
    empty = new Tile(VOID_TILE);
    rock = new Tile(ROCK_TILE);
    grass = new Tile(GRASS_TILE);
    flower = new Tile(FLOWER_TILE);

    tiles = new Tile[] {empty,rock,grass,flower};
}

public void render(int x,int y) {
    if(image!=null)image.getSubImage(xCrop, yCrop).draw(x,y,TILE_SIZE,TILE_SIZE);
}

public void update() {

}

public int getID() {
    return ID;
}

public void setID(int iD) {
    ID = iD;
}

```

}

# Answer
> -1 votes
Jumping from 400 to 40 fps means something is really going wrong.

```
image.getSubImage(xCrop, yCrop)

```

I don't actually know much of slick, but I think that this loads the image to the graphics card. Try batching this (by making an instance variable in your class). I hope it helps!

# Answer
> -1 votes
My suggestion is to used TiledMap to do so:

https://bitbucket.org/kevglass/slick/src/aa6e7b6dce00d9725ef7e4c4fb6a99107f87c218/trunk/Slick/src/org/newdawn/slick/tiled/TiledMap.java?at=development&fileviewer=file-view-default

You can also see how tiledMap store and render tiles!

---
Tags: java, game-design, rendering, slick
---


title: Delay between bullets java - new Thread

text:
# Question
Title: Delay between bullets java - new Thread
Let's say that I have a cannon on the bottom of the screen that shoots balls to the click direction. I also have some collisions algorithms and here comes the problem. I am trying to implement an OnHold method that shoots continously and it works, but I think that I need to make shooting on another Thread. I've implemented this in two ways: 1. I was checking the delay and if it passed I shot 2. I was checking previous ball y position and when it floated away I shot

The problem comes here that when I hold the button for some time, for example. 5 balls are okay (they're near each other - not colliding) and then comes a ball that is late O.o

I don't know how to implement a new Thread within these MotionEvents. If is there someone who can point me (if should I make in on Threads or something) a solution - I would be grateful :)

```
  @Override
public boolean onTouchEvent(MotionEvent event) {
    // TODO Auto-generated method stub

    touched_x = event.getX();
    touched_y = event.getY();
    int i = 100;

    int action = event.getAction();
    if (action == MotionEvent.ACTION_DOWN) {
        startShootTime = new Date().getTime();
        running = true;
    } else if (action == MotionEvent.ACTION_MOVE ) {
        shootTime = new Date().getTime();
        // movement: cancel the touch press
        running = true;
        touched_x = event.getX();
        touched_y = event.getY();
       // && game.gameLoop.current_time - shootTime > 400 &&
              //  game.gameLoop.current_time - startShootTime > 100
        //  while(actionUpflag) {
        int size = game.gameLoop.balls.size();
        if(size == 0){
            game.gameLoop.balls.add(new Ball(metrics.widthPixels, metrics.heightPixels, touched_x, touched_y, game.gameLoop.ball_bmp_width, metrics.heightPixels-game.gameLoop.ball_bmp_width/2));
        }else if(size > 0 && game.gameLoop.balls.get(size-1).image_center_y < metrics.heightPixels - game.gameLoop.ball_bmp_width-50)
        game.gameLoop.balls.add(new Ball(metrics.widthPixels, metrics.heightPixels, touched_x, touched_y, game.gameLoop.ball_bmp_width, metrics.heightPixels-game.gameLoop.ball_bmp_width/2));

        invalidate(); // request draw

    } else if (action == MotionEvent.ACTION_UP) {
        running = false;
    }

    return true;
}

```

# Answer
It looks as if you have some kind of game loop running always? And so the game has a cannon object? If this is the case, you could use the touch event to inform the cannon update.

Please excuse my pseudo code..

in the event

```
public boolean onTouchEvent(MotionEvent event)
{

    touched_x = event.getX();
    touched_y = event.getY();

    game.gameLoop.cannon.fireAtTarget(x,y);
}

```

the cannon class

```
   void cannon::fireAtTarget( x,y )
   {
     firing = true;
     targetx = x;
     targety = y;
   }

```

the cannon update

```
void cannon::update( timeNow )
{

    if( firing && (timeNow-lastTimeFired > 0.5) )
    {
        // fire at targetx, targety.
        lastTimeFired = timeNow;
    }

}

```

Dont forget to disable firing in the touch up event
> 0 votes

---
Tags: java, multithreading
---


# Question
Title: How do you create images that work for multiple resolutions?
I'm currently doing some game development and I've been curious about this situation for many years.

Let's say your game has two resolutions: 640x480 and 800x600 (using small numbers just for simplicity). I have an image that I want to, no matter, take up 1/4 of the screen. For 640x480 resolution, it would be 320x240; while 800x600 resolution, it would be 400x300. There's a few ways I think of that this could be accomplished:

1. Make the image 320x240 and scale it up on the larger resolution (will look pixelated)
2. Make the image 400x300 and scale it down on the smaller resolution (loss of detail)
3. Create two separate images for each resolution (size bloat)

Just for 4:3 aspect ration, you probably have 5-6 resolutions that are commonly found in more professional games; plus additional ones for 16:10 and 16:9. Creating separate assets for each aspect ratio makes sense, but doing it for each resolution sounds like overkill and a huge size jump.

How do developers normally handle this sort of situation?

Thanks!

UPDATE: This information would be used for a 2D platformer.

Part of the reason that I'm interested in this is trying to keep a "level playing field" for all players no matter what resolution they are at. I don't want the 800x600 resolution player to be able to see more of the level than the 640x480 player can.

Additionally, since I really have no graphics experience, I'm not sure how much the resolution changes would affect the integrity of the images.

# Answer
You've covered the basic ideas in your question. Which method you use depends on your requirements. You might use a combination of approaches.

***1. Make the image 320x240 and scale it up on the larger resolution (will look pixelated)***
Do this if you don't need higher detail and just need to show the image larger. Good for low detail images like old-style sprites.

***2. Make the image 400x300 and scale it down on the smaller resolution (loss of detail)***
Even if you were to create a separate image for lower resolutions you will still lose detail, but in many cases it doesn't really matter much. It's a compromise.

***3. Create two separate images for each resolution (size bloat)***
This one is not quite right, but close. I can't think of any game that has different images for each resolution unless it only supports a couple sizes. Once you start dealing with many screen sizes, this is unfeasible. What some games do though is create a high-res and a low-res version of the images and choose the best match depending on the screen resolution.

What you are missing however is mipmaps, which is similar to #3 but a mipmap is stored in a single file and follows the mipmap format which is supported on the graphics hardware. Mostly these are just scaled computationally but you can edit them like any other image to fix loss of detail and other oddities that come up because of scaling. The mipmapping also doesn't correspond to screen sizes. Each level of the mipmap is 1/2 the size of the last, so it still uses a best-match approach. This is what most modern games do if they need different image resolutions.
> 2 votes

# Answer
The fourth option is to generate the image when you know the resolution (after startup).

This means having enough information in the game to properly render the image to texture on startup (and maybe caching it for future play sessions). This needs to be debugged carefully to ensure all resolutions come out correctly. But for things like text it's just about the only way to keep it sharp for all resolutions.
> 3 votes

# Answer
It can depend on the kind of game you are making. It sounds like you may have some kind of 2d, non scaling sprites display. If you are doing something like a 3d fps then you will most likely be scaling up or down. The optimization in this case is how you make this efficient. Mipmaps can help but then you need to try and make the selection optimal. Here's some good idea's on that kind of thing
> 1 votes

# Answer
I normally do all three. You make it sound like you need to choose 1 method and use it for all graphics, but that's not true. Each method has different pros and cons, so I use different methods on different images.

For example, my UI generally needs to be super-sharp, but it's also not full of important tiny details; perfect candidate for #2. On the other hand, background images are naturally large (often fullscreen) but can be blurry, so on those I use #1.
> 1 votes

# Answer
You can also make an image that has a frame of not-so-important-pixels which you can sacrifice. That way you can crop the important center part cutting the borders differently for each resolution and aspect ratio.
> 0 votes

---
Tags: image, resolution, scale, aspect-ratio
---


# Question
Title: Good algorithm to generate pixels for thick line?
I am not really making some drawing as of picture manipulation but I use line function to calculate "claimed" pixels in my line race game (**demo here**):

The actual rendering is apart from the game algorithm which uses map of integers to remember which line "claimed" which pixel. I **intentionally** do the game logic based on pixels, not line intersections, because in future I want to add all kinds of shapes and analytic geometry would make that pain to implement. Instead, I'll use raster map and eventually make it look smooth on the rendering side.

The problem I have right now is that under special occasions, one line can cross another - and this is not an algorithm error but concept error. The problem happens because sometimes, the lines look like this:

As you see, there's no pixel collision - and this is not as unlikely as it seems. Making the line thicker would fix this and probably also make the game look better, but it has a flaw too - the line will now "claim" pixels it has already claimed last iteration. The current "thin" algorithm is basically just copied from wikipedia:

```
/**
 * Returns array of points that form line between x1,y1 and x2,y2. The array looks like this:
 *  [x,y,x,y,x,y...]
**/
Line.straightPoints = function(x1,y1,x2,y2) {
  var result = [];
  // Define differences and error check
  var dx = Math.abs(x2 - x1);
  var dy = Math.abs(y2 - y1);
  var sx = (x1 < x2) ? 1 : -1;
  var sy = (y1 < y2) ? 1 : -1;
  var err = dx - dy;
  // First coordinates are not being added - it's assumed they were added in the last
  // iteration
  // Main loop
  while (!((x1 == x2) && (y1 == y2))) {
    var e2 = err << 1;
    if (e2 > -dy) {
      err -= dy;
      x1 += sx;
    }
    if (e2 < dx) {
      err += dx;
      y1 += sy;
    }
    result.push(x1);
    result.push(y1);
  }
  // Return the result
  return result;
}

```

But anyway, I need a trick to get this algorithm generate thicker line and I have no idea what to change. Should I generate circle of points for every point?

# Answer
> 2 votes
One way would be to generate tangents of a certain length and use them as coordinates to generate a triangle list.

So if the red dots are your points. You make a line to join the points ( in white ) and then generate a tangent to the white line ( in green ) of a defined length. You can then use the endpoints of the tangents to create a triangle list.

It does kind of depend on your original coordinate space. For the example here the red dots have distance between them.

If you label the endpoints of the tangents with letters A-F And so create triangles to join them up. So here, make a triangle using points A,B,C

# Answer
> 0 votes
> The actual rendering is apart from the game algorithm which uses map of integers to remember which line "claimed" which pixel.

What you see on the screen is actually a sampling of the geometric line. The line equation is continuous contrary to the samples you see on the screen.

You need to perform an intersection ray/line segment test before sampling (before generating the points). once you perform a ray/line test, you can change the generation direction in case there is an between the ray and the line within specific distance. This way you can avoid intersecting lines.

# Answer
> 0 votes
If you add this logic to collision check ? (using color as ID)

```
...
   if (nextpixel.x != currentPixel.x && nextpixel.y != currentpixel.y)
        //next and cur pixel are diagonal
        if (screen[currentpixel.x,nextpixel.y].Color ==
           screen[nextpixel.x,currentpixel.y].Color )
               COLLISION!
...

```

# Answer
> 0 votes
If you store which line claimed which pixel, then you can differentiate for sure left and right cases of the picture https://i.stack.imgur.com/EyeNX.png

In the left example the diagonal pair of pixels belongs to the same line, while in the right - to different lines.

---
Tags: mathematics, algorithm, html5
---


# Question
Title: What game engine should I use to mock around?
I'm a software engineer student (about to start my 2nd year) and I did really enjoy last years object-oriented programming and working with Java (greenfoot and later eclipse) to make simple games. I would really like to delve deeper in to software development and can't wait for 2nd year of college to start ,so I mocked a bit in eclipse and boy writing all of the game engine is hard and takes a lot of time, so maybe anyone knows an easy game engine just to mock around and explore game development for fun ?

# Answer
> 5 votes
Have you taken a look at: jMonkey Engine it's a free Java game engine that uses OpenGL and is licensied under BSD. Since they distribute all the engine source code, you can change it up and experiment as needed.

# Answer
> 3 votes
I am not going to recommend a game engine to you. However, I think you may like my suggestion better, and it is already well suited to the skills you have developed in Java.

You may wish to develop MineCraft plugins. You will naturally need a MineCraft account, and need to learn how to set up a Bukkit server, but this task will give you accidental skills you will want as a software engineer later anyway.

Also, there is a thriving community of MC plugin makers (I'm one of them), and examples are plentiful and almost always open source.

Plus, you can then start adding or changing functionality of a well-established game, which will give you quicker results than trying to make a game from nothing.

# Answer
> 0 votes
LibGDX (https://libgdx.badlogicgames.com/) is also popular game engine that uses Java. It's cross-platform and open-source under Apache 2.0 licence

# Answer
> -1 votes
You can try neoaxis.It's simple looking game engine.Or maybe cryengine unity unreal.OR if you just want to mess around level editing i say you use Far cry's map editor.Its not an game engine but its still fun and you still can use what you learned from there as a level designer.

---
Tags: java
---


# Question
Title: Clamp view direction vector to nearest axis
In JMonkeyEngine, given any view direction Vector3f instance, I'd like to get a new vector facing the nearest x or z axis (positive or negative), with y set to 0.

For example

```
[-0.99915564, -0.036672898, -0.018518358]
// -> should return [-1, 0, 0]

[-0.01313778, 0.042407744, 0.99901414]
// -> should return [0, 0, 1]

```

Is there a nifty math trick for this or do I need to manually check x and z and then set y to `0`?

Thanks.

### Update

So far, what I do is this

```
dir.x = dir.x >= 0 ? Math.floor(dir.x + 0.5) : Math.ceil(dir.x - 0.5);
dir.y = 0;
dir.z = dir.z >= 0 ? Math.floor(dir.z + 0.5) : Math.ceil(dir.z - 0.5);

```

Which produce the desired output. I was wondering if this can be done in a more elegant fashion (i.e. through some nifty matrix operation).

# Answer
There is (IMO) nothing wrong with your general approach. The function is nonlinear, so there's going to be some involvement of {if ?: abs sgn floor ceil} or the like somewhere.

Your code won't work quite right though. Won't (0.707, 0, 0.707) snap to (1,0,1)? Similarly, (0.44, 0.9, 0.0) would snap to (0,0,0).

There's four possible results, which can checked as:

```
if(abs(dir.x) > abs(dir.z))
{
    return dir.x < 0 ? Vector3f(-1,0,0) : Vector3f(+1,0,0);
}
else
{
    return dir.z < 0 ? Vector3f(0,0,-1) : Vector3f(0,0,+1);
}

```

(pardon if the language syntax is wrong)
> 1 votes

# Answer
I guess you could compare the dot product with each axis?

Something like..

```
Vector3f xDir(-1, 0, 0);
Vector3f zDir(0, 0, 1);

Vector3f getClosestViewDir(Vector3f myDir)
{

    if(myDir.dot(xDir) > myDir.dot(zDir))
    {
        return xDir;
    }

    return zDir;
}

```
> 0 votes

---
Tags: vector, jmonkeyengine
---


title: Modify Element of Struct Array

text:
# Question
Title: Modify Element of Struct Array
I have this struct array in GLSL.

```
struct Test {
    vec2 value1;
    vec3 value2;
    float value3;
}
uniform Test u_test[5];

```

How can I modify the elements of this array one at a time?

I know that the location of individual objects in an element in the array can be accessed using `glGetUniformLocation(program, "u_test[0].value1")` but I'd like to upload an entire instance of Test at once.

# Answer
> 0 votes
It is not possible to set the value of a struct as a whole, since there is no location for it.

All of my lookups returned `-1`. The values of a struct have to be set individually.

---
Tags: java, shaders, glsl, lwjgl, struct
---


# Question
Title: In Unity how do i make the camera follow a character in the y axis..?
I have a character which keeps moving in the y-axis and the camera needs to be fixed to follow with the character for some extent and when the character falls down camera should freeze at the point. The attached image will make u understand better.

# Answer
Put a script on the camera, get a reference to the 'player' gameobject, then move the camera vertically to match the player when the player is higher than the camera:

```
void Update() {
  if (player.transform.position.y > this.transform.position.y) {
    this.transform.position.y = player.transform.position.y;
  }
}

```
> 2 votes

---
Tags: unity, camera
---