# Question
Title: How to calculate new velocities between resting objects (AABB) after accelerations?
lately I have been trying to create a 2D platformer engine in C++ with Direct2D. The problem I am currently having is getting objects that are resting against each other to interact correctly after accelerations like gravity have been applied to them.

Right now I can detect collisions and respond to them correctly (I think) and when objects collide they remember what other objects they're resting against so objects can be pushed by other objects (note that there is no bounce in any collisions so when objects collide they are guaranteed to become resting until something else happens). Every time the simulation advances, the acceleration for objects is applied to their velocities (for example vx += ax * t, where t is time elapsed since last advancement).

After these accelerations are applied, I want to check if any objects that are resting against each other are moving at different speeds than their counterparts (as different objects can have different accelerations) and depending on that difference either unlink the two objects so they are no longer resting, or even out their velocities so they are moving at the same speed once again. I am having trouble creating an algorithm that can do this across many resting objects.

Here's a diagram to help explain my problem

# Answer
First of all, I have some doubts about your diagram. Do the arrows represent the velocity vector? If so, when you say that objects are "resting", do you mean that they are resting in relation to each other even though the "group" is moving with same velocity?

Well, besides that, from your sample diagram (whose blocks I will call A, B, C and D from left to right) I understood the following:

* The blocks are all connected at the begining, moving to right with the same speed;
* An additional force towards right is applied to block B;
* And this causes the link between block A and B to be broken, also making block A to revert its velocity vector moving away from the new "group" (made of blocks B, C and D now).

Since your question is about how to create an algorithm to handle those changes, my suggestion is to create a composition between connected blocks to really create a group (like if they were magnetic attached). Use a compositite design pattern, for example, to join blocks together, so you can iterate through them when a force is applied to one specific block in the group. If your group structure shall store information about relative position (it can be simply the index position in the list), then you can split the group and revert the velocity of the subgroup at left/right from the block in which the force was applied (naturally, according to the direction of the force applied).
> 1 votes

---
Tags: c++, physics, collision-resolution, aabb
---


# Question
Title: XNA Transparency depending on drawing order?
I am drawing two 3D objects, both of them can fade from opaque to transparent independently, and they can intersect between them (so you cannot say when one of them is *before* the other one). Look at the image for a better understanding (one of the object is a terrain and the other one an area):

Now, if I apply transparency to both of them, and draw the terrain before the area, the terrain is not transparent respecting to the area, but the area is:

And finally, if I draw the area before the terrain, then the area is not transparent respecting of the terrain:

**QUESTION:** How can I make all the objects transparent to the rest of objects without depending on the drawing order?

# Answer
> 1 votes
In general rendering intersecting transparent objects correctly is not easy to get working. Most games try to avoid the situation instead of making it work.

Here's one way to handle your specific case of just two objects.

1. Render the terrain into the depth buffer only (disable colour writes).
2. Disable depth writes, and re-enable colour writes.
3. Render the area with a depth test of greater. This draws the bit of it that's under the terrain.
4. Switch the depth test back to less than or equal to.
5. Render the terrain.
6. Render the area. This will draw the bit of it that's above the terrain.

That sort of approach doesn't easily generalize to more than two objects though. For that you'll need some sort of order independent transparency system, which are generally expensive on the GPU. For example: http://research.microsoft.com/apps/pubs/default.aspx?id=70307

# Answer
> 0 votes
You have to set the Graphics device settings and restore them when drawing in XNA. The drawing order is coincidence and I am guessing you have SpriteBatch somewhere in there when you swap the order causing the graphics device settings to get altered.

---
Tags: xna-4.0, transparency, alpha
---


# Question
Title: What's the difference between Pygame's Sound and Music classes?
What are the key differences between the Sound and Music classes in Pygame? What are the limitations of each? In what situation would one use one or the other? Is there a benefit to using them in an unintuitive way such as using Sound objects to play music files or visa-versa? Are there specifically issues with channel limitations, and do one or both have the potential to be dropped from their channel unreliably? What are the risks of playing music as a Sound?

# Answer
> 6 votes
In a game, `music` would be the a way to play background music and `sound` the way to play sound effects (ej. jumping, firing, etc).

Music is a special streaming channel of the Mixer. This means the file is streamed from disk in small chuncks and not loaded at once.

Pygame only supports one Music at a time but you can have several Sound objects playing at once, as long as you have available channels.

Music allows you to `queue` songs and `set_endevent` to receive an event when the track ends. Note that this can also be achieved by with Sounds using the Channel object.

If you need multiple sounds playing at a time, ie: music player with crossfade, you should use Channels + Sounds. If you only need one background music at a time and mayble multiple sound effects, use Music and Sounds.

---
Tags: python, pygame, sound, audio, music
---


title: 2D game big background images for maps

text:
# Question
Title: 2D game big background images for maps
Update: this question is general, not specific to Sprite Kit or a single language/platform.

I'm toying with Sprite Kit with an idea to make a 2D side-scroller. Now the backgrounds for the maps are going to be hand-drawn and surely bigger than retina display, so the maps could span more than 1 screen in both axis.

I imagine loading such a huge image could mean trouble and I don't plan to use tiling. I'm not sure how Sprite Kit splits images bigger than max texture size, if it does. I could split the images myself and use more sprites for each part of the background.

What is the usual way to handle this?

# Answer
I don't know a whole lot about the actual implementation of it and I doubt it's the usual way to handle it, but to me ClipTextures or (Sparse) Virtual Texturing comes to mind.
Essentially -from my perspective at least- the idea is to keep only the relevant part of a very large texture file located on the hard-drive in system memory and an even smaller "clip region" of it in the GPU memory. If the position in the game changes now, and therefore the region of the texture required for rendering, the missing texture data is streamed to the GPU memory from the system memory. By adding only the missing texels and removing texel that are far away from the game view, the amount of data that needs to be streamed is limited. Also the part of the texture present in system memory should be updated accordingly, to keep longer loading times -due to the hard-drive access- away from the rendering.
It basically is sort of memory cache implementation for textures and I image a clever caching strategy and prediction of what texels will be needed next, will of course be necessary.

If you are interested, for further reading you might want to start with these slides from Id Software about virtual texturing (in Rage): Id Tech 5 Challenges. Or also this (longer) SGI Article on Clip Textures.

Also, since you mentioned retina displays. I believe most modern GPUs should support textures up to a size of 16k times 16k (at least even my 4 year old Notebook does), which should be around 50 times as much area as a retina display offers and still several times as much in one dimension. But that's just playing with numbers of course :)
> 3 votes

# Answer
There are a few options.

1. Don't use large images. Take a look at the backgrounds of many popular 2d games - especially side scrollers. You'll see that the backgrounds are usually actually composed of multiple images, usually combined with a gradient. This can give the illusion of a large image but actually take up very little space.
2. Texture compression.

Some compression techniques can reduce file size to 1/8 the original size.
> 2 votes

---
Tags: 2d, maps, side-scroller
---


# Question
Title: Using texture() in combination with JBox2D
I'm getting some trouble using the `texture()` method inside `beginShape()/endShape()` clause.

In the `display()`-method of my class TowerElement (a bar which is `DYNAMIC`), I draw the object like following:

```
void display(){
    Vec2 pos = level.getLevel().getBodyPixelCoord(body);
    float a = body.getAngle(); // needed for rotation

    pushMatrix();

    translate(pos.x, pos.y);
    rotate(-a);

    fill(temp);    // temp is a color defined in the constructor
    stroke(0);

    beginShape();
    vertex(-w/2,-h/2);
    vertex(w/2,-h/2);
    vertex(w/2,h-h/2);
    vertex(-w/2,h-h/2);
    endShape(CLOSE);

    popMatrix();

}

```

Now, according to the API, I can use the `texture()` method inside the shape definition. Now when I remove the `fill(temp)` and put `texture(img)` (img is a `PImage` defined in the constructor), the stroke gets drawn, but the bar isn't filled and I get the warning

> texture() is not available with this renderer

What can I do in order to use textures anyway? I don't even understand the error message, since I do not know much about different renderers.

# Answer
> 0 votes
I post this as an answer since I "reach the goal", but I don't know if it is good practice.

Instead of trying to attach a texture to a shape, I just draw an image(...) instead of a rect. In above code, before I tried to work with own shapes and texture, I simply had

```
void display(){
    //(...)
    rectMode(CENTER);
    pushMatrix();
    translate(pos.x, pos.y);
    rotate(-a);
    fill(temp);
    rect(0,0,w,h);
    popMatrix();
}

```

Now I tried to just remove `rectMode(CENTER)` and replacing `rect(0,0,w,h)` with

```
image(tex, -w/2, -h/2, w, h);

```

and it results in a "textured bar". Nevertheless I'm not sure if this is a good approach.

---
Tags: textures, box2d, jbox2d
---


title: Box2D relations

text:
# Question
Title: Box2D relations
As far as I know, the unit in Box2D is meters. When I use Box2D in Processing with JBox2D, I set the "world size" as the window size specified in the setup().

Now I'm wondering if there is any function that scales down the world. For example, how can I simulate the throw of tennis ball within a room, without using a window of only 5 x 5 pixels?

Additionally, is there any good documentation like the Java API?

# Answer
To expand on Sean's comment, you should create a separate class or set of classes to connect your physics world with your rendering.

I'm not entirely familiar with Processing, but usually it'd be something like this:

```
class Box2DObject{
    final float PHYSICS_SCALE = 100.0;
    b2Body body;
    Image image;
    Box2DObject(b2Body ibody, Image iimage){
        body = ibody;
        image = iimage;
    }

    void update(){
        image.x = body.GetPosition().x * PHYSICS_SCALE;
        image.y = body.GetPosition().y * PHYSICS_SCALE;
        image.draw();
    }
}

```

`update()` is called every rendering update on each Box2DObject, after calling box2d's `world.step()` method. The hard work is done by the `PHYSICS_SCALE` constant defined at the top of the class. This effectively sets a ratio of 1 meter to be 100 pixels (in this case). This means that a tennis ball with a box2d diameter of 67mm, would have a display size of 6.7 pixels. Increasing/decreasing the PHYSICS\_SCALE constant increases/decreases the display size.

