# Question
Title: Ignoring collisions without using physics layers
Trying to ignore collisions between certain prefabs, but in this case I don't want to use layers since these are specific object pairs that I want to not collide, and creating a layer for each prefab would complicate the layer matrix more than I want to.

What I tried so far:

```
public void OnCollisionEnter(Collision collision) {
    if (collision.gameObject.tag == "Bullet") {
        Physics.IgnoreCollision(collision.collider, collider);
    }
}

```

So I tried ignoring the collision in the `OnCollisionEnter`, but this only worked partially. The objects did go one through the other, but they both slowed down. My guess is that the first frame of the collision, the one that generated the call to OnCollisionEnter, was calculated regardless of the ignore command.

Any ideas how I can make all bullets not collide to one another, without putting them in a separate layer?

# Answer
Ok, so I haven't seen anyone answering with a solution for ignoring collusion between certain prefabs without assigning them their own layers (which are limited to 32).

So it's clear that in current unity versions, you must call `IgnoreCollision()` for each pair of instantiated objects.

So the solution I found, is an old one (before the layers were introduced), but it seems like it can work. It's called a "collision manager", and it's basically a class that stores references to all the objects that are instantiated, and calls `IgnoreCollision()` for every pair of objects of types that should not collide. To make it work each object has to register itself with the collision manager and it's type in the `Start()` method. This way the collision manager can make sure that every pair of objects of types that shouldn't collide will not collide, assuming all objects register themselves.

Here's the link to the article I found, although it's very lacking in explanation:

http://wiki.unity3d.com/index.php?title=CollisionIgnoreManager
> 0 votes

# Answer
> Trying to ignore collisions between certain prefabs, but in this case I don't want to use layers since these are specific object pairs that I want to not collide

When you have specific objects pair that you don't want to collide, using layers is definitively the best way to go.

> creating a layer for each prefab would complicate the layer matrix more than I want to.

"Complicate" the layer matrix is not a problem. The matrix is limited to 32 layer, if you haven't free layers to use than you might consider other solution. Until I have a free layer I'd always go for using it.

Physics.IgnoreCollision works just fine. There are some limitations documented indeed.

Btw, the problem is that you are calling it when a collision as already occurred. You have to **use it** on an object pair you want ignore collision for, **before the collision occurs**(for example set up it inside `Start` method instead).
> 0 votes

---
Tags: unity, physics
---


# Question
Title: Gravity independent of game updates per second
**Edit**

Just for clarification, my sprite's 'movement' isn't the problem. If I set my Time variable to 4 seconds, then it will cross the screen in exactly 4 seconds regardless of logic updates rate per second, rendering rate per second or screen resolution. So I am pretty sure I'm scaling the sprite's movement correctly. What I'm pretty sure I'm not doing correctly, is scaling acceleration.

**Original Question**

I'm trying to implement gravity in my 2d platformer and am having a few problems understanding how to keep it consistent when I change my updates per second.

Here's what I have.

**My Gameloop overview**

Currently, my gameloop renders at the maximum rate allowed by device and the updates are 'clamped' to an upper limit (At the moment, 60 per second). I am working on the assumption that most of the time, my game will have no problem hitting this, even if the actual rendering dips. Thus I am doing all of my calculations based Delta Time derived from this fixed 'ticksPerSecond' value.

I don't know for sure that this will remain at 60, I may decide at some point during the development to lower this upper limit.

**My Gravity - variable declaration and initial values**

At the moment, I have:

```
float spriteYTime=7f;                //This is the (initial) amount in seconds that this sprite will take to move from the top of the screen to the bottom.
float fallAccel=.5;                  //This is the value that will subtracted from he sprite's fall speed (To make it fall ever faster)
float terminalVelocity=1.5f;         //Cap speed at this rate (1.5 seconds)

```

my sprite's position is worked out on dt as follows:

```
//Delta time
float ticksPerSecond = 60;
float dt = 1f/ticksPerSecond;
//Velocity
spriteYVel = 1/spriteYTime;
//Update position
spriteYReal = spriteYReal + (spriteYVel * dt);
//Convert to screen coordinates (will be drawn at this Y coordinate)
spriteyScreen=(int) (furmanYReal*height);

```

**My Gravity - code**

```
    //If my sprite's state is 'f' (meaning falling) then apply gravity
    if(sprite.getState('f')==true){
    //Calculate new position
    spriteYReal = spriteYReal + (spriteYVel * dt);
    //Convert to screen coordinates
    sprite.yScreen=(int) (spriteYReal*r.height);
    //Reduce time by fallAccel amount & update velocity value based on new time value (So sprite falls slightly faster this frame compared to the last
    spriteYTime-=fallAccel;
    spriteYVel = 1/spriteYTime;
    //Check that speed isn't faster than terminal velocity
         if (spriteYTime<spriteVelocity)
            spriteYTime=spriteVelocity;
    }

```

**The problem**

Now, this does work, but if I change my ticksPerSecond value, it goes wrong (it falls at different rates).

I know that 'Earth Normal' gravity is approximately 9.8 meters per second per second, but this is measured 'per second' whereas I (think) I need to work with 'per frame'. This is where I'm getting confused.

So, take this example:

If set my initial Time value to 4 seconds, then if it remained constant at this speed, it would take 4 seconds to reach the bottom, if I changed my ticksPerSecond, because the time value is worked out using delta, it would still take 4 seconds but if I apply 'fallAccel" to the Time value (i.e. subract it), it goes wrong when I change the ticksPerSecond value - why?

How can I get this to fall at the same rate regardless of the value of 'ticksPerSecond' - any help in understanding this would be appreciated.

# Answer
> 1 votes
Thanks to the contributors who answered this.

I went with my own solution in the end because it was simply enough to implement and gave perfect results.

All I had to do to scale the acceleration, was the following:

```
float fallAccel=(dt * num);  //Where num is any arbitary amount and dt is the delta time between frames (hence it is scaled and also adjustable)

```

Once I apply this, my sprite will fall at the same rate regardless of how many game updates per second I run (ticksPerSecond).

I hope this may help others if they have similar problems in the future :-)

# Answer
> 3 votes
Part of the problem is that your notion of 'velocity' isn't physical. Your updating of position is fine:

```
spriteYReal = spriteYReal + (spriteYVel * dt);
sprite.yScreen=(int) (spriteYReal*r.height);

```

This just says that the sprite's position is computed as Pnew = Pold+V\*dt, which is fine - it means that V=dP/dt, which is correct. The problem is that the velocity update is incorrect, on a couple of different fronts:

```
spriteYTime-=fallAccel;
spriteYVel = 1/spriteYTime;

```

First of all, notice that unlike the position update, this one isn't corrected at all for different tick values, so changing your dt (i.e., your ticksPerSecond value) will change how quickly acceleration changes the velocity. But even correcting for that (for instance, doing something like `spriteYTime-=fallAccel*dt`) isn't really the right thing to do; that would be equivalent to saying V=1/(T0-A\*t) for some value of T0, which is physically incorrect. Instead, you want to do something roughly equivalent to what you've done for position:

```
spriteYVel = spriteYVel-(fallAccel*dt);

```

This will compute Vnew as Vold-A\*dt, which is what you want.

There's a slightly deeper problem here, though, one that's likely to get you in other ways: right now, this code closely couples the *representation* of its objects — the sprite — with their *display*; that is, the screen coordinates and especially the notion of `spriteYTime`, the 'time from top to bottom', as an inherent quantity of the object itself. I would suggest trying to separate the two ideas as much as possible; if you know approximately how long you want it to take for a sprite to travel from the top to the bottom of the screen then you can use the general formula for gravitational acceleration — X=X0+V0t+(1/2)At2 — to determine what you want its initial velocity to be in order to reach the bottom of the screen in that amount of time. (Note that this doesn't take into account terminal velocity, which makes things much more complicated, but I presume you don't need to know precisely how long it'll take to reach the bottom of the screen in any case).

# Answer
> 0 votes
Physics update rate must be independent from rendering frame rate. Becase it's not exactly 60 fps.

```
void update( float dt )
{
    float maxStep = 1/60.0f;
    if (dt > 0.25)
        dt = 0.25f; // note: max frame time to avoid spiral of death

    accumulator_ += dt;
    while (accumulator_ >= maxStep) {
        physical_world_->Step(maxStep);
        accumulator_ -= maxStep;
    }
}

```

So you have to take care about constant physics step. Sometimes for example it can be called 2 times per rendering frame.

You wrote:

```
spriteYReal = spriteYReal + (spriteYVel * dt);
//Convert to screen coordinates
sprite.yScreen=(int) (spriteYReal*r.height);
//Reduce time by fallAccel amount & update velocity value based on new time value (So sprite falls slightly faster this frame compared to the last
spriteYTime-=fallAccel;

```

I think you problem is you subtract fallAccel from time.

```
spriteYReal = spriteYReal + ((spriteYVel - fallAccel*dt) * dt);

```

Write something like this.

---
Tags: graphics, physics, platformer
---


# Question
Title: How to put a "mask" in front of the camera in Ogre?
Is there any easy way to put kind of a "mask" in front of the camera in an Ogre 3d application, so that parts of the scene are always covered by that mask? The idea is that I want to have an effect as if you would look through a keyhole, or as if you would look through a tube. There should be a black border around the center of the screen, so that the user only sees that center.

Ideally, I would be able to dynamically change the diameter of this circle through which the user looks on the scene. Thus that black border on the sides of the scene would become wider or narrower.

Any ideas how to implement that in Ogre?

# Answer
You could either use a post processing effect to draw a 2D overlay to the screen, or modify the stencil buffer to achieve the results you want. Ogre may facilitate the overlay effect easier than it would modifying the stencil buffer.

http://en.wikipedia.org/wiki/Stencil\_buffer
> 1 votes

# Answer
Another option is to create an actual 3D object that represents the keyhole or tube, and position it appropriately.

That has the advantage that it gives you more freedom to play with the camera position. You can either scale the model or move the camera to get different sized holes. It should also make it fairly easy to transition smoothly from another camera view to the looking through a keyhole one.

The only obvious awkwardness is that you may need to adjust the clip planes while it's there because the camera will be very close to it, so it might get clipped away if you don't.
> 1 votes

# Answer
Couldn't you just place a sprite with a texture that has the correct opacity pattern in front of the camera?
> 0 votes

---
Tags: camera, ogre
---


# Question
Title: Basic Python Question, Working with Function and List
I'm new to programming and learning Python over the web and I'm stuck on this problem.

The objective is to have a list of numbers and create a function that will evaluate that list of numbers and print out the matches and the position in the list the matches are found at.

I think I'm 90% there, but the function I wrote only prints out the first match it finds, then ends.

Here's what I have so far:

```
    list=[36, 36, 79, 96, 36, 91, 77, 33, 19, 3, 34, 70, 12, 12, 54, 98, 86, 11, 17, 17]

    def find(list,x):
        for i in range(len(list)):
            if x == i:
                print ("Found",x,"at position",i)

    find(list,12)
    find(list,91)
    find(list,80)

```

This correctly prints out:

"Found 12 at position 12", but fails to print the complete answer which is:

Found 12 at position 12 Found 12 at position 13 Found 91 at position 5

It appears the loop is ending prematurely, but I don't understand why. I realize this is probably pretty basic stuff, but I appreciate your time and any advice. Thanks in advance.

# Answer
The problem is that you are checking the **index** of the element, not the actual element itself. Substitute `list[i]` for `i` and it works, for:

```
list=[36, 36, 79, 96, 36, 91, 77, 33, 19, 3, 34, 70, 12, 12, 54, 98, 86, 11, 17, 17]

def find(list,x):
    for i in range(len(list)):
        if x == list[i]:
            print ("Found",x,"at position",i)

find(list,12)
find(list,91)
find(list,80)

```

However, this isn't very idiomatic ("pythonic") code. Using enumerate to iterate over a pairing of index/value, we can rewrite it as:

```
lst = [36, 36, 79, 96, 36, 91, 77, 33, 19, 3, 34, 70, 12, 12, 54, 98, 86, 11, 17, 17]

def find(lst, x):
    for i,value in enumerate(lst):
        if value == x:
            print("Found {0} at position {1}".format(value, i))

find(lst,12)
find(lst,91)
find(lst,80)

```
> 1 votes

# Answer
This belongs on stackoverflow.com.

This being said, you check if the current index (`i`) is equal to the desired number (`x`), so it will always return the same number as `x`.

Instead, you want to see **if the item in the list at the current index is equal to x**, like so: `if list[i] == x:`.

The index represent the current *position* that you're at, say first item, second, etc. You are looking for the *item* equal to `x`, so this is the nuance.

Good luck with the rest, and feel free to ask game related questions here, but make sure they are specifically about games! :)
> 0 votes

