# Question
Title: How can I avoid tons of if/else statements dealing with settings?
I am creating a sudoku game using the android sdk. I have a PreferenceActivity filled with different settings, such as "Highlight all digits" or "activate the visual helper". The problem is that I am trying to avoid using the if else pattern everywhere in my code in order to check if each settings is activated to execute a specific code. I am looking for the best pattern that could help me to handle my different settings. My code is pretty clear(I think), I have a Grid class containing all the grid information and a Game view, that handles inputs and interacts with the Grid class.

# Answer
> 3 votes
One way to avoid using a load of `if`/`else`/`else if` statements that always checks the same set of things is to use the state machine design pattern.

You start by defining the different states that influence the behaviour, based on the player preferences.

Then you extract the behaviour from where it is now, and add it to a method of a class that derives from a base class.

Depending on the user's preferences, you instantiate the appropriate derived class, and delegate the function calls to that object.

If you have these states:

* `stateHighlightAllDigits`
* `stateActivateVisualHelper`
* `stateActivateVisualHelper_HighlightAllDigits`

And if your code looks like (pseudo code):

```
class Grid:
  function draw:
    // ...

    if param[HighlightAllDigits] and [ActivateVisualHelper]:
      // draw stuff with the visual helper AND all digits highligted
    else if param[HighlightAllDigits] and not [ActivateVisualHelper]:
      // draw stuff with all digits highligted
    else if not param[HighlightAllDigits] and [ActivateVisualHelper]:
      // draw stuff with the visual helper
    else:
      // default way of drawing

    // ...

```

You would split your code into something like this:

```
class BaseState:
  function draw:
    // default way of drawing

class StateHighlightAllDigits inheritsFrom BaseState:
  function draw override:
    // draw stuff with all digits highligted

class StateActivateVisualHelper inheritsFrom BaseState:
  function draw override:
    // draw stuff with the visual helper

class StateActivateVisualHelper_HighlightAllDigits inheritsFrom BaseState:
  function draw override:
    // draw stuff with the visual helper AND all digits highligted

```

And your Grid:

```
class Grid:
  BaseState mCurrentState

  function init:
    // you still have to do the checks, but you do it only once
    if param[HighlightAllDigits] and [ActivateVisualHelper]:
      mCurrentState = new StateActivateVisualHelper_HighlightAllDigits()
    else if param[HighlightAllDigits] and not [ActivateVisualHelper]:
      mCurrentState = new StateHighlightAllDigits()
    else if not param[HighlightAllDigits] and [ActivateVisualHelper]:
      mCurrentState = new StateActivateVisualHelper()
    else:
      mCurrentState = new BaseState()

  function draw:
    // ...
    // Delegate the way of doing things to a specialized method.
    mCurrentState.draw()
    // ...

```

This way, your code is very clean: you can see clearly what it's doing without getting bothered by a bloat of `if`/`else`/`else if` everywhere.

# Answer
> 0 votes
As mentioned by @alexandre, without specific examples it's hard to offer specific fixes...

But!

It sounds like your intuition is, reasonably, that by simplifying your code structure, you'll reduce the maintenance burden and reduce the chance of bugs.

Another approach to help in this regard is *unit tests*. This aims to nail down the functionality independently from the implementation. A unit test is like a "mini app" that uses your code/classes/engine, but only does one thing at a time and confirms the result.

```
void test1() {
    Game game(setup params);
    game.moreSetup();
    game.event(someEvent);
    auto x = game.someQuery();
    assertEquals(whatXShouldBe, x);
    game.teardown();
}

```

This moves your focus from coding style to code correctness.

And *then*, as you add features and maybe think there's too many if-elses or what not, and want to try a different approach, you can refactor but keep the same tests.

Code always trends towards messiness. Sometimes we can reduce the decay a little... And unit tests are a way to know that it still works, even when it's messy.

# Answer
> 0 votes
What you can do is combine the Strategy pattern and Factory pattern.

Use the Factory pattern to build a drawer class that implements a given drawing strategy. In this way, you use composition or inheritance to determine behaviour at run time, and your if-else statements would be concentrated in the factory, instead of being scattered everywhere.

An example:

```
class GridDrawer {
    // selected strategies
    CellDrawer cell;
    LineDrawer line;
    ...
    GridDrawer(Map options) {
        // factory
        cell = BasicCellDrawer();
        line = BasicLineDrawer();
        if (options.get("highlight")) {
            cell = HighlightedCellDrawer(cell, options.get("highlightColor"));
            line = HighlightedLineDrawer(line);
        }
        if (options.get("helper")) {
            cell = VisualHelperDrawer(cell);
        }
    }
    void draw(Canvas canvas, Game game) {
        ...
    }
}

class HighlightedCellDrawer implements CellDrawer {
    HighlightedCellDrawer(CellDrawer base, Color color) { ... }
    void draw(Canvas canvas, Game game) {
        // ... draw something behind the cell ...
        base.draw(canvas, game);
        // ... draw something above the cell ...
    }
}

```

---
Tags: settings
---


# Question
Title: Rotating a swinging sword in LWJGL gives wierd results
I'm making a 2d top down game in Java using LWJGL(OpenGL, essentially). I recently tried adding a swinging sword mechanism. My coordinate system is set to the bottom left FOR ALL objects. The rotation worked, but it happens with respect to the bottom left corner of the Sword Quad. I want it to rotate with the center of the bottom line as the pivot for rotation. I tried a lot of solutions from the internet like:

* translating the object to origin(0,0 of the screen), then rotating, then translate to the point of pivot.
* translating object normally, then rotating, then again translating to the point you want it to pivot at.

But they all yield weird results.

Here's the code:

**The Sword Class:**

```
public class Sword extends GameObject {

    private static int speed = 5, deg = 0;;

    private Texture tex;

    public Sword(float x, float y, ObjectId id)  {
        super(x, y, id);

        //tex = ImageLoader.loadTexture(null, null);
    }
    protected void update(ArrayList<GameObject> objects) {
        if(deg < 360) deg += 1;
        else deg = 0;
    }

    protected void render() {
        Draw.rect(x, y, 10, 32, deg, 1, 0, 0);
    }

    public Rectangle getBounds() {
        return null;
    }

}

```

**The Draw.rect method:**

```
public static void rect( float x, float y, float width, float height,
                         float deg, float r, float g, float b) {
        glDisable(GL_TEXTURE_2D);

        glPushMatrix();
        {
            glTranslatef(0, 0, 0);
            glRotatef(deg, 0, 0, 1);
            glTranslatef(x + (width/2), y, 0);

            glColor3f(r, g, b);

            glBegin(GL_QUADS); // Specifies to the program where the drawing
                               // code begins. just to keep stuff neat.
                               // GL_QUADS specifies the type of shape
                               // you're going to be drawing.
            {
                glVertex2f(0, 0); // Specify the vertices. 0, 0 is on BOTTOM
                                  // LEFT CORNER OF SCREEN.
                glVertex2f(0, height); // 2f specifies the number of args
                                       // we're taking(2) and the type
                                       // (float)
                glVertex2f(width, height);
                glVertex2f(width, 0);
            }
            glEnd();
        }

        glPopMatrix();

        glEnable(GL_TEXTURE_2D);
    }

```

**EDIT:** Here is an image of what "weird result" is. In the pic, I'm translating first to origin\[(0, 0) of the WORLD\], then rotating(by 90 degrees), then translating to translating to \[x - (width/2) , y\]. As you can see, the red block that represents the sword is out of the "arena", even though I've set the x, and y of the sword to near the player. The image:

# Answer
There are multiple issues with this code.

First of all your quad vertices are not centered around the origin, this doesn't have to be a problem but note that it will use the corner of the quad as the pivot to rotate the sprite then.

Secondly, you are rotating on the X-axis. This seems weird since the general direction your camera in looking in is the -Z direction. If you want to rotate a quad that spans the X,Y plane you have to rotate on the Z axis.

Thirdly, and most importantly for your question, you are translating first and then rotating. This will move your sword, and then rotate it in a giant circle around the origin. Note that glTranslate(0, 0, 0); does absolutely nothing. Also note that you want to call these commands in reverse order, since OpenGL uses a matrix stack. So to rotate first and then translate (like you really want to) you would do:

glTranslatef(x + (width/2), y, 0); glRotatef(0, 0, deg, 1);
> 1 votes

# Answer
For that kind of behaviour you generally Rotate about the origin, then Translate, then Scale.

Since you want to rotate from the center bottom of your quad, from the origin you'd: 1. Translate the image to have its center at the origin (`(width/2)`) 2. Rotate 3. Translate to the desired location

I'm not familiar with the inner works of OpenGL (I work with a rendering engine), but your first translate (`glTranslatef(0, 0, 0);` does nothing, it does not translate anything because of the values are zero. I think your intention was to "set the origin at (0, 0, 0)"; to achieve that, I think you need to set the current matrix to identity instead (`glLoadIdentity();`).

So in the end it would look like:

1. Reset the transform matrix (`glLoadIdentity()`)
2. Translate the image to have its center at the origin (`(width/2)`)
3. Rotate
4. Translate to the desired location

To get to what you need, I suggest to do one step at a time. ("Ok, is my sword properly centered from the origin? No, ok let's do that... Ok, done, now let's try to rotate it about it's new origin... ok now it works as I'd like it to... ok, finally, let's put it in its final position... and... done!") That's usually what I do, otherwise I get lost and do not fully understand the process.
> 0 votes

---
Tags: opengl, java, lwjgl, rotate
---


# Question
Title: Camera (pole cam) implementation problem
In my project I have simple scene graph to render whole scene and Bullet physics SDK to provide physics simulation.

Each rendered object is represented as scene node. Camera always has target and located behind this target. Target can be any scene node.

First, I want to describe my rendering pipeline.

1)When time to render whole scene, we calculate view matrix from target's world matrix. We take offset vector in order to locate camera behind targeted scene node and transform it to scene node world's coordinate. Then add position of target with transformed offset vector. Finally, get inverse matrix of scene node. This method always is called before rendering whole scene.

```
HRESULT CameraNode::SetViewTransform(Scene *pScene)
{
    //If there is a target, make sure the camera is
    //rigidly attached right behind the target
    if(m_pTarget)
    {
        Mat4x4 mat = m_pTarget->VGet()->ToWorld();
        Vec4 at = m_CamOffsetVector;
        Vec4 atWorld = mat.Xform(at);
        Vec3 pos = mat.GetPosition() + Vec3(at);
        mat.SetPosition(pos);
        VSetTransform(&mat); // Set normal matrix and calculate inverse matrix
    }
    m_View = VGet()->FromWorld(); // Get inversed matrix
    pScene->GetRenderer()->VSetViewTransform(&m_View);
    return S_OK;
}

```

2)Then, when time to render particular scene node, we calculate projection matrix and send it to the vertex shader.

```
Mat4x4 CameraNode::GetWorldViewProjection(Scene *pScene)
{
     Mat4x4 world = pScene->GetTopMatrix();
     Mat4x4 view = VGet()->FromWorld();
     Mat4x4 worldView = world * view;
     return m_Projection * worldView;
}

```

I have next problem, when I calculate view matrix from target's world matrix and locate target on coordinate ( x = 0; y = 10; z = 1) it started to fall due to physics and jerk/twitch. \[1\]

When I set view/camera matrix only offset position. Scene node falls without jerking/twitching. \[2\]