As far as API documentation goes, most ports I have seen are largely similar to the original C++ library. The C++ API documentation can be found online at http://www.learn-cocos2d.com/api-ref/1.0/Box2D/html/index.html or in the C++ distribution which can be downloaded here https://code.google.com/p/box2d/downloads/list.

I hope this helps.
> 5 votes

---
Tags: physics, box2d, jbox2d
---


# Question
Title: What decrease of polycount should occur as a function of distance?
What decrease in polycount should occur as a function of distance. I make a terrain and I wounder what is the right formula to keep the "poly size"(the screen size) constant. Or is there some mental flaw in this approach?

# Answer
As @Adam said, one or two pixels is as small as you want to go. In fact, 1 pixel by 2 pixels is *the* correct size (unless multisampling, which decouples screen pixels from geometry pixels).

The reason it's correct is that 1x2 yields one pixel for each triangle. If your polygons are smaller than that, then multiple color outputs must be combined into a single pixel. The final result will vary depending on subtle changes like orientation. On screen, that looks like jittering textures. The pixel will be green one second, then brown, then black, when really is should be somewhat constant or smoothly changing. There are ways to fight it, but if you have exact control of the polygon count through some form of shader tessellation, aim for 1 pixel per polygon.

In terms of math and the "right formula, rendering is always an application of signal processing. This article is an interesting high-level discussion of what happens to a 1-d signal when sampling varies slightly. As that article describes, the math is almost a century old. You would probably drive yourself insane trying to apply this theory directly to your rendering, but it does yield a good rule of thumb: one or two pixels.

And obviously, the problem with bigger polygons:
> 2 votes

# Answer
In general when polygons get smaller than one or two pixels in either width or height you can get aliasing from that. This is generally called Geometry Aliasing.

It is most noticeable when the small polygons have significantly different colours to the ones next to them. Different normals can also be a problem because specular highlights will change the colour based on the normal.

The aliasing can be reduced significantly by MSAA as it effectively makes the pixels smaller, but screen space techniques like FXAA aren't very good at fixing it.

Of course the size in pixels on screen of a polygon varies with the camera position, orientation and field of view, so the ideal place to select the poly count is in real time with a shader. Failing that you can estimate it based on standard camera settings and a target screen resolution.
> 4 votes

# Answer
From my litte experience with terrain rendering, one of the visually most offensive things that happens when naively reducing the polycount with increasing distance is that -for example- the peaks of mountains can get "cut off" or valleys vanish. This obviously will happen when removing vertices uniformly from the mesh and these landscape features simply aren't positioned conveniently enough to be represented by a vertex in the mesh with reduced detail.

So generally I think you will want to retain the shape or silhouette of the terrain as much as possible. One way to achieve this might be to favor local extreme points in your heightmap. That means when reducing the polycount, you first remove vertices that aren't located in the vicinity of a local extreme point or ridge-line, as those should usually represent the peaks of mountains/hill, the bottom of valleys or any other features that greatly define the overall look of the landscape.
> 4 votes

# Answer
I don't think there is a right formula, it's more important to keep your frame rate smooth rather than keeping the number of polygons fixed. Most games have some polygons budget that they strive to keep their polygons count below. So I would say change how aggressively your application simplify the terrain based on how good the game performs and how good it looks.

It's important to measure and decide what is needed. polycount is a tangible number just like FPS both are not particularly accurate at measuring your game's performance, and there are other things to measure that govern the GPU time such as fillrate, draw batches.

There are famous terrain rendering algorithms such as ROAM that uses a heuristic approach to determine the best detail/performance ratio.
> 2 votes

---
Tags: level-of-detail
---


# Question
Title: Unknown error XNA cannot detect importer for "program.cs"
I am not too sure what I have done to cause this, but even after undoing all my edits, this error still appears

> Error 1 Cannot autodetect which importer to use for "Program.cs". There are no importers which handle this file type. Specify the importer that handles this file type in your project. (filepath)\Advanced Pong\AdvancedPongContent\Program.cs Advanced Pong

After receiving this error, everything between #if and #endif in the program.cs fades grey

```
using System;

namespace Advanced_Pong
{
#if WINDOWS || XBOX
static class Program
 {
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    static void Main(string[] args)
    {
        using (Game1 game = new Game1())
        {
            game.Run();
        }
    }
 }
#endif
}

```

I have searched this and could not find a solution anywhere. Any help is appreciated.

# Answer
> 0 votes
A copy of the file was created and left in the content area of the project where all the images/sounds are. After removing the file, the game executed as per normal. *Thanks to jaakko lipsanen*

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


title: how to android touch in Unity?

text:
# Question
Title: how to android touch in Unity?
I am creating simple game for android.I used `touchphase.moved` to power up my ball and `touchphase.ended` to throw the ball.But what happened is the ball is thrown when I moved my finger in both x and y direction.But I want the ball to be thrown only while swiping in y direction.How to do that Suggest me?

# Answer
> 4 votes
If you save the start position of the touch when the touchphase starts, you can compare the length between the start and the end position of the touch.

If you do that, you can then compare it to a specific range.

pseudo:

```
if(abs(touchStartPos.x - touchEndPos.x) < SpecifiedWidth)
{
    throw();
}

```

You can't expect the player to not move his finger a little bit to the left or right when he's throwing. Test!

---
Tags: unity
---


# Question
Title: What's wrong with this Open GL ES 2.0. Shader?
I just can't understand this. The code works perfectly on the emulator(Which is supposed to give more problems than phones…), but when I try it on a LG-E610 it doesn't compile the vertex shader. This is my log error(Which contains the shader code as well):

**EDITED**

Shader:

```
uniform mat4 u_Matrix;

uniform int u_XSpritePos;
uniform int u_YSpritePos;
uniform float u_XDisplacement;
uniform float u_YDisplacement;

attribute vec4 a_Position;
attribute vec2 a_TextureCoordinates;

varying vec2 v_TextureCoordinates;

void main(){
    v_TextureCoordinates.x= (a_TextureCoordinates.x + u_XSpritePos) * u_XDisplacement;
    v_TextureCoordinates.y= (a_TextureCoordinates.y + u_YSpritePos) * u_YDisplacement;

    gl_Position = u_Matrix * a_Position;
}

```

Log reports this before loading/compiling shader:

```
11-05 18:46:25.579: D/memalloc(1649): /dev/pmem: Mapped buffer base:0x51984000 size:5570560 offset:4956160 fd:46
11-05 18:46:25.629: D/memalloc(1649): /dev/pmem: Mapped buffer base:0x5218d000 size:5836800 offset:5570560 fd:49

```

Maybe it has something to do with that men alloc? The phone is also giving a constant error while plugged: ERROR FBIOGET\_ESDCHECKLOOP fail, from msm7627a.gralloc

**Edited:** "InfoLog:" refers to glGetShaderInfoLog, and it's returning nothing. Since I removed the log in a previous edit I will just say i'm looking for feedback on compiling shaders.

**Solution + More questions:** Ok, the problem seems to be that either ints are not working(generally speaking) or that you can't mix floats with ints. That brings to me the question, why on earth glGetShaderInfoLog is returning nothing? Shouldn't it tell me something is wrong on those lines? It surely does when I misspell something.

I solved by turning everything into floats, but If someone can add some light into this, It would be appreciated. Thanks.

# Answer
I've tried that same shader program in other mobile devices and it works. Apparently, compiling issues like that one, have to do with the GPU drivers installed on the device, and the way it handles the compiling. So, if you want compatibility with all devices, just stick to correct programming and don't mix var types, although it is supposed to work.

Apart from that, Casting/Conversion in glsl does work but done this way:

```
float(int_var);

```

In posterior versions of glsl there are other functions to make this happen.

My source: glsl version 1.10

> why on earth glGetShaderInfoLog is returning nothing? Shouldn't it tell me something is wrong on those lines?

No It doesn't have to if it is not programmed to, as Sean Middleditch said, it is not standardized.
> 0 votes

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


# Question
Title: How can I create a 3D model in Java without using modeling software?
I am a lightly experienced game developer and this is my first time trying 3D objects in Java for the first time. I have been recently creating and updating games using AWT, Swing, and Graphics, but I want to delve farther into Java.

I have looked into Java3D, but it's not what I want. I want to use Images and then crop the Image and place the respective textures in their respective places. I already know how to do the cropping and 2D Image editing, but how do I go 3D?

# Answer
> I want to use Images and then crop the Image and place the respective textures in their respective places.

Using Java3D, as mentioned, and an your already cropped Bufferdimage/Image (e.g. a `BufferedImage`):

1. Use `[TextureLoader][1]`

import com.sun.j3d.utils.image.TextureLoader;
2. Create a texture

```
Texture texImage = new TextureLoader(myCroppedbufferedImage).getTexture();
//Texture texImage = new TextureLoader(myCroppedImage, this).getTexture();

```
3. Set the texture, where app is an appearance object for your textured primitive

app.setTexture (texImage);

On how to programmatically create a primitive and texture it see this example (adapted from source):

