# Question
Title: Mobile Multiplayer games and coping with high latency
I'm currently researching regarding a design for an online (realtime) mobile multiplayer game.

As such, i'm taking into consideration that latencies (lag) is going to be high (perhaps higher than PC/consoles).

I'd like to know if there are ways to overcome this or minimize the issues of high latency?

The model i'll be using is peer-to-peer (using Photon cloud to broadcast messages to all other players).

How do i deal with a scenario where a message about a local object's state at time *t* will only get to other players at \*t + HUGE\_LAG\* ?

# Answer
Part of this is a Technical solution, the other part is a Design solution.

Peer to peer for this sort of thing has some fun drawbacks, especially as you're left with an interesting question of which client is authoritative, especially with lots of players. You can round robin between clients (this is actually useful for anti-cheating), but as everyone's talking to everyone else with different pings, things can get pretty weird.

It's a lot easier to use a server, have the server be authoritative, and have the clients just respond to, and send information to the server. The downside is that you're introducing extra latency on every action, on top of your normal lag.

It really depends on what kind of game you're making.

You're forced into using a asynchronous networking paradigm given the lag, synchronous paradigms (like lockstep) fair badly in high lag situations. This kind of networking is typically used in FPS/Driving and low latency input type situations, and you can easily find a lot of supporting information by looking at how those kind of games deal with their latency hiding. Even if your game *isn't* one of the above, you're going to want to steal how they do their latency hiding.

One of the more common techniques is to have two game *worlds* per client. One is the *client* world, which the user of the game sees. The other is the *real* world, which is as accurate as you can be given the networking data that you have. The trick is to make the *client* world always lerp towards the *real* world. Decision making usually happens on *real* data, although you can use *client* data if you want, but that can get weird fast.

This obviously means that not all clients will have the same data at the same time. At various intervals you're going to want to do a "sync up" between clients (i.e.: send as much of the full game state as you can). Sort of similar to how you get keyframes within video compression playback. You generate the intermediate frames using temporal deltas, but each keyframe is authoritative.

Designing for high latency is just as important as the technical side. Some things are just not possible. It also depends on how bad we're talking about. If you're at around 300ms, you can still get away with some FPS paradigms. If you're over 1 second, forget it, you won't be able to do any sort of on-the-fly targeting, or hit detection.

Games like WoW hide their latency quite well by using a few neat tricks

* Players don't collide with other players. This means it doesn't really matter how accurate your player data is, as it makes no difference to the simulation
* Minimal number of dynamic objects that impact determinism
By limiting the amount of items that are in the world that can possibly impact position/movement, you have far less data to send, and far less objects to lerp/simulate
* No hitscan targeting, because it will be hideously inaccurate and *feel* unfair.

The key is to make the game *feel* responsive, without actually *being* responsive. Having the client act immediately, while waiting on the result from the server/other clients and *designing* for that kind of interaction is why you don't notice the high latency in games like WoW.
> 10 votes

# Answer
I've written at length about this topic here: http://www.gabrielgambetta.com/fpm1.html. It's not exactly your case (this is for an authoritative server and dumb clients, vs your peer-to-peer architecture) but I guess the entity interpolation and server (in htis case, peer) reconciliation may apply.
> 3 votes

---
Tags: architecture, software-engineering, networking, multiplayer, socket
---


# Question
Title: How do I position a 2D camera in OpenGL?
I can't understand how the camera is working. It's a 2D game, so I'm displaying a game map from `(0, 0, 0)` to `(mapSizeX, 0, mapSizeY)`.

I'm initializing the camera as follow :

```
Camera::Camera(void)
  : position_(0.0f, 0.0f, 0.0f), rotation_(0.0f, 0.0f, -1.0f)
{}

void            Camera::initialize(void)
{
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  glTranslatef(position_.x, position_.y, position_.z);
  gluPerspective(70.0f, 800.0f/600.0f, 1.0f, 10000.0f);
  gluLookAt(0.0f, 6000.0f, 0.0f,
            0.0f, 0.0f, -1.0f,
            0.0f, 1.0f, 0.0f);
  glMatrixMode(GL_MODELVIEW);
  glLoadIdentity();
  glEnable(GL_DEPTH_TEST);
  glDepthFunc(GL_LEQUAL);
}

```

So the camera is looking down. I currently see the up right border of the map in the center of my window and the map expand to the down left border of my window. I would like to center the map.

The logical thing to do should be to move the camera to `eyeX = mapSizeX / 2` and the same for z. My map has 10 x 10 cases with `CASE = 400`, so I should have :

```
gluLookAt((10 / 2) * CASE /* = 2000 */, 6000.0f, (10 / 2) * CASE /* = 2000 */,
            0.0f, 0.0f, -1.0f,
            0.0f, 1.0f, 0.0f);

```

But that doesn't move the camera, but seems to rotate it.

Am I doing something wrong?

**EDIT :**

I tried that:

```
gluLookAt(2000.0f, 6000.0f, 0.0f,
            2000.0f, 0.0f, -1.0f,
            0.0f, 1.0f, 0.0f);

```

Which correctly moves the map in the middle of the window in width. But I can't move if correctly in height. It always returns the axis Z. When I go up, It goes down and the same for right and left.

I don't see the map anymore when I do :

```
gluLookAt(2000.0f, 6000.0f, 2000.0f,
                2000.0f, 0.0f, 2000.0f,
                0.0f, 1.0f, 0.0f);

```

# Answer
## How does `gluLookAt` work?

It seems you need help with `gluLookAt` \- it takes these nine parameters:

1. Parameters 1 through 3 are the XYZ coordinates of your camera's position.
2. Parameters 4 through 6 define the XYZ coordinates of the point that your camera will be centered on.
3. Parameters 7 through 9 define which direction is "up". This allows you to roll the camera.

## Where should one apply camera transformations?

Next, you should transform your view (move your camera) by using the Model-View matrix and not the Projection matrix.

> The gluLookAt() function gives you a transformation matrix that transforms a rotation of an object in your scene. So this is clearly a model transformation and must go into the GL\_MODELVIEW matrix.

Source

So your code should `initialize` function should look more like this:

```
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  gluPerspective(70.0f, 800.0f/600.0f, 1.0f, 10000.0f);

  glMatrixMode(GL_MODELVIEW);
  glLoadIdentity();
  glTranslatef(position_.x, position_.y, position_.z);
  gluLookAt(0.0f, 6000.0f, 0.0f,
            0.0f, 0.0f, -1.0f,
            0.0f, 1.0f, 0.0f);

  glEnable(GL_DEPTH_TEST);
  glDepthFunc(GL_LEQUAL);

```

## Is there a better way?

I think that instead of using `gluLookAt`, you should simply translate the camera instead. I'm not sure how you are drawing your 2D images, but typically you will draw your images with an X and Y coordinate and leave Z at 0. If you go this route, I recommend using `gluOrtho` instead of `glPerspective`.

## Find a good book

I recommend finding a good book about OpenGL viewing transformations. Although this book is outdated, the concepts in this chapter remain useful: http://www.glprogramming.com/red/chapter03.html
> 3 votes

# Answer
First understand the difference between the `GL_MODELVIEW` and `GL_PROJECTION` matrix stacks.

The `GL_MODELVIEW` matrix is for positioning and orientating the objects in the world with respect to the camera. This moves your objects through the following coordinate spaces:

```
Object Space -> World Space -> Eye Space

```

In object space, the object is the centre of everything. It does not yet know where in the world it is. You then apply the model transformation to the object and it positions it in the world. When this is done to every object, you have them all in world space. At this point, the (0,0,0) coordinate is just some arbitrary origin point in the world.

Your camera has some position and orientation in the world space. The view transformation rotates and translates the world space so that the camera is at the origin (0,0,0) and looking along the negative Z-axis. This is eye space. In eye space, the camera is the centre of everything.

These two transformations are combined into one, the modelview transformation, since they really just both work together to move objects around in the world with respect to the camera.

The `GL_PROJECTION` matrix transforms your objects through the following spaces:

```
Eye Space -> Clip Space

```

This can be a difficult transformation to imagine conceptually. If you imagine the frustum of the camera as a 6-faced volume (which is very near to the origin in eye space), this transformation moves and warps it so that it is in the shape of a cube with the centre of the cube at (0,0,0).

The first problem you've got is that you're trying to apply the *view* transformation to the `GL_PROJECTION` matrix. That's wrong. The *view* transformation should be part of the `GL_MODELVIEW` matrix. The view transformations you're applying are a `glTranslatef` and `gluLookAt`. These should be applied to the `GL_MODELVIEW` matrix.

Your second problem is that you misunderstand `gluLookAt` \- in particular, the 4th to 6th arguments. You are attempting to give it a direction in which the camera should look, (0,0,-1), along the negative z-axis. Firstly, if this was what `gluLookAt` expected, it would still be wrong, because you want your camera to look along the y-axis. Nonetheless, it actually expects a position in the world to look at. No matter where you place your camera, it will look at the point (0,0,-1), which happens to be right next to the corner of your map, which is at (0,0,0).

You shouldn't be using `gluLookAt` at all, because you don't want to look at a particular point. This is much easier to do with a rotation to make the camera look along the negative Y-axis, combined with a translation so that the camera is at a height away from the map. Note, you should apply the inverse transformations than you expect to, because you're really moving the map away from the camera, and not the camera away from the map. Something like this:

```
glRotatef(1.0f, 0.0f, 0.0f, 90.0f); // Rotate the camera to look down the y-axis
glTranslatef(-position_.x, -position_.y, -position_.z); // Move camera to correct location

```

Make sure these are the first transformations on the `GL_MODELVIEW` matrix.
> 1 votes

---
Tags: opengl, camera
---


# Question
Title: Does the base game I choose for a steam mod matter?
Me and a couple of my friends are planning on trying to make a source mod, but we can't figure out how to tell what game to use as a base. We hope to make a totally different game with it, and aren't sure how much of the base game will actually hang around. Like if we chose TF2 for the base would we be stuck with cartoony graphics and teams?

# Answer
> 4 votes
Based on my limited knowledge, your choice of base game gives you some of the core mechanics pre-programmed, along with a few textures, models, sounds, and the like. As such, it seems that if you wanted to make a linear single-player game, stick with one of the Half-Life 2 games as a base, or if you wanted to make an arena multiplayer game, stick with HL2MP, TF2 or Counter-Strike.

However, Valve also offers the Source SDK Base, which locks the engine to a specific version, and comes in singleplayer and multiplayer variants. These use base code from HL2EP1 and HL2EP2 (depending on version), but provide content from HL2 and HL2 Lost Coast. This article might be a useful starting point.