How I can fix this jerking/twitching when camera is following the scene node ?

I suppose that it is problem of matrices multiplication, when Bullet SDK sets new coordinates to scene node. But I have no idea how it can be solved.

# Answer
I found that, physics system was late with matrix synchronization. In the result, scene node wasn't updated on time with the desired matrix. When I got new projection matrix for rendering, world matrix had updated matrix, but view matrix was calculated with old matrix.

I realized that GLM library good accuracy in this respect, as for this, because DirectX matrix to round this error.
> 0 votes

---
Tags: camera, matrix, scene, graph
---


title: Developing a game using opengl

text:
# Question
Title: Developing a game using opengl
Hello Everyone, I want to create a game using OPEN GL to learn basics of the game development. I know C++ and OOPS and can manage the coding. I have tried using the free engines on the market like Unreal Engine, Unity and Game Maker. Unreal Engine in particular doesn't work well on my System due to it's higher requirements. Even all other engines have some kind of abstraction to themselves. I have time to spare. So, please suggest me a starting point to start developing using OPEN GL and also the math required to create them. All I want to do is learn it thoroughly at the lower level. Thanks in advance

# Answer
I was in the same boat a couple of years ago. All engines will have some abstractions that are strange and take some getting used to. Building your own engine will cause a lot of heartache and difficulties you did not expect down the road. I had to move my engine over to Box2D just to handle the massive undertaking physics had on my project.

If you're sincerely in the mood to build the engine, it doesn't take much to get started, but it takes a lot to get through the learning phase (your first couple of games).

My only input would be to not do everything yourself. OpenGL is awesome, but look for other libraries which will suit your needs in the long run.

In terms of resources for OpenGL; LearnOpenGL, compared to any other resources, this website is by far the best I've come across, It even has a section on how to build a 2D game right at the end. I tried studying The Red Book, but this is far too low level for a new comer to the API.

Goodluck!
> 1 votes

# Answer
I would STRONGLY RECOMMEND you to follow this YouTube tutorial series:

3D Game Engine Development Tutorial

It is a good starting point to learn the basics and although the tutorial is based on Java, you should be able to recreate it in any languages you prefer. (:
> 0 votes

# Answer
The official OpenGL documentation is well done, but IMHO you need a background of how a game is structured, what is and how a shader works and - first of all - how the **rendering pipeline** works. If you have time (and money), Real-Time Rendering gives you the theory you need.

Anyway, from my experience I understood that the best way to learn how to write a game is to study someone else code. I suggest you THIS: *Real Time 3D Demo* written in C++ and GLSL. Of course, on the web there are a lot of alternatives.
> 0 votes

---
Tags: opengl
---


# Question
Title: Cubemaps turn black OpenGL GLSL Java LWJGL
Recently I tried to add cubemaps to my 3D-rendering engine. The objects with a cubemap now turn completely black. This is how I load my cubemap:

```
public static int loadCubeMap(String filename)
{
    int id = GL11.glGenTextures();

    GL13.glActiveTexture(GL13.GL_TEXTURE0);
    GL11.glBindTexture(GL13.GL_TEXTURE_CUBE_MAP, id);

    for(int i = 0; i < CUBEMAP_NAMES.length; i++)
    {
        TextureData data = decodeTextureFile(CUBEMAPS_LOCATION + filename + "/" + CUBEMAP_NAMES[i]);
        GL11.glTexImage2D(GL13.GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL11.GL_RGBA, data.getWidth(), data.getHeight(), 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, data.getBuffer());
    }
    GL11.glTexParameteri(GL13.GL_TEXTURE_CUBE_MAP, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR);
    GL11.glTexParameteri(GL13.GL_TEXTURE_CUBE_MAP, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR);
    GL11.glTexParameteri(GL13.GL_TEXTURE_CUBE_MAP, GL11.GL_TEXTURE_WRAP_S, GL12.GL_CLAMP_TO_EDGE);
    GL11.glTexParameteri(GL13.GL_TEXTURE_CUBE_MAP, GL11.GL_TEXTURE_WRAP_T, GL12.GL_CLAMP_TO_EDGE);
    return id;
}

```

TextureData class only contains: int width, height and a ByteBuffer buffer

```
private static TextureData decodeTextureFile(String fileName)
{
    int width = 0;
    int height = 0;
    ByteBuffer buffer = null;
    try
    {
        FileInputStream in = new FileInputStream(TEXTURES_LOCATION + fileName + ".png");
        PNGDecoder decoder = new PNGDecoder(in);
        width = decoder.getWidth();
        height = decoder.getHeight();
        buffer = ByteBuffer.allocateDirect(4 * width * height);
        decoder.decode(buffer, width * 4, Format.RGBA);
        buffer.flip();
        in.close();
    } catch (Exception e)
    {
        e.printStackTrace();
    }
    return new TextureData(width, height, buffer);
}

```

This is how I load the cubemap to the samplerCube cubemap\[i\] in the fragment shader:

```
public void loadCubeMap(int id, CubeMap cubemap, int cubemapid)
{
    if(cubemap != null)
    {
        super.loadTexture(location_cubemaps[cubemapid], cubemap.id, id, GL13.GL_TEXTURE_CUBE_MAP);
        super.loadFloat(location_cubemap_intensity[id], cubemap.intensity);
    }else
    {
        super.loadFloat(location_cubemap_intensity[id], 0.0f);
    }
}

```

in super class:

```
protected void loadTexture(int location, int texture, int i, int texturetype)
{
    loadInt(location, i+1);
    GL13.glActiveTexture(GL13.GL_TEXTURE0 + i);
    GL11.glBindTexture(texturetype, texture);
}

```

And this is my fragment shader:

```
#version 400 core

  in vec4 color;
  in vec2 texCoord0;
  in vec3 surface_normal;
  in vec3 to_light_vector;
  in vec3 world_position_out;
  out vec4 out_Color;

  uniform sampler2D sampler0;

  uniform samplerCube cubemap[3];

  uniform vec3 lightColor;

  uniform float cubemap_intensity[3];

  uniform int hasTexture;

  void main(void)
   {
      vec3 unitNormal = normalize(surface_normal);
   vec3 unitLight  = normalize(to_light_vector);

   float nDot1 = dot(unitNormal, unitLight);
   float brightness = max(nDot1, 0.02);

   vec3 diffuse = color.xyz * brightness * lightColor * color.xyz;
   vec4 textureColor = texture(sampler0, texCoord0.xy);
   if(textureColor.a < 0.5)
       discard;
   vec4 shadedTextureColor = brightness * vec4(lightColor, 1) * textureColor;
    vec4 coloredShadedTexture = mix(vec4(diffuse, 1), shadedTextureColor, textureColor.a * hasTexture);

   vec4 reflectionColor = texture(cubemap[0], world_position_out);
   vec4 refractionColor;
   vec4 cubemapColor;

   out_Color = reflectionColor;
  }

```

# Answer
What a dump question. I put the cubemap to the wrong samplerCube. I assigned the map to cubemap\[1\] not cubemap\[0\]. Great example of "I wouldn't do something like this. The error must be somewhere in the OpenGL code!" :D
> 1 votes

---
Tags: opengl, textures, glsl, lwjgl, cubemap
---


title: Render Queue Sorting, HOW?

text:
# Question
Title: Render Queue Sorting, HOW?
Recently I'm trying to implement a render queue sorting system, i.e., ordering my renderable objects in an array in such a way that the overhead of OpenGL state changes are minumum. After some googling, the most ideal one (to me) is to generate an integer key value for each renderable object, and the sorting is based on that value. Once done sorting, objects that have similar rendering states (same shader, texture, distance, etc.) will be close to each other, so we can just loop through the object array and submit the draw calls for rendering.

Here's a detailed explanation: Order your graphics draw calls around!

My problem is, how do I loop through the renderable object's array to submit their draw calls for actual rendering? Do I need to keep track of the current OpenGL states manually?

What have come to my mind is:

```
(for each renderable object)
{
    if(objects[i].getShader() != m_currentShader)
    {
        m_currentShader = objects[i].getShader();
        m_currentShader.bind();
    }

    if(objects[i].getTexture() != m_currentTexture)
    {
        m_currentTexture = objects[i].getTexture();
        m_currentTexture.bind();
    }

    // ... and so on

    object[i].getMesh().draw();
}

```

Seems not so performance-friendly to me, but I can't find any further explanation on how to submit the actual draw calls form the object's array either on the article I've provided or other sites I can find. Perhaps there's something I have missed?

# Answer
> 6 votes
Some ideas:

* You could ignore the issue, and do what you're currently doing. Assuming those texture and shader comparisons are to OpenGL IDs (which are just integers), it's unlikely those checks are going to create a huge performance bottleneck. Comparison of integer values on modern CPUs is rather fast. Unless your profiler has told you this is currently a problem I would not worry that much about it.
* You could *group* instead of just sort; that is, find a way to assemble an aggregate key out of all the possible state you might check for and sort by and put the renderable objects into buckets based on that key. If all you're sorting by is shaders and textures, for example, a 32-bit key will give you several thousands of texture and shader IDs to work with. Using a simple bit-packed integers as a key is easy, but does tend to be limiting as you scale up the complexity of your game (you really start to lose bits once you have multiple textures in play, and so on). This sounds similar to what your current sorting key is, but it also sounds like that key isn't giving you quite the information you need in terms of state capture.
* Finally, you can process a list of *render commands* instead of renderable objects. This command list contains both "objects to render" as well as "GPU commands to issue." When you do your initial sort of your actual renderable objects, you insert state-change commands into this command buffer as you find boundaries in the sorting groups where states change. Then you simply process this command list in a linear fashion, applying each command directly without state checks, confident that your earlier sorting pass has introduced the appropriate state change commands at the appropriate time. This is the most general of the three solutions I've presented, but is obviously a lot more work to implement than the first one.

---
Tags: opengl, textures, shaders, graphics, rendering
---


# Question
Title: XNA Line to Rectangle Collision return first pixel
I have the following code:

```
    public static bool LineIntersectsRect(Point p1, Point p2, Rectangle r)
    {
        return LineIntersectsLine(p1, p2, new Point(r.X, r.Y), new Point(r.X + r.Width, r.Y)) ||
               LineIntersectsLine(p1, p2, new Point(r.X + r.Width, r.Y), new Point(r.X + r.Width, r.Y + r.Height)) ||
               LineIntersectsLine(p1, p2, new Point(r.X + r.Width, r.Y + r.Height), new Point(r.X, r.Y + r.Height)) ||
               LineIntersectsLine(p1, p2, new Point(r.X, r.Y + r.Height), new Point(r.X, r.Y)) ||
               (r.Contains(p1) && r.Contains(p2));
    }

    private static bool LineIntersectsLine(Point l1p1, Point l1p2, Point l2p1, Point l2p2)
    {
        float q = (l1p1.Y - l2p1.Y) * (l2p2.X - l2p1.X) - (l1p1.X - l2p1.X) * (l2p2.Y - l2p1.Y);
        float d = (l1p2.X - l1p1.X) * (l2p2.Y - l2p1.Y) - (l1p2.Y - l1p1.Y) * (l2p2.X - l2p1.X);

        if (d == 0)
        {
            return false;
        }

        float r = q / d;

        q = (l1p1.Y - l2p1.Y) * (l1p2.X - l1p1.X) - (l1p1.X - l2p1.X) * (l1p2.Y - l1p1.Y);
        float s = q / d;

        if (r < 0 || r > 1 || s < 0 || s > 1)
        {
            return false;
        }

        return true;
    }

```

This code checks to see if a line intersects a given rectangle. But I need to find a way to get the position of the first pixel colliding between Point 'p1' and Point 'p2'.

Any help is appreciated.

# Answer
You only have to find the intersection point in your LineIntersectsLine method.

Add something like this last:

```
Vector2 t0 = l1p2 - l1p1;
Vector2 t1 = l2p2 - l2p1;
Vector2 t2 = l2p1 - l1p1;

float dotDPerp = t0.X * t1.Y - t0.Y * d.X;
float t = (t2.X * t1.Y - t2.Y * t1.X) / dotDPerp;

Vector2 intersection = l1p1 + t * t0;

```
> 2 votes

---
Tags: xna, collision-detection, linear-algebra
---


# Question
Title: Ray tracing - draw polygon (square/bounded plane)
I'm going on with my own ray tracer as an iPad app for a school project. This is the result with soft shadow, antialiasing, pure reflective and pure transparent object:

Now i want to change the skybox, implemented with the method contained here http://www.ics.uci.edu/~gopi/CS211B/RayTracing%20tutorial.pdf with a real cube that wrap all the scene. In this way I can display the soft shadow projected on the floor. I read a lot of documentation about ray tracing polygon and I understood how to check if the ray intersect the polygon plane. Now my question is: if I want to draw a square, one for each side of my cube that will wrap the scene, ***how do I check if the point of intersecton is inside the square/polygon (so that i can shade it)?*** All the documentation seems so vague and incomplete. I can't find a complete explanation with some example, and maybe with some pseudo code, that really explain how to draw a square (bounded plane) in a ray tracer.

Thanks for helping me.

# Answer
I finally managed it. I choose one of the most simple method, that could be found here https://sites.google.com/site/justinscsstuff/object-intersection but could also be found in some of the documents linked by wondra in the comments above.

**This method work for convex polygon** (for other kind odd/even rule, winding number rule or other method must be used). The point is simple: a generalization of the test used for triangle.

Check that the point is always on the left of an edge, by checking the dot product between the normal of the polygon and the result of the cross product between and edge and a vector from the current vertex to the intersection point. Some optimisation could be useful (for example: precalculate the edge list and avoid to calculate them every time). Here is my code in Objective-c.

```
-(NSMutableDictionary *)intersect:(Ray *)ray {

   //Check intersection of ray with polygon ray.
   NSMutableDictionary *intersectionData = [self intersectWithPlaneOfPolygon:ray];

  if(intersectionData == nil) {

      return nil;
  }

  Point3D *intersectionPoint = [intersectionData objectForKey:@"point"];
  NSUInteger numberOfVertex = self.vertexList.count;

  for (int i = 0; i < numberOfVertex; i++) {

      Point3D *nextVertex = [self.vertexList objectAtIndex:((i + 1) % numberOfVertex)];
      Point3D *currentVertex = [self.vertexList objectAtIndex:i];
      Vector3D *edge = [nextVertex diff:currentVertex];

      Vector3D *edge = [self.edgeList objectAtIndex:i];
      Vector3D *vectorWithIntersection = [intersectionPoint diff:currentVertex];

      Vector3D *crossProduct = [edge cross:vectorWithIntersection];

      float dotProduct = [crossProduct dot:self.normal];

      if(dotProduct < 0) {

          //Point is outside polygon.
          return nil;
      }
  }

  return intersectionData;
}

```
> 1 votes

---
Tags: raytracing
---


# Question
Title: Ray tracing - texture and phong lighting
Other questione releated to my ray tracer implementation for iPad.

If I have a polygon that has a texture and a material, how do I calculate the color using Phong lighting model? Is the texture used in substitution of some of the component (diffuse?)? Or if there's a texture I need to just ignore the material and get only the texture color?

# Answer
> 0 votes
I don't exactly understand how would ray-tracing change anything, here is how it usually goes:

You can have a texture for any parameter you like, but the most common is a diffuse(color) map, so you just sample this based on the texture coordinates and use the texture in place of the single-color diffuse. You could also combine the texture with an arbitrary color, tinting the given element.

Other common textures include normal maps, reflection maps, which replace their respective counterparts. Normal maps can be a bit tricky, because they specify the rotation relative to the surface, so you need to construct a Tangent Bitangent Normal matrix, which will do the transformation for you.

---
Tags: textures, lighting, raytracing
---


# Question
Title: How to split a 2D sprite tile set into individual sprites?
I see a lot of sprite catalogs for games provided as single PNG image, like the one below.

I'm interested if I have to manually create tiles from that, or if there's some program that can split it into various tile combinations for me? For example, given the tile combination below, I will have to create a flat grass surface, and 8 other combinations with various edges. Is there something that can automate this task?

# Answer
> 2 votes
After a bit of struggling, I found this info:

1) Shoebox is an app that takes the map like I listed in the question and attempts to **Extract Sprites**, typically a whole blob of terrain