```
import java.applet.Applet;
import java.awt.BorderLayout;
import java.awt.GraphicsConfiguration;

import javax.media.j3d.Alpha;
import javax.media.j3d.Appearance;
import javax.media.j3d.BoundingSphere;
import javax.media.j3d.BranchGroup;
import javax.media.j3d.Canvas3D;
import javax.media.j3d.RotationInterpolator;
import javax.media.j3d.Texture;
import javax.media.j3d.TextureAttributes;
import javax.media.j3d.Transform3D;
import javax.media.j3d.TransformGroup;
import javax.vecmath.Point3d;

import com.sun.j3d.utils.applet.MainFrame;
import com.sun.j3d.utils.geometry.Box;
import com.sun.j3d.utils.image.TextureLoader; //that is the relevant part!
import com.sun.j3d.utils.universe.SimpleUniverse;

public class TextureImage extends Applet {

  private java.net.URL texImage = null;

  private SimpleUniverse u = null;

  public BranchGroup createSceneGraph() {
    // Create the root of the branch graph
    BranchGroup objRoot = new BranchGroup();

    TransformGroup objTrans = new TransformGroup();
    objTrans.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);
    objRoot.addChild(objTrans);

    // appearance object for textured cube
    Appearance app = new Appearance();
    Texture tex = new TextureLoader(texImage, this).getTexture();
    app.setTexture(tex);
    TextureAttributes texAttr = new TextureAttributes();
    texAttr.setTextureMode(TextureAttributes.MODULATE);
    app.setTextureAttributes(texAttr);

    // Create textured cube and add it to the scene graph.
    Box textureCube = new Box(0.4f, 0.4f, 0.4f,
        Box.GENERATE_TEXTURE_COORDS, app);
    objTrans.addChild(textureCube);

    Transform3D yAxis = new Transform3D();
    Alpha rotationAlpha = new Alpha(-1, Alpha.INCREASING_ENABLE, 0, 0,
        4000, 0, 0, 0, 0, 0);

    RotationInterpolator rotator = new RotationInterpolator(rotationAlpha,
        objTrans, yAxis, 0.0f, (float) Math.PI * 2.0f);
    BoundingSphere bounds = new BoundingSphere(new Point3d(0.0, 0.0, 0.0),
        100.0);
    rotator.setSchedulingBounds(bounds);
    objTrans.addChild(rotator);

    // Have Java 3D perform optimizations on this scene graph.
    objRoot.compile();

    return objRoot;
  }

  public TextureImage() {
  }

  public TextureImage(java.net.URL url) {
    texImage = url;
  }

  public void init() {
    if (texImage == null) {
      // the path to the image for an applet
      try {
        texImage = new java.net.URL(getCodeBase().toString()
            + "/stone.jpg");
      } catch (java.net.MalformedURLException ex) {
        System.out.println(ex.getMessage());
        System.exit(1);
      }
    }
    setLayout(new BorderLayout());
    GraphicsConfiguration config = SimpleUniverse
        .getPreferredConfiguration();

    Canvas3D c = new Canvas3D(config);
    add("Center", c);

    // Create a simple scene and attach it to the virtual universe
    BranchGroup scene = createSceneGraph();
    u = new SimpleUniverse(c);

    // This will move the ViewPlatform back a bit so the
    // objects in the scene can be viewed.
    u.getViewingPlatform().setNominalViewingTransform();

    u.addBranchGraph(scene);
  }

  public void destroy() {
    u.cleanup();
  }

  //
  // The following allows TextureImage to be run as an application
  // as well as an applet
  //
  public static void main(String[] args) {
    java.net.URL url = null;
    if (args.length > 0) {
      try {
        url = new java.net.URL("file:" + args[0]);
      } catch (java.net.MalformedURLException ex) {
        System.out.println(ex.getMessage());
        System.exit(1);
      }
    } else {
      // the path to the image for an application
      try {
        url = new java.net.URL("file:stone.jpg");
      } catch (java.net.MalformedURLException ex) {
        System.out.println(ex.getMessage());
        System.exit(1);
      }
    }
    new MainFrame(new TextureImage(url), 256, 256);
  }

}

```
> 0 votes

---
Tags: java, 3d, graphics, models
---


# Question
Title: What can I do to make sure that I have the energy to work on my game while working full-time?
I work as a software engineer 40+ hours a week and I find that between balancing my personal life and family responsibilities that I have literally no energy to work on game development.

What can I do to make more time for my hobby without burning myself out in front of the computer? I am sure there must be someone here successfully developing a game while working as a programmer on the side.

# Answer
> 59 votes
When I worked as a software engineering intern the past three summers, I also wanted to work on my own projects, but also spend time with friends/family. Not quite the pressure of family responsibility that you face, but still a time sink.

The only way I could make things sort of work was identifying nights that were completely dedicated to one thing over the other. If I was supposed to spend the evening with my family I wouldn't even boot my computer. Other times, I had to ask my family not to disturb me and turn off my phone so I wouldn't get distracted.

Even while working, take a break every 20-30 minutes to walk around and get your eyes off the screen. The pomodoro technique has proven handy when I've had to juggle several projects at once.

# Answer
> 43 votes
One thing that I've done lately, is getting up painfully early every morning to program- my mind is fresh, and I stay clearer throughout the day for my job and the rest of my activities.

The problem with this route is the necessity of going to bed early- and if you've ever been on a programming rampage, you know it's tough to stop for simple things like (pshh) sleep- who needs it?

But seriously, 5am-8am = programming time. While I've been doing this I've completed more games while also working full time and having a social life than I ever did programming full time.

# Answer
> 25 votes
IMHO your family should come first. The reward for time well spent on them will far out weigh any gains you acquire from your game dev. Balance your time wisely, but make sure they get the lion's share.

# Answer
> 8 votes
I use the Pomodoro technique to manage my time. I allot 8 Pomodoros minimum daily to programming.

# Answer
> 7 votes
I can only offer tips for managing/getting solid work time in the home and balancing work/family.

Like it or not, **you're going to have to be selfish** _*some of the time*\_. The difference between being a shithead and a good person is if you're selfish **all of the time.**

Hobby/family balance is taking time out for yourself. If you automatically assign **all** time outside of work to family time, then you're **not** going to have time to dev games/pursue hobbies. And that's fine. You can do that. But to pursue personal projects \_you're going to have to be a bit selfish, *some* of the time.\_

Further to being selfish:

* There must be a room for you to work in that is completely isolated
* You have to set up a policy for the times that *you're working on your hobby*.
* Seal yourself away for *short* time periods (1-2 hours tops) in the evenings (8pm-9:30pm?) where you get to pursue your hobbies. If you do longer sprints, then you're starting to get a bit too selfish.

Look, 2h family time can be \>= 4h family time. If you spend 6pm-8pm with the family, then go pursue your hobbies, all bets are your relationship will be just as healthy with them if you spent 6pm-10pm then went to sleep. As long as you see your family *every day* and you spend 1-2 hours with them, and *communicate with them* during that time, your relationship will be maintained/grow. I have no reference for this but there's a certain threshold where there is very little negative impact if you spend 1-2 hours *less* with them.

And what happened to weekends? If you spend 4 hours Sat+Sun morn (before the rest of your family gets up) that's a solid 8 more hours over the weekend.

No references for this, just personal experience what worked for me with 2 small kids in the house (who are not my own).

# Answer
> 2 votes
I've found there's about enough time available in life for work, family, and 1 hobby that you do really well. Do you have other hobbies that are less important? If so, you'll need to drop them. Take it from someone that has accumulated several hobbies and now finds that he's no longer very good at any of them (vs. when I had 1 serious hobby and was quite good at it). :-)

# Answer
> 2 votes
Get someone else to work with. Do pair programming or just work together in the same location. It really helps keep your motivation up especially when having to do something tedious or difficult.

You could recruit a friend, co-worker or if you live near a college or university, hire a student as an intern.

# Answer
> 1 votes
Energy is not everything. Take every precaution to not develop an RSI, because in that case you won't have your game and your job neither. You have to be very aware of these (now distant) things if you plan to type on a keyboard, 10+ hours a day, for years.

# Answer
> 1 votes
My opinion is that you're going to have to accept that you're just not going to. From the sounds of it you have a hobby that involves the same kind of general thing as you do in work. That's not great for a number of reasons, but - totally leaving aside the more personal ones - one thing you're going to find is that there are some days in work where you're going to feel burned out on coding/problem solving/etc and just flat out won't feel like doing any hobby coding, and vice-versa.

Doing something for X hours per day in work and then coming home and doing what is broadly the same kind of thing all over again runs a high risk of leading to a crash landing. I'd suggest picking which is most important to you, and looking to make a change in the other. So if your hobby is more important, see about getting a move to a different role in work. If work is more important, use a pre-built engine and do some map design, art, or something else for the hobby.

# Answer
> 0 votes
A list of goals. I work as an intern games developer, while not working i also do online study courses to help improve my coding or analytical skills, developing my own game and playing games. There is one thing that boils my blood, it is waking up without any clear idea of what i should be looking to achieve for the day. Managing your time effectively can be a pain in the arse especially if your days are mainly consumed by working and travelling but if done correctly you should have enough time to work, enough time to play and enough time to code your own game, while also feeling accomplished and sleeping easy.

But be weary of overshooting. Don't make your list of goals incredibly vague that it still leaves you wondering about where you should start or when to finish. Also try to estimate the time needed to accomplish a given task and look to put a cap on the time spent as something.

I also find that looking for inspiration through music or reading helps a lot.

---
Tags: software-engineering, motivation
---


title: Behaviour Trees with irregular updates

text:
# Question
Title: Behaviour Trees with irregular updates
I'm interested in behaviour trees that aren't iterated every game tick, but every so often. (Edit: the tree could specify how many frames within the main game loop to wait before running its tick function again).

Every theoretical implementation I have seen of behaviour trees talks of the tree search being carried out every game update - which seems necessary, because a leaf node (eg a behaviour, like 'return to base') needs to be constantly checked to see if is still running, failed or completed.

Can anyone suggest how I might start implementing a tree that isnt run every tick, or point me in the direction of good material specific to this case (I am struggling to find anything)?

**My thoughts so far:**

* action leaf nodes (when they start) must only push some kind of action object onto a list for an entity, rather than directly calling any code that makes the entity do something. The list of actions for the entity would be run every frame (update any that need to run, pop any that have completed from the list).
* the return state from a given action must be fed back into the tree, so that when we run the tree iteration again (and reach the same action leaf node - so the tree has so far determined that we ought to still be trying this action) - that the action has completed, or is still running etc.
* If my actual action code is running from an action list on an entity, then I possibly need to cancel previously running actions in the list - i am thinking that I can just delete the entire stack of queued up actions. I've seen the idea of ActionLists which block lower priority actions when a higher priority one is added, but this seems like very close logic to behaviour trees, and I dont want to be duplicating behaviour.

**This leaves me with some questions**

1) How would I feed the action return state back into the tree? Its obvious I need to store some information relating to 'currently executing actions' on the entity, and check that in the tree tick, but I can't imagine how.

2) Does having a seperate behaviour tree (for deciding behaviour) and action list (for carrying out actual queued up actions) sound like a reasonable approach?

3) Is the approach of updating a behaviour tree irregularly actually used by anyone? It seems like a nice idea for budgeting ai search time when you have a lot of ai entities to process.