---
Tags: python
---


title: C# Stack<> Problem

text:
# Question
Title: C# Stack<> Problem
I'm trying to change List\<\> to Stack\<\> however I'm having a hard time figuring out.

A snippet of my code on where my issue occurs is:

```
    private Stack<Gem> gems = new Stack<Gem>();
    private Stack<Enemy> enemies = new Stack<Enemy>();

    private void UpdateGems(GameTime gameTime)
    {
        for (int i = 0; i < gems.Count; ++i)
        {
            Gem gem = gems[i];

            gem.Update(gameTime);

            if (gem.BoundingCircle.Intersects(Player.BoundingRectangle))
            {
                gems.RemoveAt(i--);
                OnGemCollected(gem, Player);
            }
        }
    }

```

The error messages that I'm recieving are:

```
  3 Cannot apply indexing with [] to an expression of type
   'System.Collections.Generic.Stack<Platformer.Gem>'

  4 'System.Collections.Generic.Stack<Platformer.Gem>' does not contain a definition for
     'RemoveAt'and no extension method 'RemoveAt' accepting a first argument of type
     'System.Collections.Generic.Stack<Platformer.Gem>' could be found (are you missing
     a using directive or an assembly reference?)

```

# Answer
You are trying to use a stack like a list. A stack has no random access. By that, I mean you can only take 'pop' off the stack what you just 'pushed'. Think of a stack of plates. You can only access the plate that you just put on the top of the stack.

Also, stack data structure is almost certainly something you do not wish to use for your purpose (updating game objects).
> 2 votes

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


# Question
Title: How do I determine a device's default orientation?
I am developing a game with accelerometer controls. This works well on all the *mobile phones* I've tested it on. However, when testing on a *tablet*, the y and x axes are reversed, presumably because the device's default orientation is landscape.

How can I identify the default orientation of the device, to set my axes accordingly?

(I'm using Android SDK 1.5 - 1.7.)

# Answer
I figured out the best way to do this is to check the screen size on the device and base a boolean conditional to device on which axis to use. This is tested and working great.

> // Check the screen layout to determine if the device is a tablet.

```
public boolean isTablet(Context context) {
    boolean xlarge = ((context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == 4);
    boolean large = ((context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE);
    return (xlarge || large);
}

```

> // Changle Accelx or Accely input based on the above (Im using OpenGLES 1.1)

```
if (isTablet(glGame)) {
    world.update(deltaTime, game.getInput().getAccelX());
}
if (!isTablet(glGame)) {
    world.update(deltaTime, game.getInput().getAccelY());
}

```
> 1 votes

---
Tags: android, input, orientation, axis
---


# Question
Title: What is the best way to close dialogs in a platform game controlled by keyboard only
I'm developing a flash puzzle platform game in my free time and I got stuck on deciding how to implement a feature. The game will be controlled by keyboard only, no mouse available.

My game will have Dialog boxes, used for story telling, announcing events, tutorial hints etc. I'd really prefer not to dedicate a large portion of the screen allowing the player to play while the dialog is displayed.

So my approach is to pop up the dialog and pause the game until the player closes the dialog. That's because the game has a small resolution (640 x 320) and some of the dialogs are pretty large (up to 5 lines text, talker's thumbnail etc).

*EDIT : Another major reason I want to pause the game, is that I want to be 100% sure the player will not miss a dialog. Also, I want her to read it in a certain level area, **before** visiting another area of the level, or doing something that will advance the plot.*

The thing Is that I can't find a way to make this work right. After testing the game with a few friends, I'm not satisfied from the feedback I get.

If I force them to close the dialog with one specific key (ACTION), I see people keep hitting keys randomly (e.g FIRE or JUMP key), while they know that it's closed with ACTION, like they did that 2 minutes before. They eventually get to close the dialog, but I can see they get a bit frustrated. I don't think they adopt the control as fast as I'd expect.

If I let them close the dialog with ANY key, they find themselves closing the dialog by mistake. Some of the dialogs are popping out while they're not expecting it.

So I'm starting to think that the 'Pause for dialog - close it to Resume' might be a bad idea in the first place. Do you think it is ? Or is it OK to have the dialog pause, but I just have to find the way to do it right ? Maybe the problem is not the controls, but something else, like say, I should not pop out the dialogs unexpectedly ?

Do you have any example of some game doing that right ?

# Answer
First of all: Don't just block user input as done by some games. It creates bad user experiences. One popular example: "What a horrible night to have a curse." (Castlevania II - Simon's Quest if you didn't know it. Lookup the Angry Video Game Nerd's review on YouTube. You'll get what I'm talking about.)

For dialog/story elements or tutorials the user should be able to read without having to worry about the actual game (i.e. longer texts):

Stop the game, then show the dialog using some kind of animation (even if it's just some kind of typewriter effect revealing letter by letter). Assign some "advance" key, usually what you'd use to shoot or jump. If the user presses this key, the animation is speed up and once it's complete, another button press (holding down the button shouldn't work so people can just skip the animation if they want to) will hide/advance the text.

For short messages:

Consider showing popups without backgrounds. Again, animations (e.g. floating in/out) can help to blend these without surprising users ("uh, was there some text for a moment?"). The user shouldn't have any influence over these messages, but they shouldn't halt gameplay either.
> 2 votes

# Answer
A good way of keeping users from making a dialogue choice or skipping by accident is to not allow the choice for a period after it has appeared. Depending on the seriousness of making the mistake you should choose a time somewhere in the 2 to 5 seconds range. Having a visual cue about what is going on is usually best as it informs the user that your application is not merely sluggish and that they don't have to wait for long.

Another option that has seen use in games is to make text appear only when the player stand in a predetermined location, often the location is marked to make the mechanic clear.

You may want either to make the text-box slightly transparent or make sure that it does not cover the area that the player inhabit so that navigating away from the spot won't be a blind task.
> 1 votes

---
Tags: platformer, keyboard, ui-design, messaging
---


# Question
Title: MMORPG with level system like The Elder Scrolls
Why arent there any MMORPS with a leveling system like the elder scrolls?

(Leveling skills/stats by using them and upgrading your character level at X skill lvlups)

And what are the Pros and Cons of this system?
EG:

Player's POV:

Pro:
You cant skill/stat your character wrong, because you can maximize all your skills/stats.

Cons:

Developer/Publisher POV

Pro:

Cons:
One character can maximize all skills/stats (so a player will probably only create one Character)

# Answer
See Ultima Online.
It has
3 Attributes: Strength, Dexterity and Intelligence.
3 Derived Attributes: HP, Mana and Stamina.
And a ton of skills, from weapon related skills, healing, stealth, cooking and even forensics. No levels! Character development is continuous rather than discrete.

You improve your skills by using them, an by increasing them you also increase the attribute related to the skill.

IMO, it's the most interesting character development mechanics in a game. It would rock in an sandbox single player game. I think the levels in TES games are not really needed.
> 2 votes

# Answer
Something like that is far from being ignored by MMORPGs.

Most just favor using some classic level/skill point based approach, because it's far easier to balance and control progression ("when being there, characters will have skill x, but not skill y").

Therefore most games skip something like that alltogether, or limit it to non-story/non-combat elements like crafting.

There are a few exceptions, as mentioned already:

* **Ultima Online** uses a similar system like the one you described.
* **Mortal Online** does so as well (don't quote me on that, might confuse the name).
* **The Elder Scrolls Online** (do I have to explain?).
* *Possibly a few others...*

However, I have to disagree with some of your pros/cons, because there are ways to limit/neutralize these without actually changing the mechanics:

* You can limit the total amount of skill points available/obtainable. Once some limit is reached, you'd have to "unlearn" something to improve further. Skyrim's initial release hasn't had unlimited skill points/levels for example.
* You can further limit the overall set of skills available (e.g. not everyone is able to cast spells). This is something **The Elder Scrolls Online** will use for their class skills (stats and other skills aren't limited by class though).
> 1 votes

# Answer
I can tell you only one thing - even in single player there are some overpowered builds with such huge stats and skill base. You need ages to balance such huge rpg leveling system for mmo. Coming back to classic - DnD system is great, but you need long time to know it and learn how to play. And still, it's (mostly) main goal and lore is "fantasy". Now look on GURPS. It's simple enough to start playing almost without knowledge at all, and it's lore is can be configured easy - you can make almost any rpg universe (sci-fi, fantasy, or even dynosaurs-on-submarines-world) easily. And you can keep balance easily too, without overpowered stuff.
> 0 votes

---
Tags: mmo, rpg
---


# Question
Title: Visual Studio 2010 C++ & OpenGL project cannot detect .lib files
So I'm trying to start a C++, OpenGL project on Visual Studio 2010, and I have put glut.h and glut32.dll in the project directory, along with the glut.dll and glut32.lib files in a folder named "glut" in the project directory.

I have also gone to "Porject Properties -\> Linker -\> Input -\> Additional dependencies" and I have typed in "glut32.lib" at the end, and made sure I am not missing a semicolon.

when I try doing

```
#include "glut.h"

```

in the Main.cpp file, it complains

```
error LNK1104: cannot open file 'glut32.libkernel32.lib'

```

Am I missing any files? What am I doing wrong here?

# Answer
> error LNK1104: cannot open file 'glut32.libkernel32.lib'

It looks like you're missing a separator character in your dependency options, glut32.lib and kernel32.lib are separate libraries. If you open the additional dependencies window, every entry should be on a new line.
> 2 votes

# Answer
Set the glut32.lib and kernel32.lib paths at Project Properties-\>configuration Properties-\>Linker-\>General-\>Additional Library Directories. If you don't have these lib files in local system/machine, you can download it from web.
> 0 votes

---
Tags: opengl, c++, visual-studio
---


title: Need help drawing obj file!

text:
# Question
Title: Need help drawing obj file!
I'm using GLFW and I want to draw a obj file. How are they drawn? I know how to draw 3D in OpenGL but when I open the obj file I see "v"s, "vn"s, "f"s, "vt"s, what are these? I don't know how to read these file types. Help? Thanks in advanced!

PS:

I can't find anything helpful online, that's why I'm asking this here.

# Answer
There is a good documentation on Wikipedia. The format is made by Wavefront, you'll find lot more information online with this name. This is the Wikipedia article.

Basically, `v` means vertex position, `vt` means texture coordinate and `vn` means vertex normal. `f` defines indices of a face.

It isn't that easy to draw `*.obj` models in a modern way, since their indexing works different from how OpenGL buffers work. In an `*.obj` file, indices (faces) point to a position, a normal and a texture coordinate separately. In OpenGL instead, an index is expected to point at at a single position in all those attributes at once.

I struggled with the format for some weeks and then decided to use the great loader Assimp which supports `*.obj` and `*.3ds` among many others. You may consider to use that library from the beginning.
> 1 votes

# Answer
The problem with the obj format is that it isn't standardised. So you'll see some that use clockwise winding (not good for a naive implementation in OpenGL) some that use counter-clockwise winding (not good for a naive implementation in DirectX) plus all other kinds of quirks that are vendor-dependent (eg. triangles vs quads as primitives).

The most usual implementation is an index based list.

v starts a line that contains information referring to vertices' geometry (their position, with 3 coordinates).

The next type of starts with vt followed by two numbers referring to texture coordinates.

The last type is vn which contains the normal vector for every vertex (useful for Gouraud or Phong shading).

The last important part starts with f, meaning face. Usually these are triangles but you may encounter quads. Lines that start with f may look like this : f 1/1/1 2/2/2 3/5/3.

That means you have three vertices: 1st vertex uses the position on the first line that starts with V , the texture coordinates on the 1st line that starts with vt and so on for vn.

The third index uses the information referenced in the fifth line that uses vn, while the other two paramters are from their respective third lines.

Knowing this, it is very easy to make an OBJ parser that reads such files, as long as you keep it simple and don't try to cover all cases (clock-wise counterCW , quds vs triangles) and so on.

Have fun!
> 1 votes

---
Tags: opengl, models, obj, glfw
---


# Question
Title: OpenGL ES 2.0: 2D game rendering, no performance gain with glDraw call batching
I just did a small benchmark. To my surprise batching sprites into a single draw call doesn't give any significant performance boost. Following are my results:

*Hardware:* iPod touch 4

*Extra info:* **OpenGL ES 2.0**. 1 sprite (64x64) having some transparency (smiley face with drop shadow). NO rotation, NO scale. (Texture is bound only once at the start in the init function). Compiled in "Release" mode.

The first column labeled 'N' shows number of sprites being tested. Second column shows FPS when sprites are batched in a huge vertex array (only 1 draw call). Third column shows FPS on multi draw calls, eg: 5000 draw calls for 5000 sprites.

**Benchmark 1: Alpha blending off**

**Benchmark 2: Alpha blending ON**

**Smiley image used:**

**Source code:**

**For single draw call:**

```
Vertex hugeArray[SPRITE_COUNT*6];
GLsizei stride = sizeof(Vertex);
int drawCallCount = 0;

const GLvoid* pCoords = &hugeArray[0].Position[0];
const GLvoid* pColors = &hugeArray[0].Color[0];
const GLvoid* pTexCoords = &hugeArray[0].Texture[0];

glVertexAttribPointer(positionSlot, 2, GL_FLOAT, GL_FALSE, stride, pCoords);
glVertexAttribPointer(colorSlot, 4, GL_FLOAT, GL_FALSE, stride, pColors);
glVertexAttribPointer(textureSlot, 2, GL_FLOAT, GL_FALSE, stride, pTexCoords);

GLsizei vertexCount = sizeof(hugeArray) / sizeof(Vertex);
glDrawArrays(GL_TRIANGLES, 0, vertexCount);
drawCallCount++;

cout << "DrawCall Count: " << drawCallCount << endl;

```

**For multiple draw calls:**

```
Vertex hugeArray[SPRITE_COUNT*6];
GLsizei stride = sizeof(Vertex);
int drawCallCount = 0;

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

    const GLvoid* pCoords = &hugeArray[i*6].Position[0];
    const GLvoid* pColors = &hugeArray[i*6].Color[0];
    const GLvoid* pTexCoords = &hugeArray[i*6].Texture[0];

    glVertexAttribPointer(positionSlot, 2, GL_FLOAT, GL_FALSE, stride, pCoords);
    glVertexAttribPointer(colorSlot, 4, GL_FLOAT, GL_FALSE, stride, pColors);
    glVertexAttribPointer(textureSlot, 2, GL_FLOAT, GL_FALSE, stride, pTexCoords);

    GLsizei vertexCount = 6;
    glDrawArrays(GL_TRIANGLES, 0, vertexCount);
    drawCallCount++;
}
cout << "DrawCall Count: " << drawCallCount << endl;

```

I thought that batching sprites into a huge array resulting in a single draw call would give a HUGE performance gain but benchmarks show otherwise. Any ideas what is going on here?

Thanks for reading the question :)

# Answer
> 4 votes
Here's some guesses for you to experiment with:

* Batch count is mainly a CPU load optimization, and not a GPU one. Try measuring CPU performance instead, for example by adjusting the positions so everything get clipped off screen.
* I wouldn't be surprised if the driver realizes that each batch is actually pointing into a contiguous array and merges them all itself. D3D certainly does that in some cases.
* Rendering exactly the same thing lots of times has different performance characteristics to rendering that number of different things, due to the cost of render state changes. It might be worth trying to measure rendering something that's a bit more realistic.

# Answer
> 1 votes
You actually are getting a performance increase, which is most significant around the N = 3000 mark (in the alpha blending off case). The solid 60fps for lower counts is, of course, being caused by vsync which means that your figures actually aren't valid. You'd probably do better with something like:

```
glFinish ();
startTime = GetTime (); // substitute with your own timing function
DrawABunchOfStuff ();
glFinish ();
endTime = GetTime (); // substitute with your own timing function
moreAccurateTime = endTime - startTime;
SwapBuffers ();

```

Even in this case, you're still including overhead from other parts of the pipeline; e.g. you may be fill-bound which would cause a limit on the effectiveness of batching (try drawing to a 1x1 viewport to rule this out), or you may be transform-bound which is also a fixed overhead irrespective if you batch or not (try using the most simple, primitive vertex shader possible to rule this out).

The most important point here is that batching only reduces overhead in one part of the pipeline - submitting primitives via draw calls. You're not going to get a magical and dramatic performance increase from it if you're bottlenecked elsewhere, because that other bottleneck will then become your primary limiting factor. When measuring your performance increase from batching it's important to isolate the effects of submitting draw calls so that these other bottlenecks don't skew your figures.

---
Tags: 2d, sprites, opengl-es, performance, opengl-es2
---


# Question
Title: Trying to get enemy sprites to move on C#
In my XNA game, I'm have the enemy sprites loaded and in the game screen. However, I put in the code to update their position in the Update method of the main class. The objective is to get the sprites to move from the right hand side of the screen to the left, and the player has to jump over them. Here's my code in the update method(note, the enemy sprites are created in a Texture2d list, and their positions in a Vector2d list):

```
                Vector2 ep1 = enemyPosition[0];
                Vector2 ep2 = enemyPosition[1];
                Vector2 ep3 = enemyPosition[2];

                        if (enemyPosition[0].X < 800)
                        {
                            ep1.X--;

                        }

                        if (enemyPosition[1].X < 800)
                        {
                            ep2.X--;

                        }

                        if (enemyPosition[2].X < 800)
                        {
                            ep3.X--;

                        }

```

# Answer
you change value of the variables - ep1, ep2, ep3, but you dont change objects coords.

For moving from right side to left side you can try anything like this (also you can use foreah):

```
for (int i=0; i<3; i++)
{
    if (enemyPosition[i].X > 0)
    {
        enemyPosition[i].X--;
    }
}

```

P.S. Sorry for my bad English.
> 2 votes

# Answer
In C#, there are two situations that might happen when you copy something, for example `Vector2 position = positions[0];`:

1. If the object is a **struct**, it will copy the entire object. `float` is a structure, `int` is a structure, `double` is a structure. Basically, this quote from msdn sums it well: `Structs are copied on assignment. When a struct is assigned to a new variable, all the data is copied, and any modification to the new copy does not change the data for the original copy.`
2. If the object is a **class**, it will be passed around as a reference. `string` is a class and you usually make classes. When passed to a function or assigned to an object, modifying the copied object actually modifies the original object itself, since it is a reference.

What does this mean to us? Well, we have to be very careful when we pass variables around. When we pass a structure, we must know that it is not actually modified (unless we use keywords such as ref or out). When we pass a class, we must know that the original object might be modified (although there are ways to clone a class).

Now, Vector2 is a structure. It implies that we can't iterate through it with a foreach loop (as you have tried) and that any copy will not modify the original object. So, when you do `Vector2 ep1 = enemyPosition[0];`, you make a copy and *only modify the copied version*, so the objects won't move.

Instead, modify the objects directly, and I would recommend using a for-loop instead of doing it line-per-line. This will allow you to modify it later and add/remove objects without needing to modify your code. Do it like so (assuming that `enemyPosition` is a `List<Vector2>`):

```
for (int i = 0; i < enemyPosition.Count; ++i)
{
    if (enemyPosition[i].X < 800)
    {
        enemyPosition[i].X--;
    }
}

```

By using the loop, you remove code duplication, which makes it easier to later modify the program and fix bugs without forgetting a piece of your code. Always try to remove code duplication when you can, it will make your code more flexible.

In the same order of ideas, if we want to make it easier to change the program later on you might want to use constants rather than magic values. The `800` here requires the reader of the code to implicitly understand what it represents, therefore making it less readable and less flexible if you use this value somewhere else. I would advise against magic values. Instead, you could do the following:

```
// Somewhere in your class...
const int ScreenWidth = 800;

// In your Update method...
for (int i = 0; i < enemyPosition.Count; ++i)
{
    if (enemyPosition[i].X < ScreenWidth)
    {
        enemyPosition[i].X--;
    }
}

```

After that, you could change to a design with classes instead, which will probably make it all much cleaner. See Katana314's answer for doing so.
> 1 votes

# Answer
Jesse Emond is correct. As for how to orient your code correctly; My best suggestion to solve your problem is to take a more class-oriented approach, even if just by a little bit. Rather than maintain a list of each enemy's position, maintain a list of enemies, each of which has a position. That way you could add other attributes to enemies too. Most importantly, modifying an Enemy's position directly is going to be much easier than trying to make sure you always maintain references to the same Vector2's. (if Enemy's are Objects, then you'll know a second one won't be made unless you call **new**). I'd even recommend giving Enemy's a "move(amount)" method.
> 1 votes

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


