title: OpenGL 2.1 rotation , Gimball lock

text:
# Question
Title: OpenGL 2.1 rotation , Gimball lock
I'm working on a little app for a school project , which should be manipulating 3D objects. And i'm stuck with the rotation , as i'm facing what i think is called the gimball lock ? here's a video I uploaded that clarifies my problem : https://youtu.be/MT8nTAkvD6k

Now , from what I have understood , multiple rotations change the orientation of the object , but keep the X , Y , Z axis fixed , is that it ? Without knowing a lot about openGL , i thought that some projections like these would be enough : say Alpha is the angle following the rotation around X; The new Y and Z (let's Call them Y' and Z')axis would have this equation :

Y'=cos(Alpha)Y+sin(Alpha)Z

Z'=-sin(Alpha)Y+cos(Alpha)z

Based on this , i wrote this code (this method displays the teapot)

```
void Teapot::PrintObj()
{
        glLoadName(_NameStack);
        glPushMatrix();
        Translated();
        RotatedX();
        RotatedY();
        RotatedZ();

glColor3ub(_Color.red,_Color.green,_Color.blue);
glutSolidTeapot(2);

if(_Selected){WiredTeapot();Guizmo();}

        glPopMatrix();
};

```

Now this is the RotatedX method :

```
void Object3D::RotatedX()
{
rotY.x=0;
rotY.y=cos((angles.x/180.0f)*3.141592);
rotY.z=sin((angles.x/180.0f)*3.141592);

rotZ.x=0;
rotZ.y=-sin((angles.x/180.0f)*3.141592);
rotZ.z=cos((angles.x/180.0f)*3.141592);

glRotated(angles.x,rotX.x,rotX.y,rotX.z);
}

```

all the variables are declared within the class : the rotX , rotY and rotZ are the 3 vector axis , every time the object undergoes a rotation , these axis are modified;

The RotatedY method now :

```
void Object3D::RotatedY()
{
rotX.x=cos((angles.y/180.0f)*3.141592);
rotX.y=0;
rotX.z=-sin((angles.y/180.0f)*3.141592);

rotZ.x=sin((angles.y/180.0f)*3.141592);
rotZ.y=0;
rotZ.z=cos((angles.y/180.0f)*3.141592);
glRotated(angles.y,rotY.x,rotY.y,rotY.z);
}

```

Same thing , if this method is called it means that the object is rotated around the Y axis , hence the modification of the X and Z axis position.

and now the RotatedZ :

```
void Object3D::RotatedZ()
{
rotX.x=cos((angles.z/180.0f)*3.141592);
rotX.y=sin((angles.z/180.0f)*3.141592);
rotX.z=0;

rotY.x=-sin((angles.z/180.0f)*3.141592);
rotY.y=cos((angles.z/180.0f)*3.141592);
rotY.z=0;
glRotated(angles.z,rotZ.x,rotZ.y,rotZ.z);

```

I'm really struggling to make this work ; I've looked on the net and saw things like Quaternions (i don't even know what that is).

Thanks for helping me !

# Answer
> 1 votes
To avoid gimball lock you have to use quaternions. Since you are using the GLM library you already have code for that.

```
q1 = cos(a/2) + i ( x1 * sin(a/2)) + j (y1 * sin(a/2)) + k ( z1 * sin(a/2))

q2 = cos(a/2) + i ( x2 * sin(a/2)) + j (y2 * sin(a/2)) + k ( z2 * sin(a/2))

q3 = cos(a/2) + i ( x3 * sin(a/2)) + j (y3 * sin(a/2)) + k ( z3 * sin(a/2))

a = rotation angle
x1, y1, z1 = rotation axis 1
x2, y2, z2 = rotation axis 2
x3, y3, z3 = rotation axis 3

```

See http://glm.g-truc.net/0.9.4/api/a00153.html

---
Tags: opengl, rotation
---


title: Exact sizing in Maya

text:
# Question
Title: Exact sizing in Maya
I'm coming from modo and want to try to create mesh assets for Unity3D in Maya. As a simple example how do I create an exact 1m cube in Maya? In modo it's easy to do.

In maya I draw a roughly 1m cube onto the grid and then want to set it's exact size but the channel box already displays scale 1x1x1 even if it's not an exact 1m for each size.

How do I set it to exactly 1m (or whatever exact measurement)? Surely it must be possible?

# Answer
> 3 votes
You can change your scale to meters in preferences/settings.

From the Create menu select the little square next to polygon/cube which will bring up the options, change your size in the Single-click settings to 1x1x1 then single click on the grid to place a 1x1x1 cube.

---
Tags: maya
---


title: Moving Object on One Axis

text:
# Question
Title: Moving Object on One Axis
Hi Im trying to move some 3D text on one axis, but for some reason it moves on 2 with this code. Can someone explain why this is/ how to fix it? Maybe this is a simple solution but i cant find it.

```
using UnityEngine;
using System.Collections;

public class MoveTitle : MonoBehaviour {

    public bool ScrollDown = false;
    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update ()
    {
        if (Input.GetKeyDown("up") && ScrollDown == false)
        {
            transform.Translate(0.0f, -1.2f, 0.0f);
            ScrollDown = true;
        }
        if (Input.GetKeyUp ("up"))
        {
            ScrollDown = false;
        }
        if (Input.GetKeyDown("down") && ScrollDown == false)
        {
            transform.Translate(0.0f, 1.2f, 0.0f);
            ScrollDown = true;
        }
        if (Input.GetKeyUp ("down"))
        {
            ScrollDown = false;
        }
    }
}

```

# Answer
> 3 votes
because Translate is set to Space.Self if the Second Argument is left i would try this code below to force it to World Space

```
transform.Translate(Vector3.up * Time.deltaTime, Space.World);

```

# Answer
> 2 votes
At a guess and according to http://docs.unity3d.com/ScriptReference/Transform.Translate.html your problem might be the following:

> If relativeTo is left out or set to Space.Self the movement is applied relative to the transform's local axes. (the x, y and z axes shown when selecting the object inside the Scene View.) If relativeTo is Space.World the movement is applied relative to the world coordinate system.

As far as I understand that, you translate your object according to its own x, y, z axes, which can be different from the world x, y, z axes, for example after you rotate the object.

# Answer
> 2 votes
If you wish to change the position of your object at a set location, you can simply change the local position of your transform as such:

```
GameObject.transform.localPosition = new Vector3(0.0f, y, 0.0f);

```

Note: you need to increment the y value every time the up key is pressed.

If you are attempting to see the movement of the object from Vector3(0.0f, startY, 0.0f) to Vector3(0.0f, endY, 0.0f) every time you press up, you should probably use iTween and do something like:

```
var position = new Vector3(0.0f, y, 0.0f);
iTween.MoveTo(GameObject target, Vector3 position, float time);

```

Hope it helps.

# Answer
> 1 votes
If the movement speed/direction is not multiplied by Time.deltaTime than the movement speed on different computers might be different, so it is always good to do that to ensure the speed is the same on each computer and not depending on the performance of it.

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


title: Applying texture to a 3D object

text:
# Question
Title: Applying texture to a 3D object
I am trying to draw a 3D cube on the screen, using MonoGame. The cube was created in Blender and exported as an fbx file. The following is what the cube looks like in VS when opened in the editor:

And this is what it looks like when displayed on screen:

From the research that I've done so far, I believe that I need to apply a texture. I couldn't see any way to do this in Blender, or in the Content Pipeline Tool, and so I tried the following when drawing the effect:

```
effect.Texture = _texture;
effect.TextureEnabled = true;

```

When I run this, I get a runtime error:

> An error occurred while preparing to draw. This is probably because the current vertex declaration does not include all the elements required by the current vertex shader. The current vertex declaration includes these elements: SV\_Position0, NORMAL0, COLOR0.

Clearly I'm missing a key part of this puzzle; please can somebody point me in the right direction.

# Answer
**1. Creating textured model in Blender**
First, add a new texture by going to texture panel on the right. Select type "Image or Movie", click "Open" and locate your texture file.

Then, move your mouse to the 3d view, press Tab to select the default cube, then press "U" and select Unwrap.
Go to UV Image Editor:
and select the texture:
At this point, the cube should be textured and you can verify that by changing viewport shading to texture:
Now export the model as FBX file (all settings should be on default). When you open the model now in Visual Studio, the texture should also be visible.  **2. Converting the model**
Download Autodesk FBX 2013.3 Converter (http://usa.autodesk.com/adsk/servlet/pc/item?siteID=123112&id=22694909)
In the converter, add your fbx file, change the destination folder to the same one where your current file is (otherwise it creates a subfolder) and rename destination file so that it isn't same. Then press Convert.
Now open the Monogame pipeline tool and import both the converted model and the texture: **3. Rendering the cube**
I believe that your rendering code would now work, but to be sure, there is a simple code needed to render it properly:

```
public class Game1 : Game
{
    GraphicsDeviceManager graphics;
    private Model model;

    public Game1()
    {
        graphics = new GraphicsDeviceManager(this);
        Content.RootDirectory = "Content";
    }

    protected override void LoadContent()
    {
        model = Content.Load<Model>("Model1");
    }

    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.CornflowerBlue);

        foreach (ModelMesh mesh in model.Meshes)
        {
            foreach (BasicEffect effect in mesh.Effects)
            {

                effect.World = Matrix.CreateTranslation(new Vector3(0, 0, 0));
                effect.View = Matrix.CreateLookAt(new Vector3(5,5, 5), Vector3.Zero, Vector3.Up);
                effect.Projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45.0f), 1.6f, 0.1f, 10000.0f);
                effect.EnableDefaultLighting();
            }

            mesh.Draw();
        }

        base.Draw(gameTime);
    }
}

```
> 5 votes

---
Tags: xna, 3d, textures, monogame, vertex
---


# Question
Title: Strange anomalies when using WinForms with XNA
I haven't seen any questions related to my issue, and this leads me to believe I'm missing something minor, however;

**The Problem**

I'm creating a game that is effectively launched from a windows form. Consider the following code.

```
static void Main(string[] args) {
        main = new TestGame(); // The Game class.
        menu = new Menu(main); // The form.

        while (true) {
            if (menu.ShowDialog() == DialogResult.OK) {
                if (menu.ShouldStartGame) {
                    main.RunGame( /* Some params */ );
                } else {
                    ExitGame();
                    break;
                }
            }
        }
    }

```

This loop works fine. My issue lies in the form itself. Firstly, DialogResult does not trigger at all. When the result from menu.ShowDialog() is printed, its result is "Cancel" which is not the option set for the button (OK.) As well as this, picture boxes, the form background colour and other such controls do not work properly. And the form appears to have a UI style from Windows versions before or during XP. Is this a known issue or am I missing something?

# Answer
> 0 votes
The return value of ShowDialog is set by altering the value of Form.DialogResult. *To ensure that the correct result is set*, override the form's OnClosing invocator or hook its Closing event and set it there.

---
Tags: xna, c#, windows-forms
---


# Question
Title: MonoGame/XNA 3D fbx model produces strange rendering output
**The Problem:**

I have been making a model of a Steampunk-themed street light in Blender for use in my MonoGame/XNA Game. To test it I exported it to the \*.fbx file format using the fbx export plugin for Blender.

After setting everything up in the code and starting the game, that was the result:

As you can see some of the triangles are missing or their vertices are connected in a wrong way. In addition to this you can recognise two additional faces on the top that were not intended to be there.

I am using a pretty standard code to render my model with a `BasicEffect`:

```
        foreach (ModelMesh mesh in model.Meshes)
        {
            foreach (ModelMeshPart part in mesh.MeshParts)
            {
                part.Effect = effect;
            }
            mesh.Draw();
        }

```

**What I tried so far to solve the issue:**

* Searching on Stackexchange, no result
* Asking Google, no result
* Playing arround with the `GraphicsDevice` settings was either not solving the problem

```
    gDevice.RasterizerState.CullMode = CullMode.None;
    gDevice.DepthStencilState = DepthStencilState.Default;
    gDevice.BlendState = BlendState.Opaque;

```
* Downloading the latest Blender version and exporting again did not solve anything despite the fbx plugin was updated
* I also suspected a problem with the normals so I recalculated them in Blender but it did not help too

**What software/hardware did I use?**

* Surface Pro 2 (intel core i5 with intel hd 4400 graphics)
* Blender 2.75a
* Visual Studio Express 2013
* MonoGame Framework(I believe its version 3.4)

So here are my questions:

**What is causing this result? Could it be a problem with MonoGame/XNA or a problem with Blender/the fbx exporter (or my export settings?)?**

**Did maybe one of you had such issues with fbx models and MonoGame/XNA?**

I would very appreciate any guesses, help or solutions from you. If you need more Information, just ask for it. Thanks in advance.

# Answer
After another hour of researching and trying I finally solved the problem. As Shiro suspected it was not the rendering code that causes the problem. I tried it with models from which I know they worked for other projects and they were drawn just fine.
So I began to search for issues with the lamp model itself. With the current Blender exporter, there is no option to triangulate the model during conversion. But what I tried was to apply a triangulate modifier in Blender and then exporting it, but the result was even worse than before. Now the whole model seemed to be corrupted.
My research on the internet brought me to this bug report. According to this I tried everything again with Blender version 2.68 but this solved nothing. I continued my research on the mesh by looking specifically on the corrupted parts e.g. the right lamp. What I found was that I used linked duplicates (alt+d) to copy it from one side to the other. Also I joined all parts of the meshes together.
After playing around a bit with the two Blender versions and making duplicates real I solved it by first making all duplicates real, selecting all the single objects, applying the scale/rotation/location and checking "export selected" and "XNA strict options" in the export settings of Blender 2.68 and then exporting.

By the way to those of you who use MonoGame: the fbx exporter of Blender 2.68 does not support the binary fbx format so the fbx file will not work with the MonoGame content pipeline. To get my fbx converted to a xnb file I used a Content converter from CodePlex, and added some code to convert 3d models. I then manually put the xnb to the bin/Debug directory.

To conclude I think it was a problem with both the model/mesh and the fbx-exporter.

I hope I could help some other people too.
Thank you for your help.

Note: the original Content converter from CodePlex does not seem to have an official migration project elsewhere, however this GitHub project claims to be based on the original code.
> 1 votes

# Answer
Looks like a export setting. Make sure the model is triangulated on export or prior. Also I assume your draw call is set to indices with individual triangles? Might be worth checking if you get TriangleStrips exported.
> 0 votes

# Answer
I'm not sure what causes this problem completely, but I think that some blender models are just plain not supported well in XNA and the FBX format.

This has happened to me before, and my solution was to export the model as STL, upload it to here: https://netfabb.azurewebsites.net/ and import it back into blender and export as FBX.

The only downside is that the STL format doesn't seem to keep track of material and / or color settings, so generally this model fixing would have to be done before any texturing and stuff or you'd have to redo a lot of work.

Basically, why this works is because the STL format is for 3D printing. So the STL fixing tool (netfabb) pretty much has one main goal, make the object solid so that a 3D printer could understand it.

I hope that you find a better solution than I did, because this process can get very annoying. But if you can't, then I hope this works for you. :)
> 0 votes

# Answer
I think I know what is wrong. It seems like some of faces in your model have one side. Try to open your model in blender, match three vertices that makes some triangle you cant see and use `ctrl + N` (in edit mode as far as I remember). It should flip your face, so it would be visible. When I had that that problem I did that with every single face, but there may be some easier method to do that.
> 0 votes

---
Tags: xna, rendering, monogame, fbx, export
---


# Question
Title: Inventory system does not behave correctly
I have a game with an inventory, you can pick up items by walking on them. When you walk on an item and if it isn't already in your inventory it is added to the next free slot. If it is already in your inventory it should stack the items to a maximum of 99 similar to minecraft. The problem is (for example) the first three slots are empty and the fourth has wood in it. when you pick up another piece of wood it should stack with the wood in slot four. It doesn't, instead it starts a new stack in the first empty slot. In order for the wood to stack it has to be in the first empty slot. That's bad.

My Array looks like this:

```
public static ArrayList<cell> c = new ArrayList<cell>();

```

My code:

```
  for (int i = 0; i < c.toArray().length; i++) {

        for (int i1 = 0; i1 < play.items.p.toArray().length; i1++) {

            if(c.get(i).holdingid == play.items.p.get(i1).holdingid){
                if(play.items.p.get(i1).r.intersects(play.p.r) && play.items.p.get(i1).remove == false && c.get(i).stack < 99){

                    c.get(i).stack+=1;
                    play.items.p.get(i1).remove = true;
                    //break;
                }
            }else
            if (c.get(i).holdingid == 0) {
                if(play.items.p.get(i1).r.intersects(play.p.r) && play.items.p.get(i1).remove == false){
                    play.items.p.get(i1).remove = true;
                    c.get(i).holdingid = play.items.p.get(i1).holdingid;
                    c.get(i).stack+=1;
                    break;
                }

            }

        }

```

The first "if" condition checks to see if there are any of the same item you just picked up are in your inventory. The second checks if the item isn't in your inventory and then if it adds it to the next empty slot. I have 9 slots. The problem is that if the first if checks the first slot and then if there isn't a stack of that item in your inventory already, it moves on to the next condition and checks if slot 1 is empty and then creates a new stack of that item. similar to minecraft. I need the first if loop to check all slots and if none of them have the same item that you just picked up it moves on to the second if loop. What I currently have check the 1st slot with the first if and then the second and then moves on to the next slot. How can I fix this to check all the slots with the first if and then if none of them have got the item you just picked up, it starts checking all the slots again with the second.

My slot class:

```
   public class cell {

public int x, y;
public int id;
public int holdingid;

public boolean sel = false;
public boolean stackable = false;
public int stack = 0;
private Image img;

public Rectangle r = new Rectangle();
public cell(int x,int y,int id,int holdingid){
    this.x = x;
    this.y = y;
    this.id = id;
    r = new Rectangle(x+3,y+3,10,10);
    this.holdingid =holdingid;
}

public void tick(){
    r = new Rectangle(x+3,y+3,10,10);

}

public void render(Graphics g){
    if (sel) {
        g.setColor(new Color(0, 168, 92, 174));
        g.fillRect(x, y, 60, 60);
        g.setColor(Color.blue);
        g.drawRect(x, y, 60, 60);
    } else {
        g.setColor(new Color(0, 168, 92, 174));
        g.fillRect(x, y, 60, 60);
        g.setColor(Color.yellow);
        g.drawRect(x, y, 60, 60);

    }

    if(holdingid != 0){
        ImageIcon i2 = new ImageIcon("res/x.png");
        img = i2.getImage();
        g.drawImage(img, x+3, y+3, 10, 10, null);

        if(r.intersects(Comp.mx,Comp.my,1,1) && Comp.ml){
            holdingid = 0;
            stack = 0;
        }
    }

    if(holdingid == 0){
        //empty
    }else if(holdingid == 1){
        ImageIcon i2 = new ImageIcon("res/shovel.png");
        img = i2.getImage();
        g.drawImage(img, x+8, y+8, 40, 40, null);

    }else if(holdingid == 2){
        ImageIcon i112 = new ImageIcon("res/axe.png");
        img = i112.getImage();
        g.drawImage(img, x+10, y+10, 40, 40, null);

    }else if(holdingid == 3){
        ImageIcon i12 = new ImageIcon("res/clippers.png");
        img = i12.getImage();
        g.drawImage(img, x+12, y+10, 40, 40, null);
    }else if(holdingid == 4){
        ImageIcon i12 = new ImageIcon("res/poo.png");
        img = i12.getImage();
        g.drawImage(img, x+12, y+10, 40, 40, null);
    }else if(holdingid == 5){
        ImageIcon i12 = new ImageIcon("res/items/acorn.png");
        img = i12.getImage();
        g.drawImage(img, x+22, y+20, 20, 20, null);
    }else if(holdingid == 6){
        ImageIcon i12 = new ImageIcon("res/items/wood.png");
        img = i12.getImage();
        g.drawImage(img, x+15, y+17, 30, 30, null);
    }else if(holdingid == 7){
        ImageIcon i12 = new ImageIcon("res/items/lax.png");
        img = i12.getImage();
        g.drawImage(img, x+12, y+10, 40, 40, null);
    }

    if(holdingid != 0 && holdingid != 1&& holdingid != 2&& holdingid != 3){
        g.setColor(Color.black);
        g.setFont(new Font("italic", Font.BOLD, 15));
        g.drawString(""+stack, x+6,y+57);

        g.setColor(Color.white);
        g.setFont(new Font("italic", Font.BOLD, 15));
        g.drawString(""+stack, x+4,y+55);

    }
}

```

# Answer
> 2 votes
You made a simple mistake there, you go through your array, and as soon as the cell you look at does not have the specified item in it, you insert it into that cell or go on if it already has something else in it:

```
...else if (c.get(i).holdingid == 0) {...

```

---

instead, you could do it like this (in pseudocode):

```
insertItem(Item item) {
    int pos = index of cell with same type as item
              or if not found index of first free cell
    insert item in cell at index pos
}

```

Just go through the Array in a for loop to look at every cell and find the right value for pos

---
Tags: java, architecture
---


# Question
Title: Unity 5.x - Editor only constructor/initilization event
I have three scripts:

**Level** \- *Represents a Tile Based level.*

**LevelEditor** \- *Custom Editor for Level.*

**Tile** \- *A non monobehaviour class for storing tile information.*

Level contains an array of Tiles to be allocated with 'new'. To avoid putting 'If array != null' everywhere in the code, I want to initialize the array simply to a size of 0 before anything else is ran.

However, I do not want this initialization to happen at run time, just only for editing purposes.

Is there some event I can use that will run before Level.OnDrawGizmos(), and also not be part of runtime code? Or is LevelEditor.OnEnable() the best I can do, with some checks in Level.OnDrawGizmos()?

# Answer
If you want to initialize data, and for it to be available in the Editor, take a look at ExecuteInEditMode.

So you could add a new script component to your Level object, and have something like this:

```
#if UNITY_EDITOR

using UnityEngine;
using UnityEditor;

[ExecuteInEditMode]
public class EditorRefresh : MonoBehaviour {

    void Update()
    {
        if (array == null)
        {
            InitArray();
        }
    }
}

#endif

```
> 1 votes

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


title: 2D Rendering Based On Y Coordinates

text:
# Question
Title: 2D Rendering Based On Y Coordinates
I'm trying to build an RPG worldbuilder. I have seperate classes for images. Like this.

```
Object1::Object1(int x, int y, CSDL_Setup *sdl_set, int *p_CamX, int *p_CamY)
{
    X_pos = x;
    Y_pos = y;

    MouseX = 0;
    MouseY = 0;

    CamX = p_CamX;
    CamY = p_CamY;

    Object = new CSprite(sdl_set->GetRenderer(),"data/Trees/Tree3.png", X_pos, Y_pos, 100, 200, CamX, CamY);

}

```

I've created a vector of objects of the class Object1 and pushing it back when I create a new image. I draw them here.

```
void DrawObjects()
{
    for(std::vector<Object1*>::iterator i = Object.begin(); i != Object.end(); ++i)
    {
        (*i)->Draw();
    }
}

```

Now the rendering is done by the order the objects are created. I want to do the rendering based on y values of each object. I did a lot of research but couldn't find any example code. I also have other classes for other images. So I tried something on my own to sort y values and detect which y value corresponds to which object. But I'm stuck here.

```
int a;
void DoChanges()
{
    if(ChangeMade)
    {
        a = 0;

        for(std::vector<Object1*>::iterator i = Object1.begin(); i != Object1.end(); ++i)
        {
            ObjectArray[a] = (*i)->GetY();
            a++;
        }
        for(std::vector<Object2*>::iterator i = Object2.begin(); i != Object2.end(); ++i)
        {
            ObjectArray[a] = (*i)->GetY();
            a++;
        }
        ...

        SIZE = Object1.size() + Object2.size() + Object3.size() + ...;

        sort(ObjectArray, ObjectArray + SIZE);

        for(size_t i = 0; i < SIZE; i++)
        {
            for(size_t j = 0; j < SIZE; j++)
            {
                if(tree1[j]->GetY() == ObjectArray[i])
                {
                }
                else if(tree2[j]->GetY() == ObjectArray[i])
                {
                }
                ...
            }
        }

        ChangeMade = false;
    }

```

Is there a way to create an array of pointers to store the addresses of objects to different classes by their y values and use this array to do the rendering? Or do you have any suggestions on how to handle creating objects to the sprite class and rendering or any useful links?

Thanks.

# Answer
> 1 votes
I would forget right away the option to create the sprites in order based on their `y` coordinate as it will create a hell for you because it's not a flexible design.

You look like you need a common way to handle the drawing process. You can achieve this using *polymorphism*.

I would probably create a `IDrawable` interface, which requires children to have `getY()` and `draw()`, and would derive all the things that can be drawn on screen from it (`Object1` and `Object2` in your case).

When you're ready to draw, get all your `IDrawable` in a single vector, and sort that vector based on the `getY()`.

Once sorted, call the `draw()` method on each of your drawables.

For instance, if you have something like these base classes:

```
class IDrawable
{
public:
  double getY() const = 0;
  void   draw() = 0;
};

class Object1
{
private:
  double Y_pos;

public:
  double getY() const { return Y_pos; }
  void   draw() { /* draw Object1 in a way that makes sense for it. */ }
};

class Object2
{
public:
  double getY() const { double y; /* compute y */ return y; }
  void   draw() { /* draw Object2 in a way that makes sense for it. */ }
};

```

You could manage it like this:

```
class MgrDraw
{
private:
  std::map< int, std::vector<IDrawable*>* > mDrawableReferences;

public:
  // This would be called by entities that know of Object1 or Object2
  void addDrawableReferences(int aIdentifier, std::vector<IDrawable*>* aDrawableForType )
  {
    auto it = mDrawableReferences.find(aIdentifier);
    assert( it == mDrawableReferences.end() );
    mDrawableReferences[aIdentifier] = aDrawableForType;
  }

  // Call this when you're ready to draw.
  void draw()
  {
    std::vector<IDrawable*> allDrawables;
    for ( auto vec : mDrawableReferences)
    {
      for ( auto drawable : vec )
      {
        allDrawables.push_back( drawable );
      }
    }
    // for the XXX below, check the second form:
    // http://en.cppreference.com/w/cpp/algorithm/sort
    std::sort(allDrawables.begin(), allDrawables.end(), XXX);
    for ( auto drawable : allDrawables )
    {
      drawable->draw();
    }
  }
};

```

Now, please note that this might not be the *best* way to achieve it, but at least it seems to solve your current issue. You could probably improve the execution by making `allDrawables` member of the class to avoid having to re-create it/resize it each frame.

And XXX could look like this:

```
struct {
  bool operator()(Drawable* a, Drawable* b)
  {
    return a->getY() < b->getY();
  }
} comp;

```

---

**Edit**

I have created a fully functional example of that. It runs as a command line program and works in visual studio. I've added comments to try to answer OP's questions.

```
// main.cpp
// Runs correctly with visual studio 2013.

#include <iostream>

#include <vector>
#include <map>
#include <algorithm>
#include <random>
#include <memory>
#include <assert.h>
#include <chrono>
#include <thread>
#include <Windows.h>

// Notes
// This simple program draws numbers on the console. It sole purpose is to
// demonstrate how multiple kinds of objects can be drawn on screen based on
// a particular rule, in this case a pseudo Y coordinate.
//
// The implementation has been drawn from the OP's implementation and may not be
// the best archicteture ever as I slapped this example only for the purpose
// of the question.

/// Comment this out to see the "real-time" effect
/// Un-comment to see the order in which stuff is drawn.
#define IS_SLOW_MOTION

static const int MIN_RANGE = 1;
static const int MAX_RANGE = 10;

// http://stackoverflow.com/a/1670911/637987
// Used to draw stuff on the console.
void gotoxy(int x, int y)
{
  COORD coord;
  coord.X = x;
  coord.Y = y;
  SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}

/// Global services; singleton that must be initialized before being used.
class Global
{
private:
  Global()
    : mIsInitialized(false)
  {}

  /// Flag indicating if the singleton has been initialized
  bool mIsInitialized;

  /// Random generator.
  std::default_random_engine mGenerator;

  /// Distribution for random position generation
  std::uniform_int_distribution<int> mDistributionPosition;

  /// Distribution for random duration (in frames)
  std::uniform_int_distribution<int> mDistributionDuration;

  /// Variable used to keep the count on unique identifier generation.
  int mIdGenerator;

public:

  /// Way to access the single instance of this class.
  static Global& GetReference()
  {
    static Global Instance;
    return Instance;
  }

  /// Initialize the singleton.
  /// This is not done in the constructor because we want to explicitely do the
  /// construction.
  void init()
  {
    if (mIsInitialized)
      return;
    else
      mIsInitialized = true;

    // see http://www.cplusplus.com/reference/random/ for more details on the
    // random number generation.
    mDistributionPosition = std::uniform_int_distribution<int>(MIN_RANGE, MAX_RANGE);
    mDistributionDuration = std::uniform_int_distribution<int>(2, 4);
    mIdGenerator = 0;
  }

  /// Destroy what has to be destroyed in the singleton.
  void tearDown()
  {
    if (!mIsInitialized)
      return;
    else
      mIsInitialized = false;
  }

  /// Retrive the next 'unique' id.
  int getNextId()
  {
    assert( mIsInitialized );
    if ( !mIsInitialized )
      return -1;

    ++mIdGenerator;
    return mIdGenerator;
  }

  /// Generates a random position.
  int getRandomPosition()
  {
    // Generates a value in the range specified in the init method.
    return mDistributionPosition(mGenerator);
  }

  /// Generates a random duration.
  int getRandomDuration()
  {
    // Generates a value in the range specified in the init method.
    return mDistributionDuration(mGenerator);
  }
};

/// Item that can be drawn; drawn according to a y position.
class IDrawable
{
public:
  virtual double getY() const = 0;
  virtual void   draw() = 0;
};

/// This class makes children have a unique identifier.
class Uidable
{
public:
  Uidable() : mUid(Global::GetReference().getNextId()) {}
  int getUid() const { return mUid; }
private:
  const int mUid;
};

/// One of the things that we can draw.
/// The casual mover moves up and down with a predicatble path.
class Object1CasualMover : public IDrawable, public Uidable
{
private:

  /// Here it is a int because it's easier to manage in the update function.
  int mYpos;

  /// Flag specifying if the item is going up (true) or down (false)
  bool mIsGoingUp;

public:
  Object1CasualMover(int aStartY, bool aShouldGoUpFirst)
    : mYpos(aStartY), mIsGoingUp(aShouldGoUpFirst)
  {}

  double getY() const { return static_cast<double>(mYpos); }

  void   draw() {
    gotoxy( getUid(), getY() );
    std::cout << getUid();
  }

  void update() {
    // dummy method that makes the object move up and down.
    if (mIsGoingUp)
    {
      ++mYpos;
      if (mYpos >= MAX_RANGE)
        mIsGoingUp = false;
    }
    else
    {
      --mYpos;
      if (mYpos <= MIN_RANGE)
        mIsGoingUp = true;
    }
  }
};

/// One of the things that we can draw.
/// The houdini spawns at a random spot and stays there for a random number of
/// frame before vanishing and spawning again.
class Object2Houdini : public IDrawable, public Uidable
{
private:

  /// Here it is a int because it's easier to manage in the update function.
  int mYpos;

  /// Frames left in the current Y position
  int mFramesLefInThisPosition;

public:

  Object2Houdini()
    : mYpos(0), mFramesLefInThisPosition(0)
  {
    update();// One call to update to set it in place
  }

  double getY() const { return static_cast<double>(mYpos); }

  void   draw() {
    gotoxy( getUid(), getY() );
    std::cout << getUid();
  }

  void update() {
    // dummy method that makes the object move up and down randomly at random
    // times (frames).
    if (mFramesLefInThisPosition == 0)
    {
      mYpos = Global::GetReference().getRandomPosition();
      mFramesLefInThisPosition = Global::GetReference().getRandomDuration();
    }
    --mFramesLefInThisPosition;
  }
};

/// Draw manager. Used to keep a reference to everything that needs to be drawn,
/// and sort and draw items.
class MgrDraw
{
private:
  /// References of stuff to draw.
  /// This is _my_ way of implementing it. This was done like this for the purpose
  /// of this example. Depending on your own implementation you may need to do it
  /// in another way. I did it this way because you seemed to keep your drawables
  /// in separate vectors.
  ///
  /// The idea is to keep track of all the drawables.
  /// The idea of the map is to be able to retreive stuff later. (It's not needed
  /// in the current example, however.)
  std::map< int, std::vector<IDrawable*>* > mDrawableReferences;

  /// Structure used to sort the IDrawable based on their Y coordinate.
  /// see http://en.cppreference.com/w/cpp/algorithm/sort for more details.
  struct compareWithY{
    bool operator()(IDrawable* a, IDrawable* b)
    {
      return a->getY() < b->getY();
    }
  };

public:
  // This must be called by entities that know of the objects to draw.
  // Refer to the doc of mDrawableReferences for more details.
  void addDrawableReferences(
    int aIdentifier,
    std::vector<IDrawable*>* aDrawableForType)
  {
    // sanity checks: don't add something that was already added.
    auto it = mDrawableReferences.find(aIdentifier);
    assert(it == mDrawableReferences.end());
    if ( it != mDrawableReferences.end() )
      return;

    // keep a reference to the vector of items.
    mDrawableReferences[aIdentifier] = aDrawableForType;
  }

  /// Call this when you're ready to draw.
  void draw()
  {
    system( "CLS" ); // Windows console call to clear up the console.

    // Gather all the drawables in a single vector.
    std::vector<IDrawable*> allDrawables;
    for (auto vec : mDrawableReferences)
    {
      for (auto drawable : (*vec.second))
      {
        allDrawables.push_back(drawable);
      }
    }

    // Notes on the 'for ( auto vec : mDrawableReferences )' line.
    // This is c++11 code. Traditionnally, you would have written this:
    //for (
    //  std::map< int, std::vector<IDrawable*>* >::iterator it =
    //    mDrawableReferences.begin();
    //  it != mDrawableReferences.end();
    //  ++it )
    //{
    //  std::pair<const int, std::vector<IDrawable*> *> vec = *it;

    //  // .. do stuff with vec
    //}
    //
    // The current loop is using advantage of the auto keyword which deducts
    // the type at compile time, and the for ( bla : iterable ) with takes
    // is equivalent to a "for each" in other languages.
    // See these pages for more detail
    // http://en.cppreference.com/w/cpp/language/auto
    // http://en.cppreference.com/w/cpp/language/range-for

    // Sort the drawables according to the algorithm in compareWithY operator()
    // You delegate the logic of the sorting to a functor.
    // See this for more details:
    // http://www.cprogramming.com/tutorial/functors-function-objects-in-c++.html
    std::sort(allDrawables.begin(), allDrawables.end(), compareWithY());
    for (auto drawable : allDrawables)
    {
      drawable->draw(); // Draw the item. The item knows how to draw itself.
#if defined(IS_SLOW_MOTION)
        std::this_thread::sleep_for(std::chrono::milliseconds(500));
#endif
    }
  }
};

/// Since we don't have any user interaction, this example is more a
/// simulation than a game. I called it Sim.
class Sim
{
public:

  /// Performs clean up tasks.
  ~Sim()
  {
    for (auto item : mCasualMovers)
      delete item;
    for (auto item : mHoudinis)
      delete item;
    mMgrDraw.reset();
    Global::GetReference().tearDown();
  }

  /// Initializes our simulation
  void init()
  {
    Global::GetReference().init(); // According to the doc, the singleton must
                                   // be initialized.
    // Create 5 instances of each class of drawable.
    for (int i = 0; i < 5; ++i)
    {
      mCasualMovers.push_back(
        new Object1CasualMover(i, (i % 2 == 0) ? true : false));
    }
    for (int i = 0; i < 5; ++i)
    {
      mHoudinis.push_back(
        new Object2Houdini());
    }

    mMgrDraw = std::make_unique<MgrDraw>(); // Create the draw manager

    // Add the elements to be drawn. The numbers 1 and 2 have been chosen
    // without any particular reason. .
    mMgrDraw->addDrawableReferences( 1, &mCasualMovers );
    mMgrDraw->addDrawableReferences( 2, &mHoudinis );
  }

  /// Run a simulation frame.
  bool run()
  {
    // Update all the know objects.
    for ( auto obj1 : mCasualMovers )
    {
      static_cast<Object1CasualMover*>( obj1 )->update();
    }
    for ( auto obj2 : mHoudinis )
    {
      static_cast<Object2Houdini*>( obj2 )->update();
    }

    // Draw them.
    mMgrDraw->draw();

    // In a real game, you'd probably want an exit condition (user wants to quit
    // the game, for instance).
    return true;
  }

  std::unique_ptr<MgrDraw> mMgrDraw;     ///< The draw manager
  std::vector<IDrawable*> mCasualMovers; ///< All the casual movers
  std::vector<IDrawable*> mHoudinis;     ///< All the houdinis
};

int main(void)
{
  Sim sim;
  sim.init();

  while ( sim.run() ) // as long as the simulation wants to run, it runs!
  {

#if defined(IS_SLOW_MOTION)
    std::this_thread::sleep_for(std::chrono::milliseconds(1000));
#else
    std::this_thread::sleep_for(std::chrono::milliseconds(500));
#endif
  }

  return 0;
}

```

# Answer
> 1 votes
You could re-order your `std::vector<Object>` by creating a function that sort it by Y position of your objects

```
void SortObjects()
{
   std::sort(Object.begin(), Object.end(), CompareYAxis);
}

bool CompareYAxis(const Object first, const Object second)
{
    //Do the comparison here
}

```

I think this would work.

# Answer
> 0 votes
To expand @Alexandre Vaillancourt answer, I would even consider using a collection that *keeps* your data sorted, instead of re-sorting it every frame.

```
struct Drawable_compare {
    bool operator() (const IDrawable& d1, const IDrawable& d2) const{
            return d1.y < d2.y;
    }
};

class Renderer
{
private:
  std::multiset<IDrawable*, Drawable_compare > objects;

public:
  //similar for Unregister
  void RegisterObject(IDrawable* drawable) {
     objects.insert(drawable);
  }

  void drawAll() {
  for (auto i = objects.begin(); i != objects.end(); i++)
     i->Draw();
  }
}

```

Where did the `std::vector<Object1*>` go? The renderer does not need it now - its IDrawable for it, and if *you* do, you would probably have to duplicate the references data anyway and this way you can separate actual and logical order/storage of you data.
Why suggesting this solution? Even though, judging from your code, you dont aim for performance, this spares you re-sorting every frame and makes you code simplier. If you are looking for *faster* solution you should rather change design of your engine to be more data-driven.
Note: I did not check the syntax, and in the end which solution is better depends on personal preferences, on *your* preferences.
While it performs great for mainly static scene, the fact that you *cannot change keys* makes this solution worse if nearly all objects are moving (moving in Y axis requires re-adding the object to the collection - you need `Move()` method instead of writing to the data directly).
Alternatively, you can keep only static objects(trees, building, etc.) in this set as it handles inserting and deleting for you, and do manual re-sorting every frame for your your moving objects(orcs, player,...) .

---
Tags: c++, 2d, sprites, vector, sdl
---


# Question
Title: GLSL shaders work when hardcoded, not when loaded from file
I am trying to learn OpenGL. I have a main.cpp where I create the vertex and fragment shaders as strings, compile and link and it works fine. When I try to load the identical shaders from text files, it no longer links. Having trouble figuring out why. (I am using Linux if that matters)

Here is where I define the shader source:

```
    /*
    const char* vertex_shader = "#version 410\n"
                    "in vec3 vp;"
                    "void main () {"
                    "  gl_Position = vec4 (vp, 1.0);"
                    "}";

    const char* fragment_shader =  "#version 410\n"
                       "uniform vec4 inputColour;"
                       "out vec4 frag_colour;"
                       "void main () {"
                       "  frag_colour = inputColour;"
                       "}";

    */
    const char* vertex_shader = load_shader("test.vert").c_str();
    const char* fragment_shader = load_shader("test.frag").c_str();

```

Again, if I change what I comment out, so that the shader source is hardcoded, it works fine. If I try to load from files like I show here, it fails to link. Each individual shader seems to compile fine.

Here is my load\_shader() function, it just gets the text from the file and logs some data.

```
std::string load_shader(std::string file){
    std::ifstream fin(file);
    if(fin.is_open()){
        std::string shader = "";
        std::string line = "";
        while(!fin.eof()){
            std::getline(fin, line);
            shader.append(line +"\n");
        }
        fin.close();
        l.add_string("LOADED SHADER");
        l.add_line(file);
        l.add_line(shader);
        l.add_line("---------------------------------");
        return shader;
    }else{
        l.add_string("FAILED TO LOAD SHADER");
        l.add_line(file);
        return "";
    }
}

```

Could my load\_shader() function be making a bad string somehow?

EDIT: I got my log functions working slightly better. glGetProgramInfo() now returns this:

```
Vertex shader(s) failed to link, fragment shader(s) failed to link.
Vertex link error: INVALID_OPERATION.
ERROR: error(#97) No program main found
fragment link error: INVALID_OPERATION.
ERROR: error(#97) No program main found

```

EDIT 2: According to this, it is most likely a bad source string. But it doesn't say why. I'll keep working at it.

EDIT 3: I tried to compare the strings I was getting from each method and noticed something weird. Here is my check code, where I make strings for each input method, then loop through and print the chars to a file.

```
const char* vertex_shader = "#version 410\n"
                "in vec3 vp;"
                "void main () {"
                "  gl_Position = vec4 (vp, 1.0);"
                "}";

const char* fragment_shader =  "#version 410\n"
                   "uniform vec4 inputColour;"
                   "out vec4 frag_colour;"
                   "void main () {"
                   "  frag_colour = inputColour;"
                   "}";

const char* vertex_shader2 = load_shader("test.vert").c_str();
const char* fragment_shader2 = load_shader("test.frag").c_str();
std::ofstream shader("shaders.txt");
int i = 0;
while(vertex_shader[i] != '\0'){
    shader << vertex_shader[i];
    i++;
}
shader << std::endl;
i = 0;
while(fragment_shader[i] != '\0'){
    shader << fragment_shader[i];
    i++;
}
shader << std::endl;
i = 0;
while(vertex_shader2[i] != '\0'){
    shader << vertex_shader2[i];
    i++;
}
shader << std::endl;
i = 0;
while(fragment_shader2[i] != '\0'){
    shader << fragment_shader2[i];
    i++;
}
shader << std::endl;
shader.close();

```

And here is the shaders.txt output:

```
#version 410
in vec3 vp;void main () {  gl_Position = vec4 (vp, 1.0);}
#version 410
uniform vec4 inputColour;out vec4 frag_colour;void main () {  frag_colour = inputColour;}
#version 410
uniform vec4 inputColour;out vec4 frag_colour;void main () {  frag_colour = inputColour;}
#version 410
uniform vec4 inputColour;out vec4 frag_colour;void main () {  frag_colour = inputColour;}

```

As you can see, I'm getting a copy of the fragment shader text where I should be seeing the vertex shader. To be sure, here are the shader files I'm trying to upload.

test.vert:

```
#version 410
in vec3 vp;void main () {  gl_Position = vec4 (vp, 1.0);}

```

test.frag:

```
#version 410
uniform vec4 inputColour;out vec4 frag_colour;void main () {  frag_colour = inputColour;}

```

Also, when I changed test.frag a little, that change appeared in the wrong line in the shaders.txt. This shows that the extra copy is coming from the file input instead of the hardcoded version.

EDIT 4: I am apparently getting some sort of string overwrite problem. I tested with std::cout like so:

```
const char* vertex_shader2 = load_shader("test.vert").c_str();
const char* fragment_shader2 = load_shader("test.frag").c_str();
std::cout << vertex_shader2 << std::endl;
std::cout << fragment_shader2 << std::endl;

```

In this case, both cout statements give the test.frag string. But this one works fine:

```
const char* vertex_shader2 = load_shader("test.vert").c_str();
std::cout << vertex_shader2 << std::endl;
const char* fragment_shader2 = load_shader("test.frag").c_str();
std::cout << fragment_shader2 << std::endl;

```

So the second load\_shader() call is overwriting the first call.

# Answer
You are using pointers to data inside a temporary object:

```
const char* vertex_shader = load_shader("test.vert").c_str();
const char* fragment_shader = load_shader("test.frag").c_str();

```

Which means both `vertex_shader` and `fragment_shader` are pointing to invalid memory, since the `string`s returned by `load_shader` get destroyed at the end of each statement. Accessing that memory results in undefined behaviour.

Try keeping the strings instead:

```
std::string vertex_shader = load_shader("test.vert");
std::string fragment_shader = load_shader("test.frag");

```

And then giving their `.c_str()`s to the shader compiler.
> 8 votes

# Answer
The other answers already mention that you're getting a dangling pointer and should return the strings. But reading shaders from a file, really comes down to putting the whole file into a string. Here's one way to do it:

```
// Read shader file into one string
std::string shaderSource;
if ( !readFileIntoString( shaderFileName, shaderSource ) ) {
    return false;
}

const GLchar *source[] = { shaderSource.c_str() };
// (...) Use the source

```

And `readFileIntoString` can be written in different ways. Here you send the name of your shader file and pass a string to read the file into.

```
bool readFileIntoString( const std::string &fileName, std::string &destination ) {
    std::ifstream in( fileName, std::ios::in | std::ios::binary );
    if ( in ) {
        in.seekg( 0, std::ios::end );
        destination.resize( in.tellg() );
        in.seekg( 0, std::ios::beg );
        in.read( &destination[ 0 ], destination.size() );
        in.close();
        return true;
    }
    return false;
}

```
> 2 votes

# Answer
```
const char* vertex_shader = load_shader("test.vert").c_str();
const char* fragment_shader = load_shader("test.frag").c_str();

```

will result in dangling pointers (with undefined behavior if you dereference it), after you assign the char\* to the variable the temp std::string (and backing array you just got a pointer to) gets deleted.

```
const std::string vertex_shader = load_shader("test.vert");
const std::string fragment_shader = load_shader("test.frag");

```

Keep those variables alive as long as you need the strings.
> 1 votes

---
Tags: opengl, c++, glsl
---


title: Viewport and Camera setting

text:
# Question
Title: Viewport and Camera setting
For my first game in LibGDX and Android I got a Problem:

I have a background picture which is 2560px * 720px. The screen is 1280 * 720. How do I have to set the viewport and camera in order to get the following result: The picture is fited in height and shows the first 1280px in width.

I tried so many things and it really confused me.

**Gamescreen.java**

```
package com.joelbrun.jetskirider.screens;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.utils.viewport.FitViewport;
import com.badlogic.gdx.utils.viewport.Viewport;

public class Gamescreen implements Screen {

    public Texture jetski, wave, background;
    public SpriteBatch batch;
    public OrthographicCamera camera;
    public Label score;
    public static final int GAMESCREEN_WIDTH = 1920;
    public static final int GAMESCREEN_HEIGHT = 720;
    public static final int OBSTACLE_TYPES = 5;

    Viewport viewport;
    private Texture[] texture;

    @Override
    public void show() {
        texture = new Texture[OBSTACLE_TYPES];
        for (int i=0; i<OBSTACLE_TYPES; i++){
            texture[i] = new Texture(Gdx.files.internal("game/obstacles/obstacle" + Integer.toString(i+1)+".png"));
        }
        background = new Texture("game/background.png");
        jetski = new Texture("game/jetski.png");
        batch = new SpriteBatch();
        float aspectRatio = (float)Gdx.graphics.getWidth()/(float)Gdx.graphics.getHeight();
        camera = new OrthographicCamera();

        viewport = new FitViewport(GAMESCREEN_WIDTH, GAMESCREEN_HEIGHT);
        viewport.apply();
        camera.position.set(GAMESCREEN_WIDTH / 2, GAMESCREEN_HEIGHT / 2, 0);
        //camera.position.set(0,0,0);

    }

    @Override
    public void render(float delta) {
        Gdx.gl.glClearColor(0, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        camera.update();
        batch.setProjectionMatrix(camera.combined);
        batch.begin();
        batch.draw(background, 0, 0, 5119, 720);
        batch.draw(jetski, background.getWidth()/2, background.getHeight()/2,128,128);
        batch.end();
    }

    @Override
    public void resize(int width, int height) {
        viewport.update(width, height);
        camera.position.set(GAMESCREEN_WIDTH / 2, GAMESCREEN_HEIGHT / 2, 0);
    }

    @Override
    public void pause() {

    }

    @Override
    public void resume() {

    }

    @Override
    public void hide() {

    }

    @Override
    public void dispose() {
        batch.dispose();
        background.dispose();
        jetski.dispose();
        wave.dispose();
    }
}

```

# Answer
> 2 votes
It should work if you change these parts in `show()`:

```
viewport = new ScalingViewport(Scaling.fillY, GAMESCREEN_WIDTH, GAMESCREEN_HEIGHT, camera = new OrthographicCamera());

```

and add a resize method:

```
@Override
public void resize(int width, int height) {
    int SCREEN_WIDTH = width;
    int SCREEN_HEIGHT = height;

    viewport.setWorldSize(GAMESCREEN_WIDTH, GAMESCREEN_HEIGHT);
    viewport.update(SCREEN_WIDTH, SCREEN_HEIGHT,true);
}

```

It's important, that you set your Sprites height to `GAMESCREEN_HEIGHT` and you may need to move around your `camera` a bit but that shouldn't be that hard.

```
private void moveView(Vector3 v) {
    camera.translate(v);
    camera.update();
}

```

---
Tags: android, libgdx, box2d, camera, viewport
---


# Question
Title: Can I include a public domain book in my game?
Just for fun, I want to include a bookshelf in my game with a real book (or few) that you can actually read.

Would I run into any legal trouble if I included an out of print book in the public domain, such as *Pride and Prejudice* or *Alice in Wonderland?*

# Answer
Getting legal advice on GameDev.StackExchange is not a great idea.

Having said that, if a work is truly in the public domain, you can do whatever you want with it.
> 34 votes

# Answer
Yes and no. "Public domain" does mean that, by definition, you can do whatever you like with that creative property.

However there's an important caveat here. What's public domain is the underlying story, not every specific creative work based on that story. So, like, you could have a book titled Alice in Wonderland, but its cover can't be Disney's Alice in Wonderland.
> 20 votes

# Answer
Watch for different copyright terms in different countries. Just because a book's copyright has expired in your country does not mean it has expired in all countries in which you plan to distribute the game. Though the Berne Convention sets a minimum copyright term of 50 years after the death of the author, countries are free to set a longer copyright term. If you have questions unanswered by Wikisource's copyright resources, ask on Law Stack Exchange.

Other issues that you may run into are that the books may make the game bigger to download and may affect your game's rating from ESRB or foreign counterparts.
> 11 votes

# Answer
Public domain content is by definition not copyrighted (anymore), so it is perfectly acceptable to use that. However, there are some things to keep in mind:

* **Copyright terms are not universal.** What is public domain in one country might not be public domain in another. You should confirm the copyright durations / public domain status of the material in your country and all countries you plan to sell the game in.
* **Some countries have non-copyright copyright-like restrictions.** Some European countries have a concept of "moral rights" on top of copyright. These might be more restrictive and last longer. Again, this is going to vary heavily by locale, and you should verify the law in all locales you plan to sell this game.
* **Translations are usually copyrightable.** In most of the world that I am aware of, translations of works take on their own copyright as if they were original works. This would not be a problem for the two books you list (presuming the game is indeed in English), but might very well be a problem for other books. If you are using a translation of a public domain book, ensure the *translation itself* is public domain as well.
* **Non-public domain material might be inserted into public domain material.** Good examples of this are illustrations added after the initial publishing and front matter added by later publishers. Similar to translations, you should ensure the actual edition of the book you are using is entirely public domain. Almost all in-print copies of public domain works are not themselves entirely public domain on these grounds.
* **Adaptations are copyrightable.** As stated above, anything added to public domain works can be under copyright. This of course applies to full-on adaptations. If you are using merely the text of the original books, this should not be a concern. However, were you to be employing copyrightable material from these stories beyond just inclusion of the base material (for example, using character names), you would want to be aware of what elements of the work might have come latter. For example, Disney adaptations of out of copyright works.
* **Be aware of trademarks.** This goes along with adaptations: it is possible certain words or names have been trademarked. Again, this should not be an issue if you're using the original material verbatim, but could impact games which are adapting the material more broadly.

As others have noted, being in or out of print has nothing to do with copyright status, beyond my point above that in-print versions of public domain works likely contain copyrighted materials added later.

Project Gutenberg is a good source if you are planning on marketing in/from the US only, and generally a good source for accurate publishing dates on specific versions of books.
> 9 votes

# Answer
"Would I run into any legal trouble if I included an out of print book in the public domain, such as Pride and Prejudice or Alice in Wonderland?"

Careful there, out of print has nothing to do with public domain. A book can be public domain and still be in print, or it can be out of print without being public domain. Also, a book can be public domain in one country and still have 50 years copyright protection in another. And if I were to write a new translation of the Bible, maybe even add a couple illustrations, that new translation would not be public domain, unless I as the rights holder say so.

A book is either public domain because the rights holder decided to make it public domain, or it's public domain because the copyright has expired.

You can use anything that's public domain to make a profit. You can even print the book and sell it. You can use public domain models in your game, public domain textures, and public domain music. Careful with the music: just because Beethoven lived a long time ago does not mean a 20 year old recording of a piece written by Beethoven is public domain - it's not.

EDIT: If you can make out the rights holder you might even be able to include content that still has a copyright. Just ask them and they might say yes. It's publicity, after all.
> 4 votes

# Answer
I'm not a game developer, but I just happened to stumble across your question. I am a writer and journalist, and I've written about copyright many times in the past.

If you're specifically thinking of Alice in Wonderland, the answer to your question is an unqualified YES. The book is old enough that the copyright has expired everywhere in the world, so you can do whatever you like with it: Publish excerpts or the full-text within your game, base parts of the game or the whole thing on it, turn Alice into a crack addict living on Mars, whatever you want. That's what "public domain" means. It's out of copyright and ANYONE IN THE PUBLIC has the right to use it. In the U.S. especially it's sometimes difficult to know if something's in the public domain, but you can safely assume that anything from the 19th century (Alice in Wonderland, Sherlock Holmes, 20,000 Leagues Under the Sea, Frankenstein, Jane Eyre, etc. etc.) is fair game. In fact, most works up to 1922 or so are probably fair game, but then it starts to get complicated.

Yes, you should avoid making your visualizations of the characters look too much like the Disney versions, but don't let them scare you away either.

Also, if you just wanted to show a book on a bookshelf, without actually showing any of the content, you can legitimately show the title of ANY book, even if it's still protected by copyright. Copyright doesn't protect the titles of books, only the content of the story. You might want to avoid book titles that are also big franchise trademarks (Harry Potter, Star Wars, Chicken Soup for the Soul) but even there you'd probably be within your rights to use them. You just don't want to become the test case.

Good luck with your game!
> 1 votes

# Answer
I (not a lawyer) think the correct answer is a little more nuanced. Taking the "Alice in Wonderland" example, the original publication (old edition, paper book) is indeed yours to do whatever you want with. But if you take the xyz publisher's 99'th edition E-Book (or Audio Book, or Book Book), that derivative work can be protected by its own copyright.

So for your example of including a book in a game, if you made your own photo facsimile of an out of copyright edition, you're in the the clear; but if you take advantage of someone else's digitized "Alice" you have to consider what copyright they claim.
> 0 votes

# Answer
I would say that you could, as public domain means that it's free to be used, however I'm not too sure as far as Moral Rights/Authors Rights are concerned.

Wikipedia says that moral rights (sometimes called "authors rights") are rights retained by the author of a work, even if they no longer hold the copyright. They include the right of attribution (or of not being attributed, at the author's discretion), and the right to ensure the integrity of the work although I'm not sure whether that would hinder you inserting the book into your game.
> 0 votes

# Answer
I couldn't say anything about the issue in legal terms, but there's another way to look at it. You could count the amount of effort it has taken to create the work. While you examine the works you see available on the net, good measurement unit is the amount of effort spent to create the work. If you create a game, and half the content is copied from otherwise available public domain work, I would only give you credit of the part that you created yourself. How to determine this relies on the following process (known as effort calculation):

* Split the work to small pieces that can be examined
* determine author and work amount of each piece individually
* Sum the work amounts to get a total amounnt of effort
* Compare the work amount to what is possible to be created by the number of people claiming to be the original authors

This process allows examining the quality of the work you know is available on the internet. If you include alot of public domain content to your work, then this evaluation process will give bad results for your content, and thus people who look at the quality will determine it to be bad quality. So better not rely on large amounts of work created by someone else.

EDIT: given some comments, I would like to clarify that this process would be useful for understanding how publishers are looking at a products they encounter in the legal environment. This process can detect several issues with the products, including non-original content in the product.
> -3 votes

---
Tags: legal, licensing, assets
---


# Question
Title: DX9 How to Apply HLSL Shader with StretchRect
Using DirectX 9,I'm trying to run a HLSL pixel shader on video frame data while copying it from one texture buffer to another texture buffer without displaying it. StretchRect at the end is what copies the data from pOffsceenSurface to pTextureSurface, which should pass through the pixel shader. The video data does get passed over and I can read it back, but the shader isn't being applied.

What do I need to do to process the texture through the shader? And does register(S0) get automatically filled, or how do I set the source? The code I have allows configuring register(C0), register(C1), etc. through m\_pPixelConstantTable, but not the S registers. Some shaders take S0 and S1 so it needs to be configured somehow.

Here's the code

```
HRESULT D3D9RenderImpl::SetPixelShader(LPCSTR pPixelShaderName, LPCSTR entryPoint, LPCSTR shaderModel, LPSTR* ppError)
{
    CComPtr<ID3DXBuffer> code;
    CComPtr<ID3DXBuffer> errMsg;

    HR(D3DXCompileShaderFromFile(pPixelShaderName, NULL, NULL, entryPoint, shaderModel, 0, &code, &errMsg, &m_pPixelConstantTable));
    return m_pDevice->CreatePixelShader((DWORD*)code->GetBufferPointer(), &m_pPixelShader);
}

HRESULT D3D9RenderImpl::CreateScene(void)
{
    HR(m_pDevice->Clear(D3DADAPTER_DEFAULT, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0, 0, 0), 1.0f, 0));
    HR(m_pDevice->BeginScene());
    HR(m_pDevice->SetFVF(D3DFVF_CUSTOMVERTEX));
    // when I debug, m_pPixelShader does get set properly)
    HR(m_pDevice->SetPixelShader(m_pPixelShader));
    HR(m_pDevice->SetTexture(0, m_pTexture));
    HR(m_pDevice->DrawPrimitive(D3DPT_TRIANGLEFAN, 0, 2));
    return m_pDevice->EndScene();
}

HRESULT D3D9RenderImpl::Present(void)
{
    HR(m_pDevice->ColorFill(m_pTextureSurface, NULL, D3DCOLOR_ARGB(0xFF, 0, 0, 0)));
    return(m_pDevice->StretchRect(m_pOffsceenSurface, NULL, m_pTextureSurface, NULL, D3DTEXF_LINEAR));
    // This line doesn't seem necessary
    // return m_pDevice->Present(NULL, NULL, NULL, NULL);
}

```

What's missing?

EDIT: Here's what I'm rendering to

```
HRESULT D3D9RenderImpl::CreateRenderTarget()
{
    // HR(m_pDevice->CreateTexture(width, height, 1, D3DUSAGE_RENDERTARGET, m_displayMode.Format, D3DPOOL_DEFAULT, &m_pTexture, NULL));
    HR(m_pDevice->CreateTexture(m_videoWidth, m_videoHeight, 1, D3DUSAGE_RENDERTARGET, m_format, D3DPOOL_DEFAULT, &m_pTexture, NULL));
    HR(m_pTexture->GetSurfaceLevel(0, &m_pTextureSurface));
    HR(m_pDevice->CreateVertexBuffer(sizeof(VERTEX) * 4, D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY, D3DFVF_CUSTOMVERTEX, D3DPOOL_DEFAULT, &m_pVertexBuffer, NULL));

    VERTEX vertexArray[] =
    {
        { D3DXVECTOR3(0, 0, 0), D3DCOLOR_ARGB(255, 255, 255, 255), D3DXVECTOR2(0, 0) },  // top left
        { D3DXVECTOR3(m_videoWidth, 0, 0), D3DCOLOR_ARGB(255, 255, 255, 255), D3DXVECTOR2(1, 0) },  // top right
        { D3DXVECTOR3(m_videoWidth, m_videoHeight, 0), D3DCOLOR_ARGB(255, 255, 255, 255), D3DXVECTOR2(1, 1) },  // bottom right
        { D3DXVECTOR3(0, m_videoHeight, 0), D3DCOLOR_ARGB(255, 255, 255, 255), D3DXVECTOR2(0, 1) },  // bottom left
    };

    VERTEX *vertices;
    HR(m_pVertexBuffer->Lock(0, 0, (void**)&vertices, D3DLOCK_DISCARD));

    memcpy(vertices, vertexArray, sizeof(vertexArray));

    HR(m_pVertexBuffer->Unlock());

    return m_pDevice->SetRenderTarget(0, m_pTextureSurface);
}

```

# Answer
> 1 votes
`StretchRect` function does not execute the pixel shader.

Instead: Set up your render target and draw a polygon to cover the entire screen. This is the common way to perform a "full screen shader" pass.

---

Anecdotally, My personal recommendation is to investigate the Compute Shader.

---
Tags: c++, shaders, directx, hlsl, directx9
---


# Question
Title: How to implement level transitioning for 2D Platformer (tile-based)
I'm making a 2D tile-based platformer in C++/SDL and I want the player to move to the next level when they run off the side of the level, but I'm not sure how to implement this. I have tried putting colliders on the tiles at the edge of the map but it seems like there could be a better than than designating special tiles.

I wasn't sure what to keywords to search for when looking for a solution so if you can point me to a useful guide that would be great!

I'm looking for something very similar to how Super Metroid handles level changing.

# Answer
Without knowing any of the mechanics of your code it can be difficult to suggest a solution that is efficient, simple to integrate, and extendable. Please consider that when asking future questions. It would be a better use of time for the both of us to tailor an answer to your needs than to give general advice.

Now with that said, given free reign of the problem, I would approach it with the idea in mind that you may want to end levels through different scenarios in the future.

First I would create an interface specifically for that purpose.

```
Interface LevelFinisher {

    finishLevel()

}

```

Then you have the ability to end the level in numerous ways. You could assign the functionality to an item that you use, a platform you hit, an enemy you kill, etc.

Now your original question suggested you want to end levels after reaching a certain point. Using your new interface you can create an object that is fed the player's position and checks to see if they have passed the x or y coordinate that marks the level's end. Then simply call that object's *finishLevel()* method.
> 1 votes

---
Tags: platformer, levels
---


# Question
Title: Best way to handle cornering in a 2D maze game?
I want to implement smooth cornering in a grid, much like Pacman moving in his maze. A big difference with Pacman, my characters can stop- thus the player has to keep pressing the controls to keep moving.

I also want the speed of the character to be variable (depending on various game mechanics). Now this felt like a simple mechanic to code, however it's giving me more trouble than I expected. The code only works properly if the character aligns exactly with the tiles.

The green character moves down and the player want to enter the corridor on the right. However the character doesn't align properly thus the collision prevents it from moving.

Now the character "jumps" noticably if I did my collision check on the center of the character. I wanted the character corner a bit earlier to give the player some wiggle room. Thus I implemented 8 collision points:

It also keeps the character nicely aligned to the grid. All seemed fine until this happened:

The character keeps bouncing back and forth as the collision code pushed the character out of the colliding boundaries.

I feel my code is getting more complex than needed. I googled to check various pacman implementations, but most I found deal with fixed speeds and rely on the fact that pacman keeps moving.

So what is the best way to deal with navigating a gridlike maze with variable speeds?

My game is in Monogame (C#) my maze is an array of tiles\[x\]\[y\].

My current collision code goes like this:

For each *collision point* I check the tile in it's path (to prevent bullet through paper- while my character won't go as fast- I might get projectiles in the game later).

```
 TileData tileinpath = Line(X0, Y0, X1, Y1, new Vector2(obj.PosX + obj.CollisionPoints[i].RelativePosition.X, obj.PosY + obj.CollisionPoints[i].RelativePosition.Y));

```

`Line` is Bresenham on my tilemap to return the nearest tile in the collision path. Then depending on the location of the collisionpoint:

```
            case CollisionPosition.BottomRight:
                 if (moveY <= 0) //check if we're really moving that direction
                    break;

                    //apparently we hit something, so adjust everything accordingly.
                obj.SpeedY = 0; //stop movement in that direction.
                obj.PosY = tileinpath.Y * CollisionMap.TileHeight - obj.BoundingBox.Height / 2;
                obj.CollisionPoints[i].CollisionDetected = true;
                break;

```

Can the grid movement be done simpeler? What am I missing ...

**EDIT, based on solution:**

I ended up using *VaTTeRGeR* suggestion. I have the character move from tile center to tilecenter and make decisions based on the options whenever the character crosses a tilecenter.

```
    public void NavigateTo(Entities.Mobile mobile, Entities.Mobile.Direction intendeddirection, float dt)
    {
        Entities.Mobile.Direction CurrentDirection = mobile.CurrentDirection; //current direction of travel.
        float DeltaMove = mobile.Speed * dt; //amount of pixels moved in this frame.

        //what is our current tile?
        int currentTileX = MathHelper.Clamp((int)mobile.Position.X / CollisionMap.TileWidth, 0, CollisionMap.Width - 1);
        int currentTileY = MathHelper.Clamp((int)mobile.Position.Y / CollisionMap.TileHeight, 0, CollisionMap.Height - 1);

        Vector2 TileCenter = new Vector2(currentTileX * CollisionMap.TileWidth + CollisionMap.TileWidth / 2,
                                         currentTileY * CollisionMap.TileHeight + CollisionMap.TileHeight / 2);

        //determine the position compared to the centernode.
        bool IsInFrontOfNode = InFrontOfNode(mobile.Position, TileCenter, CurrentDirection);
        bool IsTargetPastOfNode = PastOfNode(mobile.Position, TileCenter, DeltaMove, CurrentDirection);
        bool WantsToReverse = Reversing(CurrentDirection, intendeddirection);

        if (IsInFrontOfNode)
        {

            if (WantsToReverse)
            {
                //it is assumed that the check to get here was already done.
                //the wants to reverse check already made sure we are moving in the revers direction of the travel direction
                MoveInDirection(mobile, intendeddirection, DeltaMove);
                return;
            }

            if (!IsTargetPastOfNode) //we're still in front of our node.
            {
                //Safely move the direction we were moving.
                MoveInDirection(mobile, CurrentDirection, DeltaMove);
                return;
            }

            //so now we're here:
            //the mobile wants to move past a node and can potentially change direction here.

            //check if we can move in the direction we want.
            if (intendeddirection != CurrentDirection)
            {
                //we want to change directions!
                if (IsTileAvailableInDirection(currentTileX, currentTileY, intendeddirection))
                {
                    //yes we can move that way.

                    //how much can we move in the new direction?
                    float remaining = RemainingMove(mobile.Position, TileCenter, DeltaMove, CurrentDirection);

                    //first move to the node.
                    mobile.Position = TileCenter;

                    //now move the remainder of the move.
                    MoveInDirection(mobile, intendeddirection, remaining);
                    return;
                }
                //no way, there is no tile over there.
            }

            //try to move in the current direction.
            if(IsTileAvailableInDirection(currentTileX,currentTileY,CurrentDirection))
            {
                //we can still move that direction.
                MoveInDirection(mobile, CurrentDirection,DeltaMove);
                return;
            }

            //we can not move further than the node (tilecenter).
            mobile.Position=TileCenter;
            return;
        }

        if (!IsInFrontOfNode)
        {
            //past the node. we can only reverse or continue in the direction we're moving in.

            if (WantsToReverse)
            {
                //it is assumed that the check to get here was already done.
                //the wants to reverse check already made sure we are moving in the revers direction of the travel direction
                MoveInDirection(mobile, intendeddirection, DeltaMove);
                return;
            }
            //we should already have checked this some frames ago, but there is no harm in checking each frame...

            //try to move in the current direction.
            if(IsTileAvailableInDirection(currentTileX,currentTileY,CurrentDirection))
            {
                //we can still move that direction.
                MoveInDirection(mobile, CurrentDirection,DeltaMove);
                return;
            }

            //we can not move further than the node (tilecenter).
            mobile.Position=TileCenter;
            return;
        }

    }

```

The helper functions do some minor calculations where the axis (X,Y) and relation to direction are relevant.

# Answer
> 2 votes
I would do it like this:

If the player wants to go around a corner/change direction, check if the distance he will be able to move in this tick (`speed*delta, GREEN ARROW`) is bigger than the distance from his center `LEFT BLUE DOT` to the connecting blocks center `ORANGE RECTANGLE`.

**If true:** move him to the center of the connection-block `ORANGE RECTANGLE` and then move him the remaining distance (speed\*delta minus former distance to center) in the direction he wants to turn. This moves him along the `RED ARROW` to the position the `RIGHT BLUE DOT` is at. Do all this in one tick.

**if not:** just move him forward.

# Answer
> 2 votes
I would look at the problem differently: I would use navigation graph instead. I would "bend" the original navigation graph to your problem - each junction is a node(with 0 radius), and each edge stores its length and its direction. Player navigate on graph instead of in a world full of solid walls. Player can move each frame at desired speed along edge he is on if either "correct" direction button is pressed *(note this could be generalize to support 8 or more directions)*. Another benefit is that generating such graph is trivial for uniform grid (any flood-type algorithm will do).  Whenever player would at his current speed cross a junction there is decision to be made which way he will be moved. You have many possibilities what logic choose here, first one to come to mind is pick the last held(=last pressed, still down) button direction. You could implement this for example by storing keydown(up) events on a stack.
In your original image, if player was on edge between nodes A and B, 1.1 units from B and moved 1.6 units in direction of B, decision would be made(trivial check 1.1 \< 1.6). If he held button S first(for moving down) and "short" before junction pressed button D, he would cross the junction, turning right and continued (remaining 0.5 units) on edge from B to D.

---
Tags: c#, collision-detection, tilemap, grid, cornering
---


# Question
Title: Quaternion rotations & transforms from global to local space
I am trying to solve this problem and getting no where, could really use some assistance. Rotation is defined as X (rotate left/right), Y(rotate up/down), Z(roll) Coordinates are X: Forward/backward, Y: Left/right, Z: up/down

I have two objects in simulated space, both have galactic coordinates (XYZ) and a quaternion representing their rotation.

ObjectA Coordinates: 0.593 0 0 (directly ahead of ObjB) RotationQuat: w: 0, x: 1, y: 0, z:0 (Rotated 180 yaw, facing backwards)

ObjectB Coordinates: 0 0 0 RotationQuat: w: 1, x: 0, y: 0, z: 0 (No rotation, facing towards ObjA)

Given the above information, how do I translate ObjA's location into ObjB's local space?

If ObjA fires at ObjB (or vise versa), I need to calculate which side will be hit. Forward, Aft, Port, Starboard, Ventral or Dorsal.

My project is written entirely in C. Actually this is an old project, created by someone else that I am converting to using quaternions due to gimbal lock.

Any advice?

# Answer
> 0 votes
> how do I translate ObjA's location into ObjB's local space?

Get A's coordinates as a vector from the centre of B:

```
Acb= (0.593,0,0) - (0,0,0) = (0.593,0,0)

```

Make a (non-unit) quaternion from Object A's coordinates wrt B:

```
Acq = w: 0, x: 0.593, y: 0, z: 0

```

Rotate it according to the inverse of B's orientation (Bq):

```
Bq^-1 * Acq * Bq
= (w: 1, x: 0, y: 0, z: 0) * (w: 0, x: 0.593, y: 0, z: 0) * (w: 1, x: 0, y: 0, z: 0)
= (w: 0, x: 0.593, y: 0, z: 0)

```

Extract the imaginary part: `(0.593,0,0)`

Voila.

Note: since B is aligned with the global frame here, AND is located at the world origin, the vector to A from B coordinate frame is the same as the vector to A from the world (galaxy) frame.

More information on how to rotate a vector or point with a quaternion here: https://en.wikipedia.org/wiki/Quaternions\_and\_spatial\_rotation#Using\_quaternion\_rotations

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


title: Pygame Scrolling Camera bug

text:
# Question
Title: Pygame Scrolling Camera bug
I asked a question the other day about how to implement a scrolling camera. I got a great answer which helped me achieve that... but in doing so I have lost basically all collision detection. Strangely, There are still small, invisible "platforms" that can be collided with... Above the first platform in view upon spawning (the second platform down), there is a very small area where I can get collision detection... happens near coordinates `(60, 51)`. Why is collision only happening in that tiny area, and not on any of the platforms throughout the entire level?

Thanks for any help, code at github: https://github.com/tear727/Netse/blob/master/game2.py

```
import random
import pygame
from pygame import *

display_width = 800
display_height = 640
camera = [0,0]
size = (display_width, display_height)
screen = pygame.display.set_mode(size)
black = (0,0,0)
white = (255,255,255)
player_image = pygame.image.load("yasuo.png")
background = Surface((32, 32))
background.convert()
background.fill(Color('#783131'))
level = [
    "PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP",
    "P                                          P",
    "P                                          P",
    "P                                          P",
    "P                    PPPPPPPPPPP           P",
    "P                                          P",
    "P                                          P",
    "P                                          P",
    "P    PPPPPPPP                              P",
    "P                                          P",
    "P                          PPPPPPP         P",
    "P                 PPPPPP                   P",
    "P                                          P",
    "P         PPPPPPP                          P",
    "P                                          P",
    "P                     PPPPPP               P",
    "P                                          P",
    "P   PPPPPPPPPPP                            P",
    "P                                          P",
    "P                 PPPPPPPPPPP              P",
    "P                                          P",
    "P                                          P",
    "P                                          P",
    "P                                          P",
    "PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP",
        ]

def main():
    pygame.init()
    clock = pygame.time.Clock()
    x = 0
    y = 0
    left_viewbox = display_width/2 - display_width/8
    right_viewbox = display_width/2 + display_width/10
    up_viewbox = display_height/2 - display_height/12
    down_viewbox = display_height/2 - display_height/12

    platformlst = []
    players = []

    player = Player(camera[0], camera[1])
    map = Map(x, y)
    platforms = Platform(camera[0], camera[1])
    players.append(player)

    pygame.display.set_caption("My game")
    obstacle_img = pygame.image.load("poro.png")

    def buildMap(xpos, ypos):
        for i in level:
            for j in i:
                if j == "P":
                    platformlst.append(platforms)
                    screen.blit(platforms.image, (xpos + camera[0], ypos + camera[1]))
                xpos += 64
            ypos += 64
            xpos = 0

    def follow(shift_x, shift_y):
        camera[0] += shift_x
        camera[1] += shift_y
        for i in players:
            i.rect.x += shift_x
            i.rect.y += shift_y

    def viewbox():
        if player.x <= left_viewbox:
            view_difference = left_viewbox - player.x
            player.x = left_viewbox
            follow(view_difference, 0)

        if player.x >= right_viewbox:
            view_difference = right_viewbox - player.x
            player.x = right_viewbox
            follow(view_difference, 0)

        if player.y <= up_viewbox:
            view_difference = up_viewbox - player.y
            player.y = up_viewbox
            follow(0, view_difference)

        if player.y >= down_viewbox:
            view_difference = down_viewbox - player.y
            player.y = down_viewbox
            follow(0, view_difference)

    def collide():
        if (platforms.rect.x < player.rect.x + player.rect.w and
            platforms.rect.x + platforms.rect.w > player.rect.x and
            platforms.rect.y < player.rect.y + player.rect.h and
            platforms.rect.h + platforms.rect.y > player.rect.y):
                print "collided"
                player.grounded = True

    game_exit = False

    while not game_exit:
        clock.tick(60)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                game_exit = True

            if event.type == pygame.KEYDOWN:
                print "pressed key"

                if event.key == pygame.K_LEFT:
                    player.left()

                if event.key == pygame.K_RIGHT:
                    print "move right"
                    player.right()
                if event.key == pygame.K_UP:
                    print "move up"
                    player.up()

            if event.type == pygame.KEYUP:
                if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                    player.stopx()

                if event.key == pygame.K_UP or pygame.K_DOWN:
                    player.stopy()

            if event.type == pygame.MOUSEBUTTONDOWN:
                print "pressed mouse button"
                player.boost()

            if event.type == pygame.MOUSEBUTTONUP:
                print "mouse button up"
                player.stop()

        print player.rect.x
        print player.rect.y
        map.buildBackground()
        buildMap(x, y)
        player.draw()
        player.move()
        collide()
        viewbox()
        pygame.display.update()

class Map:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def buildBackground(self):
        for i in range(32):
            for j in range(32):
                screen.blit(background, (i*32, j*32))

class Player:
    def __init__(self, x, y):
        self.grounded = True
        self.x = x
        self.y = y
        self.velx = 0
        self.vely = 0
        self.image = player_image
        self.rect = player_image.get_rect()

    def draw(self):
        screen.blit(self.image, (self.x, self.y))

    def move(self):
        self.x += self.velx
        self.y += self.vely
        if not self.grounded:
            self.y += 7
        self.grounded = False

    def right(self):
        self.velx = 20

    def left(self):
        self.velx = -20

    def up(self):
        self.vely = -20

    def stopx(self):
        self.velx = 0

    def stopy(self):
        self.vely = 0

    def boost(self):
        self.velx += 20
        self.vely += 20

    def stop(self):
        self.velx = 0
        self.vely = 0

class Platform:
    def __init__(self, x, y):
        self.image = Surface((64, 64))
        self.image.convert()
        self.image.fill(Color('#000000'))
        self.rect = Rect(x, y, 64, 64)

    def draw(self):
        screen.blit(self.image, (x, y))

if __name__ == "__main__":
    main()

```

# Answer
> 0 votes
The trick is I think you misunderstood my original answer to your previous question. The camera's position should only be taken into account when drawing (using `blit`). You're offsetting all drawn objects in the screen by the camera's position.

So two specific problems with the code you have shown:

1. The `blit` that does use the camera position should **subtract** it rather than adding it
2. **Every** `blit` needs to subtract the camera's position

# Answer
> 0 votes
This may, or may not, be the correct answer for you,

**BUT**

In your code, when you draw the platforms images to the screen, you add the camera's position to their x/y positions. This would not be necessary because you would then have problems with colliding, because your adding the cameras scroll to it so you wouldn't see them in their colliding positions.

If you wanted to keep that, then I would suggest adding the camera x/y to the collision section.

Hope this helps.

---
Tags: camera, pygame, side-scroller
---


# Question
Title: How to move on iTween path when a button is clicked
I have set the iTween path and also I have added a button. When I click on the button the object should start moving along the iTween path.But issue I'm facing is when I run my project at initial stage itself the object is moving on the iTween path which I have set not on the button click. Then I tried out placing the same code for moving upon button click and it'S still not working. Can anybody help me solve this issue and provide me with a piece of code for it. The code is here

```
void Start () {

    //iTween.MoveTo(gameObject,iTween.Hash ("path",iTweenPath.GetPath("BoxOut"),"time",5));
    iTween.MoveTo(gameObject,iTween.Hash ("path",iTweenPath.GetPath("Pass"),"time",50));

}

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

}

```

The above code worked initially, when the project started running, the object starts moving on the path. Then I edited the code and added the code on button click and it's not working anymore. The edited code is below.

```
void Start () {

    //iTween.MoveTo(gameObject,iTween.Hash ("path",iTweenPath.GetPath("BoxOut"),"time",5));
    iTween.MoveTo(gameObject,iTween.Hash ("path",iTweenPath.GetPath("Pass"),"time",50));

}

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

}
void OnGUI()

{
    if(GUI.Button(new Rect(100,100,100,100),"gggggg"))
    {
        Debug.Log("fffffffffffffffffffffff");
        resp=true;
    }
}

```

Its not working. Please help me out with a piece of code.

# Answer
> 1 votes
You might want to try the new Unity 5 Gui, the OnGUI method is pretty outdated. Hope this code block is just for testing purpose. The function GUI.Button() draws the button on screen and also returns whether that button was pressed (a boolean). So whatever code you need to execute must be written inside the if block. Hope this solves the issue.

```
    void Start ()
    {

    }

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

    }
    void OnGUI()

    {
        if(GUI.Button(new Rect(100,100,100,100),"gggggg"))
        {
            Debug.Log("Button Clicked");
            iTween.MoveTo(gameObject,iTween.Hash ("path",iTweenPath.GetPath("Pass"),"time",50));
        }
    }

```

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


# Question
Title: SQLite Query from unknown table based on known column value single query
I'm working on a database to back up my online TCG. It's currently SQLite, but I'm going to transition it to a MySQL database later.

Currently, I have three distinct types of cards with their own unique fields. For example. However, all cards have a single uniqueid that I use to refer to them.

```
TABLE cards {
    CARD_ID as INT
    CARD_TYPE as INT
    TYPE_ID as INT
}

TABLE creature_cards {
    CARD_ID as INT
    TYPE_ID as INT
    NAME as TEXT
    FLAVOR as TEXT
    ATTACK as INT
    DEFENSE as INT
    ELEMENT as INT
    FLAGS as INT
    MANA_COST as TEXT
}

TABLE spell_cards {
    CARD_ID as INT
    TYPE_ID as INT
    NAME as TEXT
    FLAVOR as TEXT
    SPELL_TYPE as INT
    ELEMENT as INT
    MANA_COST as TEXT
}

TABLE mana_cards {
    CARD_ID as INT
    TYPE_ID as INT
    NAME as TEXT
    FLAVOR as TEXT
    ELEMENT as INT
}

```

I'm trying to figure out how to build a query that will allow me to get all fields from a specific table without knowing the table I need to pull from ahead of time.

Basically, I want to be able to supply CARD\_ID, query the cards table, and use the CARD\_TYPE and TYPE\_ID to return the row from creature\_cards where CARD\_TYPE is 1, spell\_cards where CARD\_TYPE is 2, and mana\_cards where CARD\_TYPE is 3.

I'm currently doing this through two separate queries and doing the logic on the backend, but I'm wondering if there's a way to get the data all in one query, because my queries can be quite time consuming.

Would it just be better to jam all card fields into one table, rather than keeping them in three separate tables?

# Answer
> Would it just be better to jam all card fields into one table, rather than keeping them in three separate tables?

That depends on 2 things: How many you have and how different they are. Basically if you don't aim to have more than several thousand items (that's just a random number order I throw, it's system and query dependent), you are probably better of with just 1 table, it will save you a lot of time.

That's brings me to the second point. It depends on how different the cards are. If I look at your schema, you have 5 common fields between cards, and the rest is a bit different. That's in my opinion not enough to justify having different tables. The logic is the same behind each cards (they are used in the same way, only with different effect?).

However, your main concern over this seems to be performance. For performance, it depends on the frequency mainly of your calls. If you have in a database all of your possible cards, then you don't need to query the database more than once. You just load all of them in memory and go through the memory whenever you need to, it's way faster than accessing disk.

Finally, to answer your question, you can use JOINS (examples). And if you are interested, see the performance of joins here.

Hope this answers.
> 1 votes

---
Tags: multiplayer, databases, online, card-game, sql
---


# Question
Title: Minecraft Forge modding 1.8 instance changing tool/armor material + color
I am developing a minecraft mod in forge, and I need to find a way to create tools and armor where individual instances of items would have different tool material properties, armor material properties, and hues in how they are displayed. If you can offer help for any of those things, or for how to achieve these dynamic properties in general, I would be very appreciative.

# Answer
I'm unsure about Forge in specific, but back in Bukkit a few years back, I managed to get custom NBT tags saving data regarding items. You might look into working with NBT tags for setting and storing custom properties on items.
> 2 votes

# Answer
I'm not sure about Forge aswell, but it is possible to change the nbt tags of individual items in Minecraft. I doubt that there is no implemenation of changing NBT data in Forge. Just google it! :-)
> 0 votes

---
Tags: minecraft-modding
---


# Question
Title: What algorithm is used to select a voxel (from a player's perspective)?
In first-person voxel games (like Minecraft, shown below) you can select voxels by going over them. What kind of algorithm is used to select a voxel?

I haven't implemented it in my voxel application yet, but the only solution I could think of would be casting a ray and checking for intersections but it seems very inefficient.

# Answer
Raycasting is what you want. As far as I know Minecraft uses raycasting aswell. How it works is basicly, that you send a "ray", represented as a 3D vector from the middle of your camera. The voxel you look at then is the first one the ray " collides with. ThinMatrix made a tutorial on ray casting.
> 1 votes

---
Tags: 3d, voxels, mouse, interface
---


# Question
Title: How do I make the background color fade into a different color after hovering it?
I was trying to make the starter inputs for my text rpg change the background color in a fade effect with JQuery, but I cant figure out what i did wrong. Heres the part im focusing on:

```
  <script>
    $(document).ready(function() {
      $Intro_Inputs = $('#Header_Intro input');
      $Intro_Inputs.hover(function() {
        $(this).animate({'background-color':'#2E8AE5'}, 'slow');
      });
    });
  </script>

```

If anyone could help me out with the mistake i made i would greatly appreciate it!

(The problem was that it wouldnt fade the colors in)

# Answer
> 0 votes
Here's what the jQuery documentation says:

> All animated properties should be animated to a single numeric value, except as noted below; most properties that are non-numeric cannot be animated using basic jQuery functionality (For example, width, height, or left can be animated but background-color cannot be, unless the jQuery.Color plugin is used).

You can't do it with jQuery without the jQuery.Color plugin.

Alternatively, you could do it with CSS without javascript:
`//animates to the hover state`
`#Header_Intro input:hover {
 background: #2E8AE5;
 transition: 0.5s;
 -moz-transition: 0.5s;
 -webkit-transition: 0.5s;
 -o-transition: 0.5s;
}`
`//animates to the normal state`
`#Header_Intro input {
 background: #FFFFFF;
 transition: 0.5s;
 -moz-transition: 0.5s;
 -webkit-transition: 0.5s;
 -o-transition: 0.5s;
}`

---
Tags: javascript, jquery, html
---