(Edit) - I am also thinking about storing a single instance of a given behaviour tree in memory, and providing it by reference to any entity that uses it. So any information about what action was last selected for execution on an entity must be stored in a data context relative to the entity (which the tree can check). (I am probably answering my own questions as i go!)

I hope I have expressed my questions adequately! Thanks in advance for any help :)

# Answer
**Feed back the action return state**

I'm not quite clear on what you mean here, but I see this as fairly simple. The action returns are going to come back at some point -- on some game loop tick, during the action execution phase. You can do these as either method returns, as gamestate changes, or as both (method returns from action methods writing into global state which is held for later examination). Then, the next time you run the tree tick / AI "thought" phase, you're going to examine those results, whether that's on the same game loop tick or a later tick. Do clarify if this is not what you mean.

**Periodic AI updates**

Absolutely. Periodic updates are by no means limited to behaviour tree AI. Periodic AI updates (which may be selective, based on what category of AI) are a standard approach to reducing AI processing costs over time. All you need is to implement some interface that cleanly encapsulates the concept of *frequency of update* per AI instance or category. I would suggest something like the strategy pattern, perhaps, called periodically. This would decouple the actual AI update logic from the idea of its being called. It's kind of like saying, "I don't know whether water or mud will come out when I turn that tap handle over there, but I know that it's a tap handle, and when I turn it, something will come out of the nozzle." Likewise, you don't know what a given AI will do, you only want to make sure it does its job. For this reason, the strategy pattern has a standard zero-args `execute` method which allows you to apply some action generically, without worrying about different function names or arguments. It's a "one size fits all" method call.

**Actions vs. Behaviours**

Your current thoughts on this are sound, particularly separating out the action list to maintain the necessary conceptual distinction.
> 1 votes

---
Tags: ai, behavior
---


# Question
Title: Complex, yet simple crafting system model
I'm working on some arcade shooter/slasher, and the main logline is "Kick'em with everything you want". There's not so many enemies in GDD, main focus is on tons of weapons and gadgets to cause mayhem. To get weapon, you need to craft it, and now crafting system looks simple, like:

1) You got three slots for weapon parts (like A, B, C) 2) You collect misc weapon parts, and when you got atleast one for every slot, you can craft a weapon (for example, if you got A1, B1, B2, B3 and C1, you can craft such models - A1B1C1, A1B2C1, A1B3C1)

As for me, this crafting system is too simple, because weapon parts will just fall from the top of screen, often enough. That's why I'm thinking about adding some more crafting system levels, like resources (collect 10 scrap pieces to make part A1 or C3), etc.

My question is: How can i add some more complex, still simple, transparent levels in crafting system?

upd. For example, in Minecraft or Terraria, first 5-10 crafting recipies quite transparent and simple IMHO. But then it turns into huge mess to understand, how to craft this or that (for example, fishing rod)

upd. Okay, somehow i've figured out mechanics like this: 1) Player gather resources (while playing game, automatic gathering from loot) 2) When there's enough resources to craft some weapon part, dedicated icon flashes, so player can craft weapon part in one click (automatic crafting) 3) Having several weapon parts, player can adjust different parts to create weapon (manual crafting)

I think, this will be complex and simple enough, now over-weighted by to many buttons and receipes, still, enough of freedom and manual creativity, trying to mix this and that.

# Answer
> 1 votes
I feel like your approach of adding levels points in the right direction. I one implemented a similiar system with generic crafting parts.

Like a sword need a *hilt*, a *core* and a *blade* / a gun needs a *handle*, a *barrel* and a *muzzle*. Each of this **components** is defined by **materials**, like the hilt need 1 *metal* and 2 *wood* or *leather* and so on. The player can then combine raw materials to get different components (like a wooden hilt or a leather hilt) and combine these components into a weapon.

This approach will allow you to have a **small defined set of reciepes** with quite **a lot outcomes**. You can then extend the system by addind some special reciepes (like hilt with a gem slot in it for extra elemental damage \[*ruby = fire, onyx = earth and so on*\]).

Hope this gets you started with the general idea, feel free to comment if you got questions.

---
Tags: game-design
---


# Question
Title: Fair dice over network w/o trusted 3rd party
Though it should be a pretty basic problem, I did not find a solution for it: *How to play dice over a network without a trusted third party?*

The *M* players shall roll *N* dice, one player after another. No player may "cheat", i.e. change the outcome to his advantage, or "look into the future" before the next roll.

Is that possible?

---

I guess the solution would be something like public key crypto, where each player turns in an encrypted message. After all messages were collected you exchange the keys to decode the messages. Then the `sha1(joined string of all decrypted messages) mod 6 + 1` is used to determine the die.

The major problem I have: since the message \[c/s\]hould be anything, I don't know how to prevent tampering with the private keys. Esp. the last player to turn in his key could easily cheat (I guess).

The game should even stay fair, if all players "conspire" against one player.

# Answer
## Combining Randomness

You need an algorithm that allows each player to contribute to the final random number in such a way that he can change the final outcome to every possible value, whatever the others have contributed to the random number. This way, even all other players may try to work together against a single player, but can not decide the outcome (or in any way influence it).

How to do that? Imagine we want simulate a dice of 6 sides. If we play alone, we use a random number generator that outputs a large random number r. Then we get the final value by calculating `result = (r mod 6)+1`. The same works for multiple players, that role their dice individually. Imagine you have a box (or urn). Every player runs its random number generator (concealed) and writes that number (r1, r2, r3, ... rn) on a sheet of paper and puts it into the box. Now the players take all the numbers out of the box and calculate their sum to generate the groups random number `r = r1+r2+r3+r4+...+rn`. This one is used to calculate the result using `result = (r mod 6)+1`. If the other players would cheat (by working together), a single player could still change the result to any value.

Why is that the case? Imagine we had 3 players. Player 1 and Player 2 try to cheats and work together against Player 3. Player 1 and Player 2 only contribute `r1` and `r2` to the sum `r`. So what they can decide is what the result of `r1+r2`. The value `((r1+r2+r3) mod 6) + 1` is the same as `(((r1 mod 6) + (r2 mod 6) + (r3 mod 6)) mod 6) + 1`. As Players 1 and 2 may decide r1 and r2 they can decide the part `(r1 mod 6) + (r2 mod 6)` let us call this one `c`. The final result is then `((c + (r3 mod 6)) mod 6) + 1`.

So whatever players 1 and 2 are trying r3 can change the result to any value from 1 to 6 without changing the probabilities. If you do not believe it, try c = 0 and r3 = 0 .. 5, which gives you the result 1 to 6. Try c = 1 and r3 = 0 .. 5, it will give you the results 2,3,4,5,6,1. Try c = 2, r3 = 0 .. 5. You'll get: 3,4,5,6,1,2.

To depict this phenomena imagine a Wheel of Fortune of a game show. It has 6 zones (0, 1, 2, 3, 4, 5) that lock in "digitally". You can push a button to turn it one zone forward (from 0 to 1, from 1 to 2, from 2 to 3, ... from 5 to 0 and so on). The Game starts with the wheel at position "0" and each player is writing down (concealed) any positive number. Now they must put away the pencils, so anyone can change the number and each player must show all others his number. Now each player pushes the button as many times as he has written down on his sheet of paper. And we get our final random number (0..5). This game would take very long and would be very annoying, if we would not remember to following: each 6 times the button is pressed the wheel is again at the same position. So each player may just calculate his number "mod 6" and push the button and turn the wheel forward that many times. The result is obviously the same. Or as a formula: `(r1+r2+r3) mod 6 = ((r1 mod 6) + (r2 mod 6) + (r3 mod 6)) mod 6`.

## Exchanging Values

Now over a network we don't have a "box" to put in the random values of the player (trusted third party). We also can't check the players have put their pencils away. So we need another algorithm for that.