# Question
Title: My Sprite Rectangle moves, but my sprite doesn't
Here's the issue, When I build, everything loads fine, everything works, but then, when you enter the game, the sprite is there. However, The sprite does not move, the sprite RECTANGLE does. Meaning that, if I used my arrow keys to move the "sprite", as I defined them in the update method of my class, the rectangle would move freely, and cut off parts of the sprite. If I moved it the right far enough, the rectangle would leave the sprite, and the sprite will disappear.

Here's a picture of what it looks like:

and another when I use my arrow keys to move:

Here is the code from my sprite class:

```
class Player : Sprite
{
    const string PLAYER_ASSETNAME = "CharacterLeft";
    const int START_POSITION_X = 125;
    const int START_POSITION_Y = 245;
    const int WIZARD_SPEED = 160;
    const int MOVE_UP = -1;
    const int MOVE_DOWN = 1;
    const int MOVE_LEFT = -1;
    const int MOVE_RIGHT = 1;

    enum State
    {
        Walking
    }
    State mCurrentState = State.Walking;

    Vector2 mDirection = Vector2.Zero;
    Vector2 mSpeed = Vector2.Zero;

    KeyboardState mPreviousKeyboardState;

    public void LoadContent(ContentManager theContentManager)
    {
        Position = new Vector2(START_POSITION_X, START_POSITION_Y);
        base.LoadContent(theContentManager, PLAYER_ASSETNAME);
    }

    public void Update(GameTime theGameTime)
    {
        KeyboardState aCurrentKeyboardState = Keyboard.GetState();

        UpdateMovement(aCurrentKeyboardState);

        mPreviousKeyboardState = aCurrentKeyboardState;

        base.Update(theGameTime, mSpeed, mDirection);
    }
    private void UpdateMovement(KeyboardState aCurrentKeyboardState)
    {
        if (mCurrentState == State.Walking)
        {
            mSpeed = Vector2.Zero;
            mDirection = Vector2.Zero;

            if (aCurrentKeyboardState.IsKeyDown(Keys.Left) == true)
            {
                mSpeed.X = WIZARD_SPEED;
                mDirection.X = MOVE_LEFT;
            }
            else if (aCurrentKeyboardState.IsKeyDown(Keys.Right) == true)
            {
                mSpeed.X = WIZARD_SPEED;
                mDirection.X = MOVE_RIGHT;
            }

            if (aCurrentKeyboardState.IsKeyDown(Keys.Up) == true)
            {
                mSpeed.Y = WIZARD_SPEED;
                mDirection.Y = MOVE_UP;
            }
            else if (aCurrentKeyboardState.IsKeyDown(Keys.Down) == true)
            {
                mSpeed.Y = WIZARD_SPEED;
                mDirection.Y = MOVE_DOWN;
            }
        }
    }

}

```

}

and here's the code to my main sprite class:

```
class Sprite
{
    //The asset name for the Sprite's Texture
    public string AssetName;

    //The Size of the Sprite (with scale applied)
    public Rectangle Size;

    //The amount to increase/decrease the size of the original sprite.
    private float mScale = 1.0f;

    //The current position of the Sprite
    public Vector2 Position = new Vector2(0, 0);

    //The texture object used when drawing the sprite
    private Texture2D mSpriteTexture;

    //The player Rectangle
    private Rectangle SpriteRect;

    //Load the texture for the sprite using the Content Pipeline
    public void LoadContent(ContentManager theContentManager, string theAssetName)
    {
        mSpriteTexture = theContentManager.Load<Texture2D>(theAssetName);
        AssetName = theAssetName;
        Size = new Rectangle(0, 0, (int)(mSpriteTexture.Width * mScale), (int)(mSpriteTexture.Height * mScale));
    }

    //Draw the sprite to the screen
    public void Draw(SpriteBatch theSpriteBatch)
    {
        SpriteRect = new Rectangle((int)Position.X, (int)Position.Y, mSpriteTexture.Width, mSpriteTexture.Height);
        theSpriteBatch.Draw(mSpriteTexture, Position,SpriteRect, Color.White, 0.0f, Vector2.UnitX, 1f, SpriteEffects.None, 0);
    }

    public void Update(GameTime theGameTime, Vector2 theSpeed, Vector2 theDirection)
    {
        Position += theDirection * theSpeed * (float)theGameTime.ElapsedGameTime.TotalSeconds;
    }

    //When the scale is modified throught he property, the Size of the
    //sprite is recalculated with the new scale applied.
    public float Scale
    {
        get { return mScale; }
        set
        {
            mScale = value;
            //Recalculate the Size of the Sprite with the new scale
            Size = new Rectangle(0, 0, (int)(mSpriteTexture.Width * Scale), (int)(mSpriteTexture.Height * Scale));
        }
    }

}

```

}

# Answer
In the overload of `SpriteBatch.Draw` that you are using, which you call like so:

```
SpriteRect = new Rectangle((int)Position.X, (int)Position.Y,
    mSpriteTexture.Width, mSpriteTexture.Height);
theSpriteBatch.Draw(mSpriteTexture, Position,SpriteRect, Color.White, 0.0f,
    Vector2.UnitX, 1f, SpriteEffects.None, 0);

```

You are passing `SpriteRect` into the method parameter which defines the sprite's source rectangle. Here's the method signature.

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

```

Also from that linked MSDN documentation:

> *sourceRectangle*
>
> Type: Nullable\<Rectangle\> A rectangle that specifies (in texels) the source texels from a texture. Use **null** to draw the entire texture.

So when your sprite's position changes, the drawn texture is a different region of your asset. That is the source of your symptoms.

You need to change one or both of those lines to the following:

```
// (this Rectangle SpriteRect doesn't need to update!)
SpriteRect = new Rectangle(0, 0, mSpriteTexture.Width, mSpriteTexture.Height);
// (Or even exist!)
theSpriteBatch.Draw(mSpriteTexture, Position, null, Color.White, 0.0f,
    Vector2.UnitX, 1f, SpriteEffects.None, 0);