2) What I wanted to do next was **split this image into 9 tiles**, and be able to reassemble them in various combinations. Shoebox also seems to be able to do this (**Extract Tiles**). This creates a TMX files

3) It seems that the next step is to import the resulting .TMX map into **a tile map editor**, like Tiled: http://www.mapeditor.org/download.html . From the video, it seems that I would be able to rearrange tiles and create various combinations I need.

It appears that ShoeBox has a bug on mac where it appends the folder name before the png file name (Line 4) within the TMX file, so I had to remove it manually :

```
name="[REMOVE FOLDER]base_....

```

List of frameworks that support TMX maps: https://github.com/bjorn/tiled/wiki/Support-for-TMX-maps

# Answer
> 10 votes
Go to piskelapp.com , then choose 'Create new Piskel'. Click the menu on the right, and choose import your own image; select it, then put the number of size of each tile. After you are done editing, choose Export in separate images. Done!

# Answer
> 2 votes
If you're starting with a tileset with **regular dimensions and layout** (as in your example), and your goal is to **create tile maps in Tiled**, there is no need to use third-party tools. Tiled supports these natively and easily.

There are a few tutorials on using Tiled like this one, but it's very simple:

* Create a new map, choose its dimensions and tile size
* Add a new tileset from file, input its tile size and margin/spacing, if any (there is none in the example)
* Start painting tiles. Your loaded tileset is in the sidebar.

There are also other handy features in Tiled; the trees you see in the tileset will be loaded as separate tiles, but you can use Tiled's Brush features to draw those trees in one go. There's also the Terrain Tool which helps you paint tile transitions, after you've defined the border tiles.

From there, it's best to treat the tile maps as a whole, via the frameworks that support TMX maps, rather than individual tiles. For example, you would load and render tile layers, or draw all your "wall" tiles in the same layer and perform a layer collision. There is usually no need to split a properly-authored tile set into individual tiles.

---
Tags: 2d, sprites, tiles
---


title: Can I put real people in my game?

text:
# Question
Title: Can I put real people in my game?
When and how can I use the likeness of real people in my game? What are the legal restrictions involved?

Real people are rarely found in games because it's hard to present them tastefully, but they have sometimes appeared when the setting was suitable. Games have featured the likenesses of historical figures such as McNamara, Hitler, Kim Jong Il to take a few examples.

What factors affect how I can use these real people? Whether they are living? Whether the depiction is entirely factual? Do any disclaimers need to be used? Does it differ significantly across jurisdictions?

# Answer
> 1 votes
Depends largely on local laws and don't rely on the Internet for legal advice but here are some guidelines: Basically you can't unless they fit the following conditions:

1. They are historical figures, basically anyone who has been dead for a long time (80 years+)). You can basically do with these people as you please
2. Anyone who serves an important public function, games are a form of media and are therefor allowed to report and display people with public functions (politicians and related). Note that this is more limited as this has to remain fact based.
3. Parody is protected speech: you are allowed to make a parody of any person who you can reasonably make a parody of, this is however usually limited to somewhat famous people as otherwise it's very difficult to get a parody (this is always very difficult to get right).
4. Anyone who has given you permission (obvious)
5. anyone who (and whose family) is unable to sue you for whatever reason (for example if they would get arrested if they got into your country or you know they won't be able to sue for any other reason). Note that that technically doesn't make it legal but you can't be punished for it. In these cases make your own ethical decision.

# Answer
> 1 votes
For anybody that is alive you need explicit permission from the person even if you are going to mock them, there's no way around it, I know shows like south park do a lot of these things and is able to get away with it, but it's just because most "victims" ignore it to avoid the Streisand effect (https://en.wikipedia.org/wiki/Streisand\_effect).

People might even sue you because you are making money off their image and they are not being compensated, so always ask permission from the alive ones.

For the dead ones, you can be sued if a close relative feel offended by your material, it has happened something like this in Brazil when relatives of our founding fathers were displeased with how they were portrayed in a soap opera, keep in mind that most of the subjects were dead for a long time.

And remember, there's a fine line between freedom of speech and trying to humiliate a person, so, you should seek advice from a lawyer where he will be able to analyze your content.

---
Tags: legal
---


# Question
Title: Collision detection between draggable object and world objects?
I have a game I'm making in Javascript that will involve combining items by dragging and dropping them onto each other. Think Alchemy or similar.

So far, so good, but I hit a snag while trying to figure out how I can detect collisions between the two entities! I have a (really) basic bounding box test -

```
function isColliding(a, b) {
    if (a.x + a.width < b.x || a.x > b.x + b.width || a.y + a.height < b.y || a.y > b.y + b.height) {
        return false;
    } else {
        return true;
    }
}

```

The trouble I'm having is that in practice, this is fine for detecting the mouse colliding with an object to pick it up, but I'm stuck on how I can, after I've grabbed an object, test to see if that object I have grabbed is colliding with any of the multiple other objects that exist in the window. I tried doing -

```
Core.objectCollision = function() {
    if (Core.Mouse.isHolding != null) {
        for (i in Core.Objects) {
            if (isColliding(Core.Mouse.isHolding, Core.Objects[i])) {
                console.log("Colliding with world object!");
            }
        }
    }
}

```

This function is inside my update loop, but of course the object I'm holding is within my Core.Objects array too, so technically collides with itself.

I really think I'm missing something obvious, but a lot of my searches for help have been returning how to simply detect collision between two already known items, however I need it so any item I grab can be tested against any other item in the view.

Please also note I'm trying to avoid libraries for the time being, I'd rather learn the functionality myself. Thanks for any help!

# Answer
> 1 votes
To prevent the check of the object colliding against itself, just check the reference like so:

```
Core.objectCollision = function() {
    if (Core.Mouse.isHolding != null) {
        for (i in Core.Objects) {

            // Skip the object that was grabbed.
            if (i == Core.Mouse.isHolding)
                continue;

            if (isColliding(Core.Mouse.isHolding, Core.Objects[i])) {
                console.log("Colliding with world object!");
            }
        }
    }
}

```

Now, if you want to implement a physics engine, I really recommend you see this series https://www.youtube.com/watch?v=3Oay1YxkP5c even thou he implements a 3D engine, the core logic is the same.

Then, to get a better performance, you might want to look at quad trees so that objects that are far from each other are not checked for collision, this: http://buildnewgames.com/gamephysics/ should give you some directions.

# Answer
> 0 votes
To avoid checking collision on the same object you can generate a unique id on every object and then when you are looping over them check so they dont have the same id.

Jon is wondering about your objects shapes since a rectangular bbox will in most cases be too large and hence you will detect collision even though objects are not colliding. Can be solved by using multiple bboxes or pixel collision detection (there are more ways to do it ).

---
Tags: collision-detection, javascript, html5
---


# Question
Title: Quaternion.Lerp not working properly in Unity3d
I'm using `Quaternion.Lerp` to rotate a joint with a certain angle, but when I use the below code I find the joint rotating very far although I specified it to rotate with only 5. Any thoughts please?

```
Vector3 newRot.y += currentTransform.localRotation.y + 5f;
blendWeight = 0;
if ( blendWeight < 1)
{
    animationRotation = currentTransform.transform.localRotation;
    newRotation = Quaternion.Euler(newRot.x, newRot.y, newRot.z);
    blendWeight += Time.deltaTime/0.9f;
    currentTransform.transform.localRotation = Quaternion.Lerp (animationRotation,newRotation, blendWeight);
}

```

# Answer
Try decreasing the amount of the rotation, so change 5 to a lower number like 2, if that's still a lot decrease it even more.
> 0 votes

---
Tags: unity, unityscript, quaternion, lerp
---


# Question
Title: Using an array of 3d points to construct point cloud or surface in OpenGL
I have an array of 3 dimensional point objects, I can manipulate the input into this array into any configuration I want, for example, it could be a vector of floating point numbers, a vector of ints, etc.

Anyway, I want to display this 3d point cloud using OpenGL. How should I go about doing this? I know enough that I can create a 3d cube from structured inputs but how would I go about creating vertices from this unstructured input? If I don't need to construct these vertices how would I go about simply displaying these points as a cloud? Any suggestions or advice is welcome.

# Answer
> 1 votes
As stated in the comments, drawing points is as simple as drawing `GL_POINTS` instead of `GL_TRIANGLES`, you'll need one vertex instead of three of course.

Now to your non-structured input:

Of course it is structured. It may not be in the format OpenGL expects, but it definitely has some sort of structure, some format you're able to parse. In case of a text-format containing lines of three integers, you have to first parse those lines to get your three integers in binary format since ASCII (and other charsets) means nothing to the computer. After this, i recommend converting it to floats. Since OpenGL expects the data in one contiguous stream of data (at least if you don't do any advanced things with glVertexAttribPointer) you need to one float after the other, 4 bytes each, 3 floats per vertex -\> 12 bytes per vertex tightly packed without empty space between them.

TLDR: Since you already know how to draw triangles or a cube (which itself is just built out of multiple triangles), you already know how the data looks OpenGL-expects and how to draw. So all you need to do now is convert your input data to the same format and draw your `GL_POINTS`.

# Answer
> 1 votes
The simplest solution to this would be simply buffering the vertices into a VBO like you normally do, then rendering them as `GL_POINTS` instead of `GL_TRIANGLES` or `GL_TRIANGLE_STRIP`.

This will give you a cloud of dots, that you can rotate the usual way with your vertex shader.

If you want nicely sized circles, you should use a geometry shader to create a camera-facing impostor/billboard from each vertex and process those using a fragment shader, you could event texture these.

While technically you could do the same with the built-in `GL_POINTS` approach, it is not supported properly by drivers in my experience, so you have to resort to your own geometry shader.

---
Tags: opengl, 3d, 3d-meshes, point-cloud
---


# Question
Title: How to stop game but animation is running?
i want stop my game but the animation is runnig. how to make it ?? for Example : i call anim, i want when press the eScape , my game stop but animation is running.

```
void Update()
{
   myAnim.setSpeed(animSpeed);
   myAnim.run();

   if(Input.getKey(keyCode.Escape)
   {
      Time.timeScale=0;
   }

}

```

# Answer
Use `Time.timeScale = 0` to stop everything.
> -1 votes

# Answer
In your Animator Component, change Update Mode to *Unscaled Time*.

Now the Animator can play even when TimeScale is 0. Useful for pause menus and similar.

Docs
> 1 votes

---
Tags: unity, animation
---


title: How to set a background image in Unity?

text:
# Question
Title: How to set a background image in Unity?
I am trying to create a game on Unity but I am still learning. I want to make a start menu, and I want to set a background image. Then, I will add "Play" or "Exit" buttons on top of this image.

How can I do that?

Can you help me with this?

# Answer
You must engineer your background just like any other object in your scene.

Create a **Quad**, place it behind all your other GameObjects, orientate it towards the camera and enlarge it to cover the whole view. Then add your background **Sprite** to the **Quad**.
> 0 votes

---
Tags: unity
---


title: scrolling ruining bullet physics

text:
# Question
Title: scrolling ruining bullet physics
the code below is the bullet class for my shooter game in pygame. as you can see if you run the full game (https://github.com/hailfire006/economy\_game/blob/master/shooter\_game.py) the code works great to fire bullets at the cursor as long as the player isn't moving. However, I recently added scrolling, where I change a global offsetx and offsety every time the player gets close to an edge. These offsets are then used to draw each object in their respective draw functions.

unfortunately, my bullet physics in the bullet's **init** function no longer work as soon as the player scrolls and the offsets are added. Why are the offsets messing up my math and how can I change the code to get the bullets to fire in the right direction?

```
class Bullet:
    def __init__(self,mouse,player):
        self.exists = True
        centerx = (player.x + player.width/2)
        centery = (player.y + player.height/2)
        self.x = centerx
        self.y = centery
        self.launch_point = (self.x,self.y)
        self.width = 20
        self.height = 20
        self.name = "bullet"
        self.speed = 5
        self.rect = None
        self.mouse = mouse
        self.dx,self.dy = self.mouse

        distance = [self.dx - self.x, self.dy - self.y]
        norm = math.sqrt(distance[0] ** 2 + distance[1] ** 2)
        direction = [distance[0] / norm, distance[1] / norm]
        self.bullet_vector = [direction[0] * self.speed, direction[1] * self.speed]

    def move(self):
        self.x += self.bullet_vector[0]
        self.y += self.bullet_vector[1]

    def draw(self):
        make_bullet_trail(self,self.launch_point)
        self.rect = pygame.Rect((self.x + offsetx,self.y + offsety),(self.width,self.height))
        pygame.draw.rect(screen,(255,0,40),self.rect)

```

# Answer
> 0 votes
To simply fix your error:

after the line `self.dx,self.dy = self.mouse` try adding

```
self.dx -= offsetx
self.dy -= offsety

```

Note this is not an ideal solution. In general though to avoid similar future problems I would further separate the concept of screen space and world space, possibly by the addition of something like a "camera" class. You could even add in features like zoom and rotate this way. Something like your Bullet class should have no awareness of your screen screen space or the mouse at all. It would receive only coordinates in the world space.

---
Tags: vector, python, pygame
---


title: Spaceship Shield Flare

text:
# Question
Title: Spaceship Shield Flare
I'm trying to implement a system whereby a "shield flare" will be shown whenever a projectile impacts the shield. The shield itself is one like in Star Wars, where it's more like a skin around the spaceship, rather than a simple bubble.

The problem I'm having is determining how to draw a simple flare effect where the projectile impacted the shield. I can determine the Vector2 point where the shield was hit. Right now, I'm able to show the whole shield whenever it's hit just fine.

The problem as I see it, is that I somehow need to mask out the shield, except for a few pixels around the point of impact. Either that, or I'm going about this the completely wrong way.

What I can do so far is draw the whole shield:

What I need is to be able to draw a piece of the shield on the point of impact:

Any help would be appreciated.

# Answer
> 4 votes
You can do this via masking on the cpu if you prefer to not use shaders yet.

You'll need these resources:

* Spaceship texture (no shield visible, **left**)
* Shield texture (only the shield visible, needs to fit the ship, **middle**)
* Empty editable Texture (pixmap) that you can draw onto (same size as shield texture, **right**)
* Point of impact

You can draw your ship like normal. After drawing the ship, you need to copy the shield textures pixels, which are at a certain distance (a few pixels, maybe 3 or 4) from the impact-point, to your empty texture, and render this edited texture on top of your ship. You should repeat the copying for every impact point, just copy everything to the same texture.

This image shows the textures from left to right in the same order as in my list. (the red parts are just to visualize borders and stuff)

If you want it to be fast too, you need to render it with a custom pixel-masking shader, it should be just as simple as this process, if you know how to use shaders, but i do not know how to help you there.

**Edit: An easy way get this running in an approximated way is to just draw a particle effect at the point of the impact like Felsir suggested, which is also rotated towards the center of the ship (or just center of the texture). You probably won't see a huge difference between this and a masked shield texture, it'll be a lot faster too.**

# Answer
> 3 votes
You could draw this using a multiply blendstate.

```
BlendState multiplyblend = new BlendState();
multiplyblend.ColorBlendFunction = BlendFunction.Add;
multiplyblend.ColorSourceBlend = Blend.DestinationColor;
multiplyblend.ColorDestinationBlend = Blend.Zero;

```

Create a bitmap of a white circle in a black background (mask). The white is the part of the shield that should be visible. Since you know the point of impact, you know where to put the centre of the circle. Draw the shield, multiply the graphic with the white circle (effectively drawing everything else black). Then add the spaceship sprite in normal blendmode.

Keep in mind you'll need `SpriteSortMode.Immediate` for this to work.

If you have a lot of shields/ships, prepare all white circles on one screen-sized texture and have the effect drawn once. The mask should be on a transparent background for this- as the mask rendertarget will be colored black:

1. Draw all shields on screen
2. Clear the mask rendertarget with black
3. Draw all white circles where shields should be visible on the rendertarget (effectively create one screen sized mask)
4. Multiply the screen and the mask rendertarget.
5. Draw the rest of the game entities.

---
Tags: xna, 2d
---


# Question
Title: Setting up a Visual Studio project for OpenGL and OpenGL ES
I want to make a small game with OpenGL and glew for desktop, android and web.

So far I know how to set up a project for opengl and a project for opengl es but I would like to have the game source code just once. For the web version I want to use emscripten.

Now my question is how do I set up the project for this? I thought about making three projects in one solution: One for OpenGL, one for OpenGL ES and one for the game itself. But should I include the OpenGL projects into the game project (and choose the correct one when initalizing/drawing)? Or should I include the game project into the OpenGL projects and have a single game object which returns all the objects to draw?

Or is this a bad approach and can be done better?

# Answer
> 1 votes
If you really want to target OpenGL, GLES and WebGL you should reuse as much code as possible but it's not a simple task. OpenGL and OpenGL ES are fairly similar. In fact a lot of the code can be reused between the two. WebGL isn't quite as easy as, you're right, you need to recompile with emscripten which is a whole separate task.

Your project organization can be really different but this is how I would organize it:

* Visual Studio Solution

+ Project for library code (compile this for GL, GLES or WebGL)
    + Game project (includes previous project, doesn't care about GL or GLES)

When compiling your library for different projects I recommend writing out a CMake project. It will take your 1 code base and setup a project based on what your targets are. That way you can avoid including GL libraries when all you need are GLES and visa versa. It will also make it easier to setup a VS project to target WebGL by automatically setting itself up with the emscripten compiler. Other people might be able to suggest different alternatives but CMake is very robust and widely used.

I'd suggest writing on your native platform with OpenGL first. After that targeting GLES is probably the easiest next step. This is going to require a fair amount of `#ifdef` macros. Whatever GL code will need to be GLES on other platforms will probably be wrapped like this:

```
#ifdef _ANDROID_
    // call GLES code
#else
    // Call GL code
#endif

```

This is a super simple example and you'll need to double check your platform macros but this is the general idea. You should wrap as much code as possible together in one `#ifdef` statement. In fact in my engine when I target separate platforms I usually end up having one header and then different implementation (.cpp) files for each platform. Each implementation gets wrapped in a macro that is specific for that platform. Obviously any non-platform specific code is kept in a generic, platform agnostic implementation file that has no macro shenanigans.

So that's the idea on handling GL and GLES. What about WebGL? To be fair WebGL isn't my specialty. However there are a lot of resources around about it because it's the hot new thing in browser-based game development. I've found some neat resources around the web like this:

http://blog.scottlogic.com/2014/03/12/native-code-emscripten-webgl-simmer-gently.html

That resource mostly uses emscripten at the command line in Linux or Mac OS. There IS of course a way to use emscripten with Visual Stuido: http://kripken.github.io/emscripten-site/docs/getting\_started/getting\_started\_with\_emscripten\_and\_vs2010.html

The trick with targeting WebGL is that you're mostly going to be writing more library code than client code. There is no `main` when dealing with WebGL as the entry point is the browser! Think of it more as writing a library that you'll access from Javascript. Of course there is an `EMSCRIPTEN` macro so you can `#ifdef` your code that needs to be just for emscripten. WebGL is just OpenGL code so you shouldn't need to use any GLES on this target.

Setting up your project is really up to you but I feel that it makes sense to organize your project while keeping all this in mind.

---
Tags: opengl, opengl-es2, visual-studio
---


title: Using hard coded values for Items?

text:
# Question
Title: Using hard coded values for Items?
Is it a bad idea to use hard coded values for things like items (static data) that would change infrequently in an online game? I'm designing an online game in node js, and I'm trying to decide if it would be better to store the data in a database, or hardcoded in a javascript hash (and maybe cache some of the data in a db for filtering). Points I've thought up:

Since javascript is a scripting language, updating it wouldn't be a big deal, it would mean restarting the server, but it would seem most online games go through some sort of restart when introducing new things anyways.

Items in my game are really hard to define in data, as they can have wildly different functions, if its a javascript object, I can define a 'use' function for all of them and don't need to worry about creating a complex item definitions in the database.

If I used a database only, I would have to come up with some sort of way to define every possible item ever, and I don't think its likely I will imagine all of them.

I could use a database for things like name, and description, but still have a hash of functions somewhere.

Maybe having all these items hard coded could increase memory foot print of the web application as they would all always be loaded into memory?

I'm afraid I'm missing something important though? Is there a better answer? Or just preference? Is there a clear right way to do this?

# Answer
> 3 votes
Rather than hard-coding your data in Javascript, why not use JSON. It's always a good idea to separate your data from your program, and splitting out item definitions into JSON files would be very clean I think. Node even let's you use "require" with JSON files, how handy: How to parse JSON with node

Databases are a great technology to learn if you haven't already, but you should be careful to add that sort of complexity to your game before you really need it. Unless you have tens of thousands of item definitions, I would not worry about the memory or bandwidth impact you would have storing this data in a file that's loaded by clients all at once.

# Answer
> 2 votes
> Since javascript is a scripting language, updating it wouldn't be a big deal, it would mean restarting the server, but it would seem most online games go through some sort of restart when introducing new things anyways.

You really don't want this.

Yes, some items will need reboots, because they'll need new accompanying game logic. Minor updates, GM-driven quests, marketing-driven quests and bonus items (or pricing changes), etc. should *absolutely not* require a reboot.

Honestly, even code changes shouldn't require a reboot in this day and age. Incremental rollouts are quite possible, even in an MMO.

> Items in my game are really hard to define in data, as they can have wildly different functions, if its a javascript object, I can define a 'use' function for all of them and don't need to worry about creating a complex item definitions in the database.

This is not a good reason to hard-code the data. Your need to hard-code the behavior of an item is irrelevant to your need to associate a name, or a cost, or a weight, or an icon, or anything else with the item. Hard-code what you need to; nothing else.

Even with item behavior you probably want to parameterize all that. You shouldn't need 10 different `use()` functions for similar but different features. A single `heal()` function could be used across most if not all healing items, for instance, allowing the item to define in data how much healing is applied.

Then you can allow items to have multiple functions. Instead of a complex `heal_100hp_and_cast_lvl3_fireball()` you can instead have `heal(hp)` and `cast(spell, level)` functions and then allow an item to require both of them. Even the `heal(hp)` function can be further parameterized to allow a single function to handle healing by explicit amount, by percentage of max HP, etc.

Put your mind to it and you'll see that you only need a relatively small set of individual functions to implement a very wide variety of both simple and complex items. That makes your code much simpler, decouples your behavior from your items, and even allows totally new complex items to be created and released without ever touching a single line of code.

> If I used a database only, I would have to come up with some sort of way to define every possible item ever, and I don't think its likely I will imagine all of them.

You have to do that even without the database. Whether they're in your code or in your data, you have to keep around all items you release forever.

Players don't tend to like it when items they "own" just up and disappear because you decided to trim a few hundred thousand lines of code out of a bloated codebase.

Once an item is released, it exists forever. Do you want your *code* to keep growing forever until it's utterly unmaintainable or would you rather have a big database designed for handling terabytes of data hold on to some legacy data entries?

> I could use a database for things like name, and description, but still have a hash of functions somewhere.

Yes. Do that. Combine that with database-supplied parameters for the functions.

> Maybe having all these items hard coded could increase memory foot print of the web application as they would all always be loaded into memory?

Well, yes, but that's not a good reason to avoid it. There *are* good reasons (see above); that's just not one of them. :)

---
Tags: architecture, javascript, data-structure, databases
---


# Question
Title: Making certain GameObjects visible for a camera
I have 2 cameras in my 2D game.

One displays gameobjects normally, and the other camera draws some of these gameobjects reflected (scale.y \*= -1). The reflected camera would draw only objects in the "Water" layer, and I would change the layer of the GameObjects I want to reflect on the precull and postrender functions. This way I can decide which GameObjects would be reflected, changing the layer on the fly at runtime, which is a requirement.

```
-Precull: Change the desired GameObjects layer to "water", and apply scale.y*= -1

-OnPostRender:  Change the Gameobjects layer to their original value, and apply scale*= -1

```

This was working correctly when my objects were simple, but now my objects are more complex, and I can't rely on changing the layer of the gameobjectson the fly, as I can't tell what their original layer was for each part of the object, in order to revert the changes applied during the precull.

Is there anyway to tell a camera which objects should it render besides using the culling mask?

# Answer
> 1 votes
You could use shaders instead.

Here is a link of one that may help http://wiki.unity3d.com/index.php/SurfaceReflection.

---
Tags: unity, camera, culling
---


# Question
Title: What will happen with PlayerPrefs data after updating the app?
I'm using PlayerPrefs (Unity3D, on Android).

If a user updates my application via the Google Play store, what happens to the data I've stored in PlayerPrefs?

# Answer
If you store it in:

```
Aplication.persistenDataPath

```

you can be certain, that it won't be deleted after an update. (except the user uninstalls and then reinstalls the game manually)
> 0 votes

# Answer
Unity preferences have Android preferences underlying it, and they are kept until the user manually uninstall the app.
> 0 votes

---
Tags: unity, android
---


# Question
Title: 2D - Smooth lighting with shadows for a tile-based game
for the last week or so I have been completely stuck on trying to implement *efficient* lighting. I've been researching and experimenting and I've looked everywhere that I have been capable of finding, and I just cannot figure it out. So, now I'm posting here, with the hope that someone can maybe help me. I'm trying to make a 2D tile-based game, similar to Terraria, and I'm trying to avoid Terraria's style of tile-based lighting and go for something smoother, like Starbound (here), except with more visual shadows. I have successfully implemented something to what I would like to see, but, sadly, it's incredibly inefficient. This is what I've tried so far:

1. Tiled based lighting that is put in a lightmap as a single grayscale pixel and is then scaled up and (with a shader?) smoothed out so that it looks non-tiled. This approach is similar to what I've seen (here), but is done in xna and I'm not sure if there is a BlendState equivalent thing. I also had never done anything with shaders and my attempt at smoothing out the tiles ended after I could only smooth them horizontally or vertically (not in a circle as it should be).
2. Raycasting and drawing each pixel with a certain alpha value for the distance it is away from the light source. This approach is the one that worked, but was inefficient. The first problem I encountered with this is that raycasting with around 360 rays per point light missed a bunch of pixels. I solved this by then using a shader to make a black pixel within the radius of a light the proper color if it was next to at least two non-black pixels, so that it wasn't a shadow. This worked, but sadly, it was far too inefficient, dropping about 300 FPS per light. But did bring me close to what I want, and I would post a picture, but sadly I'm limited to two links :(

and now I'm here, quite unsure of what to do next, are either of these two approaches that I've done before usable? Is there an even better route to take?

Thank you for taking the time to read my problem and hopefully help me out :)

P.S. I've heard of Box2D, and I really don't want to use it, mainly because this is a learning experience for me and I don't learn too much by using someone else's code.

Edit: I'm completely new to libGDX and OpenGL in general, and I know that there's a way to create a mesh using vertices and I was wondering if that might be the key, if I create a mesh from the raycasts' end points and somehow, using a shader, create an alpha gradient on the mesh? I really don't know how to create a mesh nor do I know how to create a gradient on a weirdly shaped object.

Edit2: This is a picture of what I want, and what I have, that is very inefficient :

Edit3: It works! For the most part, thank you for the help Felsir, but, of course, there are still problems, I've gotten the actual lighting to work, and it's actually MORE than efficient since I don't have to draw the tiles that are not lit up by light, but the problem is, well, darkening the rest of the screen, especially since there will be multiple lights. My first thought would be to not draw the tiles within the radius of the light, but since it creates triangles and not perfect squares like it's supposed to, this happens:

As you can see, it doesn't blacken out the tiles near the edges, and creates some other problems. My other idea was to make a shader that goes through the whole screen and uses a sampler so that if the alpha value is 0, set it black, but, obviously, this doesn't work since the screen doesn't have alpha values other than 1. My last idea would be to make a mesh that's inverted from the light, but that becomes absurdly complicated with multiple lights and probably inefficient, is there any way I can black out the non-lit screen?

Edit4: So, it's still not working, I've gotten the light to work, now I need the absence of light to work, and it's not. My new idea is if I can render all the tiles, then render a black mesh over the screen with an alpha value of one, I'm wondering if it's possible, using blendFuncs and blendEquations, to subtract the alpha of the black mesh from the mesh of the light. So the darkness is rendered, then the light afterwards, and I don't know if there's a way just to remove some of the alpha from some of the pixels that are overlapping using blend funcs. I really really need to get this or something to work, I want to complete my lighting. I decided to go through every single combination of blends functions, srcs, and dsts, since I know so little about how they work, and nothing worked, I'm probably doing something wrong, please help.

# Answer
> 1 votes
This is a post by @OrangePixel for one way to make efficient lightning with Libgdx.

It describes a simple technique. You can put alpha blended Dot above the map and make it seem like a lightning effect. The article is interesting and all the thanks go to the author!

http://techblog.orangepixel.net/2015/07/shine-a-light-on-it/

# Answer
> 1 votes
Instead of casting rays in 360 degree fashion, cast rays to the corners of the tiles in range of the lightsource.

Sort the angles from the light source to the tile corners and do a 'sweep'. You can optimize the algorithm to look for the nearest tiles first and ignore angles for culled tiles:

```
    A--B E--F
o   |T1| |T2|
    C--D G--H

```

Angles would be sorted: A, B, E, F, H, G ,D, C (draw lines from o to the corners). First tile T1 is checked, because it is closer. A is visible, B is not. C is visible and D is not. This results in tile T2: E, F, H, G angles being ignored because they're all between A and C.

If the lights are in fixed positions or rarely move, calculate the polygon only when the light is placed or moved. Store the polygon shape and use that to draw the light effect.

See: http://ncase.me/sight-and-light/ for an example of the light ray algorithm.

# Answer
> 0 votes
Have you consider using chunk of pixel in your second point to get better performance?

If you search for a different aproach you can investigate Cellular automaton , starting from lights chunk for each neighbour lite them according to distance and material repeat for its neighbours ...

---
Tags: java, libgdx, lighting
---


# Question
Title: What is the alternative to Time.time for scrolling texture?
In my game, I'm using the standard SetTextureOffset method to smoothly scroll texture on background quad.

However, on game over, instead of reloading the scene, I'm just reseting all values initial position to give illusion that scene was reloaded. With this approash, i'm unable to use Time.time or Time.timeSinceLevelLoad because, the level was not reloaded and this value stays high. So scrolling is too fast right in the beginning.

Are there any time independent methods to smoothly scroll texture? Thanks.

# Answer
After a bit of tinkering, I found Time.time,Time.timeSinceLevelLoaded were the ones working fine. They had the property of increasing linearly. So I used a float variable "damp" which is incremented by a small value e.g damp+=0.1f; Now it works smoothly.
> 0 votes

# Answer
```
Time.time - timeSinceReset

```

and when you "reset" you set it to `timeSinceReset = Time.time;`
> 1 votes

# Answer
You can use CoRoutines instead of Time.time

```
void IEnumerators( float x )
{
    //x is your time delay. in your code, x=Time.time-lastScrolledTime
    yield return new WaitForSecond(x);
    //scroll texture here
}

```
> 0 votes

---
Tags: unity
---


title: Marketing my mobile game

text:
# Question
Title: Marketing my mobile game
I have almost finished my game; I want to upload it to Google Play and the App Store. I will make it free but with Admob advertising. What is the best way to market my app (without any app promotion companies)? Please give me a detailed explanation.

# Answer
> 5 votes
A great way to get some cheap advertisement for your game out there, is to go out and buy a nice, large bell. The initial investment might set you back about $20, but it will keep you out of having to deal with any pesky companies.

So the general concept, is to dress up in some clothing that will stand out in a crowd. Then you would ring your bell and yell "Hear Ye! Hear Ye!" to gather up a crowd around you. Once you get people's attention, you can then talk about your game.

Try to be concise when you detail your game, as you don't want to bore people. And remember to smile.

It is also a great idea to have hand-out material ready for people to pick up so that they can take that information with them.

# Answer
> 0 votes
Typically, developers that are on a budget and don't have a lot of money for advertisement will invest more time.

Here are some techniques used:

* Blog about it on their website
* Give news about it on their social network accounts (Twitter and Facebook)
* Give talks about it during game development conferences (E3, GDC, and more)
* Talk about it in webinars
* Do various fund-raising campaigns (Kickstarter)
* Participate in discussion forums and have links pointing to their game in their profile
* Comment posts of reviews on game review sites (such as IGN) (The idea is that they get to know you in order to be willing to review your game upon release)

The goal is to rise awareness and get as much potential players to follow you before the release of your game.

As you might have noticed, most of this must be started *long before* the game is released to hook as much as people as possible.

This has the advantage of getting feedback during the development of the game because people will comment on what you post.

---
Tags: marketing, google-play, appstore
---


title: UNET Error handling

text:
# Question
Title: UNET Error handling
I am trying to handle errors received by a UNET (new Unity3D networking) client. The below code successfully connects to a server when it is present, but obviously gives a timeout error when there is no server present.

I am trying to determine **which type of error was received by the OnError callback** method. MsgType is equal to MsgType.Error, which isn't specific, and all of the Read functions I have tried do not return valid data. At minimum I would like to be able to print the same error that prints to the debug log in a location the player can see it.

```
public class TestClient: MonoBehavior {

    private NetworkClient client;

    void Start () {
        client = new NetworkClient();
        client.Connect("127.0.0.1", 1234);
        client.RegisterHandler(MsgType.Error, OnError);
    }

    public void OnError(NetworkMessage netMsg) {

        //Read netMsg here somehow

        Debug.Log("Failed to connect to server");
    }
}

```

Note: This code is a retyped copy the working code, so there might be a typo or twenty. It also takes 15-30 seconds to throw the error (I didn't time it).

# Answer
> 0 votes
You must include read it as an ErrorMessage from the UnityEngine.Networking.NetworkSystem namespace.

```
netMsg.ReadMessage<ErrorMessage>();

```

http://forum.unity3d.com/threads/error-handling-in-unet.346525/

Note: It is amazing how fast you can find an answer AFTER posting to stackexchange.

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


title: Libgdx particle editor absorb effect

text:
# Question
Title: Libgdx particle editor absorb effect
I am trying to achieve a certain kind of *absorb* effect within libgdx via the particle editor.

To be more descriptive: I want particles to spawn in a circle and then move towards the center point of that circle (and then disappear there).

I can of course spawn the particles in a circle, but then I cannot seem to find a way to make sure they all move toward a center point.

So my questions can be divided into two parts:

* Is their any way I could use the particle editor to achieve this absorb effect I described?
* If not, then what would the best way to achieve it in libgdx? Is their some way I could hack into the particle effect behavior itself and make this work?

# Answer
I would say that No, you can't do that *easily* with the particle editor. It would require the synchronisation of three values:

* xOffset
* yOffset
* velocity

In the libGDX particle effect implementation these are generated using `RangedNumericalValue`s and `ScaledNumericalValue`, and they provide a new value independently of each other. The offsets are ranged, so you can't even draw an elaborate sine-curve to get them to give you the values matching the velocity set by the angle property.

However; if you don't mind the tedious work of manually creating many emitters you can get something that's close to what you want. If you set the offsets and the angle up manually, and do one emitter per angle you can get something that looks like this:

In this example I used four emitters, but you can with a little work get that up to as many as you need for your effect.

The effect file for the above example looks like this;

```
A000
- Delay -
active: false
- Duration -
lowMin: 1000.0
lowMax: 1000.0
- Count -
min: 0
max: 200
- Emission -
lowMin: 0.0
lowMax: 0.0
highMin: 8.0
highMax: 8.0
relative: false
scalingCount: 1
scaling0: 1.0
timelineCount: 1
timeline0: 0.0
- Life -
lowMin: 0.0
lowMax: 0.0
highMin: 2000.0
highMax: 2000.0
relative: false
scalingCount: 2
scaling0: 1.0
scaling1: 1.0
timelineCount: 2
timeline0: 0.0
timeline1: 1.0
- Life Offset -
active: false
- X Offset -
active: true
lowMin: -128.0
lowMax: -128.0
highMin: 0.0
highMax: 0.0
relative: false
scalingCount: 1
scaling0: 1.0
timelineCount: 1
timeline0: 0.0
- Y Offset -
active: true
lowMin: 0.0
lowMax: 0.0
highMin: 0.0
highMax: 0.0
relative: false
scalingCount: 1
scaling0: 1.0
timelineCount: 1
timeline0: 0.0
- Spawn Shape -
shape: point
- Spawn Width -
lowMin: 0.0
lowMax: 0.0
highMin: 0.0
highMax: 0.0
relative: false
scalingCount: 1
scaling0: 1.0
timelineCount: 1
timeline0: 0.0
- Spawn Height -
lowMin: 0.0
lowMax: 0.0
highMin: 0.0
highMax: 0.0
relative: false
scalingCount: 1
scaling0: 1.0
timelineCount: 1
timeline0: 0.0
- Scale -
lowMin: 0.0
lowMax: 0.0
highMin: 16.0
highMax: 16.0
relative: false
scalingCount: 6
scaling0: 0.0
scaling1: 0.23529412
scaling2: 1.0
scaling3: 1.0
scaling4: 0.7647059
scaling5: 0.0
timelineCount: 6
timeline0: 0.0
timeline1: 0.19863014
timeline2: 0.30821916
timeline3: 0.65068495
timeline4: 0.89726025
timeline5: 1.0
- Velocity -
active: true
lowMin: 0.0
lowMax: 0.0
highMin: 64.0
highMax: 64.0
relative: false
scalingCount: 1
scaling0: 1.0
timelineCount: 1
timeline0: 0.0
- Angle -
active: true
lowMin: -5.0
lowMax: 5.0
highMin: 0.0
highMax: 0.0
relative: false
scalingCount: 2
scaling0: 0.0
scaling1: 0.0
timelineCount: 2
timeline0: 0.0
timeline1: 1.0
- Rotation -
active: false
- Wind -
active: false
- Gravity -
active: false
- Tint -
colorsCount: 3
colors0: 1.0
colors1: 0.12156863
colors2: 0.047058824
timelineCount: 1
timeline0: 0.0
- Transparency -
lowMin: 0.0
lowMax: 0.0
highMin: 1.0
highMax: 1.0
relative: false
scalingCount: 4
scaling0: 0.0
scaling1: 1.0
scaling2: 0.75
scaling3: 0.0
timelineCount: 4
timeline0: 0.0
timeline1: 0.2
timeline2: 0.8
timeline3: 1.0
- Options -
attached: false
continuous: false
aligned: false
additive: true
behind: false
premultipliedAlpha: false
- Image Path -
particle.png

A090
- Delay -
active: false
- Duration -
lowMin: 1000.0
lowMax: 1000.0
- Count -
min: 0
max: 200
- Emission -
lowMin: 0.0
lowMax: 0.0
highMin: 8.0
highMax: 8.0
relative: false
scalingCount: 1
scaling0: 1.0
timelineCount: 1
timeline0: 0.0
- Life -
lowMin: 0.0
lowMax: 0.0
highMin: 2000.0
highMax: 2000.0
relative: false
scalingCount: 2
scaling0: 1.0
scaling1: 1.0
timelineCount: 2
timeline0: 0.0
timeline1: 1.0
- Life Offset -
active: false
- X Offset -
active: true
lowMin: 0.0
lowMax: 0.0
highMin: 0.0
highMax: 0.0
relative: false
scalingCount: 1
scaling0: 1.0
timelineCount: 1
timeline0: 0.0
- Y Offset -
active: true
lowMin: -128.0
lowMax: -128.0
highMin: 0.0
highMax: 0.0
relative: false
scalingCount: 1
scaling0: 1.0
timelineCount: 1
timeline0: 0.0
- Spawn Shape -
shape: point
- Spawn Width -
lowMin: 0.0
lowMax: 0.0
highMin: 0.0
highMax: 0.0
relative: false
scalingCount: 1
scaling0: 1.0
timelineCount: 1
timeline0: 0.0
- Spawn Height -
lowMin: 0.0
lowMax: 0.0
highMin: 0.0
highMax: 0.0
relative: false
scalingCount: 1
scaling0: 1.0
timelineCount: 1
timeline0: 0.0
- Scale -
lowMin: 0.0
lowMax: 0.0
highMin: 16.0
highMax: 16.0
relative: false
scalingCount: 6
scaling0: 0.0
scaling1: 0.23529412
scaling2: 1.0
scaling3: 1.0
scaling4: 0.7647059
scaling5: 0.0
timelineCount: 6
timeline0: 0.0
timeline1: 0.19863014
timeline2: 0.30821916
timeline3: 0.65068495
timeline4: 0.89726025
timeline5: 1.0
- Velocity -
active: true
lowMin: 0.0
lowMax: 0.0
highMin: 64.0
highMax: 64.0
relative: false
scalingCount: 1
scaling0: 1.0
timelineCount: 1
timeline0: 0.0
- Angle -
active: true
lowMin: 85.0
lowMax: 95.0
highMin: 0.0
highMax: 0.0
relative: false
scalingCount: 2
scaling0: 0.0
scaling1: 0.0
timelineCount: 2
timeline0: 0.0
timeline1: 1.0
- Rotation -
active: false
- Wind -
active: false
- Gravity -
active: false
- Tint -
colorsCount: 3
colors0: 1.0
colors1: 0.12156863
colors2: 0.047058824
timelineCount: 1
timeline0: 0.0
- Transparency -
lowMin: 0.0
lowMax: 0.0
highMin: 1.0
highMax: 1.0
relative: false
scalingCount: 4
scaling0: 0.0
scaling1: 1.0
scaling2: 0.75
scaling3: 0.0
timelineCount: 4
timeline0: 0.0
timeline1: 0.2
timeline2: 0.8
timeline3: 1.0
- Options -
attached: false
continuous: false
aligned: false
additive: true
behind: false
premultipliedAlpha: false
- Image Path -
particle.png

A180
- Delay -
active: false
- Duration -
lowMin: 1000.0
lowMax: 1000.0
- Count -
min: 0
max: 200
- Emission -
lowMin: 0.0
lowMax: 0.0
highMin: 8.0
highMax: 8.0
relative: false
scalingCount: 1
scaling0: 1.0
timelineCount: 1
timeline0: 0.0
- Life -
lowMin: 0.0
lowMax: 0.0
highMin: 2000.0
highMax: 2000.0
relative: false
scalingCount: 2
scaling0: 1.0
scaling1: 1.0
timelineCount: 2
timeline0: 0.0
timeline1: 1.0
- Life Offset -
active: false
- X Offset -
active: true
lowMin: 128.0
lowMax: 128.0
highMin: 0.0
highMax: 0.0
relative: false
scalingCount: 1
scaling0: 1.0
timelineCount: 1
timeline0: 0.0
- Y Offset -
active: true
lowMin: 0.0
lowMax: 0.0
highMin: 0.0
highMax: 0.0
relative: false
scalingCount: 1
scaling0: 1.0
timelineCount: 1
timeline0: 0.0
- Spawn Shape -
shape: point
- Spawn Width -
lowMin: 0.0
lowMax: 0.0
highMin: 0.0
highMax: 0.0
relative: false
scalingCount: 1
scaling0: 1.0
timelineCount: 1
timeline0: 0.0
- Spawn Height -
lowMin: 0.0
lowMax: 0.0
highMin: 0.0
highMax: 0.0
relative: false
scalingCount: 1
scaling0: 1.0
timelineCount: 1
timeline0: 0.0
- Scale -
lowMin: 0.0
lowMax: 0.0
highMin: 16.0
highMax: 16.0
relative: false
scalingCount: 6
scaling0: 0.0
scaling1: 0.23529412
scaling2: 1.0
scaling3: 1.0
scaling4: 0.7647059
scaling5: 0.0
timelineCount: 6
timeline0: 0.0
timeline1: 0.19863014
timeline2: 0.30821916
timeline3: 0.65068495
timeline4: 0.89726025
timeline5: 1.0
- Velocity -
active: true
lowMin: 0.0
lowMax: 0.0
highMin: 64.0
highMax: 64.0
relative: false
scalingCount: 1
scaling0: 1.0
timelineCount: 1
timeline0: 0.0
- Angle -
active: true
lowMin: 175.0
lowMax: 185.0
highMin: 0.0
highMax: 0.0
relative: false
scalingCount: 2
scaling0: 0.0
scaling1: 0.0
timelineCount: 2
timeline0: 0.0
timeline1: 1.0
- Rotation -
active: false
- Wind -
active: false
- Gravity -
active: false
- Tint -
colorsCount: 3
colors0: 1.0
colors1: 0.12156863
colors2: 0.047058824
timelineCount: 1
timeline0: 0.0
- Transparency -
lowMin: 0.0
lowMax: 0.0
highMin: 1.0
highMax: 1.0
relative: false
scalingCount: 4
scaling0: 0.0
scaling1: 1.0
scaling2: 0.75
scaling3: 0.0
timelineCount: 4
timeline0: 0.0
timeline1: 0.2
timeline2: 0.8
timeline3: 1.0
- Options -
attached: false
continuous: false
aligned: false
additive: true
behind: false
premultipliedAlpha: false
- Image Path -
particle.png

A270
- Delay -
active: false
- Duration -
lowMin: 1000.0
lowMax: 1000.0
- Count -
min: 0
max: 200
- Emission -
lowMin: 0.0
lowMax: 0.0
highMin: 8.0
highMax: 8.0
relative: false
scalingCount: 1
scaling0: 1.0
timelineCount: 1
timeline0: 0.0
- Life -
lowMin: 0.0
lowMax: 0.0
highMin: 2000.0
highMax: 2000.0
relative: false
scalingCount: 2
scaling0: 1.0
scaling1: 1.0
timelineCount: 2
timeline0: 0.0
timeline1: 1.0
- Life Offset -
active: false
- X Offset -
active: true
lowMin: 0.0
lowMax: 0.0
highMin: 0.0
highMax: 0.0
relative: false
scalingCount: 1
scaling0: 1.0
timelineCount: 1
timeline0: 0.0
- Y Offset -
active: true
lowMin: 128.0
lowMax: 128.0
highMin: 0.0
highMax: 0.0
relative: false
scalingCount: 1
scaling0: 1.0
timelineCount: 1
timeline0: 0.0
- Spawn Shape -
shape: point
- Spawn Width -
lowMin: 0.0
lowMax: 0.0
highMin: 0.0
highMax: 0.0
relative: false
scalingCount: 1
scaling0: 1.0
timelineCount: 1
timeline0: 0.0
- Spawn Height -
lowMin: 0.0
lowMax: 0.0
highMin: 0.0
highMax: 0.0
relative: false
scalingCount: 1
scaling0: 1.0
timelineCount: 1
timeline0: 0.0
- Scale -
lowMin: 0.0
lowMax: 0.0
highMin: 16.0
highMax: 16.0
relative: false
scalingCount: 6
scaling0: 0.0
scaling1: 0.23529412
scaling2: 1.0
scaling3: 1.0
scaling4: 0.7647059
scaling5: 0.0
timelineCount: 6
timeline0: 0.0
timeline1: 0.19863014
timeline2: 0.30821916
timeline3: 0.65068495
timeline4: 0.89726025
timeline5: 1.0
- Velocity -
active: true
lowMin: 0.0
lowMax: 0.0
highMin: 64.0
highMax: 64.0
relative: false
scalingCount: 1
scaling0: 1.0
timelineCount: 1
timeline0: 0.0
- Angle -
active: true
lowMin: 265.0
lowMax: 275.0
highMin: 0.0
highMax: 0.0
relative: false
scalingCount: 2
scaling0: 0.0
scaling1: 0.0
timelineCount: 2
timeline0: 0.0
timeline1: 1.0
- Rotation -
active: false
- Wind -
active: false
- Gravity -
active: false
- Tint -
colorsCount: 3
colors0: 1.0
colors1: 0.12156863
colors2: 0.047058824
timelineCount: 1
timeline0: 0.0
- Transparency -
lowMin: 0.0
lowMax: 0.0
highMin: 1.0
highMax: 1.0
relative: false
scalingCount: 4
scaling0: 0.0
scaling1: 1.0
scaling2: 0.75
scaling3: 0.0
timelineCount: 4
timeline0: 0.0
timeline1: 0.2
timeline2: 0.8
timeline3: 1.0
- Options -
attached: false
continuous: false
aligned: false
additive: true
behind: false
premultipliedAlpha: false
- Image Path -
particle.png

```

As for the second question, if you can hack libGDX to do this for you, the answer is Yes, absolutely. Look at the `ParticleEmitter` class, particularly the `activateParticle` method. you could open up that for inheritance a bit allowing you to hook in to the position setting of the newly created particle. If you do that you could set the x and y offsets according to the angle value and then you can achieve the effect you're looking for.

This would mean you'd have to change libGDX source code, but since it's open that's easy enough.
> 1 votes

---
Tags: libgdx, particles
---


title: WebGL - send part of texture to GPU

text:
# Question
Title: WebGL - send part of texture to GPU
I have a matrix of pixels in RAM memory, e.g. 1000x1000 pixels. I send it to GPU using

```
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1000,1000, 0, gl.RGBA, gl.UNSIGNED_BYTE, pixels);

```

Which works great. But then I change some pixels, located in rectangle x=50, y=50, width =100, height=100. Sending the whole 1000x1000px picture again takes too much time, I would like to send only changed sub-area to the GPU.

I have tired

```
gl.texSubImage2D(gl.TEXTURE_2D, 0, 50,50, 100,100, gl.RGBA, gl.UNSIGNED_BYTE, pixels);

```

but it seems, that parameter "pixels" should be the sub-area of 100x100 pixels. Copying out a sub-area from a large picture also takes too much time. Can I somehow specify a sub-rectangle for source pixels in RAM? Maybe somehow using `gl.pixelStorei()` ?

**UPDATE**: I discovered that it is possible in WebGL 2.0 (= OpenGL ES 3.0) using gl.pixelStorei() by changing PACK\_ROW\_LENGTH, PACK\_SKIP\_ROWS, PACK\_SKIP\_PIXELS parameters. Too bad WebGL 2.0 is not supported in most of devices now :(

# Answer
> 2 votes
I don't think it's possible to specify a source pitch for the buffer in CPU memory like you could with a lower level API.

However, you can specify an offset into your pixels using a DataView, so you could upload a 1000x100 portion of the texture that way.

---
Tags: textures, webgl
---


title: 3D Object not drawing in Monogame

text:
# Question
Title: 3D Object not drawing in Monogame
I'm quite new to working with 3D objects. I'm currently trying to get one to load in Monogame. The object itself was imported into Blender and exported as an fbx file (which was the only file type I could get the new content pipeline to work with).

The command to load the model is here:

```
var _model = content.Load<Microsoft.Xna.Framework.Graphics.Model>("Ship");

```

And the code to draw it is:

```
public override void Draw(IDrawParameters p)
{
    // Copy any parent transforms.
    Matrix[] transforms = new Matrix[_model.Bones.Count];
    _model.CopyAbsoluteBoneTransformsTo(transforms);

    // Draw the model. A model can have multiple meshes, so loop.
    foreach (ModelMesh mesh in _model.Meshes)
    {
        // This is where the mesh orientation is set, as well
        // as our camera and projection.
        foreach (BasicEffect effect in mesh.Effects)
        {
            effect.EnableDefaultLighting();
            effect.World = transforms[mesh.ParentBone.Index] *
                Matrix.CreateRotationX(_modelRotation) *
                Matrix.CreateRotationY(_modelRotation);
            effect.View = Matrix.CreateLookAt(eye, Vector3.Zero,
              Vector3.Up);
            effect.Projection = Matrix.CreatePerspectiveFieldOfView(
              MathHelper.ToRadians(45.0f), _aspectRatio, 1.0f, 10000.0f);
        }
        // Draw the mesh, using the effects set above.
        mesh.Draw();
    }
    base.Draw(p);
}

```

I've tried a number of variations of the draw code, mostly taken from the web. However, whatever I try, I get nothing appearing on the screen - no error, but nothing on the screen.

Is there anything specific in the code below that might cause this; or, is there a possibility that the `content.Load` didn't work, but it just didn't tell me?

UPDATE

More than one of the answers below are correct in my case. The first problem that I had was the transform:

```
effect.World = transforms[mesh.ParentBone.Index] *
                Matrix.CreateRotationX(_modelRotation) *
                Matrix.CreateRotationY(_modelRotation);

```

The second issue was with the Alpha flag; both of these together made it show, but only because I'd written a routine to change the eye position - the original rendering was inside the object.

# Answer
I had a similar problem while trying to render a skybox. Mine was only a problem with .x files, but you might find some luck with this. It seems that the alpha is set to 0 on the rendering. My code inside the `BasicEffect` loop looked like this from XNA:

```
currentEffect.LightingEnabled = false;
currentEffect.PreferPerPixelLighting = false;
currentEffect.World = modelTransforms[mesh.ParentBone.Index]
 * Matrix.CreateTranslation(position)
 * Matrix.CreateScale(0.05f);
currentEffect.View = camera.ViewMatrix;
currentEffect.Projection = camera.ProjectionMatrix;

```

In order for the skybox to show I had to add this line to show it:

```
currentEffect.Alpha = 1;

```

It solved my problem. From what you've said in your question, you saw NOTHING when you rendered. Same with me, so it could be a problem with the effect.
> 4 votes

# Answer
Since it looks like your model is loaded correctly by the pipeline, this is the most barebones solution that should work to draw it(I've just tested it). It is built with VS2015 and the most recent MonoGame DirectX template using the standard blender cube.

```
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<Microsoft.Xna.Framework.Graphics.Model>("box");
    }

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

        foreach (ModelMesh mesh in model.Meshes)
        {
            foreach (BasicEffect effect in mesh.Effects)
            {
                effect.EnableDefaultLighting();
                effect.World = Matrix.CreateTranslation(new Vector3(0, 0, 0));
                effect.View = Matrix.CreateLookAt(new Vector3(0, 0, 10), Vector3.Zero, Vector3.Up);
                effect.Projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45.0f), 1.6f, 0.1f, 10000.0f);
            }

            mesh.Draw();
        }

        base.Draw(gameTime);
    }
}

```
> 2 votes

# Answer
If the content load failed you should have got an error. But it's easy to check if something was loaded. Set a breakpoint and open up \_model, you should have at least one ModelMesh within it, and it should contain at least one MeshPart.

Have you checked if there's any effects to iterate in your rendering loop? Otherwise you might need to add a BasicEffect to each mesh at load time.
> 0 votes

---
Tags: c#, 3d, monogame, 3d-meshes, xna-content-pipeline
---


title: Runtime resolution changing with GLFW3

text:
# Question
Title: Runtime resolution changing with GLFW3
I've been trying to figure out the correct method for changing the resolution/fullscreen state of a GLFW window for a while now, but after searching all I found were references of how to do it with older versions of the library such as this. I suspect you'd just destroy the window object and re-create it, but was not sure because of how some functions such as `glfwSetKeyCallback` take a `GLFWwindow*` as a parameter, and I don't know if that'd continue to work after it has been re-created. The documentation also does not have any examples on doing such a thing, so any help would be appreciated.

# Answer
> 1 votes
To the best of my knowledge, still there isn't a function to toggle between windowed and fullscreen modes. Here is the listing of all functions provided by the library at the current version. Such feature might be added in the future though, if enough requests for it pop up.

However, the window and the OpenGL context are two tightly coupled things, so changing window and video modes like this tends to be complicated and prone to different behaviors (and bugs!) on different systems and implementation of the GL. Perhaps that is why the library is steering clear of these issues.

My advice here would be to do as proposed in the link you've shared: Destroy the current window and create a new fullscreen one with proper video mode. AFAIK, this is how most games that allow this switching do it anyway.

You will have to recreate all GPU related resources too, like textures, buffers and shaders, so plan your code accordingly. Perhaps you might want to have a pair of `onContextLost()/onContextRecovered()` methods on your resource objects that recreate the OpenGL handles once such window destruction/re-creation happens. With GLFW, the safest approach would be to also fully shutdown and re-initialize the library, providing fresh callbacks to it. Again, this is not a big issue if you plan your code in a way to facilitate this rebooting. If you have a `Window` object of sorts that wraps GLFW, that would be just a matter of destroying the current and creating a new one.

# Answer
> 0 votes
You are correct that you cannot take the same window with the same GL context and change between fullscreen and windowed.

What I have done is set up my rendering system (and input, etc...) to generically set itself up, and extended that slightly to allow it to re-set itself up without leaking memory. So when the application first launches, everything is loaded and the setup functions are called. Then, if I swap between full-screen and windowed, I just issue another system-wide setup. All the objects maintain their current data (location, orientation, logic time, etc...) they just rebind themselves to the window's context.

It takes a bit of thought up front, but then once it's done everything "just works" as you add new features or object types or whatever into this paradigm. Here is the relevant code from my project:

```
void Engine::ToggleFullscreen()
{
    bool wasFullscreen = glfwGetWindowMonitor(_window) != nullptr;
    glfwDestroyWindow(_window);

    if (wasFullscreen)
    {
        CreateWindow(false);
    }
    else {
        CreateWindow(true);
    }

    Shaders::RequireRebindAll();

    for (unique_ptr<Scene> &s : _scenes)
    {
        s->RebindObjectsToCurrentContext();

        int w, h;
        glfwGetWindowSize(_window, &w, &h);
        s->ResizeView(w, h);
    }
}

// Private member functions
void Engine::CreateWindow(bool goFullscreen)
{
    GLFWmonitor* monitor = NULL;
    int width = 1280;
    int height = 720;

    if (goFullscreen)
    {
        // actually, try to get the second monitor if there is one, otherwise the primary
        int mon_count = -1;
        GLFWmonitor **mon_list = glfwGetMonitors(&mon_count);

        assert(mon_count > 0);
        if (mon_count > 1)
        {
            monitor = mon_list[1];
        }
        else {
            monitor = mon_list[0];
        }

        width = glfwGetVideoMode(monitor)->width;
        height = glfwGetVideoMode(monitor)->height;
    }

    _window = glfwCreateWindow(width, height, "TEST Windoh", monitor, NULL);
    if (!_window)
    {
        throw "unable to create glfw window";
    }

    glfwSetWindowSizeCallback(_window, &Engine::ViewResized);

    glfwMakeContextCurrent(_window);
    glfwSwapInterval(0);

    glEnable(GL_SCISSOR_TEST);
    glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_LESS);

    // glew must be initialized AFTER there is a working gl context
    GLenum err = glewInit();
    if (err != GLEW_OK)
    {
        cout << "Error loading glew: " << glewGetErrorString(err);
    }
}

```

The function `ToggleFullscreen` is called by the key command to switch for now, but you could attach it to a UI callback or whatever else you wanted.

---
Tags: opengl, c++, glfw
---


# Question
Title: Creating a path including loops and spirals
I have a paper airplane that I would like to take a "random" path towards its destination based on the game layouts size. I want it to include spirals and loops and gliding a little back and forth.

How would I go on about creating those random movements?

# Answer
> 2 votes
*I assume you know the basic maths stuff concerning angles, movement, distance and all the other stuff.*

You have these goals:

* reach destination
* do random stuff
* stay inside (rectangular?) area of playfield

Your plane could have these properties:

* position `pos`
* forward-speed `vel`
* forward-acceleration `acc`
* heading/rotation in degrees `rot`
* angular velocity (rotation per second) `rotVel`
* angular acceleration (change of rotation per second) `rotAcc`

Of which `pos`, `vel` and `rot` are chosen when spawning the plane and then **never touched again by the random movement code** and the others are used to steer it (randomly) towards it's target.

To move the plane, this is getting executed each tick (delta is the time between two updates):

```
vel += acc*delta;
pos += vel*unitVectorOfAngle(rot)*delta;
rotVel += rotAcc*delta;
rot += rotVel*delta;

```

---

So what you could do with this:

**1. Loops and turns**

You set `rotAcc` to a random positive or negative value, and leave it like that until you reach a randomly chosen Angle (*or for a randomly chosen time or until you are heading towards a randomly chosen point, whatever works best*) and then set `rotAcc = -rotAcc` to smoothly decrease your turnrate until `rotVel` is zero again. In the image, two example-paths are shown, red is the acceleration phase, green the deceleration phase.

---

##

**2. Gliding back and forth**

You set `acc` to a relatively big negative value and decelerate until you move back fast enough. Then you wait for a random amount of time and set `acc` to a high positive value until you reach your original speed again, then set it to zero.

**3. Reaching your destination**

You should constrain the randomness of your planes movement based on the time that has elapsed since it was started and the distance to your goal. just initiate the random moves less frequently and try to correct its path towards the target, by tweaking `rotAcc`.

**4. Constraining the fly area**

For countering situations in which the plane goes to near to a border, you could use a combination of gliding back and doing a fast loop or a manual turn.

**5. Mix it up and time it**

I can't help you there, you will need to figure out all the tweaking and timing out for yourself.

# Answer
> 1 votes
The most simple solution must be to randomize path points. Each point can only be within a certain angle from the previous ones. After x points have been created, change the angle setting to make it steer towards the destination.

Something like this:

```
Vector2 currPos = plane.pos;
Vector2 currDir = plane.startDir;

for(int num = 0; num < MaxPoints; num++){
   double angle;
   if(num < SteerToExit){
    angle = Random(-HalfMaxAngle, HalfMaxAngle);
   }
   else
   {
   Vector2 vToExit = ExitPos - currPos;
   double exitAngle = AngleBetweenVectors(vToExit, currDir);
    //You could add some check here and make sure angle stays
    //within +-HalfMaxAngle. Otherwise the plane might do a 180 turn at this point.
    //If it's outside, just make the loop run a few more times
   angle = exitAngle;
 }

   Vector2 newDir = Vector2.Transform(currDir, Matrix.CreateRotationZ(angle));
   newDir = Vector2.Normalize(newDir) * Step;
   currPos = currPos + newDir;
   path.Add(currPos);
   currDir = newDir;

   if((currPos - ExitPos).Length() < CertainValue)
     num = MaxPoints; //Yay we found the destination!
}

```

---
Tags: ai, patterns
---