Kolrabi already explained it. You can let calculate a hash value (e.g. SHA1 hash) of the random value by each player first. Then they all have to release their hash value to the others. If you do it correctly, nobody can just "quickly" calculate the random number from that. So nobody can just take the hash of the others to change the final result in a deterministic way (Imagine: he is the last player and he just spins the wheel forward by his number of times. But he doesn't know what the position of the wheel is when he starts to turn it - so he can not decide the outcome).

If everyone has got the hashes of all others, everyone checks that he got the same hashes from all the others. Don't know if this is really needed. But, afterwards everyone has the the same hashes.

Now, exchange the random numbers. Everyone checks, that the numbers match to the hash value (by calculating the hash values of all numbers and checking that they are equal to the hashes that the player had exchanged before).

If there was no problem above (all had exchanged the hashes correctly, hashes match the random values) you can calculate the result by summing up the random values and calculating "mod x" + 1, which gives you the result of a dice with x sides. This result should be (I'm not a cryptograph) random evenly distributed as long as at least one player used a random number generator that generates evenly distributed values.

## What means "If you do it correctly"?

You must prevent that any player may calculate the random values from the hashes. There exist at least two ways how a player could do that:

1. He just tries through all values 0, 1, 2, 3... and calculates the hashes. If the hash matches, he has found the value for the hash. To prevent this approach to have success, your random number range should be very large (not just 0 to 5 or 0 to 65535, which a player could just quickly check out within short time). A 32 bit number should be fine. This is why the players should exchange the raw random number generator output and not the value "mod 6". If your random number generator does not give you that huge values generate multiple random numbers and combine them to a single big number (use bit-shift operations to combine them; ask, if you need to do that and don't know how to do it... its important to do this right!). But, in most cases the random value range of the generator is big enough...
2. The second method would be to use a lookup table. If you know that the numbers are within a special range you could calculate all the hashes in advance and store them into a database, sorted alphabetically. Later you could just look up the hash to get the value. To prevent this, you can do two things: a) the number range (as above) must be very large so that it becomes impossible to store such a database. b) exchange a random string (contributed in parts by all players, doesn't need to be concealed) in each new round. That random string is to be appended to all the values when calculating the hashes. So you can't build a database before you know this random string - or you had to build a database for any such random string, which would need even more computational power and storage.

Another possibility to cheat would be to "change" the random number to another number that matches has the same hash value. The approach would be the same as above. While in most cases it is very hard to find another number that has the same hash value, this could be pre-calculated, if you just use the hash of the number. Therefore, you should exchange that random prefix (or suffix) string that has to be added when calculating the hash value. I'm not 100%ly sure, but I remember there was some technique for the MD5 hashing algorithm to quickly calculate other matching values for the same hash, if you are given a value that results in that hash. So better don't use MD5. I don't know about this kind of attack for SHA1, but there might be one. At least make sure the hashing algorithm has no known weakness of that kind -or- the calculation at least takes very long.

If you have done the above right, you should further improve the security of the method by limiting the time for the exchange of the hashes and values. Only if the exchange is executed within some time limit, it should be valid. This ensures, that neither party has enough time to apply one of the above 'hacks'. If it takes too long the procedure must be repeated.

## What still needs to be solved

One of the parties may still be able to influence the outcome by applying the above techniques. In most cases (e.g. 99,99999% of the cases depending on parameters) the time will be too short. But, given enough chances one party might be lucky to break the hashing. For example, a Player could just randomly try out numbers to find another "random" value with the same hash value he had send to the other players (last approach) for as long as possible (to not let the timeout catch him). Especially, if the player lets all the others send him their random values first, he would know what kind of values would give him the biggest win. So he could just try these ones. The evil player then would either let everything time out and restart (to get another chance without loosing) or just lets the game go on and use the next dice round for another try. You could decide, that if a player doesn't deliver its hash or random value within the timeout would automatically loose. So this reduces the problem, but it still increases the chance of a player by some very very small amount.

This weakness is especially critical, if this very small amount of additional chance is enough to disturb... For example if one player could this way decide a complex outcome and wins a lot of money. For imagination, assume you apply this algorithm to a lottery game where one of the "players" is the Bank-Server. We ignore for the moment that if we have a lot of players the amount of data transfer would be not realistic (each person had to tell all other person, its hash and random value; which resulted in N\*(N-1)/2 messages needed to be exchanged, which is over 1 Million for just N=2000 players and increases quadratically). Okay, back to the issue. If just one player would "break" his hash and is able to decide the outcome, he could illegally win some Million Dollars from the Jack Pot... Got it?

If you have such a critical application, you must calculate the chance, that at least one player cracks his hash code within the time. Then multiply this by the maximum possible win of all players, not under your control (e.g. the bank player is trustworthy). This would give you the maximum loss per round. In the lottery example, the lottery bank would loose this much money per round, if all players would try to cheat. The lottery chances therefore would need to be adapted in a way -or- the probability of a successful 'hack' must be further reduced.

To reduce the probability you can: a) reduce the timeout time, b) use a more complicated hashing function, c) use longer numbers, OR: d) distribute the outcome over multiple rounds.

Distributing the outcome over multiple rounds would work by only deciding -a part- of the "result" within one round and executing multiple rounds. For the lottery example, each number could have its own round. This way, a lucky cheater would only had the possibility to change one number each time he manages to break the hash. So he would have to have luck 6 times in a row (if the lottery is selecting 6 numbers) to illegally win the jackpot. WARNING: Each round should only influence one special part of the outcome (e.g. one of the numbers in the lottery). Do not just exchange multiple random values / hashes and sum them up, as before. If you do this a player having luck in the last round would be able to change the whole outcome (!). But, for example, you could do one round for each "bit" of a random number.

Another problem to take care of is, that one player may "disturb" the game by letting the whole thing time out over and over again. This might be a problem, if players are anonymous and you cannot just bann people who do not play fair.

OK, I hope this covers all problems and attacks ...

Good luck ;-)
> 7 votes

# Answer
It should be possible. At least the "tamper detection" part of it.

You will need:

1. A good cryptography strength random number generator, creating random numbers that are hard to predict or to guess.
2. A good hashing algorithm, relatively slow to bruteforce, hard to reverse.

Then I propose the following algorithm.

1. Have every client commit to a random number. Make it a sufficiently long one so it is hard for an attacker to try every possible value. Maybe the length of the output of your hash algorithm.
2. Have every client broadcast to every other client a hash of that number.
3. Repeat steps 1 and 2 for how many dice rolls you need.
4. Have every client broadcast to every other client their random numbers.
5. If a client "changed their mind" about their number, the hashes won't match their numbers.
6. Use only "good" numbers that match their hashes for generating the outcome of the rolls.

That way no client knows the result of a roll before sending their numbers, cannot predict what numbers would change the outcome. They can invalidate their own numbers but it won't do them any good.

If at least one client is honest and the random number generator is good, it will be possible to arrive at a fair roll. If everyone is cheating however, it will not be. But in that case nobody wants to play a fair game anyway.

What this cannot avoid, though, is a client pretending the outcome of a roll is a different one than it really is. If they are refusing reality there isn't really much you can do.
> 3 votes

# Answer
When a random number needs to be generated, have each player generate a random string.

Each player creates a cryptographic signature of their strings, and sends it to all other players. After all players acknowledged that they received the signatures, the strings themself are sent to all players.

All players now verify the signatures, concatenate these strings, and create a hash of it using a cryptographically secure hash function.

This hash is then used to generate the random number.

As long as at least one player contributes an unpredictable string to the total hash, the result is unpredictable. The only possible attack scenario would be when one of the players can predict what random string the others will produce. That's the reason for exchanging the signatures first: When the signatures are exchanged beforehand, a player can't wait for the others to send their strings and then generate a string which would result in a favorable result.
> 0 votes

# Answer
maybe let 2 clients have his own random seed the other clients don't know, when you need a new random number all the clients generate a number then you add all those for a shared seed make a the final random number.
> -1 votes

---
Tags: networking, random, anti-cheat
---


# Question
Title: How do I get information about the level to the player object?
I have a design problem with my Player and Level class in my game.

So below is a picture of the game. The problem is I don't want to move on the black space and only the white space. I know how to do this as all I need to do is get the check for the sf::Color::Black and I have methods to do this in the Level class. The problem is this piece of code

```
   void Game::input()
{
    player.input();
}

void Game::update()
{
    (*level).update();
    player.update();
}

void Game::render()
{
    (*level).render();
    player.render();
}

```

So as you there is a problem in that how do I get the map information from the Level class to the Player class.

Now I was thinking if I made the Player position static and pass it into the Level as parameter in update I could do it. The problem is interaction. I don't know what to do. I could maybe make player go into the Level class. However, what if I want multiple levels?

So I have big design problems that I'm trying to solve.

# Answer
> 0 votes
> Now I was thinking if I made the Player position static and pass it into the Level as parameter in update I could do it. The problem is interaction. I don't know what to do. I could maybe make player go into the Level class. However, what if I want multiple levels?

If I understood your problem correctly, your problem is, that your player has no position on the map, if you do this. And this causes your problem with interactions, right?

The players position should never be "static". Only its position on the screen. To achieve this you should set the View port position (= camera position) relative to your players position. So the background scrolls, while the player stays at the middle of the screen.

This way you have a position of your player, relative to the map. You also have positions of things you can interact with, also relative to the map. Thus, you can implement collision / proximity detection or whatever you like easily.

## EDIT #1

As you changed your questions title, I assume another possible problem. If you want the player class to get access your map...

Let us have a look at your code here...

```
void Game::update()
{
    (*level).update();
   player.update();
}

```

In this case your player.update should have the parameter "level".

```
void Game::update()
{
    (*level).update();
   player.update(level);
}

```

That's it.... the player can then access the level data.

---
Tags: c++, sfml
---


title: Normal maps red in OpenGL?

text:
# Question
Title: Normal maps red in OpenGL?
I am using Assimp to import 3d models, and FreeImage to parse textures.

The problem I am having is that the normal maps are actually red rather than blue when I try to render them as normal diffuse textures.

When I open the images in a image-viewing program they do indeed show up as blue.

Heres when I create the texture;

```
OpenGLTexture::OpenGLTexture(const std::vector<uint8_t>& textureData, uint32_t textureWidth, uint32_t textureHeight, TextureType textureType, Logger& logger) : mLogger(logger), mTextureID(gNextTextureID++), mTextureType(textureType)
{
    glGenTextures(1, &mTexture);
    CHECK_GL_ERROR(mLogger);

    glBindTexture(GL_TEXTURE_2D, mTexture);
    CHECK_GL_ERROR(mLogger);

    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, textureWidth, textureHeight, 0, glTextureFormat, GL_UNSIGNED_BYTE, &textureData[0]);
    CHECK_GL_ERROR(mLogger);

    glGenerateMipmap(GL_TEXTURE_2D);
    CHECK_GL_ERROR(mLogger);

    glBindTexture(GL_TEXTURE_2D, 0);
    CHECK_GL_ERROR(mLogger);
}

```

Here is my fragment shader. You can see I just commented out the normal-map parsing and treated the normal map texture as the diffuse texture to display it and illustrate the problem. As for the rest of the code it interacts as expected with the diffuse textures so I dont see a obvious problem there.