---
Tags: steam, source-engine
---


# Question
Title: How to synchronize actions like jump in multiplayer?
I am a newbie game developer and I have been researching about multiplayer games. I observed that there's always some latency, the players always get updates from past actions. But there are techniques like dead reckoning to handle the latency. I can predict the movement and make movements smooth. But how would I make actions synchronize like jumping, stopped walking, etc.

Suppose, client A was moving, he was at 100m at 10.2 time with 100m/sec velocity and sended this information. Client B would receive this information somewhat later, let it be 10.4. So at client B, I can use prediction and place client A at 120m. But what if, client made a jump at 110m at 10.3. I can't predict that and since I have been using prediction I can't show client A jump in past.

I may deal with this problem by not sending jump action at all. But what if my game has some voids where players can fall and die. So, If I don't sync jump actions, other players will observe that one player was running then he falls in void and then again appear on the screen destroying the visual engagement.

Jump is just an example, there might many scenarios where prediction can't work. So, How do deal with them. One such example can be Multiplayer Online battle arena games like Awesomenauts.

# Answer
> 9 votes
Dead reckoning may not be the best idea in this case; you should do entity interpolation (effectively rendering the other players in the past, which always gives you real, valid positions). I've written about this with much more detail here. Whether or not seeing players slightly in the past is acceptable or not depends on the details of what you're trying to do.

# Answer
> 1 votes
There is a fairly detailed write up regarding the source engine. It would appear some of the relevant source code is also available as part of the Source SDK.

https://developer.valvesoftware.com/wiki/Source\_Multiplayer\_Networking

It uses a number of techniques to try and deal with network latency in a server-client model. The main point seems to be that the local client handles input and other events locally as if there was no server, and then deals with the possibility the server says the client did it wrong later.

---
Tags: networking, multiplayer, game-mechanics, mmo, synchronization
---


# Question
Title: How collisions should be handled in terms of design
I'm not sure how should I design the collision part in order to respond the all the game requests.

First that comes in mind is 1. Update the game objects positions 2. Check the collision 3. Update the positions based on collision data

Now the problem is what if an object needs to know when it did collide in order to perform some actions. Lets say a player picks a chests, so he must not be bounced by the chest and also all the player, chest and cut scene sequence need to be triggered.

So if I do everything in collision routine (without triggers) then all the game logic is biased toward one game and is not flexible, its need to be adapted/rewritten for each game.

If I use triggers and call every object collision function what if player needs to move backward and collisions needs to be rechecked, do I need to make a flag to recalculate and collisions for objects that has this flag set until collisions are done?

Or do I check for chest collision in player update method (before the global collision routine) and do all the calculations there... but what if I don't want the player to react to collision if chest is closed and react if its opened (not just a player-chest collision pair setting)?

What is the best way to implement this kind of system that will be flexible for future games and in the same time respond to all requests of game design (in this case the example I wrote above, player-chest)

# Answer
> 0 votes
> If I use triggers and call every object collision function what if player needs to move backward and collisions needs to be rechecked, do I need to make a flag to recalculate and collisions for objects that has this flag set until collisions are done?

Don't do it that way, the reason for this is simple.

Your gamecode needs to know *exactly* which object can collide with which, this means that you can't use schemes that reduce the amout/count of collision tests, which means that your game will run too slow with enougth objects which can collide with each other ( time complexity).

> Now the problem is what if an object needs to know when it did collide in order to perform some actions. Lets say a player picks a chests, so he must not be bounced by the chest and also all the player, chest and cut scene sequence need to be triggered.

You can write your collision callback function/delegate in that way that it returns true if the two objects did collide, if they did you calculate the collision response.

To illustrate this idea here is the calltrace for a object which didn't collide

```
(in collision response phase, in physics engine source)
(object A and B did collide)
CollisionSouldBeHandled = this.onCollision(A, B);

if( CollisionShouldBeHandled )
{
   this.calculateResponseForces(A, B);
}

// collision event call code can come here

```

So in the onCollision method you check if A is a chest and B is a player or the other way around and you return false if it is that case.

To handle the event you have two possibilities

1. handle it immediatly
2. put it into a queue and handle all at once after the collision detection/resolve phase

# Answer
> 0 votes
The way I do it is. First check for collision of one object at the position it would be at if you did move. If something is there then move until you hit that object and then stop. (or bounce but keep the distance in mind)

In order to get the triggers working make sure your objects like chest have a callable method which player can call when it hits something (like from a parent class) things that don't do anything should have this empty while things such as chests that do an event will perform it in this method that an object will call on it when it notices it has collided with another object.

here is psuedocode one direction just for simplicity:

```
// first figure out where the object would be when it moved
//
int speed = 10
newx = x+speed;
newy = y;

// check the collision at that point
if(object = collision(newx,newy)){
    //move to the objects edge
    for(int i = 1; i < 10; i++){
        if(collision(x+speed,y)){
            x = newx + i-1;
            y = newy;
        }
    }

object.collidedwithyou(this);
}

```

---
Tags: collision-detection, response
---


# Question
Title: Best way to manage sprite sheets on Android using NME
I'm creating a 2D game for mobile touchscreen devices, specifically Android and iOS. I would like to know what is the best way (regarding performance and best practices) to manage sprite sheets.

Should I create different sprite sheets (for ldpi, mdpi and hdpi) and then scale according depending on the screen resolution or there is a better solution?.

I know that maybe the solution that someone could provide me would be platform independant but I'm using the NME framework (http://www.nme.io/), perhaps you know a good solution using this framework.

# Answer
There are solutions to this question all over the web. Android documentation gives an excellent series of tutorials on this subject. Specifically:

> http://developer.android.com/training/displaying-bitmaps/index.html

These same principles can be applied to the 2d textures you are a using for your openGL objects. Although, I have never worked with openFL bitmap manipulation is handled in android using

```
 ByteBuffer class and BitmapFactory

```

which imports from

```
android.graphics

```

and not

```
javax.microedition.khronos.opengles.*;

```
> 1 votes

---
Tags: android, mobile, spritesheet, haxe
---


# Question
Title: How can I tell if OpenGL has finished rendering the current frame?
If I make a call to http://developer.android.com/reference/android/opengl/GLSurfaceView.html#requestRender() from my game loop, how can I tell when OpenGL has finished rendering?

I don't want to make a call to `requestRender()` again in the next frame until the previous frame has finished rendering.

Sorry for the basic question I'm new to opengl and trying to switch to it from canvas.

Also, is GLSurfaceView.requestRender() a blocking call?

# Answer
> 3 votes
Jimmy Shelter is right. When you implement a GLSurfaceView.Renderer the onDrawFrame() handles the game loop for you. See this link: http://www.javacodegeeks.com/2011/09/android-game-development-switching-from.html

If you need data on the progression of the loop put a counter within your Renderer class in your onDrawFrame() method:

```
public class GlRender implements GLSurfaceView.Renderer {

 private int counter = 0;
 @Override
 public void onDrawFrame(GL10 gl)
{
      counter++;
}}

```

Depending on the amount of calculations you have going on in your loop you may need to slow it down to 60fps otherwise your animations may be occurring too frequently.

```
public class GlRender implements GLSurfaceView.Renderer {

 private long loopStart =0;
 private long loopEnd = 0;
 private long loopRunTime = 0;
 private final int FPS = (1000/60);

 @Override
 public void onDrawFrame(GL10 gl)
{
      loopStart = System.currentTimeMillis();
  if(loopRunTime < FPS )
 {
 Thread.sleep(FPS - loopRunTime);
  }

 loopEnd = System.currentTimeMillis();
 loopRunTime = ((loopEnd - loopStart));
}
}

```

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


# Question
Title: What am I missing? (Converting 2D mouse coords to 3D space)
I'm making a networked game which has a birds-eye view and I'm trying to convert the 2D mouse coordinates into 3D space. Right now I have a perfectly flat grid and it intends to remain perfectly flat, all I really want is the mouse coordinates to translate onto this grid.

I had a solution figured out that worked fine if the camera was perfectly straight looking down which I thought was going to be enough for what I wanted, but now I've found that it would be nicer if the camera had a slight tilt to it which completely messes with what I have. Could someone help me out in what I'm missing?

```
nearsourceV = GD.Viewport.Unproject(new Vector3(mouse.X, mouse.Y, 0f), camera.Projection, camera.View, camera.World);
farsourceV = GD.Viewport.Unproject(new Vector3(mouse.X, mouse.Y, 1f), camera.Projection, camera.View, camera.World);

mouseCoordinatesIn3D = Vector3.Normalize(farsourceV - nearsourceV);

zoomMultiplier = -mouseCoordinatesIn3D.Y;
zoomMultiplier = camera.CameraOffset.Y / zoomMultiplier;

mouseCoordinatesIn3D = mouseCoordinatesIn3D * zoomMultiplier;

mouseCoordinatesIn3D.X = mouseCoordinatesIn3D.X + camera.CameraOffset.X;
mouseCoordinatesIn3D.Z = mouseCoordinatesIn3D.Z + camera.CameraOffset.Z;

//Sends data and moves character

```

I figured I needed to include the camera rotation into it somehow, but I'm not really sure how or where.

Thanks!

# Answer
> 1 votes
1. The grid has a plane associated. It should be Y=0, if you want to get 2D coords easily, the normal will be Vector3.UnitY
2. If you want to do zoom you should do it by modifying the camera view
3. The Camera.World has not sense, it should be the plane world... or the transformations that you apply to the grid... if you don't apply it should be Matrix.Identity

This way the plane coords can be calculated this way:

```
var plane = new Plane(Vector3.UnitY, 0); // At (0,0,0)
nearsourceV = GD.Viewport.Unproject(new Vector3(mouse.X, mouse.Y, 0f), camera.Projection, camera.View, PlaneWorld);
farsourceV = GD.Viewport.Unproject(new Vector3(mouse.X, mouse.Y, 1f), camera.Projection, camera.View, PlaneWorld);

var ray = new Ray( nearsourceV , Vector3.Normalize(farsourceV - nearsourceV));

var distance = ray.Intersects(plane);

if (distance.HasValue) {
        coords3D = ray.Position + ray.Direction * distance;
        // if your plane is Y=0, the 2D grid coords are x,z
}

```

# Answer
> 0 votes
> Right now I have a perfectly flat grid and it intends to remain perfectly flat, all I really want is the mouse coordinates to translate onto this grid.
>
> \[...\]
>
> I figured I needed to include the camera rotation into it somehow, but I'm not really sure how or where.