```
> 2 votes

---
Tags: c#, xna-4.0, sprites, spritebatch
---


# Question
Title: Can I write code from 2 computers at the same time?
So I know it might not be that related to game dev, but I'm now starting a project with friends and we want to code. Thing is, we are not living close, and when several programmers write different classes or parts of code, syncing is a problem. Skype is not fast enough, it actually makes it worse (you need to pack and unpack .zip solution file), nor email.

***Any one got a software that can connect 2 (or more) computers, and when we write code it will show up (simultaneously) on one of them/both?***

I don't care much for lags, if we need to wait few secs till it shows up, it's fine.

I thought about TeamViewer, but as far as I remember only one can write/do an action at a time.

Thanks!

# Answer
> 4 votes
If you are using Visual Studio, you can download VS Anywhere. You can have many person typing codes simultaneously, and it doesn't lag much. Though it's kinda buggy sometimes. I'm using it with my friends all the time! Here's the link , enjoy :)

http://visualstudiogallery.msdn.microsoft.com/99466148-ae68-4bd5-b66b-08bae7423a03

# Answer
> 11 votes
This is really hard to pull off, because real concurrent editing (on the same files) can be rather tricky.

I'd focus on some source code versioning system like SVN, Mercurial, or Git.

If you're using Visual Studio, the best option would be using their Team Foundation Server or - with the addon being in beta right now - Git.

Setting up a Git repository isn't that hard (you can also use third party hosting like the on provided by GitHub and others).

You'll then just have to install the Visual Studio Tools for Git to interact with your repository, sync code, etc.

This will require some setup and getting used to, but it should help you a lot merging changes and conflicts (i.e. when someone is editing the same files at the same time).

If you want fully automated syncing, you should try Dropbox, Cubby, or BitTorrent's Sync. These work more automated, but will give you trouble if both of you edit something at the same time.

# Answer
> 6 votes
There is a great number of text editors which allow several users to simultaneously edit the text. "Simultaneously" in this case means that when you open a document and someone else is/are editing it, you see those someone else's cursors, and what changes they make -- in real time. Obviously, you can make your own changes too, and they will be broadcast to other users.

This is called a Collaborative real-time editor (Wikipedia article provides quite a comprehensive list of those).

# Answer
> 5 votes
You're looking for a source control solution. These are a common part of the industry. Large Open Source projects often have dozens (and in a few cases hundreds or thousands) of individual developers spread over the entire world.

Solutions like GitHub, BitBucket, SourceForge, and more offer these services for free (often only if you make your code publicly viewable, though). They allow you to "commit" changes and "push" them to a central server, then allowing the other developer(s) to "pull" those changes.

This is not instant. You don't usually want it to be. You want to be able to compile and run your changes against a known stable/functional base and then only sync up when you have completed a feature or fix, thereby ensuring that you aren't held back by a teammates incomplete changes or vice versa.

If you both edit the same file, you will have to "merge" your changes when syncing. Modern tools usually do a fairly good job of figuring this out automatically, though something you'll have to help it out and manually figure out how to merge some overlapping changes. Typically, just avoid doing this; there is usually little reason for two developers to be simultaneously working on the same feature or fix, even if sitting next to each other, much less when geographically separated. Your project likely has a number of different tasks which can be completed in parallel.

This is how multi-developer projects are handled in the corporate world, the Open Source world, and even most smooth private/small/school/hobbyist projects.

An additional advantage to a good source control system is that it maintains history, allowing you to back up to an older version if necessary, see who made which change, and so on.

If you really want instantaneous syncing, you might consider using DropBox. Your IDE will typically have some trouble if edits are made to the file, but again, just don't do that.

There are also some text editors (generally not full IDEs) that have networked text editing, or even some online editors. The experience will not be a good one.

# Answer
> 4 votes
The normal answer to work on different files rather than trying to edit the same one. Anything big enough to involve multiple people will also involve multiple files.

---
Tags: c#, synchronization
---


# Question
Title: Farseer: Difficulties with ContactListener
How can I register the ContactListener in XNA? In the box2d manual is written:

9.4 Contact Listener ... At run-time you can create an instance of the listener and register it with b2World::SetContactListener. Be sure your listener remains in scope while the world object exists.

http://www.box2d.org/manual.html#\_Toc258082975

How can I do that? I want to use PreSolve to disable collision between the character and some tiles.

# Answer
Problem solved with:

```
world.ContactManager.PreSolve += new PreSolveDelegate(PreSolve);

```
> 2 votes

---
Tags: xna, c#, physics, farseer-physics-engine
---


title: Slick2D and TileD

text:
# Question
Title: Slick2D and TileD
I've been learning Java for a while, and with my aims of being a game developer later in life, I've came across Slick2D+lwjgl and following tutorials and making some little things. However; I don't have a clue what to do when it comes to the tileD maps. here's what I've done so far; I've made my map and it's called map.tmx and it has collision objects in it, how do I get my code to run this map and the sprite to "interact" with it. Thanks for any help :)

Edit: I got it rendered onto the program... but how can I make the sprite stop on some platforms I've made? :)

# Answer
> 1 votes
You need to create polygons to check for collisions and check them every step in updating the position. I found example in the internet and try translate comments to English. You can download example.

Other way is creating collision map, like this

P.S. Sorry for Google-translate.

---
Tags: java, tiles, lwjgl, slick, eclipse
---


# Question
Title: What are some ways to prevent or reduce cheating in online multiplayer games?
Punkbuster exists just to prevent cheating, and yet cheating is common in punkbuster enabled games. Modern Warefare 2 is seriously locked down from the end user running their own server or making any mods, and cheating happens constantly.

For a multiplayer game where each client is running on a PC, what can be done to reduce or eliminate cheating?

# Answer
> 18 votes
It depends how they're cheating, focusing on one of the primary ways of creating cheats, other processes latching into your application and modifying it - you can enumerate through all other processes, and hook their memory manipulation methods, and their keyboard/mouse emulation methods.

Wallhacks are typically written by injecting code between your process and the DirectX/GL libraries to set the transparency on materials so they can be seen through. You can add some code to your scenegraph/culling system to specifically not draw other players/useful entities if they're behind walls (to prevent cheating that way).

If you're going multiplayer and want to prevent packets being modified between client/server, then creating a checksum of the data you're sending via some algorithm of your own and checking this as it comes through on the other side can be effective. (You will probably end up doing this anyway for various QA purposes).

The same goes for most of your in-memory resources, creating a checksum at the beginning of a frame, and verifying it at various stages can yield in some pretty handy memory manipulation detection.

This is quite an involved topic, but hopefully this sets you in a vaguely acceptable direction.

# Answer
> 17 votes
At the most extreme solution, you basically never trust the client. For games like MMOs, users don't run their servers, and any gameplay logic is handled server side. Never give the client the authority to say "I have X health" or "I have X ammo", etc.

# Answer
> 10 votes
If you've got a system where the logic is expensive and must be done mostly on the client to save server cycles, you can implement a probabilistic cheat detection system. Every few minutes it chooses a different few players to inspect closely and consistency-check on the server. Since cheaters rarely limit their cheating to short and rare periods of time, they *will* be caught eventually.

Another benefit to this is that they won't have a rapid turnaround cycle for development - if it takes 10 hours of gameplay on average for the server to pay attention to you, then that's a 10-hour turnaround cycle every time you want to see if something worked. And if it *did* work, it's even longer because they won't know if the server has given them a thumbs-up or just hasn't gotten around to them.

# Answer
> 5 votes
There are also many types of aim-assist hacks for first person shooters that also work by hooking into graphics library calls. OGC Hook for Counter-Strike / HL1 had a multitude of options beyond making walls transparent.

If the location info for enemies is at some point passed to a lower level library which has widely available code, those calls can be hooked into and the location, scale, rotation, etc. data can be used to precisely calculate the best vector for firing upon that enemy. Anti-cheat systems like PunkBuster often include heuristic-type detection (how often does this player get a perfect shot, how often do they spin around 180 degress to land a one-shot kill, etc.) in addition to memory and process monitoring.

Ultimately the task of preventing cheating in multiplayer games is a game of cat and mouse. As new cheats are developed, new anti-cheat methods are created, and then new cheats are built to avoid the new anti-cheat technologies.

As Tetrad said in his response, the only hard and fast rules for "game security" are to provide the client as little information as possible, and to trust the client as little as possible. Different types of games will have different requirements that can impact how well you can adhere to these rules, though.

In an FPS game, because the speed of gameplay is so fast, it is often not possible to only provide the client with data it should know about this exact instant. If you don't tell the client there is an enemy around the corner and the player does go around that corner you suddenly have to send them that information in a matter of milliseconds or risk having the player be killed by an enemy they didn't ever see.

The only "fix" for these issues that is currently available would probably be OnLive. Because that service only delivers audio and video content from a client running safely in the datacenter the only means for cheating would be to essentially create a human AI that could analyse the incoming video stream and take action based upon that -- a task that few, if any, cheaters are up to.

# Answer
> 3 votes
All the answers above are great, but I'll add another piece:

Some games have a very solid replay feature, which allows to save every game's replay after the game's end in a compact format, and watch it in various ways - different player perspectives, real-time statistics UI and so on.

Example that I'm very familiar with: Starcraft 2. One of the ways that Blizzard blocks hackers is by receiving cheating evidence as game replays.

An example for usage in an FPS would be: if you played a game and you suspect that the other person cheated with a wall-hack, you watch the replay, and then see that in his normal replay vision, he couldn't have possibly seen you and throw a grenade over the corner, or whatever.

You then report him with the replay, and if the evidence against him is good enough, he's banned. As far as I know, companies who do this things only take serious evidence, or multiple sources of evidence of the same behavior before banning.

So this is not an anti-debugging technique, it's a user report system that allows convenient human-assisted proof of cheating.

# Answer
> 0 votes
This may not be a full answer, but I have some input here. One of the best ways to prevent cheating is obfuscation or using C/C++. This prevents people from modifying the client code.

---
Tags: multiplayer, anti-cheat, security
---


# Question
Title: Get the address of a matrix in GLM library
Is there a way to get the address of a matrix from a GLM matrix?

I'm using opengl 4 and glm library though I can't seem to find anything, which might help.

# Answer
You can access the memory of any glm type by using glm::value\_ptr. Matrix types store their values in column-major order, and as floats.
> 1 votes

---
Tags: c++, opengl, glm
---


title: How to rotate camera around some point?

text:
# Question
Title: How to rotate camera around some point?
I have screen with dimensions: `800x600`. The object that I want to rotate around is located at `(400,300, -50)` \- center of the screen. Orthogonal projection: Near plan - 0.1f, far plane - 1000.0f left - 0, bottom - 0, right - 800, top - 600

Camera: position at `(0,0,0)` look at `(0,0,-50)` up vector `(0,1,0)`

Now what I'm doing to rotate is calculate the `X` of "look at" using: `0 + width * cos(A)`. `Y` remains the same (0). Z is calculated using: `-50 + width * sin(A)`.

Now the problem that I'm facing is that after some angle the object starts to disappear, and it doesn't rotate around the object. What can be the problem?

# Answer
> 1 votes
The image of a point A under a rotation around another point B (an affine rotation if B is not the origin of the space) is A', with

```
A' = B + R*(A-B)

```

where R is the matrix of the associated linear rotation.

For example, in dimension 2, say you want to rotate A = (1,0) around B = (1,1) by 90 degrees counter-clockwise. That will yield (2,1). Make a picture if needed. And, if we call R the matrix of the linear counter-clockwise rotation of angle 90 degrees, we have

```
R = (0 -1)
    (1  0)

```

and

```
(1,1) + R*( (1,0) - (1,1) ) = (1,1) + R*(0,-1)
                            = (1,1) + (1,0)
                            = (2,1)