```
"#version 330                                                                                \n \
                                                                                \n \
layout(std140) uniform;                                                                                \n \
                                                                                \n \
const int MAX_LIGHTS = 8;                                                                                \n \
                                                                                \n \
struct Light                                                                                \n \
{                                                                                \n \
    vec4  mLightColor;                                                                                \n \
    vec4  mLightPosition;                                                                                \n \
    vec4  mLightDirection;                                                                                \n \
                                                                                \n \
    int   mLightType;                                                                                \n \
    float mLightIntensity;                                                                                \n \
    float mLightRadius;                                                                                \n \
    float mMaxDistance;                                                                                \n \
};                                                                                \n \
                                                                                \n \
uniform UnifLighting                                                                                \n \
{                                                                                \n \
    vec4  mGamma;                                                                                \n \
    vec3  mViewDirection;                                                                                \n \
    int   mNumLights;                                                                                \n \
                                                                                \n \
    Light mLights[MAX_LIGHTS];                                                                                \n \
} Lighting;                                                                                \n \
                                                                                \n \
uniform UnifMaterial                                                                                \n \
{                                                                                \n \
    vec4  mDiffuseColor;                                                                                \n \
    vec4  mAmbientColor;                                                                                \n \
    vec4  mSpecularColor;                                                                                \n \
    vec4  mEmissiveColor;                                                                                \n \
                                                                                \n \
    bool  mHasDiffuseTexture;                                                                                \n \
    bool  mHasNormalTexture;                                                                                \n \
    bool  mLightingEnabled;                                                                                \n \
    float mSpecularShininess;                                                                                \n \
} Material;                                                                                \n \
                                                                                \n \
uniform sampler2D unifDiffuseTexture;                                                                               \n \
uniform sampler2D unifNormalTexture;                                                                                \n \
                                                                                \n \
in vec3 frag_position;                                                                                \n \
in vec3 frag_normal;                                                                                \n \
in vec2 frag_texcoord;                                                                                \n \
in vec3 frag_tangent;                                                                                \n \
in vec3 frag_bitangent;                                                                                \n \
                                                                                \n \
out vec4 finalColor;                                                                                "
                                                                                "         \n \
                                                                                \n \
void CalcGaussianSpecular(in vec3 dirToLight, in vec3 normal, out float gaussianTerm)                                               \n \
{                                                                                \n \
    vec3 viewDirection = normalize(Lighting.mViewDirection);                                                        \n \
    vec3 halfAngle     = normalize(dirToLight + viewDirection);                                                     \n \
                                                                                \n \
    float angleNormalHalf = acos(dot(halfAngle, normalize(normal)));                                           \n \
    float exponent        = angleNormalHalf / Material.mSpecularShininess;                                          \n \
    exponent              = -(exponent * exponent);                                                                 \n \
                                                                                \n \
    gaussianTerm = exp(exponent);                                                                                \n \
}                                                                                \n \
                                                                                \n \
vec4 CalculateLighting(in Light light, in vec4 diffuseTexture, in vec3 normal)                                                      \n \
{                                                                                \n \
    if (light.mLightType == 1)          // point light                                                              \n \
    {                                                                                \n \
        vec3 positionDiff = light.mLightPosition.xyz - frag_position;                                                   \n \
        float dist        = max(length(positionDiff) - light.mLightRadius, 0);                                          \n \
                                                                                \n \
        float attenuation = 1 / ((dist/light.mLightRadius + 1) * (dist/light.mLightRadius + 1));                        \n \
        attenuation       = max((attenuation - light.mMaxDistance) / (1 - light.mMaxDistance), 0);                      \n \
                                                                                \n \
        vec3 dirToLight   = normalize(positionDiff);                                                                    \n \
        float angleNormal = clamp(dot(normalize(normal), dirToLight), 0, 1);                                       \n \
                                                                                \n \
        float gaussianTerm = 0.0;                                                                                \n \
        if (angleNormal > 0.0)                                                                                \n \
            CalcGaussianSpecular(dirToLight, normal, gaussianTerm);                                                                               \n \
                                                                                \n \
        return diffuseTexture * (attenuation * angleNormal  * Material.mDiffuseColor  * light.mLightIntensity * light.mLightColor) +      \n \
                                (attenuation * gaussianTerm * Material.mSpecularColor * light.mLightIntensity * light.mLightColor);       \n \
    }                                                                                \n \
    else if (light.mLightType == 2)     // directional light                                                                              \n \
    {                                                                                \n \
        vec3 dirToLight   = normalize(light.mLightDirection.xyz);                                                                         \n \
        float angleNormal = clamp(dot(normalize(normal), dirToLight), 0, 1);                                                         \n \
                                                                                \n \
        float gaussianTerm = 0.0;                                                                                \n \
        if (angleNormal > 0.0)                                                                                \n \
            CalcGaussianSpecular(dirToLight, normal, gaussianTerm);                                                             \n \
                                                                                \n \
        return diffuseTexture * (angleNormal  * Material.mDiffuseColor  * light.mLightIntensity * light.mLightColor) +  \n \
                                (gaussianTerm * Material.mSpecularColor * light.mLightIntensity * light.mLightColor);   \n \
    }                                                                                \n \
    else if (light.mLightType == 4)     // ambient light                                                            \n \
        return diffuseTexture * Material.mAmbientColor * light.mLightIntensity * light.mLightColor;                 \n \
    else                                                                                \n \
        return vec4(0.0);                                                                                \n \
}                                                                                \n \
                                                                                \n \
void main()                                                                                \n \
{                                                                                \n \
    vec4 diffuseTexture = vec4(1.0);                                                                                \n \
    if (Material.mHasDiffuseTexture)                                                                                \n \
        diffuseTexture = texture(unifDiffuseTexture, frag_texcoord);                                                \n \
                                                                                \n \
    vec3 normal = frag_normal;                                                                                \n \
    if (Material.mHasNormalTexture)                                                                                \n \
    {                                                                                \n \
        diffuseTexture = vec4(normalize(texture(unifNormalTexture, frag_texcoord).xyz * 2.0 - 1.0), 1.0);  \n \
       // vec3 normalTangentSpace  = normalize(texture(unifNormalTexture, frag_texcoord).xyz * 2.0 - 1.0);            \n \
        //mat3 tangentToWorldSpace = mat3(normalize(frag_tangent), normalize(frag_bitangent), normalize(frag_normal)); \n \
                                                                                \n \
       // normal = tangentToWorldSpace * normalTangentSpace;                                                              \n \
    }                                                                                \n \
                                                                                \n \
    if (Material.mLightingEnabled)                                                                                \n \
    {                                                                                \n \
        vec4 accumLighting = vec4(0.0);                                                                             \n \
                                                                                \n \
        for (int lightIndex = 0; lightIndex < Lighting.mNumLights; lightIndex++)                                    \n \
            accumLighting += Material.mEmissiveColor * diffuseTexture +                                             \n \
                                CalculateLighting(Lighting.mLights[lightIndex], diffuseTexture, normal);                       \n \
                                                                                \n \
        finalColor = pow(accumLighting, Lighting.mGamma);                                                           \n \
    }                                                                                \n \
    else {                                                                                \n \
        finalColor = pow(diffuseTexture, Lighting.mGamma);                                                          \n \
    }                                                                                \n \
}                                                                                \n";

```

Why is this? does normal-map textures need some sort of special treatment in opengl?

# Answer
The bitmaps might be getting loaded in BGRA format instead of RGBA. Windows .bmp files are always stored in BGRA order, for example. If that's the case, you just need to tell OpenGL so, by passing `GL_BGRA` instead of `GL_RGBA` in your `glTexImage2D` call.
> 7 votes

# Answer
If you just want to view the normal map as any image-viewer would, you should remove the transformation from \[0,1\] to \[-1,1\] done by `texture(...).xyz * 2 - 1.0` and also skip the normalization. Try using the texture like this:

```
diffuseTexture = vec4(texture(unifNormalTexture, frag_texcoord).xyz, 1.0);

```

If you aren't already aware of it, that transformation is done with normal maps, because normal vectors can of course contain negative entries, but you don't want to store negative values in the texture files. Therefore, normal vectors are mapped to a range of \[0,1\] for storage, and have to be remapped to the original range when used for lighting calculations.
I suspect that, by doing transformation to the \[-1,1\] range, in your case the green and/or blue color channels are mapped to negative values and are therefore considered 0 by the fragment shader output. Only the red channel remains visible, which would explain the red texture you see.
To make things worse, the normalization will produce a unit vector, further distorting the color of the texture, e.g. some vector like (0.4,-0.3,0.0) should be normalized to (0.8,-0.6,0.0), further increasing the intensity of the red channel while the green channel is still clipped to 0 and you end up with a rather bright red color.
> 2 votes

---
Tags: c++, opengl, normal-mapping
---


# Question
Title: What is required for casting shadows in JavaFX 8 3D?
In a scene with an added point light the shapes are not casting shadows on each other. Is anything required to cause them to cast shadows?

# Answer
There is nothing in the latest distribution of JavaFX that would suggest a 3D shadow middleware being incorporated in Java3D. See here for the reference. The DropShadow classes are unrelated.

Java3D is not in the business of implementing game/model engine implementations for you. Light and shadows are among the most complex topics in 3D graphics programming, and the chosen algorithm should meet your task requirement.

Here would be a code-start for the absolute simplest of cases.

I hope this helps.
> 2 votes

---
Tags: java, 3d, shadows
---


# Question
Title: isometric background that covers the viewport
The technique I use now is a loop with an innerloop that draws images on a canvas element, but it looks like a rotated square.

This is a nice example that covers the whole viewport.

I have read something vague about clickthrough maps? What kind of techniques are there that are most efficient with mobile devices and javascript?

Edit

I other words, howto create a grid, in HTML5 that looks like the picture above, where you can place elements on. ( in the picture, it is the garden ) If it's not isometric, what is it and can it be created in html5. What I use now, creates a repititive background.

```
function draw() {

    c.clearRect(0, 0, canvas.width, canvas.height);

    for (var row = 0; row < 10; row++) {
        for (var col = 0; col < 10; col++) {

            var tilePositionX = (row - col) * tile.height;

            // Center the grid horizontally
            tilePositionX += (canvas.width / 2) - (tile.width / 2);

            var tilePositionY = (row + col) * (tile.height / 2);

            if (tileMap[row] != null && tileMap[row][col] != null) {
                tilePositionY -= tileMap[row][col].height - tile.height;
                tilePositionX -= (tileMap[row][col].width / 2) - (tile.width / 2);

                if (!(tileMap[row][col] instanceof BuildingPortion)) {
                    c.drawImage(tileMap[row][col].texture, Math.round(tilePositionX), Math.round(tilePositionY), tileMap[row][col].width, tileMap[row][col].height);
                }
            } else {
                c.drawImage(tile, Math.round(tilePositionX), Math.round(tilePositionY), tile.width, tile.height);
            }
        }
    }
}
}

```

thanks

# Answer
> 2 votes
I am not sure how this:

> *but it looks like a rotated square*

connects to the picture you are showing us.

> *If it's not isometric, what is it*

It is an *axonometric projection*. If you would rotate the X,Y,Z axis of your hypothetical or rendered 3D \[tiled\]-world equally it would be an *isometric projection*.

HTML5 offers many methods of implementation with different end-goals. You have settled for a resolution-dependent bitmap canvas render. A well performing choice.

Assuming with *click-through* you are referring to the z-index dependent mouse-event handling, then you have just pinpointed one of the draw backs of HTML5 canvas, from a developer's perspective: You will have to implement all the meta information for your objects and event-handling yourself.