The Unproject call takes all the camera information it needs, so you're probably just missing the ray/grid intersect calculation.

```
mouseCoordinatesIn3D.X = mouseCoordinatesIn3D.X + camera.CameraOffset.X;
mouseCoordinatesIn3D.Z = mouseCoordinatesIn3D.Z + camera.CameraOffset.Z;

```

So you no longer need to do that - the plane intersect would calculate the appropriate (x,z) using your ray.

XNA gives you a handy function: Ray.Intersects.

Your mouseCoordinatesIn3D variable is probably better being called the rayDirection, and your nearsourceV is the starting Position of the ray.

---
Tags: xna, 2d, 3d, coordinates
---


# Question
Title: Design question: How to handle input more efficiently?
I'm designing a system to handle the keyboard input for my game. To get it more simple, I have a class that has two methods, KeyUp and KeyDown which tell me which key has been pressed, this is already implemented by the library I'm using, now I want to have a way to send that information to the classes that are handling input (I'm using an MCV pattern, those would be the controllers). I've thought of two ways of doing that, both seem valid to me, and I don't know which is better, so I'm asking which would be the best way, in terms of object-oriented design, and if it has any significant impact, also efficiency.

The first way I thought of is having the class which receives the input hold references to all the controllers, and then call some methods of those controller classes in an event-like fashion when a key event is triggered in this class.

The other method is the other way round, the controllers hold a refference to the input handler class, which in this design has some kind of data structure (I was thinking of an EnumMap) that holds the status of all the relevant game keys, and then the controller classes might query the input handler for a key with some getters (just to encapsulate the data structure).

So, that's it, I'd like some help on how to do this. Any comments on which of both is better, or a new design that might be better than this are more than welcome.

Thanks in advance.

# Answer
> 1 votes
Possibly duplicated with this post

Essentially you are asking the differences between polling and interrupt/event-driven. You can Google it and there are a lot of answers out there. They both have advantages and disadvantages and which one to use depends on the scale and architecture of your application.

Here is another discussion you can look at.

---
Tags: java, libgdx, input, keyboard
---


# Question
Title: How can I handle sprite sheets with nonuniform sprite dimensions?
For a spritesheet with *non-uniform* sprite dimensions, how can I get the *bounding-rectangles* for each individual sprite (i.e. the blue boxes in the following image / I only drew a few examples)?

What I would like to determine are: `offset_x, offset_y, width, height`

So far, I have only used spritesheets on which all sprites have *identical* dimensions. In that case, one simply needs to specify the x- and y-offset to get a particular sprite. However, for spritesheets of *non-uniform* dimensions this doesn't work.

EDIT: Having read through the comments and answers, I rephrased my question to make it more inclusive wrt. the actual process of using a spritesheet in a game. Previously, the question contained the points why people produce spritesheets of non-uniform dimensions and how I can deal with that.

# Answer
> 8 votes
Most sprite sheets of non-identical dimensions usually have some kind of meta data with where the anchor of the sprite is. There are a lot of tools that do things like strip out full alpha pixels and give you the data you need so that this data isn't manually generated.

If you don't have this meta data you have to author it yourself. The most accurate way is the one you said in your question, which is to just do it by hand. It may take a while, but it's probably faster than making new sprites.

# Answer
> 5 votes
You can perform analysis on the image to locate the bounding rectangles of each sprite, sort those bounding rectangles (perhaps by increasing minimum X, then Y) and you'll have a set of bounding regions that correspond to the frames of the sprite sheet.

Because this process can be relatively expensive, you will probably want to do this offline, for example as part of the build process for your game. You can then serialize the bounding region information into a file that you store with the corresponding sprite sheet image. At runtime you load both the image and the boundary definition file and you have the information you need to access each individual sprite.

That is easier said than done, though. Essentially you'll want to do feature detection and specifically blob detection which are machine vision problems. You could also threshold the image (to black and white) and use an edge detection technique. The relevant math behind those techniques is explained far better on those links than I could, and in the case where you don't feel up to implementing that math yourself, there are a few libraries available that can assist you. The following set of links seemed the most promising to me:

# Answer
> 4 votes
I made my own tool for that kind of non-uniform spritesheet. It allows editing offsets, et cetera. Here's a screenshot to give you an idea:

# Answer
> 0 votes
Check out texturepacker

http://www.texturepacker.com/

It outputs a file like this (depending on your preffered settings)

```
    {
    "filename": "image_front_1",
    "frame": {"x":1,"y":160,"w":34,"h":52},
    "rotated": false,
    "trimmed": false,
    "spriteSourceSize": {"x":0,"y":2,"w":36,"h":40},
    "sourceSize": {"w":36,"h":40}
},
{
    "filename": "image_front_2.png",
    "frame": {"x":36,"y":160,"w":34,"h":52},
    "rotated": false,
    "trimmed": false,
    "spriteSourceSize": {"x":0,"y":0,"w":36,"h":42},
    "sourceSize": {"w":36,"h":42}
},
{
    "filename": "image_front_3.png",
    "frame": {"x":71,"y":160,"w":34,"h":52},
    "rotated": false,
    "trimmed": false,
    "spriteSourceSize": {"x":0,"y":0,"w":34,"h":52},
    "sourceSize": {"w":36,"h":42}
},
{
    "filename": "image_front_4.png",
    "frame": {"x":106,"y":160,"w":34,"h":52},
    "rotated": false,
    "trimmed": false,
    "spriteSourceSize": {"x":0,"y":0,"w":34,"h":52},
    "sourceSize": {"w":36,"h":42}
}

```

Using this data, you can easily grab the seperate rectangles from the image.

# Answer
> -1 votes
spritebuddy.com has worked great for me. Couldn't find any help on the site itself, but this Google Groups post explains it really well. It auto-guesses the bounds for your sprites, lets you adjust it, AND lets you arrange them into animation sequences. Then it spits out a metadata file for all this in either JSON or XML. Then all you have to do is parse that data file in your game to get the correct bounding rectangles.

---
Tags: c++, sprites, spritesheet, clipping
---


# Question
Title: How to change/modify or animate an existing OpenGL object on Android?
I maybe know understand it all a little bit better so i thoug i make a new shorter question to eventually get an answer.

Get back or delete an existing OpenGL object, then change it and draw at new. How?

So if and Admin reads this post, he can feel free to delete it.

I'm working on OpenGL since a Week, so i'm new to the most stuff. (also my englisch isn't the best. Hop you can understand the most anyway)

So i'm working on an Tamagotchi App for a school project and want to make it with OpenGL. I allready came this far:

But now i want to animate things. My mind told me that it shoud be possible to change or modify an existing OpenGL object. In my situation there are 3 opjekts:

1. Body
2. Eyes
3. Mouth

For example her is my code from the mouth:

```
public class GLMouth {

private int points = 1000;
private float vertices[]={0.0f,0.0f,0.0f};
private FloatBuffer vertBuff;
private FloatBuffer vertBuff2;

public GLMouth(){

    vertices = new float[points * 2];
    for(int i=0; i<= (points+3); i+=3)
    {
      double rad = (Math.PI *i) / points;

      vertices[i]=(float)Math.cos(rad);
      vertices[i+1]=(float)Math.sin(rad);
      vertices[i+2]=0;
    }

    ByteBuffer bBuff=ByteBuffer.allocateDirect(vertices.length*4);
    bBuff.order(ByteOrder.nativeOrder());
    vertBuff=bBuff.asFloatBuffer();
    vertBuff.put(vertices);
    vertBuff.position(0);

    vertices = new float[points * 2];
    for(int i=0; i< (points+3); i+=3)
    {
      double rad = -(Math.PI *i) / points;

      vertices[i]=(float)Math.cos(rad);
      vertices[i+1]=(float)Math.sin(rad);
      vertices[i+2]=0;
    }

    bBuff=ByteBuffer.allocateDirect(vertices.length*4);
    bBuff.order(ByteOrder.nativeOrder());
    vertBuff2=bBuff.asFloatBuffer();
    vertBuff2.put(vertices);
    vertBuff2.position(0);

}

public void draw(GL10 gl){

    gl.glPushMatrix();
    gl.glTranslatef(0.0f, -1.0f, 0.0f);
    gl.glScalef(1.8f, 0.15f, 1.0f);
    gl.glColor4f(0.0f,0.0f,0.0f, 1.0f);
    gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertBuff);
    gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glDrawArrays(GL10.GL_TRIANGLE_FAN, 0, points/2);
    gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glPopMatrix();

    gl.glPushMatrix();
    gl.glTranslatef(0.0f, -1.0f, 0.0f);
    gl.glScalef(1.8f, 1.0f, 1.0f);
    gl.glColor4f(0.0f,0.0f,0.0f, 1.0f);
    gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertBuff2);
    gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glDrawArrays(GL10.GL_TRIANGLE_FAN, 0, points/2);
    gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glPopMatrix();

}

}

```

In my renderer i just creat a mouth object and then draw it with mouth.draw.

So i thought i have allready drawn the mouth and now i can cange for example the gl.glScalef(1.8f, 0.15f, 1.0f); from that existing mouth to zero with some time in between to let it look like the mouth is closing.

But how can i do that? I don't find anything with google, mostly because i don't know what i have to look up. If i understand OpenGL right, than it will just draw new mouths over the original.

**edit** Or it is a question about where is the opjekt? Can i save it an take it back (delete it etc) and draw it new with other properties.

# Answer
Very cool app idea! I suppose there are more than one way to handle this problem. First, you could make a sprite sheet for the mouth and use

```
glTranslafef()

```

on the

```
GL10.GL_TEXTURE

```

and handle the logic in the render loop.

You could make multiple GLMouth variation classes, but would be better OO to inherit the GLMouth class itself.

Alternatively, and arguably the simplest way to do it would be to modify your

```
GLMouth.onDraw();

```

To take additional parameters that specify what set of vertices to use and then build a vertex buffer for every part of the mouth you want to draw.

```
GLMouth.onDraw(GL10 gl,int Mouth_Version_Indicator){
if(Mouth_Version_Indicator == 0){ //Draw Default VertextBuffer 1 and VertexBuffer 2 }
if(Mouth_Version_Indicator == 1){ //Draw VertexBuffer 2 and VertexBuffer 3}
... }

```

After that you declare a variable in your engine or renderer class to store whatever event you want to trigger the mouth movement has a occurred, and a counter to keep track of the number of frames:

```
onDrawFrame(){

if(mouth_trigger_event == true)
{
   if(counter > 2){mouth_trigger_event = false; counter = 0;}

  GLMouth.onDraw(gl, counter);
  counter++;
 }
else{
 GLMouth.onDraw(gl, 0);
  }
 }

```

I hope this is gives you some logic to play around with. You will still need to do all the standard openGL-ES things. Cheers.
> 1 votes

---
Tags: android, animation, opengl-es
---


# Question
Title: Unity3D filling visible camera area with objects
I'm developing an isometric tile-based game using Unity 3D.

I'm using an orthographic camera looking down yaw:45° and pitch:45°.

The game has an infinite world, which is loaded from a remote server. Because it is impossible to load everything at once, the game should only load visible areas of world.

But I don't know how to determine which tiles should be requested from server in order to fill up all the visible space on the screen.

I tried loading tiles by chunks e.g. 16x16 tiles chunk around camera. But this looks hacky to me and sometimes leaves blank edges visible on the screen.

**Is there better solution to simulate a continuous world on the client side?**

# Answer
It looks like you are on the right lines with your approach of loading the world in chunks, however you may need to take this a bit further.

The way most games achieve this (a notable example is minecraft) is to divide the world into chunks of a predetermined size (16 x 16 for example) and only load the chunk the player is in, and the four (or eight) surrounding chunks. By doing it this way, you reduce the amount of data needed in memory, but prevent the player from encountering an unloaded area.

When the player enters a new chunk, you repeat the process, unloading the chunks that are now too far away (squares in red on the picture), and loading the new neighbouring ones (squares in green).

If you try this but still notice blank edges then you may need to increase the size of your chunks (or load more) to store more of the game world at a time.
> 2 votes

---
Tags: unity
---


# Question
Title: How to create a legally valid timestamp of unpublished game artwork
Before publishing promotional material of my first indie game I wanted to mark all my artwork with a legally valid timestamp.

There are two ways I know to do this:

```
 1 go to a sollecitor/lawyer and pay for them to certify the document
 2 use an online webservice to mark any given file/folder readable to the service

```

Anyone has already done this and if yes how (e.g. which website have you used? which type of solecitor have you contacted? etc..)?

I am doing all this because I have prepared a kickstarter video that I wanted to publish in these days to ask for some additional funds to complete my game and, as it contains sequences of the game, I am at the same time worried about publishing it (somebody might copy the characters as I say in the video that I would like to do also a comic book series based on those characters). I guess that "eCO" (or something similar) becomes a must in this case right?

Kind Regards

PS: I know that there is always the good old "send yourself a mail with a stamp and a date" but is not very strong as proof.

# Answer
> 1 votes
When your intention is to secure copyright by proving that you published your work first, and you don't want to pay for a certification by a 3rd party, just put your work on the web.

The internet wayback machine is often used as evidence how a website looked at a past date and what content it had.

# Answer
> 0 votes
while not quite the answer you search, just a little word of advice I learn recently : one of my friend's father is lawyer specialized in corporation business, and he told me to launch an alpha version, shows a demo, or even just show off to friend and family the concept of your game as early as possible as an Indie game dev. What you want to do is to make them sign a form prior to showing them. You write down that your working title is confidential, that they cant talk about it blablabla. The important part of that document is the date, as it serve as a proof that you were working on this project at the date shown on the document, and that you have a person who can attest to it.

---
Tags: game-design, legal, game-industry, art
---


title: Texture atlasing in Unity

text:
# Question
Title: Texture atlasing in Unity
I'm researching new ways to optimize games for better performance. Currently I am working on texture atlasing, which is giving me a hard time. I made the atlas using `Texture2D.PackTextures` and saved the offset and height and width values to a text file.

Now when I insert the values to a material the texture is shown correctly, but since batching requires that the same material is used - how I can I use the same material with different offsets?

Picture: All the cubes use the same texture. Only the two on the right batch as they use the same material.

# Answer
I think you have 3 options:

1. Change UVs to point directly to the object on the texture atlas (in effect having N:N meshes:textures)
2. Create a seperate material per texture
3. If you change tiling via script it should work on the same material (although it might just be creating a clone of the current material)

P.S. I haven't read the whole post but it seems to be discussing your question: http://answers.unity3d.com/questions/276212/what-is-the-simple-way-of-applying-texture-atlas-t.html
> 1 votes

---
Tags: unity, textures, rendering, uv-mapping, texture-atlas
---


title: Unity third person controller and hills

text:
# Question
Title: Unity third person controller and hills
So I've been building a game and using the out of the box unity third person controller demo stuff.

I found that even the tiniest of slopes seems to stop the "dude" dead in his tracks.

Is there an easy way to adjust the sensitivity on the scripts somewhere?

I tried messing with the sensitivity options in the input options setup thinking that it might help but it didn't and I don't really want to go messing about in the scripts unless I really have to because i end up complicating my life when I do that.

# Answer
I'm assuming it uses Unity's Character Controller component - you can adjust the slope limit to work for hills too.

You can read more about it here: http://docs.unity3d.com/Documentation/Components/class-CharacterController.html
> 2 votes

---
Tags: unity, third-person-view
---


# Question
Title: How do I come up with the game mechanics for a puzzle game?
I want to make a puzzle game, but I don't know how to start. I have observed that each puzzle game has a core mechanic that enables opportunity for numerous puzzles. I'm not sure how to think of ideas. I was wondering how to come up with ideas for my game. I do not want any of your ideas because I want the game to be original.

# Answer
> 11 votes
Those released games you play, they are finished games, obviously, and have gone through countless iterations. The gameplay mechanics you're enjoying might not even have been a part of the original idea. They can be happy accidents, or at the very least, iterated to "perfection". Most likely a combination. Judging ones own work against finished products is never easy, you should have seen those games when they were in their first stages: might not have been that impressive.

What I'm saying, great "ideas" take work, they don't magically appear from some void. You start with something simple, and you build from there. Think of a few core gameplay mechanics, experiment, and see what you come up with.

I don't know what kind of game you want to do, but if I wanted to do a game with say, physics and puzzles, I'd start simple. I'd make a player I could move. I'd facilitate a way he could manipulate objects. Maybe he could pick them up, push them, throw them, run into. Or perhaps some sort of gravity gun like in Half-Life. Maybe something completely different. Then I'd throw some obstacles into the mix, and some other moving parts, that Braid trick, where you rewind time, that was great, huh?

If you can't come up with some ideas, take some ideas from other places, experiment, be inspired, and maybe out of that something "magic" and original happens!

**The prototype**

Starting development on a new game isn’t writing the story, making assets, or even the game engine. You want to make a game, you need gameplay mechanics, that’s where you should start. If you can get your mechanics to work, if they are fun, even if your graphics are all stick figures and blank textures, then you know this game is worth more effort. Now you’re ready to make it look nice. But how to get here? The answer is of course prototyping mechanics, and it’s the most important phase of development.

A prototype should be more than just drawings on paper — although paper prototyping might be a stage in your game development — I’d strongly advice you should have made several playable prototypes before starting on anything more concrete. It should be very simple and small of course, but a playable game nonetheless: rudimentary controls and mechanics so you can get a fairly realistic impression of what the finished gameplay might be like. You need to have enough in your prototype for it to be of value.

The whole point of a prototype is to find out if an idea works in practice. Since we’re talking about video games, we might say that the point is to find out if the idea is fun in practice. But the prototype should also give you insights into game design, I’m not talking about visuals or story here, but game design in terms of game rules and mechanics. In fact, prototyping is game design. You want to test out as many ideas and mechanics as possible, to find several that works great, but each prototype should have a narrow focus. Be very specific about what you are actually testing.

When making a prototype, don’t worry much about anything, because you’re not going to keep anything except for the core mechanics, which will all be redesigned and iterated. You don’t need to think about how to structure your code, your architecture, you use whatever language or engine or whatever tools that gets the job done in the shortest amount of time possible.

http://www.gamasutra.com/view/feature/2438/how\_to\_prototype\_a\_game\_in\_under\_7\_.php

# Answer
> 2 votes
In addition to the advice recommended by Eric and Jeff, you may be able to benefit from paper prototyping. Once you have come up with several ideas for game mechanics, you could try using paper prototyping to flesh them out quickly. This could also be useful for identifying bad game mechanic ideas without wasting any time actually programming these game mechanics.

I've noticed several partipants of the Ludum Dare use paper prototyping in their efforts to create a game in 48 hours. They've said good things about it, and it seemed to be pretty beneficial for those who made puzzle games.

# Answer
> 1 votes
When I get stuck thinking of an original idea, I try to just play a bunch of games similar to what I'm going for and usually an idea stems from that. I would just play a bunch of puzzle games and see what you really like and what you don't. Be careful not to base your idea too much off of one game though. And if you're still having trouble, try to write code to mimic some other game to see how they could have went about enabling their core mechanic. That way you kind of learn what may have went through their head when writing the game. Or you will think of a new idea as you are coding and maybe decide to do that instead. Either way you'll learn something. Just start coding and the ideas will come. Good luck!

# Answer
> 1 votes
You can try combining two different gameplay mechanics into one to create a brand new game (e.g. Gunpoint combines stealth and puzzle gameplay mechanics).

If you can not think of any good ideas or what gameplay mechanics to combine, you could use this random mechanic mixer which will combine different gameplay mechanics. At the bottom of the page is a description of all the different gameplay mechanics.

Lastly, just like everyone else said, play games to get ideas, and prototype your ideas to see if they are fun.

# Answer
> 0 votes
It's very hard to come up with a revolutionary new game mechanic. Next to impossible.

What is interesting is the ability to piece different existing pieces together in some kind of remix.

Refer to Jasper Jules' Family Tree (http://www.jesperjuul.net/text/swapadjacent/index\_image006.jpg) of match 3 games. Each one challenges an underlying rule/premise for the game. What if we held time constant? What if the Match 3 was circular?

What makes Match 3 really interesting and popular (Candy Crush is currently the #1 game on Facebook) is that the basic mechanics are very familiar, but it's an iterative twist.

---
Tags: game-design, game-mechanics
---


# Question
Title: How do you make the first person object the main camera?
How can a first person object character be made to be the primary viewing camera in unityscript? Do I remove the main camera? or just turn one or the other on/off?

# Answer
> 1 votes
Unity will use the first camera tagged as `MainCamera`, so you'll need to change the tag of the camera you want to be main and remove the tag from the old main (or just delete it).

# Answer
> 1 votes
If you have more than 1 camera in the scene you will have to change their `Depths` accordingly.

Also, unless you have a specific reason for having more than 1 camera (for example, render textures, GUI camera, split screen, etc) you should just delete any unnecessary cameras.

And to access `Camera.main` you should simply tag your camera as `Main Camera`.

---
Tags: unity, unityscript
---


title: pathFinding performance in Unity3d

text:
# Question
Title: pathFinding performance in Unity3d
I am making Sniper game in unity 3d. In this game zombies will come randomly towards the sniper and sniper have to kill them. I am using RAIN(indie) for path finding. It works best when zombies are few . As I increase the Zombies( that is 10) the performance decrease a lot. The fbs drops to 25.

I want to know is there any technique or steps so I can improve fps Any other technique/algorithm that I can use for pathfinding weith good fps.

PS

I already remove Sensor component from AI. FPS of game without AI is 61

# Answer
The main technique is to simply not run the pathfinder every frame. Typically, you only need to run it once a second or less to get good results. Depending on what you're using it for, you may even just need to run it once *ever*.

Another common technique, when pathfinding for multiple units in different places to the same end location, is to instead search outwards **from** the end location **to** each of the units. This requires only a single pathfinding call for all the units, rather than one for each unit. This requires you to actually get down into the pathfinder-implementation, though; if your library does not already support this technique, there is no way for you to "fake" it, you'd have to switch libraries or write your own pathfinding code.

---

I can also second the recommendation for Aron Granberg's Unity pathfinding library; I've looked at his code and actually spoken with him personally, and I can vouch that the library is very well-optimized. I am not familiar at all with RAIN.

If you do decide to go the code-your-own-pathfinder route, I have written a priority queue optimized specifically for pathfinding that would be useful. I have not tested it with Mono/Unity, but I believe it should work fine.
> 2 votes

# Answer
I'm unfamiliar with RAIN, however using Aron's terrific A\* pathfinding for Unity3d with dozens of units (on mobile devices) work like a charm:

http://arongranberg.com/astar/

P.S. RAIN might be as good as the package I've suggested or even better, it might be that you're just using it incorrectly.
> -1 votes

---
Tags: unity, ai, path-finding
---


# Question
Title: Detecting tile with height in isometric game
I'm trying to create an isometric tile-based game (for iPhone) and I'm having trouble with height in tiles.

What I currently do (without heights) is apply some mathematic transformations to my 2D-matrix (which represent the tiles) so that I know where in the screen (x,y) should I place the isometric tile. Then, when the user clicks somewhere in the screen, I take that values and pass them through a function (kind of f^-1) to get which tile it belongs to.

This works perfectly. My problem is: imagine that I want some tiles to have a different height from others. In order to draw the tile itself its pretty simple, since the z-coordinate has no transformation in the isometric approach used in games (z'=z). BUT what if I want to calculate the tile coordinate (defined by X-tile and Y-tile) from the touch coordinates (x,y)? Any guess?

# Answer
> 1 votes
Keep a z coordinate and make the x and y its actual x and y positions. the drawn position will be affected by the z coordinate. make sure the check tile pressed event also takes the new z variable into account and then all you will have to do is check what the x y value is after you figure out what tile was clicked.

---
Tags: tiles, isometric
---


title: Smooth jumping in 2D platformers

text:
# Question
Title: Smooth jumping in 2D platformers
I have a very simple 2D game, similar to old-school Mario or Metroid. I'm having a lot of trouble figuring out the proper way to handle player jumping. I've tried several different methods. The first method being that as soon as the player presses the space bar, his position on the Y-Axis is automatically updated so that he is now 50 pixels higher. This didn't work, because his player model immediately jumped up instead of going for that smooth up/down look. The second method I tried was using a `Timer`. With this, once the player pressed the space bar, his position on the Y-Axis would be incremented every x milliseconds. This also didn't work, for the exact same reason that the first way didn't work. It shot straight up without looking smooth. The last method I tried was a resemblance of my movement on the X-Axis. Instead of waiting for player input, the Y-Axis is constantly being added, but when the player isn't jumping, the `yVelocity = 0`. When input does come in, an amount is added `yVelocity` and the player jumps up. I didn't expect this to work, obviously, but it looked better.

So how do you apply jumping correctly? This is something that I've been struggling with for a while, and I just want to get it right. Please don't confuse this question like this question, as they're both different. I need an efficient way to handle jumping so that he looks smooth (as in one motion) going up and down. I can make his falling look good, just not the going up part. Can anybody explain to me how they make jumping look good?

Note: I wrote this question without code because I want a general description of how one might do it. If you do need code or extra details, or anything to understand the question, I'll be happy to add any extra details that you might need.

# Answer
> 3 votes
You should Maintain 3 vectors: Position, Velocity and Acceleration

Initially set acceleration -ve in y-axis to simulate gravity

And Update these vectors at every frame like this

```
Position += Velocity
Velocity += Acceleration

```

(But if you are on ground, don't update the y component of velocity and position)

Now when you need to jump, simply set the Y component of Velocity to some +ve value. And you will automatically observe a smooth jump.

What actually happens here, when you set the velocity's Y to positive value, the player starts to rise up in space but since there is also some -ve acceleration, the velocity will also decrease, and at a particular height, velocity will become 0 and starts to drop down. The best part of this approach is that, it gives you a great feel of realistic gravity.

Note: (I am taking down left as (0,0) coordinate)

# Answer
> 0 votes
You must use Y vector applied to coordinate.

Every timer tick Y vector decreases by gravitation, so as higher player jumps as slower it will happens.

i.e. You set vector to 100px/s. This mean that in 1 second player must up to 100px. BUT, gravitation will reduce this height every timer tick. For example it will reduce 100px vector in 1 second. This mean that our vector will be fully decreased in 1 second.

If you have 30 timer ticks for this 1 second, so gravitation will reduce vector by 100/30 every tick.

You must update coordinates every tick by it's vector\*time. Time in my example = 1/30s

Trajectory will like parabola in this case. It will be smooth enough.

# Answer
> 0 votes
Consider next values:

Vectors

* pos0: The position of the character when he begin to jump.
* speed0: The speed of the character when he begin to jump.
* pos: current position
* speed: current speed

Values:

* g: gravity.
* t0: time when the character begin to jump.
* t: time elapsed in the current jump.
* speedJump: The momentum added by jumping (vertical) (constant)
* isJumping: if your character is currently jumping

When the player press the space key, your hold the t0 and pos0, and compute speed0:

```
if (!isJumping) // Only jump if it is not yet currently jumping
{
    t0=currentTime();
    pos0=pos;
    speed0 = speed;
    speed0.y += speedJump;
    isJumping = true;
}

```

Every frame, you may compute the new position of the character with:

```
if (isJumping)
{
    t = currentTime()-t0;
    pos.y = pos0.y + speed0.y*t - g*t*t;
    pos.x = pos0.x + speed0.x*t;

    // And test that the character is not on the ground again.
    if (pos.y < groundHeight(pos.x))
    {
        pos.y=groundHeight(pos.x);
        isJumping = false;
    }
}

```

# Answer
> 0 votes
For this problem, I usually have a preset value for GRAVITY that pulls you down.

```
public void updatePosition() {
  if (onGround) {
    velocity_y = 0;   //If standing on ground surface, velocity in y-axis is stable.

  } else {
    velocity_y--;
    //Otherwise velocity in y-axis always goes downward,
    //Depending on which platform you're working on, it could be velocity_y++;

    if (velocity_y < GRAVITY) velocity_y = GRAVITY;
    // Have a threshold for velocity_y
  }
  // Update the actual position with the velocity calculated.
  x += velocity_x;
  y += velocity_y;
}

```

The above function is called at every frame

```
public void jump() {
  velocity_y = 20;
}

```

And jumping occurs when an event like key press happens.

---
Tags: physics, jumping
---


# Question
Title: VBO in a class doesn't draw when The class has a destructor
I am making this class QuadTemplate

```
class QuadTemplate
   {
    public:
    QuadTemplate()
    {
        vbo=0;
        uvbuffer=0;
        vao=0;
        TextureID=0;
        vboType=0;
        drawStart=0;
        drawCount=0;
        programID=0;
        TextureShaderID=0;
    }

    ~QuadTemplate()
    {
        glDeleteBuffers(1, &vbo);
        glDeleteBuffers(1, &uvbuffer);
        glDeleteProgram(programID);
        glDeleteTextures(1, &TextureShaderID);
        glDeleteVertexArrays(1, &vao);
    }

    GLuint vbo;
    GLfloat vboData[12];
    GLenum vboType;

    GLuint uvbuffer;
    GLfloat uvDate[8];
    GLenum uvType;

    GLuint vao;

    GLint drawStart;
    GLint drawCount;

    GLuint TextureID;
    GLuint TextureShaderID;
    GLuint programID;
};

```

this class like the name says is a template where I store all the Vbo's date, it doesn't have any other function because I have a function that give it the values, the problem is when I try to draw the Vbo, it doesn't work, not only that it also presents some graphics mistakes, but when I comment the destructor, it work perfectly fine. why it doesn't work with the destructor?

# Answer
Obviously the destructor get´s called at some point and deletes your VBO before you draw it, my guess is that you create a temporary object somewhere, which get´s deleted or have an issue with copies or assignments.

Example:

```
QuadTemplate quad;

void foo()
{
    QuadTemplate quad2();
    quad2.vbo = CreateVBO(); //function that creates VBO
    quad = quad2;
    //... do stuff
}//destructor for quad2 is called here

```

This first creates an object "quad2", then create quad2´s VBO. Afterwards you call the assign operator for your class, which copies all the data from "quad2" to "quad". When you then reach the end of the function "foo" the object "quad2" gets out of scope and the destructor is called, which will delete your vbo. when you use quad later on its vbo is deleted since both instances referred to the same vbo.

You can find those situations by either putting a breakpoint into your destructor or defining a private assignment-operator and copy-constructor to get compiler errors when you try to access those in code.

It´s rather difficult to solve these situations, you should either try to avoid all calls of the destructor unless you really want to or try to change your design to avoid that problem entirely. And allways create copy-constructors and assignemnt operators, although this is likely to cause performance trouble since you have to interact with the GPU alot to create a second VBO whenever you copy your data to another object.
> 3 votes

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


# Question
Title: Is my social game technical solution viable?
I'm currently working on a board social game using HTML5 (canvas) & Asp.net MVC 4, Azure, Sql server, EF.
I'd like to do a server side realtime validation (using Ajax) of a player moves (not more than one every 2 seconds).
The problem is that I can't allow a communication to be longer than 200 ms (time of the client side animation). On the server side I have to go to the database to do the validation.
I'm not sure that it is possible to keep a good communication speed over time with a growing community.

**What would be a better scenario ?**

---

**Edit**:
An other possibility would be to load the grid answers on the grid load but then every player with a bit of firebug background could get the answers with no pain.. Then I'm forced to go server side. Maybe the best would be to load in the web role memory all the grids to not have to go to the database.

Another scenario could be:
1 ajax request to check in the server memory the grid solution
1 ajax request to confirm the player move in database
but it's not cheater safe neither..

---

Thank for your help

David

# Answer
> I'm not sure that it is possible to keep a good communication speed over time with a growing community.

You have limited control over this.

> The problem is that I can't allow a communication to be longer than 200 ms (time of the client side animation). On the server side I have to go to the database to do the validation.

100 ms ping is short enough where you are going to really cut into your potential user base including all of the below.

* Anyone from another country
* People in remote areas from your country
* Anyone with satilight internet
* 3G phones
* 4G phones

The standard solution is to have enough logic client side to let the game proceed normally. Verify after every move and if you detect an illegal move it means it means someone is spoofing requests.

In this case it is perfectly fine to disrupt the game and reset it to the last valid state. You might also want to send back a “don’t cheat” warning and have a 3 strikes you’re banned sort of thing.
> 2 votes

---
Tags: c#, html5, mvc, ajax
---


# Question
Title: Masking an area inside/outside a line strip
I have some point lights in my game which are just sprites implemented with help of HLSL. Currently I'm trying to implement dynamic shadows and I managed to make the program calculate the area in which the light should be drawn (area that is not behind walls etc).

Here is what it looks like when I draw a line strip between the calculated points:

So I was wondering how I would draw the light sprite only inside that line strip? For example if a pixel is inside that area, then draw it, etc. Can it be done with HLSL (I'm not that good at HLSL), or perhaps I should just do it in XNA?

# Answer
> 2 votes
If you want to block out the parts of that sprite that should be shadowed, there is an alternative approach to doing this that uses simpler geometry and doesn't require a lot of shader manipulation.

1. Calculate the shadow volumes themselves. This is a fairly common practice and there is lots written up about it. Check out this GameDev article for some information.
2. Render these shadow volumes to the stencil buffer, providing us with a mask of where we won't render the point light sprite.
3. Render the point light sprite but disqualify the fragments that are inside of the stencil buffer.

MSDN XNA documentation has an introductory article to using the stencil buffer for this operation.

Corollary: when doing any sort of graphics programming (and dealing with shadows especially), its helpful to think in **both** terms of what *can* be seen and what *can't* be seen. It comes up a lot that one is far easier to work with in certain situations than the other.

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


title: AI discover algorithm

text:
# Question
Title: AI discover algorithm
I am curious as to what algorithm/logic game AI/NPCs would use when discovering information about their environment.

There are two scenarios that I could envision.

1. The NPCs are all knowing in regards to elements in the environment, but choose to ignore them unless certain conditions are met (e.g. the guard will not "find" his fallen comrade's body unless he is x feet from the body)
2. The NPCs really do *discover* the environment by scanning it or something... (maybe similar to path finding?)

Maybe these are both used in conjunction...

Could anyone point me in the right direction towards any preferred methods?

I tried googling for this information, but could not find anything that seemed relevant.

# Answer
> 0 votes
You have two main ways to go here:

1) Most simpler games simply have the game engine apply rules, then dispatch alerts when certain conditions are met. So on a game tick they check to see (using your example) if a dead body is within x feet of a living guard and/or his field of vision, and if so they throw a livingGuard.hostileAlert() call and let the guard's logic take over from there.

Here the rules are with the game engine, and not with the NPC object itself, with something like collision detection. The advantage of this system is all the perception logic is on one place in the engine, and so if there is a bug in 'seeing' something it would be universal to all enemies, not just one guard that seems unable to ever see anything.

2) More fully modular/object-oriented games would feature the guard having its own set of perception rolls (like in DnD systems), where at certain ticks they ask the game engine if they can see something interesting. The "Game Master" (the game engine) compares the NPCs abilities/limitations (field of vision, line of sight, visible range, etc) to the environment, and responds to the guard accordingly.

The game engine would take the guards request to Perceive, look up/request its abilities, make the calculation, and respond with "all clear" or "hostile visible", etc. It would then be up to the guard object to decide how to respond with it's own internal logic.

The advantage of this system is that every NPC can easily be customized to have it's own perceptive abilities, and the engine can also be customized to deal with things like low-light or fog conditions, illusion/invisibility effects, etc. So you could create a camera that only "takes a picture" every 10 seconds by only having it request a Perceive function every 10 seconds.

Using the same system you can also force "obvious" effects, like if a person pulls out a weapon the game engine immediately triggers a hostileAlert() of all nearby NPCs, etc.

On the downside, every 'feature' is a potential 'bug', like a dragon with a sight range of 1 inside his own cave, or see-in-the-dark bats that can't see anything because its dark, or 1 guard you typo'd and can see people coming a mile away for no reason.

---
Tags: algorithm, ai
---


title: What are levels made of in games?

text:
# Question
Title: What are levels made of in games?
I feel like most will think this is a dumb question but I'm really curious.

Are levels made of just multiple textures or just a collection of models that make up the whole area? I'm working on creating assets at this point and I feel like this is a question I should ask now because I get to deep in the wrong direction. (if i'm headed there)

Example, Lets say I wanna make level setups like those in Bastion, would that be models that represent each area of the map? Or possibly one big model for each square area?

# Answer
> 2 votes
Levels can range from very complex to simple. They can be statically defined or procedurally generated. They can be pure 2D like Mario, and 3D but played in a 2D manner like Trine, or they can be full 3D like GTA. They can be a combination of 2D and 3D assets. They can be tile based or free placement based. Levels will be defined and designed differently for each game. Levels are made of the stuff you put in them for the game you're making.

# Answer
> 0 votes
You don't only have assets/in the case of an 3d game models in your game but also

* Scripts
* Triggers
* Lights
* Entities which interact with the player
* Static/dynamic landscape
* static objects
* dynamic objects

else the game would be very very boring.

In the case of a pure 2d game you have the same, but it is displayed differently (sprites instead of 3d models/meshes).

---
Tags: xna
---


# Question
Title: Separate axis theorem applied to AABB misunderstood
I'm trying to implement a collision system for a 2D platformer using the SAT algorithm. For what I need, my implementation only handles AABB's, I followed the instructions given here. It works, there is only a little something I'm having trouble solving, let me explain.

In this scenario I expect the player to swing along the left side of the wall. From what I understand of the SAT algorithm, in this case, when the player reaches the bottom of one of the static entities constituting the wall, a collision on Y would happens.

To illustrate, that's what I'm trying to do in the picture, at some point, the overlap on the Y axis will become lower than the one on the X axis. Regarding the linked tutorial, the overlap on Y should then be used to create the projection vector.

It's what's happening in my implementation, I only accept collisions on X pushing away the player to the left, but it's not the case. Collision on Y happens when my player reaches the bottom of an entity resulting to an odd feeling.

**Am I misunderstanding the SAT algorithm, should this case never happen? Or is there a way to avoid it?**.

Here is the SAT part of my collision system implementation:

```
    private Vector2 testCollision(SATAABB box1, SATAABB box2, Vector2 velocity) {
        float ox = (box1.wx.len() + box2.wx.len())
                - box1.getDistanceBetweenCentersOnX(box2);
        if (ox <= 0) //no overlap on X, no collision
            return null;
        float oy = (box1.wy.len() + box2.wy.len())
                - box1.getDistanceBetweenCentersOnY(box2);
        if (oy <= 0) //no overlap on Y, no collision
            return null;

        if (ox < oy) {
            projectionVector.set((box1.center.x > box2.center.x) ? ox : -ox, 0);
            velocity.x = 0;
        } else {
            projectionVector.set(0, (box1.center.y > box2.center.y) ? oy : -oy);
            velocity.y = 0;
        }
        return projectionVector;

```

The SATAABB is a simple class holding half width vectors on both axis and a center position.

---

EDIT: After using time equations, it's way better, still a case remains I'm having trouble with. The player is moving on the ground with a positive X velocity and a positive Y velocity (gravity). Here is the equations for that particular case:

```
timeCollisionX = (player.topright.x - wall.topleft.x) / velocity.x;
timeCollisionY = (player.bottomright.y - wall.topleft.y) / velocity.y;

```

And I come in a situation where those equations are equal to:

```
timeCollisionX = (324,000000 - 320,000000) / 5,000000 = 0,800000
timeCollisionY = (448,200012 - 448,000000) / 0,200000 = 1,000061

```

Which results to a X collision where only Y collisions should occur because the difference between the player top right corner and the wall top left corner on X is lower than the actual velocity on X. Any idea on how to deal with this?

# Answer
You're not misunderstanding the SAT algorithm, but you're confusing collision detection with collision resolution. The SAT algorithm just detects collisions; it doesn't tell you what to do about them.

The projection vector that you can generate with SAT is not necessarily useful for collision resolution; people commonly want to use this vector to push apart the colliding objects, but that causes problems like the one you're seeing, where the direction of the push can suddenly change in undesirable ways.

Basically the way to fix it is to look for the *earliest* collision along the trajectory of the moving object(s), rather than looking for the minimum vector to push them apart. There are some other questions here that touch on this issue: Finding the contact point with SAT and How to deal with corner collisions in 2D. You may also want to google about "continuous collision detection". It's not a simple problem to solve in general, though.

When you have multiple objects in the world, you might detect a collision with several objects in the same frame. When this happens, again you need to look for the earliest collision across all of them. So you can't just stop with the first object where you find a collision; you have to calculate the collision time for all colliding objects and choose the earliest.

Once the earliest collision has been resolved (i.e. you changed the position so that the objects no longer collide) you should re-run the whole collision detection algorithm with the new position, since there could be another collision you need to handle. For instance if the character is running along the ground and hits a wall, you first resolve the collision with the ground and prevent him falling through it, but then his modified position still hits the wall, so you need to re-run the algorithm to detect and resolve that as well.

For a 2D platformer with rectangular objects, running it twice is probably enough. In general you might need to run it many times, which gets expensive fast, and can cause all sorts of problems when multiple moving objects hit each other. Algorithms for resolving multiple collisions robustly and fast are a subject of intense research, and this is where a lot of the complexity of a physics engine is.
> 3 votes

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


# Question
Title: How to simulate acceleration and then deceleration?
Currently I am only using deceleration.

Here is how I do it

I need to cover Vector(x,y) unit distance to reach B from A.

I simply do -

rendering loop-\>

1. position = A + Vector(x,y).scale(factor);
2. Vector(x,y) = Vector(x,y) - Vector(x,y).scale(factor);

...factor = 10 for example So if I have to cover 100 units, I cover 10 then 9 then 8.1 and so on in every frame.

How do I simulate acceleration then deceleration here?

# Answer
> 3 votes
A simple way is to animate the object using a smoothstep curve:

```
lerpFactor = (curTime - startTime) / timeToReachTarget;
smoothstepFactor = lerpFactor * lerpFactor * (3.0 - 2.0 * lerpFactor);
position = lerp(startPos, targetPos, smoothstepFactor);

```

Here, I'm assuming a specified amount of time to reach the target (`timeToReachTarget`) and calculating how far the object should have moved by the current time (`lerpFactor`), then passing it through the smoothstep curve to make it accelerate and decelerate smoothly.

This isn't an especially physics-based approach, nor does it work well if the target point is moving, but it does create a smooth-looking motion.

---
Tags: vector
---


title: OpenGL tile rendering

text:
# Question
Title: OpenGL tile rendering
Currently I'm trying to render a TileMap using OpenGL 2.1, GLSL 1.2. I would like to draw every tile in just one draw call. I use a single texture with all tiles, identifying each one by an index.

The vertex data per tile is:

```
vec2 worldPos; // the position to transform the tile Quad in world coordinates
vec2 texCoord; // the uv coordinates, calculated using the tile index, by CPU (top-left corner).

```

But I can't find a way to draw everything with one draw call: \- The uv coordinates can't be calculated in shader because the vertex shader don't know which corner of the quad it is processing. \- Can't draw by element because my quad vertex data only contains 4 vertices, store repeated vertices is a memory waste. Only if I could use a separate element buffer just for the vertex (0, 1, 2, 3, 0, 1, ...).

Does someone have any suggestion about how should I proceed? Thanks!

# Answer
> The uv coordinates can't be calculated in shader because the vertex shader don't know which corner of the quad it is processing.

```
int corner = gl_VertexID % 4;

```

There; now your shader knows what corner it is. This requires GL 3.x and a `#version` declaration of `130` or above.

> store repeated vertices is a memory waste

Yes. That's why it's called a "memory vs. performance tradeoff." You spend memory to make things faster.

You're doing 2D rendering. Do you honestly think that making a proper array is going to tax your GPU's memory significantly?

Even if your tiles are 4x4 pixels in size, and you're rendering at 2560x1600, that's only 256,000 tiles for a single screen. With each tile being 32 bytes in size (four vertices, where each vertex has 2 signed shorts for the position, 2 signed shorts for the texture coordinate), that means your vertex data takes up 8,192,000 bytes of memory.

Is ~8MB of storage *really* going to be a problem for you? Even on cards with 128MB of graphics memory, that's less than 10% of the space. And that's the worst-case scenario; for more reasonable tile sizes like 8x8 or 16x16, you're looking at 2MB or 512KB, respectively

Also, instancing for tiles is more likely to kill your performance than to help it. Instancing works most optimally when:

* The number of instances is large. 500+.
* The size of each instance's data is between 100 and 2,000 vertices or so.

Your case fails #2.
> 3 votes

# Answer
Here´s an alternate approach. which I used for something slighty diffrent, but i think it might help you too, it´s super low memory, one draw call and very fast:

What you need:

* Your View and Projection Matrix
* A vertexbuffer holding a fullscreen quad
* A texture where each pixels represents a tile and stores the tile´s texture ID (needs to be float or integer texture
* A texture atlas containing all possible tile textures
* the following shader ( i didn´t test it, you might have to do some minor corrections)

Vertexshader ( you can avoid alot of this if you use orthographic projection):

```
varying vec3 pos3D; //position of Vertex in 3D

uniform mat4 invWVP; //Inverse of (Projection * View)
uniform vec3 CPos; // Camera Position

void main()
{
    vec4 pos = invWVP * gl_Vertex; //You defined a fullscreen quad in Screen coordinates, this brings it back to 3D

    pos /= pos.w;   //homogenous coordinate correction

    vec3 dir = pos.xyz - CPos; //you don´t exactly know how far the plane your tiles are on is from the camera, so we do a ray plane intersection

    float t = -CPos.z / (dir.z); //assumes XY-Plane as your world plane

    pos3D = CPos + t * dir; // final 3D position of the corners

    gl_Position = gl_Vertex; // just render the screen coordniates, we need it to fill the whole screen
}

```

Fragment Shader:

```
varying vec3 pos3D; //pixel´s 3D position

uniform sampler2D tiles; //tile-map
uniform sampler2D atlas; // texture atlas

void main()
{
 vec2 tile = vec2(floor(pos3D.x) / 512.0,floor(pos3D.y) / 512.0); // figure out which tile we´re in from the 3D coordinates
 float tex = texture2D(tiles,tile).r; // get tile´s texture ID

 vec2 UV = vec2(0.0625 * (tex + fract(pos3D.x)), fract(pos3D.y)); // calculate UV within the texture|. The factor 0.0625 is if you have 16 textures next to each other from left to right in your atlas, this entirely depends on your layout for it

 gl_FragColor = vec4(texture2D(atlas,UV)); //fetch texel for fragment
}

```

All this assumes that you use the XY-Plane as your world and display everything on that one, you have to change a little in case you use a diffrent plane. It can be simplified if you use orthographic projection and no tilt in you view matrix. The advantage of this is that you don´t need more than 4 vertices and 2 textures, the shaders are not too heavy so it should run pretty fast any one drawcall is enought for everything and as long as you keep the matrices and CPos up-to-date camera movement will be rendered correctly.
> 2 votes

# Answer
It sounds like you're using vertex instancing with an inner vertex buffer representing a single quad, and an outer vertex buffer with one entry per tile. If that's the case, you specify the UV of one corner of the tile in the per-tile vertex buffer (as it sounds like you're already doing), and a per-corner UV offset in the inner vertex buffer. Just add the two together in the vertex shader to generate the UVs for the tile.
> 0 votes

---
Tags: opengl, tiles, glsl, tilemap
---


# Question
Title: Adding false if statement to pixel shader produces a lag
One of lines in pixel shader produces a lag (lower fps). I can't understand why.

```
if (TextureEnabled)
    color *= texDiffuse.Sample(texDiffuseSam, input.UV);

```

Interesting fact is: **TextureEnabled** is always **false**. I have already checked.

```
// they are null
Texture2D texDiffuse : register(t0);
sampler texDiffuseSam : register(s0);

```

Is it possible, or i have mistake in other place(?), or is it HLSL so slow?

# Answer
> 3 votes
Even if the condition is always false, you're still adding an if-statement to every single pixel you draw with this shader, and that's going to take a nonzero amount of time.

I'm guessing you're confused because you've read statements to the effect that shader dynamic branching is slow when different pixels take different branches. It's *especially* slow in that case, but it's not free even when all the pixels take the same branch. There is a cost just to have the branch in there.

Typically, the way people handle flags like this is to generate multiple versions of the shader, e.g. one with the texturing code enabled and one with it disabled. This is known as the "ubershader" approach. It can be done using `#defines`, or it can also be done using `uniform bool` variables and different entry points. People often write shader-generators to create all the different combinations automatically, or add the combinations as different techniques in an effect file.

Another approach is to write a shader that always samples the texture, and just set it to a 1x1 white texture when the texture is not used. This will be quite fast to sample, although not as fast as removing the texture altogether, and it simplifies the code.

---
Tags: c++, directx, hlsl, directx11
---


title: OpenGL Transform Feedback output size

text:
# Question
Title: OpenGL Transform Feedback output size
I'm working on a particle system using transform feedback, and I would like to know if it is possible to render to anything other than floats, like halfs, using Transform Feedback (OpenGL 3.3)? It would save some bytes and possibly speed up the process a little bit.

# Answer
> 1 votes
You can write unsigned integers and use bit manipulation to pack data into them into half of those integers.

You can use the ARB\_shading\_language\_packing extension to help out in this process; it's pretty widely supported, even on older AMD HD3-5xxx cards (though I make no claim as to how well this actually *works*. They simply claim to support it).

---
Tags: opengl, vertex-arrays
---


# Question
Title: How to determine where on a path my object will be at a given point in time?
I have map and an obj that is meant to move from `start` to `end` in `X` amount of time.

The movements are all straight lines, as curves are beyond my ability at the moment. So I am trying to get the object to move from these points, but along the way there are way points which keep it on a given path.

The speed of the object is determined by how long it will take to get from start to end (based on X).

This is what i have so far:

```
//get_now() returns seconds since epoch
var timepassed = get_now() - myObj[id].start; //seconds since epoch for departure
var timeleft = myObj[id].end - get_now(); //seconds since epoch for arrival
var journey_time = 60; //this means 60 minutes total journey time
var array = [[650,250]]; //way points along the straight paths

if(step == 0 || step =< array.length){
  var destinationx = array[step][0];
  var destinationy = array[step][1];
}else if( step == array.length){
  var destinationx = 250;
  var destinationy = 100;
} else {
  var destinationx = myObj[id].startx;
  var destinationy = myObj[id].starty;
}
step++;

```

When the user logs in at any given time, the object needs to be drawn in the correct place of the path, almost as if its been travelling along the path whilst the user has not been at the PC with the available information i have above.

How do I do this?

Note: The camera angle in the game is a birds eye view so its a straight forward X:Y rather than isometric angles.

# Answer
I am not completely certain that this is the best answer to your problem but I know this is a way to at least solve your problem.

In times like these it's important to remember the formula for uniform motion from which you know:

> Distance = Rate * Time
>
> Rate = Distance/Time
>
> Time = Distance/Rate

Why do we need to know this? Well obviously because we are trying to figure out how far we are along a path we are at any given time. So at any given time, we obviously have the time component, but we don't have the rate to help us determine the distance! Or do we?

What we know is that starting at point A we would like to reach point B in X amount of time. Well hey there! We have a line segment and using the distance formula we can figure out what the total length of the line segment is.

So using the data from knowing our start and end state we now have a distance and a time from which we can determine our rate. Awesome! Now we just have to figure out how to find a point on a line given a certain distance which we can do with vector math and as it turns out, this answer covers the topic nicely and I'll paraphrase the answer here.

In short:

1. Calculate the vector from (X1, Y1) to (X2, Y2)
2. Calculate the magnitude / length of the vector
3. Normalize the vector
4. Calculate the new vector

The code / math for this last part would look something like this:

```
vectorX = X2 - X1; //X coordinate of the calculated vector
vectorY = Y2 - Y1; //Y coordinate of the calculated vector
magnitude = sqrt(vectorX*vectorX + vectorY*vectorY);
normalizedX = vectorX / magnitude;
normalizedY = vectorY / magnitude;
destinationX = x1 + normalizedX * distance;
destinationY = y1 + normalizedY * distance;

```
> 4 votes

---
Tags: javascript, path-finding
---


# Question
Title: How to program dynamic touch events that scale according to device?
When using openGL to build a UI for my prototype I find that that I am still required to use pixels to capture touch events. To make matters worse the Android Docs make this subject slightly confusing. http://developer.android.com/guide/practices/screens\_support.html specifically states:

> You should always use dp units when defining your application's UI, to ensure proper display of your UI on screens with different densities.

Yet

```
MotionEvent event = new MotionEvent();
event.getX();

```

returns pixels when used to locate the touchscreen event. http://developer.android.com/reference/android/view/MotionEvent.html#getX()

To make matters even more confusing,

```
public final float getRawX ()

```

> Added in API level 1 Returns the original raw X coordinate of this event. For touch events on the screen, this is the original location of the event on the screen, before it had been adjusted for the containing window and views.

Seems to imply that there are alterations being made to adjust for the window and views when using

```
event.getX()

```

My last bit of confusion comes in when trying to tie both of these concepts together. I see all the moving parts I am just unable to make them connect.

* How to convert openGL vertices into terms that work with pixels or dp.
* How to program for dynamic touch events using MotionEvent when pixel location will change by scale according to device density.

# Answer
> 2 votes
I solved this by creating a custom class that creates an object that handles the touch events. In case anyone is curious as to how to go about this:

1. Step one is to design your touch events for a 160 dpi device. This translates into one actual pixel for every density independent pixel. I would also suggest using a very small screen size in order to understand exactly how big your touch event areas need to be.
2. Step two is to set up your custom touch handler class to get the device screen density on instantiate and pass this into your constructor. Use:

```
context.getResources().getDisplayMetrics().density

```

This will return the devices density. For a 160 dpi screen it will be 1, for 480dpi it will be 1.5, etc.. refer to Android Developer for the whole list.
3. Step three is where the magic happens. You take the points of your desired touch location that you designed in step one, and build them based on the actual devices screen density. You do this by taking your density independent numbers (step 1) and multiplying them by the dynamically obtained device density (step 2) at run time.

```
private int Convert_To_Device_Pixel(int pixel)
{
pixel = (int)(pixel * density);

return pixel;
}

```

This will return the pixel translated based on the devices dpi. It works for both x and Y coordinates. At this point you now have everything you need to build your touch events that will scale across all devices. You can take your

```
MotionEvent.getX();
MotionEvent.getY();

```

... and compare them to your now converted numbers from step 1 to determine if the device has been touched in that area. Keep in mind that this results in a touch area that will not grow on bigger screens or shrink on smaller ones. It will always be the same relative size.

Kudos to rajarko.com for helping me see the light.

---
Tags: opengl, java, android
---


# Question
Title: OpenGL additive blending not working as expected
I am trying to achieve additive blending with point sprites. When the sprites overlap, all I get is solid red, when I expect to get a smooth blend from red-\>yellow-\>white. My sprite texture has all four channels set equal, with portions being white and others transparent.

I set up blending as such:

```
  glEnable(GL_BLEND);
  glBlendFunc(GL_ONE, GL_ONE);

```

My fragment shader is as follows:

```
  vec4 texCol = texture(pointsprite, gl_PointCoord);
  colorOut = vec4(texCol.rgb * vec4(ocolor, 1.0).rgb, texCol.a);

```

Where `pointsprite` is a sampler2D and `ocolor` is \`(1.0, 0.0, 0.0)

My background is cleared as

```
  glClearColor(0.0f, 0.0f, 0.0f, 1.0f);

```

I have tried some of the various methods suggested in this question, none offering any results. I can verify my alpha channel is correctly loaded from my image into my texture.

EDIT: Missed mentioning that my intention is for clusters of point sprites with the same pigment (red) to additive blend to yellow and white.

# Answer
You can achieve the effect you are looking for by setting the color value to non-pure red. In the picture below I have drawn a circle with additive blending multiple times with small offsets. On the left the color is pure red (255, 0, 0) and on the right it is (255, 20, 5). From these you can calculate that to get full yellow, you need 255/20=13 overlapping circles and to get pure white you need 255/5=51 overlapping circles. When you reach full yellow (green channel goes to 255), there is also 65 (25%) on the blue channel, but that should not be an issue. Adjust the numbers as you feel.

In your case the color you should change is `ocolor`. If you are not rendering sprites with multiple colors, you could also use white for `ocolor` and draw the different colors in the texture itself. This would give more freedom to define how each pixel on the sprite behaves with additive blending.
> 8 votes

# Answer
> Missed mentioning that my intention is for clusters of point sprites with the same pigment (red) to additive blend to yellow and white.

That right there is indicative of your problem.

You cannot take a color value of (0.25, 0, 0), and add it to itself and get anything besides *more red*. It will not magically become yellow, then white. It will always be red, and it will always have zero green or blue (which are necessary to achieve yellow and white).

Blending is just math; nothing more, nothing less. Math on colors is no different from math on things that aren't colors.

If you want adding "red" to eventually produce yellow and white, then you're going to need to have some blue and green in there.

Furthermore, you're going to have to use some form of tone mapping and high-dynamic range rendering to make this work out in a reasonable way.
> 5 votes

# Answer
Well, your `glBlendFunc(GL_ONE, GL_ONE)` is likely to blame.

The 1st argument to `glBlendFunc` is *how much of the source* (new pixel) to use. The 2nd arg is how much of the *destination* (pixel already there in the frame buffer) to use. You said to just add 100% of the source pixel with 100% of the destination pixel. That's probably not how you want to blend for translucency though.

Common settings to get translucency are calling `glBlendFunc` with

```
glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;

```

An example of the math that happens is here. That says, ok, say the new pixel had alpha =0.75. Then the blended color would be 0.75\*NEWPIXEL + 0.25\*OLDPIXEL. Which looks like transparency.

Don't forget to turn off depth mask!.
> 2 votes

---
Tags: opengl, blending, fragment-shader
---


# Question
Title: Problems with moving 2D circle/box collision detection
This is my first game ever and I'm a newbie in computer physics. I've got this code for the collision detection and it works fine for BOTTOM and TOP collision.It miss the collision detection with the paddle's edge and angles so I've (roughly) tried to implement it.

Main method that is called for bouncing, it checks if it bounce with wall, or with top (+ right/left side) or with bottom (+ right/left side):

```
protected void handleBounces(float px, float py) {
    handleWallBounce(px, py);
    if(mBall.y < getHeight()/4){
        if (handleRedFastBounce(mRed, px, py)) return;
        if (handleRightSideBounce(mRed,px,py)) return;
        if (handleLeftSideBounce(mRed,px,py)) return;
    }
    if(mBall.y > getHeight()/4 * 3){
        if (handleBlueFastBounce(mBlue, px, py)) return;
        if (handleRightSideBounce(mBlue,px,py)) return;
        if (handleLeftSideBounce(mBlue,px,py)) return;
    }
}

```

This is the code for the BOTTOM bounce:

```
protected boolean handleRedFastBounce(Paddle paddle, float px, float py) {
    if (mBall.goingUp() == false)
        return false;

    // next position
    tx = mBall.x;
    ty = mBall.y - mBall.getRadius();

    // actual position
    ptx = px;
    pty = py - mBall.getRadius();

    dyp = ty - paddle.getBottom();
    xc = tx + (tx - ptx) * dyp / (ty - pty);

    if ((ty < paddle.getBottom() && pty > paddle.getBottom()
            && xc > paddle.getLeft() && xc < paddle.getRight()))
            {

        mBall.x = xc;
        mBall.y = paddle.getBottom() + mBall.getRadius();
        mBall.bouncePaddle(paddle);
        playSound(mPaddleSFX);
        increaseDifficulty();
        return true;
    }
    else return false;
}

```

As long as I understood it should be something like this:

So I tried to make the "left side" and "right side" bounce method:

```
protected boolean handleLeftSideBounce(Paddle paddle, float px, float py){

    // next position
    tx = mBall.x + mBall.getRadius();
    ty = mBall.y;

    // actual position
    ptx = px + mBall.getRadius();
    pty = py;

    dyp = tx - paddle.getLeft();
    yc = ty + (pty - ty) * dyp / (ptx - tx);

    if (ptx < paddle.getLeft() && tx > paddle.getLeft()){
        System.out.println("left side bounce1");
        System.out.println("yc: " + yc + "top: " + paddle.getTop() + " bottom: " + paddle.getBottom());
        if (yc > paddle.getTop() && yc < paddle.getBottom()){
            System.out.println("left side bounce2");
            mBall.y = yc;
            mBall.x = paddle.getLeft() - mBall.getRadius();
            mBall.bouncePaddle(paddle);
            playSound(mPaddleSFX);
            increaseDifficulty();
            return true;
        }
    }
    return false;
}

```

I think I'm quite near to the solution but I'm having big troubles with the new "yc" formula. I tried so many versions of it but since I don't know the theory behind it I can't adjust for the Y axis. Since the Y axis is inverted I even tried this: `yc = ty - (pty - ty) * dyp / (ptx - tx);`

I tried Googling it but I can't seem to find a solution for it. Also this method fails when ball touches the angle and I don't think is a nice way because it just test "one" point of the ball and probably there will be many cases in which the ball won't bounce.

# Answer
Well here it goes. It seems your trying to account for different collisions individually. Which, instead, you should just have one robust circle-rectangle collision code. And use your velocities and positions to determine which paddle has been collided with.

This method will return whether a collision has occurred. It CAN detect collisions with the rectangles corners.

```
public bool Intersects(Rectangle rect){
    float x = clamp(position.x, rect.x, rect.x + rect.w);
    float y = clamp(position.y, rect.y, rect.y + rect.h);
    return distance(position, Vector2(x, y)) < radius;
}

```

Then, when collision occurs, you can invert the ball.vel.x, or if you have paddles on the top and bottom, then the ball.vel.y.

I'm sorry if none of this helped, but I'm lost as to exactly what your looking for.

I'll be happy to help if you have anymore questions. :) Good luck!

-Mike

**EDIT** Annnnd I just realized I totally necro'd this post. Sorry. :)
> 1 votes

---
Tags: 2d, java, collision-detection
---