```

Now, the solution to your problem actually depends on your implementation of world and camera geometry. You can either rotate your camera around point B or you can "rotate the world" around the camera by the inverse of the previous rotation (as usual in the "ProjectionMatrix * CameraMatrix * ModelMatrix * positionOfVertex" part of a vertex shader, if it's OpenGL or DirectX you're using).

---
Tags: c++, opengl, glm
---


# Question
Title: smooth shading vs flat shading, what's the difference in the models?
I'm loading the exact same model with Assimp, except one is exported from Blender, shaded smoothly, and the other was exported from Blender, shaded flatly. Here is my results from loading both into my game:

The Flat drawn model has 1968 vertices and the Smooth drawn model only has 671, why is this happening, I don't understand why there would be less vertices when it's shaded smoothly...?

# Answer
> 4 votes
For smooth shading, two adjacent triangles must share common vertex normals. The reason is interpolation. The normal from one vertex is smoothly interpolated to the normal on the second vertex. You need to ensure that the normal of triangle at a particular vertex matches the normal of all adjacent triangles at that same vertex. If you think of a smooth sphere, each vertex on the surface (which is used by multiple triangles) has a single normal.

With flat shading, the normal for each vertex on every triangle must be the same so that when interpolated the value is the same across the whole surface. This means that if a single vertex is shared by multiple triangles then the vertex must be duplicated for each triangle in order to have an independent normal for each triangle.

Overall this means that a smoothly-shaded model can share vertices in ways that a flat-shaded model cannot.

---
Tags: opengl, c++, assimp
---


# Question
Title: In the Direct3D 9 Effect API, how do you find the texture variable linked to a sampler?
In Direct3D 9 effect files you can write a sampler state that specifies a texture variable to use, like

```
Texture2D g_texSkyDome;
SamplerState g_samplerSkyDome
{
    Texture = <g_texSkyDome>;
    // ...other sampler states...
};

```

Using the ID3DXEffect API, is it possible to extract the texture variable assigned to a given sampler state variable? I've been searching the docs but can't find anything about this.

# Answer
> 1 votes
I still haven't found an "official" way to do this via the API. In fact, there is no provision for extracting any of the contents of a SamplerState block - either the texture or any of the state settings.

There are some hacky, roundabout ways one could do this:

1. You could give each sampler state an annotation that names the corresponding texture variable, or vice versa. A variant on this approach is to set up a naming convention, e.g. the texture is named `texFoo` and sampler `samplerFoo`. Of course, nothing would prevent these from getting out of sync with the actual texture variable assignments.
2. Scan the HLSL file for `SamplerState` definitions and parse them yourself. You'd probably want to run it through the preprocessor first. The parser doesn't have to be *too* complicated if you make a few simplifying assumptions, e.g. that the word "SamplerState" never occurs anywhere but the definition of a sampler variable.
3. You could create a dummy texture, assign it to a texture variable with `ID3DXBaseEffect::SetTexture`, then run through all the texture units with `IDirect3DDevice9::GetTexture` and see which one ended up with your dummy texture. You could then correlate this with the sampler index obtained by `ID3DXConstantTable::GetSamplerIndex` from each sampler variable in the effect. You could also use `IDirect3DDevice9::GetSamplerState` to get the rest of the sampler state.

# Answer
> 2 votes
Similar to solution #3 in your answer, but perhaps a little cleaner in that no device state will be modified: you could create an ID3DXEffectStateManager that no-ops all of the operations, but tracks the index to which your dummy texture was assigned. (You could also use your custom state manager to snoop the sampler state settings.)

---
Tags: shaders, hlsl, directx9
---


title: 2D Graphics in CMD in C#

text:
# Question
Title: 2D Graphics in CMD in C#
So, almost every programmer used Doom as inspiration for new Projects, right? So Doom and other classic MS-DOS game were played on something like Command Prompt. How do you display images in Command Prompt without using System.Windows.Forms? By the way, I don't accept add-ons. (It doesn't have to be 3D)

# Answer
> 2 votes
Games like Doom ran in 16 bit real mode under DOS. In this environment, there were system calls, called interrupts, that you could call to switch the display into several graphics modes.

The most popular at the time was mode 13h. It was called this, because you called interrupt 10h (h specify that this is a base 16 number), with register al loaded with 13h, ah set to zero. 16 bit assembly going something like:

```
xor ah,ah
mov al,13h
int 10h

```

Once in this mode, you could write directly to graphics memory that started at offset 0xA0000. See the wikipedia article, or many mode 13h tutorials on the web for how to do this.

Do note, to do any of this today, you need to have a compiler capable of outputting 16-bit code, or an 16-bit assembler.

*Edit*
To be clear, I answered to provide some historical background on your question, and to show you how you could do this sort of programming still today, if you wanted to, for purely educational purposes. Please note, this is not possible with C#.

# Answer
> 0 votes
Doom itself had little to nothing to do with the command line. They actually had APIs to do graphics back then, much of the use written ones use the method Stephan explained. I've also seen command line graphics done in C++ though, but it had to do with lots of code. None of this is possible in C#.

Anyway if you want to do graphics why bother with the command line? Try an API such as XNA or OpenTK?

I also would not advise such bland questions on this site. Please explain more next time!

---
Tags: c#, 2d, .net, console
---


title: Pygame top down shooter firing bullets

text:
# Question
Title: Pygame top down shooter firing bullets
I'm working on a top down shooter in pygame and am having trouble getting bullets to fire. I'm using a class for the bullets, I'll show what I think is the relevant code.

This is what I do after the mouse button is clicked:

```
if event.type == pygame.MOUSEBUTTONDOWN:
        bullet_vel=[0,0]
        fired_pos=pygame.mouse.get_pos()
        player.fired=True
        bullet_pos_from_player=[0,0]

        bullet_pos_from_player[0]=fired_pos[0]-player.rect[0]
        bullet_pos_from_player[1]=fired_pos[1]-player.rect[1]
        bulletdistance=math.sqrt(abs((bullet_pos_from_player[0])^2) + abs((bullet_pos_from_player[1])^2))
        bullet_vel[0]=bullet_pos_from_player[0]/bulletdistance
        bullet_vel[1]=bullet_pos_from_player[1]/bulletdistance

        print bullet_vel[0], bullet_vel[1]

        bulletgroup.add(bullet((bullet_vel)))

```

and here is my class for the bullet:

```
class bullet(pygame.sprite.Sprite):
def __init__(self, bullet_vel):
    super(bullet,self).__init__()
    self.pos=player.draw_pos
    self.image=pygame.transform.rotate(bullet_image, player.angle)
    self.vel=bullet_vel

def update(self):
    self.pos[0]=self.pos[0]+self.vel[0]
    self.pos[1]=self.pos[1]+self.vel[1]
    screen.blit(self.image, self.pos)

```

Hope someone can help out,

thanks guys.

# Answer
> 2 votes
The error is likely the typo in the line:

```
pygame.sprite.Sprite.__init(self)

```

The `__init__` function in python is special, and should be called as such. That being said, your code would be cleaner and you could avoid these issues if you used new-style class inheritance:

```
class bullet(pygame.sprite.Sprite):
    def __init__(self, bullet_vel):
        super(bullet, self).__init__()
....

```

Another fairly egregious error is in these lines:

```
    bullet_vel[0]=math.ceil(math.sinh(bullet_angle)*bulletspeed)
    bullet_vel[1]=math.ceil(math.cosh(bullet_angle)*bulletspeed)

```

The problems are:

1. `sinh` and `cosh` are hyperbolic functions, and not what you want. You're probably looking for the regular `sin` and `cos` functions.
2. `cos` corresponds to the x-axis, and `sin` corresponds to the y-axis. You have them reversed.
3. There is no need to take the cieling of them... python does a good job of handling floating point. If you need them to be integers for the sake of pygame's libraries, then it's better to call `int()` on them once you need to.
4. The `sin` and `cos` functions take arguments in radians

Finally, you're not saving the value of your bullet\_vel variable in your bullet's `__init__` function. Hence, if you ever do reach the bullet's `update` call, then it will raise an error. You will need to add something like

```
self.vel = bullet_vel

```

to the `__init__` function and call `self.pos.move(self.vel)` in the bullet's `update` function.

---
Tags: python, pygame
---


# Question
Title: sprite array problem with initialization
I have a problem with my Sprites. I'm trying to create a lot of Sprites. However, I got a problem in that I have several grass tiles and I don't want to do this

grass1 = new Sprite...; grass2 = new Sprite..;

The problem is I make an array of Sprites say Sprite\[\] grass = new Sprite\[7\]; I don't know how I would intialize them. I need to put

```
for(int i=0; i<grass.length;i++){
        grass[i] = new Sprite(16,0,i,SpriteSheet.tiles);
    }

```

Somewhere, however I get an error saying you have to put it in a bracket. I get a syntax error. I'm thinking that I should put it into the constructor so I have

```
    public Sprite(){
    for(int i=0; i<grass.length;i++){
            grass[i] = new Sprite(16,0,i,SpriteSheet.tiles);
         }
    }

```

However, I think that is bad for memory. I don't know how to solve this. I think I need to use an array list. Maybe, create an array list of grass and then add elements in it.

```
   public class Sprite {
        public final int SIZE;
        private int x;
        private int y;
        public int[] pixels;
        private SpriteSheet sheet;

        public static Sprite[] grass = new Sprite[7];
        for(int i=0; i<grass.length;i++){
            grass[i] = new Sprite(16,0,i,SpriteSheet.tiles);
        }

        public static Sprite voidTile = new Sprite(16,0xffffff);

        public static Sprite player_up = new Sprite(32,0,5, SpriteSheet.tiles);
        public static Sprite player_back = new Sprite(32,2,5, SpriteSheet.tiles);
        public static Sprite player_right = new Sprite(32,1,5, SpriteSheet.tiles);
        public static Sprite player_left = new Sprite(32,3,5, SpriteSheet.tiles);

        public static Sprite player_up1 = new Sprite(32,0,6, SpriteSheet.tiles);
        public static Sprite player_back1 = new Sprite(32,2,6, SpriteSheet.tiles);
        public static Sprite player_right1 = new Sprite(32,1,6, SpriteSheet.tiles);
        public static Sprite player_left1 = new Sprite(32,3,6, SpriteSheet.tiles);

        public static Sprite player_up2 = new Sprite(32,0,7, SpriteSheet.tiles);
        public static Sprite player_back2 = new Sprite(32,2,7, SpriteSheet.tiles);
        public static Sprite player_right2 = new Sprite(32,1,7, SpriteSheet.tiles);
        public static Sprite player_left2 = new Sprite(32,3,7, SpriteSheet.tiles);

        public Sprite(int size, int x, int y, SpriteSheet sheet){
            this.SIZE=size;
            pixels = new int[SIZE*SIZE];
            this.x=x*SIZE;
            this.y=y*SIZE;
            this.sheet = sheet;
            load();
        }

        public Sprite(int size, int colour){
            SIZE=size;
            pixels= new int[size*size];
            setColour(colour);
        }

        private void setColour(int colour) {
            for(int i=0; i<SIZE*SIZE; i++){
                pixels[i]=colour;
            }
        }

        private void load() {
            for(int y=0; y<SIZE; y++){
                for(int x=0; x<SIZE; x++){
                    pixels[x+y*SIZE]=sheet.pixels[(this.x+x)+(this.y+y)*sheet.SIZE];
                }
            }

        }

    }