At this point I would **recommend using an existing JavaScript tiling / game engine**. The goal of making a 2D Tiling engine sounds easy but as you point out efficient implementation with proper input event handling is more difficult than meets the eye.
For instance you would likely require translating inputs from the device's viewpoint to the game-world's view.

Here are **recommendations of 2D JavaScript Game Engines**:

---
Tags: tiles, isometric
---


# Question
Title: glm quaternion camera rotating on wrong axis
I'm trying to get my camera implemented with a `glm::quat` used to store the rotation.

However, whenever I do circles with the mouse, the camera rotates along the axis I am viewing (i.e. I think it's called the target axis). For example, if I rotated the mouse in a clockwise fashion, the camera rotates clockwise around the axis.

I initialize my quaternion like so:

```
void Camera::initialize()
{
    orientationQuaternion_ = glm::quat();
    orientationQuaternion_ = glm::normalize(orientationQuaternion_);
}

```

I rotate like so:

```
void Camera::rotate(const glm::detail::float32& degrees, const glm::vec3& axis)
{
    orientationQuaternion_ = orientationQuaternion_ * glm::normalize(glm::angleAxis(degrees, axis));
}

```

and I set the viewMatrix like so:

```
void Camera::render()
{
    glm::quat temp = glm::conjugate(orientationQuaternion_);

    viewMatrix_ = glm::mat4_cast(temp);
    viewMatrix_ = glm::translate(viewMatrix_, glm::vec3(-pos_.x, -pos_.y, -pos_.z));
}

```

The only axis' I actually try to rotate are the X and Y axis (i.e. (1,0,0) and (0,1,0)).

Here is a video of what is going on: Camera weird rotation

Anyone have any idea why I see my camera rotating around the target axis?

**EDIT**

I added some debug output for the values that are getting calculated.

First entry is the initialized quaternion, calculated with

```
std::cout << "quat initialized: " << glm::to_string(glm::eulerAngles(orientationQuaternion_)) << std::endl;

```

Then I output (in the `rotate` method) the before and after quaternion, and also the rotation. I output them with:

```
void Camera::rotate(const glm::detail::float32& degrees, const glm::vec3& axis)
{
    std::cout << "orientation before: " << glm::to_string( glm::eulerAngles(orientationQuaternion_) ) << std::endl;

    orientationQuaternion_ = glm::normalize(orientationQuaternion_) * glm::normalize(glm::angleAxis(degrees, glm::normalize(axis)));
    orientationQuaternion_ = glm::normalize(orientationQuaternion_);

    std::cout << "rotation: " << glm::to_string( glm::eulerAngles(glm::angleAxis(degrees, axis)) ) << std::endl;
    std::cout << "orientation after: " << glm::to_string( glm::eulerAngles(orientationQuaternion_) ) << std::endl;
}

```

Here's the output data:

```
quat initialized: fvec3(0.000000, -0.000000, 0.000000)

orientation before: fvec3(0.000000, -0.000000, 0.000000)
rotation: fvec3(-0.363636, -0.000000, 0.000000)
orientation after: fvec3(-0.363636, 0.000000, 0.000000)

orientation before: fvec3(-0.363636, 0.000000, 0.000000)
rotation: fvec3(0.000000, -0.545454, 0.000000)
orientation after: fvec3(-0.363653, -0.545444, 0.003462)

orientation before: fvec3(-0.363653, -0.545444, 0.003462)
rotation: fvec3(-4.909091, -0.000000, 0.000000)
orientation after: fvec3(-5.272744, -0.545443, 0.003462)

orientation before: fvec3(-5.272744, -0.545443, 0.003462)
rotation: fvec3(0.000000, 5.272728, 0.000000)
orientation after: fvec3(-5.290381, 4.704929, -0.482044)

orientation before: fvec3(-5.290381, 4.704929, -0.482044)
rotation: fvec3(13.272726, -0.000000, 0.000000)
orientation after: fvec3(7.982345, 4.704931, -0.482044)

orientation before: fvec3(7.982345, 4.704931, -0.482044)
rotation: fvec3(0.000000, 6.909091, 0.000000)
orientation after: fvec3(8.120677, 11.546086, 0.494900)

orientation before: fvec3(8.120677, 11.546086, 0.494900)
rotation: fvec3(7.636363, -0.000000, 0.000000)
orientation after: fvec3(15.757041, 11.546085, 0.494900)

orientation before: fvec3(15.757041, 11.546085, 0.494900)
rotation: fvec3(0.000000, 10.181817, 0.000000)
orientation after: fvec3(16.596092, 21.327044, 3.448837)

orientation before: fvec3(16.596092, 21.327044, 3.448837)
rotation: fvec3(6.181818, -0.000000, 0.000000)
orientation after: fvec3(22.777910, 21.327044, 3.448836)

orientation before: fvec3(22.777910, 21.327044, 3.448836)
rotation: fvec3(0.000000, 12.000000, 0.000000)
orientation after: fvec3(25.255577, 32.297348, 8.913291)

orientation before: fvec3(25.255577, 32.297348, 8.913291)
rotation: fvec3(3.636364, -0.000000, 0.000000)
orientation after: fvec3(28.891941, 32.297352, 8.913290)

orientation before: fvec3(28.891941, 32.297352, 8.913290)
rotation: fvec3(0.000000, 12.727273, 0.000000)
orientation after: fvec3(34.057663, 43.175217, 17.306284)

orientation before: fvec3(34.057663, 43.175217, 17.306284)
rotation: fvec3(0.363636, -0.000000, 0.000000)
orientation after: fvec3(34.421299, 43.175220, 17.306288)

orientation before: fvec3(34.421299, 43.175220, 17.306288)
rotation: fvec3(0.000000, 5.636363, 0.000000)
orientation after: fvec3(37.799271, 47.732010, 22.041012)

orientation before: fvec3(37.799271, 47.732010, 22.041012)
rotation: fvec3(-0.909091, -0.000000, 0.000000)
orientation after: fvec3(36.890179, 47.732010, 22.041016)

orientation before: fvec3(36.890179, 47.732010, 22.041016)
rotation: fvec3(0.000000, 12.545454, 0.000000)
orientation after: fvec3(47.936203, 57.054291, 35.913132)

orientation before: fvec3(47.936203, 57.054291, 35.913132)
rotation: fvec3(-10.727273, -0.000000, 0.000000)
orientation after: fvec3(37.208916, 57.054287, 35.913124)

orientation before: fvec3(37.208916, 57.054287, 35.913124)
rotation: fvec3(0.000000, 2.000000, 0.000000)
orientation after: fvec3(39.175983, 58.626469, 38.236393)

orientation before: fvec3(39.175983, 58.626469, 38.236393)
rotation: fvec3(-4.909091, -0.000000, 0.000000)
orientation after: fvec3(34.266888, 58.626469, 38.236393)

orientation before: fvec3(34.266888, 58.626469, 38.236393)
rotation: fvec3(0.000000, 1.272727, 0.000000)
orientation after: fvec3(35.485283, 59.670666, 39.655521)

orientation before: fvec3(35.485283, 59.670666, 39.655521)
rotation: fvec3(-10.181816, -0.000000, 0.000000)
orientation after: fvec3(25.303461, 59.670673, 39.655521)

```

It almost looks like a rounding error? I'm not sure. I tried normalizing the quaternion during and after the calculation, but it didn't help...

**EDIT** \- **Solution**

Changed the `rotate(..)` method to this:

```
void Camera::rotate(const glm::detail::float32& degrees, const glm::vec3& axis)
{
    if ( axis == glm::vec3(0.0f, 1.0f, 0.0f) )
        orientationQuaternion_ =  glm::normalize(glm::angleAxis(degrees, axis)) * orientationQuaternion_;
    else
        orientationQuaternion_ = orientationQuaternion_ * glm::normalize(glm::angleAxis(degrees, axis));
}

```

Still have some work to do here, but it seems to fix the problem from before.

# Answer
Your camera (and every object with a transform) has its own local space axes, which will usually not be the same as the world axes. Transforming around the world-space axis will give a different result than transforming around a local-space axis. Cameras typically need to work with both.

You usually want to rotate a camera horizontally around "world up" and vertically around "camera right" in my experience.
> 2 votes

---
Tags: c++, quaternion, glm
---


# Question
Title: Is it possible to create native application for Google Chrome Store?
I'm developing small game using c++ and OpenGL. I would like to post it also in Chrome Web Store.

I've seen that a lot of apps are just redirection to specific url. I can use Java Applet and JNI to launch it in chrome, but that would be only waste of memory.

# Answer
> 3 votes
For best results, you'll want to create a port of your application. A quick (and probably dirty) way to do that might be using Google native client (allows running natively compiled code in the browser).

Otherwise you'll have to take the long road of porting your code from C++ to Javascript Dart or pure HTML5.

# Answer
> 2 votes
Emscripten is the best way to do this as of today. It can compile pure C++ code into a subset of JavaScript called asm.js which is very efficient and can be even further optimized. As of today only Firefox has explicit optimizations for asm.js, but the compiled code will run (quite well) on every major up-to-date browser (even IE!) and can be used in the Chrome Web Store.

It requires that you use OpenGL ES 2.0 for graphics (since it uses WebGL in the translation, which is roughly equivalent to GLES2). It is easy to use SDL for windowing and input as Emscripten natively supports bindings for that, though some other common toolkits are also supported; for any other libraries you'd need to do the binding yourself. I/O, audio, networking, and so on are supported. Threading is not yet supported but work is underway to handle it.

There are a few small things you need to do for a basic port (especially regarding the main loop, as JavaScript has its own internal main loop you must use) and more advanced applications may need some additional special porting work, but in general it's not too bad.

Note that even big game engines like Unreal have been ported to the Web via Emscripten, so it's very much a viable and production-ready toolset.

There are some other C++-to-JS transpilers out there, but Emscripten is the most well-known and developed right now.

# Answer
> 0 votes
Of course, Google's Webstore policy allows it.

There are many offerings which require an additional native executable to be installed by the user in order to aid the browser extension with information.

---
Tags: web, chrome
---


# Question
Title: AABB vs OBB Collision Resolution jitter on corners
I've implemented a collision library for a character who is an AABB and am resolving collisions between AABB vs AABB and AABB vs OBB. I wanted slopes for certain sections, so I've toyed around with using several OBBs to make one, and it's working great except for one glaring issue; The collision resolution on the corner of an OBB makes the player's AABB jitter up and down constantly. I've tried a few things I've thought of, but I just can't wrap my head around what's going on exactly. Here's a video of what's happening as well as my code:

Here's the function to get the collision resolution (I'm likely not doing this the right way, so this may be where the issue lies):