```

# Answer
> 0 votes
I assume you're using C#. Even if you're using Java your problem lies here:

```
public static Sprite[] grass = new Sprite[7];
for(int i=0; i<grass.length;i++){
    grass[i] = new Sprite(16,0,i,SpriteSheet.tiles);
}

```

This `for()` loop is outside any function, and as such not acceptable.

You can't initialize array members that way for static members (or any other members).

If you're using Java, you can use the following code for inspiration, but it won't work 1:1.

There might be better methods to do this in newer versions of C#/.NET, but I'd just create some initializer code called in every constructor (this will work in any version of .NET):

```
private void Initialize() {
    static bool init_done = false;
    if (!init_done) {
        for(int i=0; i<grass.length;i++){
            grass[i] = new Sprite(16,0,i,SpriteSheet.tiles);
        init_done = true;
    }
}

```

The static boolean value will keep the code from running each and every call.

I think .NET version 3 or so introduced the concept of static constructors, which would be the perfect choice for this, but you might not have access to it:

```
static Sprite() {
    for(int i=0; i<grass.length;i++){
        grass[i] = new Sprite(16,0,i,SpriteSheet.tiles);
}

```

This code will run once when static members are (have been) initialized.

Essentially, keep in mind that your variable declaration ends after the `;`. There must not be any other code other than other declarations following on that Level.

---
Tags: java, sprites
---


# Question
Title: What's the proper way to check if an Entity is on top of a surface?
What would be the best way to implement gravity if I have a list of different "surfaces" which if the player is on top of acceleration will stop? Would there be a better way than to loop through all of the surfaces on the map and see if the player is colliding with it?

**BTW, I'm using XNA Game studios, but pseudo code is fine.**

# Answer
> 0 votes
> Would there be a better way than to loop through all of the surfaces on the map and see if the player is colliding with it?

This is essentially the basic concept and pretty much the only way to do it overall. But besides this, there is space for optimization, what John simply called "Spatial Hashing".

The idea behind this is reducing the amount of calculations required to get to your goal, by not having to look at each and every element (essentially narrowing down the selection; which usually happens based on location/size).

So, we've got the "spatial" portion, but what about hashing? Hashing is essentially transforming some complex collection of data (like different rectangles or coordinates) into some shorter/more simple representation allowing faster comparison (e.g. rather than compare 4 values only compare 1).

Just some random assumptions to make this more clear, why it is important (this is intentionally naive):

* Let's assume there are 1000 objects in our level. These could be blocks, platforms, power-ups, enemies, etc.
* When the player moves, there are four positions being checked (feet, head, left, and right).
* So every time the player moves (essentially once per logic iteration) you'll have to go through all 1000 objects and determine whether they overlap with one of the four collision points.
* That means you've got 4000 checks per iteration. Now imagine you have to do this for more objects, not just the player, and this is getting out of hands pretty fast.

So how to optimize this? Lower the number of checks first:

* You could determine whether some objects overlap at all, e.g. does the player even get close to that object? The most common principle for this is bounding box collision (collide boxes including the objects).
* Now you still iterate over all 1000 objects, but before checking 4 points you just see whether the objects nearly touch/overlap. You're now down to 1000 comparisons! That's reducing overall processing time, unless the objects overlap all the time (which is very unlikely).

The next logical step would be creating categories for your objects (not always feasible). For example, you don't check an object for collisions unless it is explicitly defined as being some "collideable":

* This check could happen before checking overlapping, but it could as well happen by defining different collections (so you don't have to iterate over non-collideables in the first place).
* Depending on the amount of non-collideables, this might reduce the number of iterations by quite some margin.

But what happens if you've indeed got lots of collideables? For example, your whole map could be made of collision shapes, or maybe even some shown textures that require pixel perfect collision. Introduce some organisational grouping to allow smaller sub groups of elements:

* There are different approaches available for this. If you've ever heard of "Balanced Trees", "BSP Trees", etc. this is where this is going. I won't go into detail and just explain a rather simple Approach.
* Split your game world into multiple small parts. For example, split the map into different "Screens".
* The world can still be continuous, this is just for organisational behind-the-scenes stuff.
* To do this, add some additional array where each element can contain a number of objects (e.g. `List<GameObject>`).
* Add the objects to this list based on their location in the game world. For example, objects in the leftmost part of the world would go into `objectsByScreen[0]`. Objects one screen further to the right would go into `objectsByScreen[1]`, etc.
* Now, to check collisions, you only look into these sub groups based on the player's current screen rather than iterating over all objects in your world/level.
* Based on your design, complexity, etc. this might reduce the initial iteration over 1000 objects down to maybe 10. This is quite a lot!

However, there is one downside to this: Moving elements will give you quite some trouble, because you'll have to update the lists they're in, if they move around. To solve this there are different approaches: \- Create another set for dynamic content that is updated/recreated once every frame (might be too ineffective based on the number of elements moving). \- Store the "parents" for every object and only remove/add them just-in-time when required (e.g. moving over a boundary).

As for the actual implementation, that's really up to you, because it might as well depend on whether your game world is 2D or 3D.

---
Tags: xna
---


# Question
Title: How do I convert my XNA game to Android without using MonoGame?
I want to convert my XNA Game to Android, but I don't want to use MonoGame or ExEn. How can I do this?

# Answer
> 7 votes
There are no conversions of XNA to the android platform without using either MonoGame or EXNA. You will need to rewrite your game including all the rendering logic in either C# using Xamarin.Android or a complete rewrite in Java.

---
Tags: xna, android, xna-4.0, monogame
---


title: Storing huge 2D tiled map in a txt file

text:
# Question
Title: Storing huge 2D tiled map in a txt file
I'm working on a global startegy game that uses a 2D tiled map. The map is to be 8000x8000 tiles large (this size is fixed, the map stays the way it is throughout the game), since I'm covering a large real-world area, but have to do so in detail. I want to store this map in a txt file. To do so I want to use simple IDs for the tiles, but that still leaves me with 2 bytes per tile and a total of about 185 Mb for my txt file, which is far too large. So I went ahead and thought of ways to reduce the size of the file that contains the map. This is what I came up with: Instead of stupidly defining an ID per field, I define regions, lines and specific fields:

region: a rectangle of any size (requires 23 bytes, regardless of its size)

line: a straight line of any length in any simple compass-direction (north, west, east, south) (requires 20 bytes, regardless of its length)

specific field: a specific single field (requires 13 bytes, due to the coordinates that have to be given)

using these three simple "objects" I managed to reduce the size of the file significantly. I may want to add that fields that have already been defined can be overwritten. Take the following rectangle for example:

1 1 1 1 2

1 1 1 1 2

2 2 2 2 2

This could be defined as a 5x3 rectangle of 2s with a 4x2 rectangle of 1s overwriting part of it (total of 46 bytes, as opposed to 195 bytes when defining every field specifically)

The problem I have now is the following: I'm trying to write a map-editor to simplify the process of making such a map. Obviously this editor should automatically generate the map-file, using the previously described objects to reduce the size. The question is, how do I go about writing such an algorithm, meaning one that finds optimal or near-optimal combinations of regions, lines and specific fields, possibly without taking 3 hours to do so? The algorithm that qucikly came to mind was your typical straightforward approach of going through all possible rectangles, picking out those that work best, then going through the undefined fields and defining lines and then specifying the rest specifically, but as you can probably tell, this approach takes a lot of time, so I'd rather avoid it. I had the idea of splitting the large map into smaller parts, but in the process the algorithm loses some of its precision, as this would eliminate rectangles and lines that cross over two or more of these smaller parts.

So, does anyone perhaps have an idea how to optimize the algorithm, or maybe even a better approach? I'd be very grateful for some help here, since I can't quite go on writing the game without the map in place...

I realise this is a lot of text and perhaps an even bigger problem, but anyways

Thanks in advance,

LegionaryCohort

# Answer
Don't make a text file, make an image file. Now whatever pixel editor you prefer is a working tool for editing the map, and you can compress it as a png in 4, 8 or 24 bit resolution depending on how many distinct tile types you need.

Edit, this will fit poorly in the comment section:
Yes, editing a 8000 x 8000 image is a pain, and I have no doubt that some pixel editors will not be able to handle such images in a satisfactory manner, but there must be some software that can do it. I see that even if the image editor works as it should it will not be easy for a human to handle such an image, but will a custom editor change that? The real question, why would you want such a big map in the first place? I don't recall any tile based game that has used a map that is even close to that size.

You certainly shouldn't use a text file for that much data, even the most rudimentary binary encoding will get you a file format of 1 byte per tile. You could shrink that further by applying a basic compression algorithm, anything your language of choice has library for will do. Png is just a pre-baked format that does these two things for you, but it is not particularly hard to roll something similar of your own doing.
> 4 votes

# Answer
If you feel uneasy utilizing an image (really easy to be done and depending on the format you've got up to 32 bits per pixel/entry), you could still use a text file or your own binary format utilizing RLE (run-length encoding).

What this essentially means is you're storing consecutive fields with the same value as a length with a value. Assuming you're happy with having 128 different IDs, you'd be able to use the most significant bit as an indicator:

* If the MSB isn't set, the value is a single ID.
* If the MSB is set, the value (ignoring the MSB) defines the length of the following ID.
* If the MSB of consecutive bytes is set, their values are added as lengths.

For example:

* 1 occurrence of the value 5: `0000 0101`
* 2 occurrences of the value 5: `1000 0010, 0000 0101` (or: `0000 0101, 0000 0101`)
* 3 occurrences of the value 5: `1000 0011, 0000 0101`
* 5 occurrences of the value 5: `1000 0101, 0000 0101`
* 128 occurrences of the value 5: `1111 1111, 1000 0001, 000 0101`
* 1 occurrence of the value 5 (shouldn't happen due to being counter productive): `1000 0001, 000 0101`

Just to note: The same can be done with larger numbers, e.g. 32 bit integers. It's just easier to explain with shorter bit sequences. Also keep in mind that RLE compression will perform rather bad (i.e. almost no to no savings) if there are lots of different values.
> 0 votes

# Answer
You haven't said what platform / language / libraries you're using, but there is an implementation of the DEFLATE algorithm for just about every language there is. This is the compression algorithm used by PNG, Gzip and many other formats (I've used it many times for large XML files).

I would recommend that you split your huge map into sections, so that you don't have to decompress the entire thing all at once, and compress the sections using deflate.

Most of the time deflate does just as well, if not better, than any custom compression that you can come up with on your own.

(Bear in mind, that the development platform you are using may have a class / method called compress, gzip, zip, zlib or something else rather than just "deflate")
> 0 votes

# Answer
Once I made an image format that was smaller in size. Here's an example file:

```
255 255 255

0*100 ^100

```

This would produce a white 100x100 image.I know this is a very simple example and others would take much more but you can use the same technique for your map files and it's very easy to decode it.
> 0 votes

---
Tags: 2d, algorithm, tilemap, storage
---


# Question
Title: Linking error when compiling Allegro example
I am currently learning about game development tools and decided to use Allegro and OpenGL for starters. I've run into some problems in getting examples to compile though. It seems the `allergro.h` library isn't linking correctly. Some web searching didn't help.

Here's my example code:

```
#include <stdio.h>
#include <allegro.h>

int main()
{
    allegro_init();
    //...
    return 0;
}
END_OF_MAIN();

```

I'm running this command to compile it:

`g++ allegroTemplate.cpp -o allegroTemplate`

This is the error I'm getting:

```
/tmp/ccbpAXIY.o: In function `main':
allegroTemplate.cpp:(.text+0x2a): undefined reference to `_install_allegro_version_check'
collect2: ld returned 1 exit status

```

I'm running this in Ubuntu.

# Answer
> 1 votes
> g++ allegroTemplate.cpp -o allegroTemplate

You aren't linking with Allegro. With Allegro 4, it's recommended to use the `allegro-config` command, like

```
g++ souce.cpp -o game $(allegro-config --libs)

```

If you are just getting started, you really should take a look at Allegro 5 instead. It has integrated OpenGL support and is actively being developed, unlike Allegro 4.

---
Tags: c++, allegro
---


# Question
Title: How do you implement Libgdx touchDragged?
I'm a beginner in Java and in Game Development too. I was following some tutorials, but now I'm stuck on implementing a touchDragged listener using libgdx,

Can anyone suggest how to drag the image when the user touches it and then move with the users finger position?

I am using both a stage and an actor. I want to catch a touchDragged event on an actor.

Thanks.

```
public void create () {
    Texture.setEnforcePotImages(false);

    stage = new Stage();
    Gdx.input.setInputProcessor(stage);
    // create a SpriteBatch with which to render the sprite
    batch = new SpriteBatch();

    // load the sprite's texture. note: usually you have more than
    // one sprite in a texture, see {@see TextureAtlas} and {@see TextureRegion}.
    texture = new Texture(Gdx.files.internal("ball3.png"));
    Skin skin = new Skin();
    skin.add("default", new Label.LabelStyle(new BitmapFont(), Color.WHITE));
    skin.add("ball", texture);
    Image sourceImage = new Image(skin, "ball");
    sourceImage.setBounds(50, 125, 100, 100);
    stage.addActor(sourceImage);

    // create an {@link OrthographicCamera} which is used to transform
    // touch coordinates to world coordinates.
    camera = new OrthographicCamera();

    // we want the camera to setup a viewport with pixels as units, with the
    // y-axis pointing upwards. The origin will be in the lower left corner
    // of the screen.
    camera.setToOrtho(false);
}

public void render () {
    Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
    stage.act(Gdx.graphics.getDeltaTime());
    stage.draw();
    Table.drawDebug(stage);

    // if a finger is down, set the sprite's x/y coordinate.
    if (Gdx.input.isTouched()) {
        // the unproject method takes a Vector3 in window coordinates (origin in
        // upper left corner, y-axis pointing down) and transforms it to world
        // coordinates.
        camera.unproject(spritePosition.set(Gdx.input.getX(), Gdx.input.getY(), 0));
    }
}

```

# Answer
> 0 votes
You have to implement InputProcessor where you can then handle the input.

Then in your main class in `create()` method you have to pass your `InputProcessor` to Gdx like this:

```
public void create() {
        float w = Gdx.graphics.getWidth();
        float h = Gdx.graphics.getHeight();

        camera = new OrthographicCamera(w,h);
        batch = new SpriteBatch();

        Gdx.input.setInputProcessor(new MyInputPocessor()); // THIS PART HERE
}

```

`InputProcessor` gives you `touchDragged(int x, int y, int pointer)` like this:

```
@Override
   public boolean touchDragged (int x, int y, int pointer) {
      // Move your image here.
      return false;
   }

```

also you can use other methods of `InputProcessor` like `touchDown()`, for example to check if user touched the image and not outside of it. And `touchUp()` for example to store the position when finger/mouse left the screen.

---
Tags: android, libgdx
---


title: Replay on game like "impossible game"

text:
# Question
Title: Replay on game like "impossible game"
So I am making a simple game like "the impossible game" where the character just moves forward(from a 2D prespective) and the only thing you have to do is press the screen to jump at the correct time to avoid crashing into obstacles.

My record algorithm is quite simple:

```
   onJump()
   {
       events.append(player.pos.x);
   }

```

And my replay is:

```
   onUpdate()
   {
       if(player.x==events[nextevent])
            player.jump();
   }

```

Everything works O.K but sometimes in extreme situations(the player jumped just before he crash on an obstacle)while the player didn't actually crash, on replay the player crashes. I know this is happening because of the delta time(different delta on record and on replay). How can I fix it without having the need to record my delta time too?

**EDIT**:it seems that many didn't actually understood my question ,the question is not how to implements a replay system (knight666 answer is full and complete and it deserves the accept but its not what i asked) but how to deal with the changes of delta time.for example ,lets say the player jumps just before he crash ,while he is still in the air he passes 1 pixel away from the obstacle and it doesn't crash, but in the replay cause the delta can happen to be different than the delta while it was recorded the player passes -1 pixel away from the obstacle and it crashes.

# Answer
For the specific case in the question I see two options:

1. Override the time step when you're getting close to a jump location, so that at the end of that time step the player is in the correct position for the jump.
2. Use a fixed timestep so it can't go wrong in that way.

Note that there's also other ways for it to fail. For example, anything that's controlled by randomness could easily mess up the replay, unless you write code to handle it.
> 1 votes

# Answer
What you want to do is seperate your actual input from your input processing. The game logic shouldn't care about where the event came from, only that it happened.

The easiest thing for you to do is to record the player's input and timestamp it. For example, let's say you store it as JSON:

```
"InputEvents": [
    "KeyPressed": {
        "Timestamp": 1230,
        "Key": "Space"
    },
    "KeyPressed": {
        "Timestamp": 4492,
        "Key": "Space"
    },
    "KeyPressed": {
        "Timestamp": 12093,
        "Key": "Space"
    }

```

When you want to replay a level, you load this file and pretend it's live data.

Let's say you have a `Keyboard` class that handles all keyboard processing:

```
class Keyboard
{

public:

    void KeyPressed(int a_Key);
    void KeyReleased(int a_Key);

};

```

Derive a virtual `IKeyboard` interface from this and make sure your code uses this interface instead:

```
class IKeyboard
{

public:

    virtual void KeyPressed(int a_Key) = 0;
    virtual void KeyReleased(int a_Key) = 0;

};

class Keyboard
    : public IKeyboard
{

public:

    void KeyPressed(int a_Key);
    void KeyReleased(int a_Key);

};

```

Now you can derive a second implementation, one that reads from the replay file:

```
class KeyboardReplay
    : public IKeyboard
{

public:

    void Update(float a_DeltaTime);

    bool LoadReplay(const std::string& a_FilePath);

    void KeyPressed(int a_Key);
    void KeyReleased(int a_Key);

private:

    float m_TimeOffset;

};

```

Add the `Update` method to the virtual interface and call it from the main loop. The default keyboard implementation will just stub it out:

```
void Keyboard::Update(float a_DeltaTime)
{
    // do nothing
}

```

But the new class will check if an event has occurred:

```
void KeyboardReplay::Update(float a_DeltaTime)
{
    m_TimeOffset += a_DeltaTime;

    if (m_TimeOffset > m_EventNext->GetTimeOffset())
    {
        m_EventNext->Execute();
        m_EventNext = _GetNextEvent();
    }
}

```

Now you can record player input to a file, load it and play it back.

However, one thing that is *crucial* for this to work: the times have to be synchronized. You have to be sure that when it says "+1000 milliseconds" that you don't add 999 or 1001 milliseconds, because errors will stack up and the entire simulation will collapse.
> 2 votes

---
Tags: game-mechanics, replays, game-recording
---


# Question
Title: What values to construct "Projection Matrix" from?
I am curious to what standard values I should use to create a camera's projection matrix, as well as if certain measurements need to be taken if I want to represent a very small world or a very big world and make it feel natural.

What values (field-of-view, nearplane, farplane) to construct a projection matrix should be used if:

* 1 unit to represent 1 meter?
* 1 unit to represent 1 cm?
* 1 unit to represent 100 meter?

# Answer
What values should be used for the near and far planes depends entirely on your scene. It doesn't matter what units you're using, as long as the near and far planes are specified in the same units as everything else.

* Set the field of view to whatever you think looks good.
* Set the near plane as far as you can get away with - as far as you can make it without causing obvious clipping when the camera gets close to a wall, etc.
* The far plane setting doesn't matter very much. Set it as far as you need to fit your scene, or even make it infinite (which generates a perfectly valid projection matrix; counterintuitively, it can even be more precise than a finite one, over most of the depth range).
> 3 votes

---
Tags: 3d, camera, matrix
---