```
public Vector2 GetCollisionResolveAmount(RectangleCollisionObject resolvedObject, OrientedRectangleCollisionObject b)
{
    Vector2 overlap = Vector2.Zero;
    LineSegment edge = GetOrientedRectangleEdge(b, 0);

    if (!SeparatingAxisForRectangle(edge, resolvedObject))
    {
        LineSegment rEdgeA = new LineSegment(), rEdgeB = new LineSegment();
        Range axisRange = new Range(), rEdgeARange = new Range(), rEdgeBRange = new Range(), rProjection = new Range();
        Vector2 n = edge.PointA - edge.PointB;

        rEdgeA.PointA = RectangleCorner(resolvedObject, 0);
        rEdgeA.PointB = RectangleCorner(resolvedObject, 1);
        rEdgeB.PointA = RectangleCorner(resolvedObject, 2);
        rEdgeB.PointB = RectangleCorner(resolvedObject, 3);
        rEdgeARange = ProjectLineSegment(rEdgeA, n);
        rEdgeBRange = ProjectLineSegment(rEdgeB, n);
        rProjection = GetRangeHull(rEdgeARange, rEdgeBRange);
        axisRange = ProjectLineSegment(edge, n);

        float axisMid = (axisRange.Maximum + axisRange.Minimum) / 2;
        float projectionMid = (rProjection.Maximum + rProjection.Minimum) / 2;

        if (projectionMid > axisMid)
        {
            overlap.X = axisRange.Maximum - rProjection.Minimum;
        }
        else
        {
            overlap.X = rProjection.Maximum - axisRange.Minimum;
            overlap.X = -overlap.X;
        }
    }

    edge = GetOrientedRectangleEdge(b, 1);
    if (!SeparatingAxisForRectangle(edge, resolvedObject))
    {
        LineSegment rEdgeA = new LineSegment(), rEdgeB = new LineSegment();
        Range axisRange = new Range(), rEdgeARange = new Range(), rEdgeBRange = new Range(), rProjection = new Range();
        Vector2 n = edge.PointA - edge.PointB;

        rEdgeA.PointA = RectangleCorner(resolvedObject, 0);
        rEdgeA.PointB = RectangleCorner(resolvedObject, 1);
        rEdgeB.PointA = RectangleCorner(resolvedObject, 2);
        rEdgeB.PointB = RectangleCorner(resolvedObject, 3);
        rEdgeARange = ProjectLineSegment(rEdgeA, n);
        rEdgeBRange = ProjectLineSegment(rEdgeB, n);
        rProjection = GetRangeHull(rEdgeARange, rEdgeBRange);
        axisRange = ProjectLineSegment(edge, n);

        float axisMid = (axisRange.Maximum + axisRange.Minimum) / 2;
        float projectionMid = (rProjection.Maximum + rProjection.Minimum) / 2;

        if (projectionMid > axisMid)
        {
            overlap.Y = axisRange.Maximum - rProjection.Minimum;
            overlap.Y = -overlap.Y;
        }
        else
        {
            overlap.Y = rProjection.Maximum - axisRange.Minimum;
        }
    }

    return overlap;
}

```

And here is what I'm doing to resolve it right now:

```
if (collisionDetection.OrientedRectangleAndRectangleCollide(obb, player.PlayerCollision))
{
    var resolveAmount = collisionDetection.GetCollisionResolveAmount(player.PlayerCollision, obb);

    if (Math.Abs(resolveAmount.Y) < Math.Abs(resolveAmount.X))
    {
        var roundedAmount = (float)Math.Floor(resolveAmount.Y);
        player.PlayerCollision._position.Y -= roundedAmount;
    }
    else if (Math.Abs(resolveAmount.Y) <= 30.0f) //Catch cases where the player should be able to step over the top of something
    {
        var roundedAmount = (float)Math.Floor(resolveAmount.Y);
        player.PlayerCollision._position.Y -= roundedAmount;
    }
    else
    {
        var roundedAmount = (float)Math.Floor(resolveAmount.X);
        player.PlayerCollision._position.X -= roundedAmount;
    }
}

```

Can anyone see what might be the issue here, or has anyone experienced this before that knows a possible solution? I've tried for a few days to figure this out on my own, but I'm just stumped.

Edit: I've added another video that more clearly demonstrates what's going on.

# Answer
> 2 votes
I ended up implementing an AABB/Line Segment collision just to test if it would also have these issues, and i ended up figuring out the problem. It was an issue with my collision resolution.

When the AABB was resting on the corner of an OBB or on the top-most point of a line segment, it was resolving the Y resolution amount using the formula for the line, but was plugging in an X value that was outside of its range.

Here's the line segment/AABB resolution code I ended up going with:

```
public Vector2 GetCollisionResolveAmount(RectangleCollisionObject resolvedObject, LineSegmentCollisionObject line)
{
    Vector2 overlap = Vector2.Zero;
    var topRight = new Vector2(resolvedObject.Position.X + resolvedObject.HalfWidth, resolvedObject.Position.Y - resolvedObject.HalfHeight);
    var topLeft = new Vector2(resolvedObject.Position.X - resolvedObject.HalfWidth, resolvedObject.Position.Y - resolvedObject.HalfHeight);
    var bottomLeft = new Vector2(resolvedObject.Position.X - resolvedObject.HalfWidth, resolvedObject.Position.Y + resolvedObject.HalfHeight);
    var bottomRight = new Vector2(resolvedObject.Position.X + resolvedObject.HalfWidth, resolvedObject.Position.Y + resolvedObject.HalfHeight);

    var leftLinePoint = line.PointA.X < line.PointB.X ? line.PointA : line.PointB;
    var rightLinePoint = line.PointA.X > line.PointB.X ? line.PointA : line.PointB;

    if (leftLinePoint.Y > rightLinePoint.Y) //Line is rotated to the left
    {
        float diffOne = Math.Abs(FindYGivenX(leftLinePoint, rightLinePoint, bottomRight.X) - bottomRight.Y);
        float diffTwo = Math.Abs(FindYGivenX(leftLinePoint, rightLinePoint, topLeft.X) - topLeft.Y);

        if (diffOne < diffTwo) //We're above the line
        {
            if(bottomRight.X > rightLinePoint.X)
                diffOne = Math.Abs(rightLinePoint.Y - bottomRight.Y);
            overlap.Y = diffOne * -1;
        }
        else //We're below the line
        {
            overlap.Y = diffTwo;
        }
    }
    else if (rightLinePoint.Y > leftLinePoint.Y) //Line is rotated to the right
    {
        float diffOne = Math.Abs(FindYGivenX(leftLinePoint, rightLinePoint, bottomLeft.X) - bottomLeft.Y);
        float diffTwo = Math.Abs(FindYGivenX(leftLinePoint, rightLinePoint, topRight.X) - topRight.Y);

        if (diffOne < diffTwo) //We're above the line
        {
            if (bottomLeft.X < leftLinePoint.X)
                diffOne = Math.Abs(leftLinePoint.Y - bottomLeft.Y);

            overlap.Y = diffOne * -1;
        }
        else //We're below the line
        {
            overlap.Y = diffTwo;
        }
    }
    else if (rightLinePoint.X == leftLinePoint.X) //Line is vertically straight
    {
        if (resolvedObject.Position.X < line.PointA.X)
        {
            overlap.X = Math.Abs(topRight.X - line.PointA.X) * -1;
        }
        else
        {
            overlap.X = Math.Abs(line.PointA.X - topLeft.X);
        }
    }
    else //Line is horizontally straight
    {
        if (resolvedObject.Position.Y < line.PointA.Y) //above
        {
            overlap.Y = Math.Abs(bottomLeft.Y - line.PointA.Y) * -1;
        }
        else
        {
            overlap.Y = Math.Abs(topLeft.Y - line.PointA.Y);
        }
    }

    return overlap;
}

```

---
Tags: collision-resolution, separating-axis-theorem, aabb
---


# Question
Title: Make a laser beam effect with Ogre and a BillboardChain
http://www.lpi.usra.edu/lunar/missions/apollo/apollo\_15/images/laser\_beam\_lg.gif

I want to be able to such an effect, but I don't really know how the BillboardChain class works or how I can use it, examples for this class seems to be rare.

# Answer
```
BillboardChain bbchain;
bbchain.addChainElement(BillboardChain::Element(Vector3(0,0,0), 10, 0, ColourValue(1, 0, 0)));

```

The main reason it was not working for me is because I did not set a high enough width.
> 1 votes

# Answer
I have created an impressive laser by using particles, here is an example of what a laser particle script would look like:

```
particle_system Space/Laser
{
    material        Examples/Flare
    particle_width  3
    particle_height 3
    cull_each       false
    quota           1000000
    billboard_type  point
    local_space true

    // Area emitter
    emitter Point
    {
       angle           0
       emission_rate   500
       time_to_live_min 1000
       time_to_live_max 1000
       direction       0 0 -1
       velocity       1000
       colour 1.0 0.27 0.0
    }
}

```

Simply create a particle system using this script, attach to its own node, and toggle visibility on the node to make the laser appear/disappear.

This will create a nice Orange laser beam where you can change the size by editing the particle\_width and particle\_height attributes. To change the length of the laser edit the time\_to\_live\_min and time\_to\_live\_max attributes but make sure they are the same value.

The material Examples/Flare comes with the OgreSDK by default so you don't have to worry about it (It just uses a nice flare image that the particle script will re-color and use).

Be sure to save it as a .particle file
> 2 votes

# Answer
The closest thing I have seen to this effect is this

There is also this thread that asks the exact same question. It only has 3 replies, but probably worth watching (unless of course you asked this question :P)
> 1 votes

---
Tags: sprites, ogre
---