title: Avoiding constant IF checks for loops

text:
# Question
Title: Avoiding constant IF checks for loops
As an example, I have 3 different loops that are executed in certain conditions. I want to know if there's any way short of something like this:

```
if(day)
   x++;
else if(night)
   y++;
else
   z++;

```

Avoiding the continuous if checks, because I know under what conditions they will be executing... do I make myself clear?

I've thought of something along the lines of starting to execute a loop under the said x or y conditions, like so:

```
if(day)
 loopX();
else if(night)
 loopY();
else if(something else)
 loopZ();

```

But by doing this I'll effectively have to do checks for when to exit the loops, which ends up being the same, right?

I want to be able to say: "Start doing this!", and then eventually, at my discretion, "Now start doing this, instead!", without constant polling of conditions!

For example, were I currently in the "something else" state, I'd be doing 3 if checks every frame just to enter the loop! If I had something like 100 states, and was on the 100th, I would be checking 100 conditions just to get to the loop I want to execute!

A pratical game programming example: every frame, I do collision checking. Suddenly, I want to stop doing the collision checking. I do not want to have it check an if(collideStuff), I want it to straight out not do it.

```
void gameloop() {
   movestuff();
   something();
   collision(); // this would suddenly not have effect, as if it weren't there
}

```

# Answer
A `switch` statement, at a very low level, is extremely efficient at this. The compiled code will include a static lookup table in the machine code that will require only one step to go to the correct code block, independent of the number of conditions. Be sure to use best practice with it at all times, (`break`s and `default`s and yada yada...). My java muscles are very atrophied, but I bet it enforces those rules by default.

It seems to me that you are exercising premature optimization. If you are really need this degree of performance, and reducing the total number of if statements is your bottleneck, then you need to stop using java.
> 4 votes

# Answer
Your second loop example is flawed. You will never want to write code like that because there are many common parts of your game that must run on each main loop iteration. More likely you'd end up with something like:

```
MainLoop():
  while not_quit:
    PumpOSMessages()

    PreFrameCommonUpdate()

    if is_day:
      UpdateDay()
    else if is_night:
      UpdateNight()

    PostFrameCommonUpdate()

```

Only one loop. Your logic is split into functions that handle a single iteration of loop.

You could consider using a Finite State Machine in place of the explicit conditions. Each of your special loops could be a single state. Every state has some code that is run each iteration of your game loop, let's call it update. Each State also has a way to transition to another state, which is the check you speak of.

You can organize your code such that these checks are in their own methods on each state object. E.g., your DayState might be (in pseudocode):

```
class DayState:
  void Update():
    // do your day loop code here once; Update is itself called in a loop

  State NewState():
    if should_be_night:
      return new NightState
    else
      return nil

```

Now on each iteration of your loop, the current state's Update is called, then NewState is called, and if it returns a new state, the state is switched. You can also then add method for transitions so special code can run when Day ends or Night begins and so on.

```
PreFrameCommonUpdate()

current_state->Update()
new_state = current_state->NewState()
if new_state is not nil:
  current_state->End()
  current_state = new_state
  current_state->Begin()

PostFrameCommonUpdate()

```

You can now add new states and transitions much easier than with a bunch of hard-wired conditions everywhere.

A second approach (which can be combined with the first) is to use events. If you have some other system which is tracking time of day, it will know when day transitions to night. It can emit a "EndDay" event that interested systems listen to. You will probably find that your main loops for day/night are very similar and that only some specific systems will change, e.g. maybe your MonsterSpawner changes what monsters it spawns. If it listens for EndDay and EndNight, it can change its active list of monsters to spawn from when it receives the event and doesn't need to check each loop iteration.

```
spawn_system->RegisterEvent('EndDay', time_system)
spawn_system->RegisterEvent('EndNight', time_system)

while not_quit:
  // might cause things to happen in other systems via events
  time_system->UpdateDayNightCycle()

  // uses current state to decide what to spawn
  spawn_system->MaybeSpawn()

```

In general, though, if you're just checking a few conditions each iteration of you main loop, you're fine. Your only worry should be whether the code is easy to understand and modify. There's no reason to be afraid of if-checks at such top-level code (doing an if-check inside some inner loop run 100,000 times per frame is another story).

Without knowing specifically what you're doing, I would suggest keeping the single loop and just put if-checks where the behavior needs to change. Making multiple loops is likely just going to result in a lot of redundant code for no real gain. Split your code up into logical modules to start and see how much flexibility that gains you.
> 5 votes

# Answer
### Prudence

First of all, if you have an `if` statement that is run once per game loop, don't bother trying to optimise it away, your development time and the extra code complexity is always better spent somewhere else. If you have an `if` statement that is run 1000 times per game loop, it is probably not worth it either unless you already done all the big things and still need better performance.

### Getting rid of some branching

That said, there are times when `if` statements make a serious performance impact. Especially situations where branch prediction fails (and it often does that a lot) they can be surprisingly costly. One of the best things you can do about "small" `if` statements is to rewrite them into arithmetic expressions. Instead of `day` and `night` being boolean variables you could make them integers and store `1` or `0` instead of `true` or `false`. (Note that in some languages true and false are basically treated as plain numbers, that makes this kind of code a bit more straight forward.)

Then you could simply write:

```
x+=day;
y+=night; //(assuming day and night are exclusive)
z+=1-(day|night);

```

Assuming that the compiler hasn't already decided on a similar optimization (which is reasonably probable, but you never really know with compilers, they behave odd at times) this code will be way faster.

Code like this is in general harder to both read and write than the equivalent `if` structure, don't use it in production unless it really makes a difference.

### Function pointers for optimization

Function pointers can be a smart tool, but beware that your code when calling a function through a pointer needs to dereference that pointer. It is not much, but there is a little extra overhead involved. A worse consequence of trying to switch in different versions of a function is that it probably increases the code footprint. More code use more cache, and as a result cache misses become more frequent. The performance hit of a few extra misses may not be much, but if the gain from including the extra code in the first place wasn't a lot either the overall gain may in fact be a loss. Note that benchmarking this stuff can be really hard, the performance of the exact piece of code that was "optimised" may be better while the performance of the whole application is worse as the extra cache misses may hit anywhere.
> 2 votes

# Answer
Why not go for a polymorphic approach where your logic is separated into objects with an update function?

You then add these objects to a list and simply loop over this list to update all. You can give each number a priority so that when you add an object to your list you can sort them easily so that you're sure each object is updated in the right order/

If you wan't to take out a system you simply take it out of the list.

```
public abstract class LogicObject{
  int priority = 0;
  abstract  void update(float dt);
  void setPriority(int value){priority = value}
  int getPriority(){return priority;
 }

```

-

```
public Collision extends LogicObjects{

  //Add more properties

  @Override
  public void update(float dt){
     //updatecollision here
  }

}

```

-

```
 Collision collision = new Collision();
 collision.setPriority(3);

 private List<LogicObjects> gameLogicList = new ArrayList<LogicObjects>();
 gameLogicList.add(collision);

 //sort your list on priority

 //somewhere in your main loop
 for(int i;  i < gameLogicList.size(); i++)
 {
    gameLogicList[i].update();
 }

```

Like sean said, working with events to trigger when something should or should not be used is an elegant way of doing it.
> 1 votes

# Answer
The only way to eliminate checks is to use hardware interrupts.

Then you can write an infinite loop which assumes that it's forever daytime: it does not waste a single cycle checking that day has turned into night.

This loop is executed by a dedicated thread.

When day turns to night, a hardware interrupt goes off. The interrupt service routine responds by placing a breakpoint into the top of the loop executed by the daytime thread and then returns from the interrupt.

When the daytime thread reaches the top of the loop, the breakpoint triggers a software interrupt. (Again, the thread is not checking anything: the hardware is).

That software interrupt then removes the breakpoint and puts the daytime thread to sleep, and makes the nighttime thread runnable.
> 1 votes

# Answer
As a possible alternative, you might consider a *job system*. You would create jobs/commands/tasks -- essentially, bundles of information that tell you what and how to execute to e.g. do collision checking -- and schedule them for the subsequent frame. Each frame you would build the list of things you'd want to do for next frame, possibly including dependencies between the jobs (a *task graph*, loosely).

Note that this will have far more overhead -- both in code size and in execution time -- than a switch or other branch-around mechanism, generally speaking.

However, it does allow you to do more interesting things later: you can support parallel job execution, or even possibly distributed job execution (across a network, or across CPU and GPU, or other things of this nature); you could record info about what jobs executed for profiling and/or state changes for replay purposes.

If I know all the dependencies in my collision job/task, for example, I suddenly might run it concurrently in parallel with my sound task, or my particle VFX task, or what-have-you.

If you don't want something to execute, remove it from the task list/graph, or simply don't add it in the first place if you're building the list/graph each frame.

Structuring jobs/tasks in this way can have other maintainability benefits -- you're forced to more carefully consider your API boundaries and how data flows from system to system -- but on the other hand it's likely to be a performance loss for simple code, and the increase in complexity can be a burden on maintenance or introducing new programmers.

This is probably entirely overkill for your needs at the moment, I just wanted to put an alternative here.

If you're curious, there are plenty of interesting resources out there, e.g. the GDC Vault Task Graphing in Mortal Kombat (this is behind an expensive paywall, but the talk has been given at a few places, I think including GameFest, so the slides ought to be around somewhere -- I'll try to dig them up and return to edit this post). These are all *big* systems, but you can definitely pull little tidbits that are useful for even small projects.
> 0 votes

---
Tags: java, game-loop, polling
---


title: Moving camera along generated terrain?

text:
# Question
Title: Moving camera along generated terrain?
I'm generating my terrain on the GPU, using diamond square subdivision (no height map involved). How can I anchor the camera's position to always be on top of the generated terrain?

Thanks

# Answer
> 1 votes
The most expeditious way to extract height information might be to draw it:

1. Set draw parameters to an orthographic projection directly down toward the terrain.
2. Draw to a render target with a depth-map shader.
3. Store render target contents to a 2D array, sample it for heights, and save it for as long as it is useful (no need to reproduce every frame).

I think this method will give you everything you need. It won't require a non-GPU implementation of your algorithm. It can be re-run if your camera moves to a new area of terrain. It can be low resolution; allowing you to interpolate between its "pixels".

# Answer
> 0 votes
`cameraPos_Y = desiredDistanceFromGround + currentTerrainVertex_Y`**.**

As the camera moves, keep updating `cameraPosY` checking the height of which vertex the camera is over or closest to. Use the the camera's **X** and **Z** coordinates to help single out which vertex the camera is over.

In case you you have big faces for your terrain, you may have to use a bounding box and get the average height of all vertices detected.

`cameraPos_Y = desiredDistanceFromGround + ((vertex1 + vertex2 + vertex3) / 3)`**.**

Lets say your bounding box for your camera at whatever current position detects 3 vertices with heights of 3.5, 4.2 and 2.9. You also want to camera to stay at a distance of 2 off the ground. The average height will be 3.53, so roughly, `cameraPosY = 2.0 + 3.53`**.**

From here, you may need to incorporate change in height smoothly.

---
Tags: camera, procedural-generation, terrain
---


# Question
Title: What perspective is suitable for sharing a screen across a table?
I'm thinking about a 2 player 2D arena game for a mobile phone, but I have the obvious problem of gripping. To avoid this, I think it shouldn't be a problem to play one in front of the other with touchscreen controls. The problem is, of course, the perspective of the sprites in the screen so they look okay to both players.

I'm thinking fully orthogonal perspective, but it hurts visibility a lot, specially if using human sprites viewed from the top of the head. Is there any example of a game that did this right?

# Answer
Most any top down perspective will work. 2D games have done this in the past with games like PacMan:

Additionally, any top down perspective where the camera is at the center of the screen. This gives the kind of view you showed in your comment:

Both of these assume the players are sharing a play field. If the players are not sharing a play field, you can split the view symmetrically and draw two views in whatever perspective you want.
> 5 votes

# Answer
One good way is to use split screen. Take the 2D image and render it on a side angle (from the player's view). As long as the player is looking at their side there shouldn't be a problem. You can just add a 2D splitter in the middle of the screen.
> 3 votes

---
Tags: multiplayer, camera, multitouch
---


# Question
Title: MMOFPS Choosing protocol for high-traffic network (UDP or TCP)?
my question about the player position sender protocol. In this article, he says "Never use TCP for networking a multiplayer game". Ok but UDP datas are not ordered. In this case, if somebody walking, his position will be received and sent to other players. While walking other players can see the player's NPC teleporting like movement. Some positions will be incorrect. Otherwise TCP isn't suitable, I agree but how can we use UDP? (UDP reliability?)

> ***EDIT (Question):*** There is an other problem. If player1 send his data to server this data can be lost. Otherwise if data received by server, server will send it back to other clients. In this case some datas can be lost again. Namely UDP creates an undefined position update (namely everybody -clients- can see player at different positions). What can we do about that?

**EDIT:** Oh, I'll use TCP for login-room like request because they are important (must be reliable) datas. There is no problem about this.

**EDIT2:** I don't know how can I use UDP for player positions.

# Answer
> 2 votes
You can solve the ordering problem by adding a sequence number to messages where order matters and simply ignore any messages which were made obsolete by a message with a later sequence number.

So when your client receives a position message which position 2 although it already got position 3, it keeps the object at position 3.

# Answer
> 1 votes
If you use UDP for ordering-sensitive data such as player positions, you will have to implement it yourself. At minimum, you need to drop packets that arrive late. Which requires some sort of sequencing/timestamping.

Flow control with TCP might mean a laggy game compared to a crashed server due to network congestion. And nagling with TCP can be disabled.

Using UDP-only as that article suggests might require a lot of extra work (essentially reimplementing parts of TCP) that is already built into TCP.

# Answer
> 1 votes
If you want to save effort, use TCP. TCP does a lot of things automatically for you, including:

* **retransmission** (unacknowledged packets are automatically resent),
* **reordering** (packets received out of order are buffered until they can be processed in correct order),
* **flow control** (the maximum transmission rate is automatically adjusted up and down to maximize throughput without excessive packet loss),
* **MTU discovery** (finding out the largest packet size a given connection will handle), and possibly
* **fragmentation** (splitting packets into smaller pieces along the connection and reassembling them at the receiver).

The problem with TCP is that it's a general-purpose protocol, and the way it handles these things is not always optimal for games. For example, it your game sends two position updates to the server, and first update packet is lost along the way, then TCP will hold on to the second packet until the first one has been successfully retransmitted, and only then let the server process both. In a fast-paced game, you'd probably prefer to have the second update processed as soon as it arrives and just forget about the lost first update.

Unfortunately, while TCP does offer some options to tweak the buffering and retransmission algorithms, there's no way to tell it to just drop lost packets. For that, you'll need a lower-level protocol like UDP. The problem with UDP, on the other hand, is that it's a *very* low-level protocol — a very thin wrapper over raw IP, in fact — and takes care of *none* of the things listed above.

Thus, if you want to use UDP, you basically have two choices: either use an existing UDP-based networking library like OGP that takes care of some of the things that TCP handles, but in a more game-friendly manner, or study network protocols like TCP and figure out how to implement the same features yourself. Unless you *really* like network programming, I'd only recommend the latter option as a last resort.

---
Tags: c#, networking, mmo
---


# Question
Title: How to make camera rotation independent from frame rate?
I multiply the mouse movement by a given number to get camera rotation of a desired speed. But it only works at 60 FPS. When I don't limit the frame rate I get around 350 FPS and the camera rotation is significantly too slow.

In my calculation, I already consider the frame time.

```
rotateCamera(ivec2 deltaMouse, float deltaTime, float sensitivity)
{
    // apply multipliers
    deltaMouse *= deltaTime;
    deltaMouse *= sensitivity;

    // rotate camera by deltaMouse
    // ...
}

```

Is this approach wrong? Why isn't the mouse movement independent from the frame rate in my code? How to achieve that?

# Answer
> 2 votes
Where's deltaMouse coming from? If the API you're using is giving you translation units like pixels or centimeters, you shouldn't scale by deltaTime. Moving your mouse 1 cm should rotate the camera by, say, 15 degrees, regardless of how many frames or how long it took to move that 1 cm.

---
Tags: camera, rotation, mouse, frame-rate, timestep
---


# Question
Title: How do I find an optimal FPS for best user experience while preserving battery life?
I'm developing an Android game. The "graphics" I'm using need little CPU/GPU, so they run with high FPS. Because saving energy is important on Android devices, I want to limit frame-rate (`if deltaTime < limitDeltaTime -> Thread.sleep(...)` ).

How high should the frame-rate be to get an optimal balance between saving resources and a "fluid" gameplay experience. At which point is the user experience optimal or no longer improving?

# Answer
The lowest framerate you can get away with depends on the game.

In chess, a **still image** is just fine until someone makes a move! In a fast-paced FPS, you'll typically want **\>30** frames per second.

This comparison of an animation at 15, 30 and 60 frames/second should give you a rough idea, but it's best just to try it out -- every game is different.
> 6 votes

---
Tags: android, mobile, frame-rate, user-experience
---


# Question
Title: Farseer: Ball is not bouncing realistically
I created a ball that is rolling over platforms. When it falls from one platform to another, it should bounce just like in real life, but the ball keeps bouncing constantly and I don't know how to recreate a realistic bounce-behaviour in Farseer. In addition, the ball sometimes bounces higher but I don't know the reason for this. How can I improve the bouncing of the ball?

In this video, you can see how it bounces: http://www.vidup.de/v/I55qn/

```
public class Game1 : Microsoft.Xna.Framework.Game
{
    GraphicsDeviceManager graphics;
    SpriteBatch spriteBatch;
    World world;
    Body rectangle, rectangle2, rectangle3, rectangle4, rectangle5, playerrect;
    Texture2D rectangleSprite, playerSprite;

    private static float _displayUnitsToSimUnitsRatio = 100f;

    public static Vector2 ToDisplayUnits(Vector2 simUnits)
    {
        return simUnits * _displayUnitsToSimUnitsRatio;
    }

    private bool isOnGround;

    bool Player_OnCollision(Fixture fixtureA, Fixture fixtureB, FarseerPhysics.Dynamics.Contacts.Contact contact)
    {
        if (fixtureB.CollisionCategories == Category.Cat5)
        {
            isOnGround = true;
        }
        return true;
    }
    void Player_OnSeparation(Fixture fixtureA, Fixture fixtureB)
    {
        if (fixtureB.CollisionCategories == Category.Cat5)
        {
            isOnGround = false;
        }
    }

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

    protected override void Initialize()
    {
        base.Initialize();
    }

    protected override void LoadContent()
    {
        spriteBatch = new SpriteBatch(GraphicsDevice);
        playerSprite = Content.Load<Texture2D>("ball");
        rectangleSprite = Content.Load<Texture2D>("tile");

        if (world == null)
        {
            world = new World(new Vector2(0, 1));
        }
        else
        {
            world.Clear();
        }

        playerrect = BodyFactory.CreateCircle(world, 0.25f, 1.0f);
        playerrect.BodyType = BodyType.Dynamic;
        playerrect.Position = new Vector2(2.76f, 0f);

        rectangle = BodyFactory.CreateRectangle(world, 1.50f, 0.50f, 1.0f);
        rectangle.BodyType = BodyType.Static;
        rectangle.Position = new Vector2(2.96f, 1.16f);
        rectangle.Rotation = -0.3f;
        rectangle.CollisionCategories = Category.Cat5;

        rectangle2 = BodyFactory.CreateRectangle(world, 1.50f, 0.50f, 1.0f);
        rectangle2.BodyType = BodyType.Static;
        rectangle2.Position = new Vector2(1.0f, 1.80f);
        rectangle2.Rotation = 1.0f;
        rectangle2.CollisionCategories = Category.Cat5;

        rectangle3 = BodyFactory.CreateRectangle(world, 1.50f, 0.50f, 1.0f);
        rectangle3.BodyType = BodyType.Static;
        rectangle3.Position = new Vector2(4.1f, 4.80f);
        rectangle3.CollisionCategories = Category.Cat5;

        rectangle4 = BodyFactory.CreateRectangle(world, 1.50f, 0.50f, 1.0f);
        rectangle4.BodyType = BodyType.Static;
        rectangle4.Position = new Vector2(2.6f, 4.80f);
        rectangle4.CollisionCategories = Category.Cat5;

        rectangle5 = BodyFactory.CreateRectangle(world, 1.50f, 0.50f, 1.0f);
        rectangle5.BodyType = BodyType.Static;
        rectangle5.Position = new Vector2(5.6f, 4.80f);
        rectangle5.CollisionCategories = Category.Cat5;

        playerrect.OnCollision += Player_OnCollision;
        playerrect.OnSeparation += Player_OnSeparation;
    }

    protected override void Update(GameTime gameTime)
    {
        float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;
        world.Step(Math.Min(elapsed, (1f / 60f)));
        KeyboardState kbState = Keyboard.GetState();

        if (isOnGround == true)
        {
          playerrect.ApplyForce(new Vector2(0, -4.5f));
        }

        base.Update(gameTime);
    }

    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.CornflowerBlue);
        spriteBatch.Begin();
        spriteBatch.Draw(playerSprite, ConvertUnits.ToDisplayUnits(playerrect.Position),
                                       null,
                                       Color.White, playerrect.Rotation, new Vector2(playerSprite.Width / 2.0f, playerSprite.Height / 2.0f), 1.0f,
                                       SpriteEffects.None, 0f);

        spriteBatch.Draw(rectangleSprite, ConvertUnits.ToDisplayUnits(rectangle.Position),
                                        null,
                                        Color.White, rectangle.Rotation, new Vector2(rectangleSprite.Width / 2.0f, rectangleSprite.Height / 2.0f), 1f,
                                        SpriteEffects.None, 0f);

        spriteBatch.Draw(rectangleSprite, ConvertUnits.ToDisplayUnits(rectangle2.Position),
                                        null,
                                        Color.White, rectangle2.Rotation, new Vector2(rectangleSprite.Width / 2.0f, rectangleSprite.Height / 2.0f), 1f,
                                        SpriteEffects.None, 0f);

        spriteBatch.Draw(rectangleSprite, ConvertUnits.ToDisplayUnits(rectangle3.Position),
                                        null,
                                        Color.White, rectangle3.Rotation, new Vector2(rectangleSprite.Width / 2.0f, rectangleSprite.Height / 2.0f), 1f,
                                        SpriteEffects.None, 0f);

        spriteBatch.Draw(rectangleSprite, ConvertUnits.ToDisplayUnits(rectangle4.Position),
                                        null,
                                        Color.White, rectangle4.Rotation, new Vector2(rectangleSprite.Width / 2.0f, rectangleSprite.Height / 2.0f), 1f,
                                        SpriteEffects.None, 0f);
        spriteBatch.Draw(rectangleSprite, ConvertUnits.ToDisplayUnits(rectangle5.Position),
                                       null,
                                       Color.White, rectangle5.Rotation, new Vector2(rectangleSprite.Width / 2.0f, rectangleSprite.Height / 2.0f), 1f,
                                       SpriteEffects.None, 0f);
        spriteBatch.End();

        base.Draw(gameTime);
    }
}

```

# Answer
Are you just adding force to the ball? If you need elastic collisions don't do this. Farseer body has property called restitution, it controls ratio of the speed before and after collision.
> 2 votes

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


# Question
Title: Unity3D custom camera matrix breaking shadows/lights in deferred rendering
EDIT 1: So it seems this is a common issue with Unity, and it comes from a bug in which custom camera matrices break deferred lighting and shadows. This topic right here talks about it a bit, but the solution they provide doesn't seem to work in my case. So now I need to figure out why Unity does this, and if I can't fix it, figure out how I can get the lights/shadows on to the render texture I display.

I've been using the script below to render a portal effect, all it is is a modified version of Unity's water.cs script.

Now this script works in forward rendering, but for some reason when I turn the rendering path to deferred it doesn't render any lights or shadows on the rendertexture (I've tested it, the error is happening in the render texture this script produces.)

I've been scouring through the script, and testing every section, but I can't seem to find why it wouldn't be rendering lights or shadows to the render texture it outputs.

I'm going to continue researching and looking through the script, it seems the problem is due to the custom projection matrix I make for the camera.

This is the area that is causing the problem:

```
            // Render reflection
            // Reflect camera around reflection plane
            Vector4     reflectionPlaneUp   = new Vector4 (normal.x, normal.y, normal.z, - m_ClipPlaneOffset);
            Vector4     reflectionPlaneRt   = new Vector4 (right.x,  right.y,  right.z,  0);

            Matrix4x4   reflectionUp        = Matrix4x4.zero;
            Matrix4x4   reflectionRt        = Matrix4x4.zero;
            Matrix4x4   reflectionSum       = Matrix4x4.zero;
            Quaternion  rotate              = transform.rotation * Quaternion.Inverse(SecondPortal.transform.rotation);

            CalculateReflectionMatrix(ref reflectionUp, reflectionPlaneUp);
            CalculateReflectionMatrix(ref reflectionRt, reflectionPlaneRt);

            //Step1 Move to BEGIN OF COORDINATES
            reflectionSum = Matrix4x4.TRS(transform.position, Quaternion.identity, new Vector3(1,1,1));
            //Step2 reflect from Normal and Right vectors
            reflectionSum *= reflectionUp * reflectionRt;
            //Step3 Rotate Camera on Difference Quaternion between 2 portals
            reflectionSum *= Matrix4x4.TRS(new Vector3(0,0,0), rotate, new Vector3(1,1,1));
            //Step4 Move to Other portal position
            reflectionSum *= Matrix4x4.TRS(-SecondPortal.transform.position, Quaternion.identity, new Vector3(1,1,1));

            //Apply all transformations on Portal camera
            reflectionCamera.worldToCameraMatrix = cam.worldToCameraMatrix * reflectionSum;

            // Setup oblique projection matrix so that near plane is our reflection
            // plane. This way we clip everything below/above it for free.

            Vector4 clipPlane = CameraSpacePlane( reflectionCamera, SecondPortal.transform.position, SecondPortal.transform.up, 1.0f );
            Matrix4x4 projection = cam.projectionMatrix;
            CalculateObliqueMatrix (ref projection, clipPlane);
            reflectionCamera.projectionMatrix = projection;

```

And these are the functions you see it call in the snippet above:

```
// Given position/normal of the plane, calculates plane in camera space.
    private Vector4 CameraSpacePlane (Camera cam, Vector3 pos, Vector3 normal, float sideSign)
    {
        Vector3 offsetPos = pos + normal * m_ClipPlaneOffset;
        Matrix4x4 m = cam.worldToCameraMatrix;
        Vector3 cpos = m.MultiplyPoint( offsetPos );
        Vector3 cnormal = m.MultiplyVector( normal ).normalized * sideSign;
        return new Vector4( cnormal.x, cnormal.y, cnormal.z, -Vector3.Dot(cpos,cnormal) );
    }

    // Adjusts the given projection matrix so that near plane is the given clipPlane
    // clipPlane is given in camera space. See article in Game Programming Gems 5 and
    // http://aras-p.info/texts/obliqueortho.html
    private static void CalculateObliqueMatrix (ref Matrix4x4 projection, Vector4 clipPlane)
    {
        Vector4 q = projection.inverse * new Vector4(
            sgn(clipPlane.x),
            sgn(clipPlane.y),
            1.0f,
            1.0f
        );
        Vector4 c = clipPlane * (2.0F / (Vector4.Dot (clipPlane, q)));
        // third row = clip plane - fourth row
        projection[2] = c.x - projection[3];
        projection[6] = c.y - projection[7];
        projection[10] = c.z - projection[11];
        projection[14] = c.w - projection[15];
    }

    // Calculates reflection matrix around the given plane
    private static void CalculateReflectionMatrix (ref Matrix4x4 reflectionMat, Vector4 plane)
    {
        reflectionMat.m00 = (1F - 2F*plane[0]*plane[0]);
        reflectionMat.m01 = (    -2F*plane[0]*plane[1]);
        reflectionMat.m02 = (    -2F*plane[0]*plane[2]);
        reflectionMat.m03 = (    -2F*plane[3]*plane[0]);

        reflectionMat.m10 = (    -2F*plane[1]*plane[0]);
        reflectionMat.m11 = (1F - 2F*plane[1]*plane[1]);
        reflectionMat.m12 = (    -2F*plane[1]*plane[2]);
        reflectionMat.m13 = (    -2F*plane[3]*plane[1]);

        reflectionMat.m20 = (    -2F*plane[2]*plane[0]);
        reflectionMat.m21 = (    -2F*plane[2]*plane[1]);
        reflectionMat.m22 = (1F - 2F*plane[2]*plane[2]);
        reflectionMat.m23 = (    -2F*plane[3]*plane[2]);

        reflectionMat.m30 = 0F;
        reflectionMat.m31 = 0F;
        reflectionMat.m32 = 0F;
        reflectionMat.m33 = 1F;
    }

```

Here's the full script:

```
    public bool m_DisablePixelLights = true;
    public int m_TextureSize = 256;
    public float m_ClipPlaneOffset = 0.01f;

    public LayerMask m_ReflectLayers = -1;

    private Hashtable m_ReflectionCameras  = new Hashtable(); // Camera -> Camera  table

    private RenderTexture m_ReflectionTexture = null;
    private int m_OldReflectionTextureSize = 0;

    private static bool s_InsideRendering = false;

    public Transform SecondPortal = null;

    // This is called when it's known that the object will be rendered by some
    // camera. We render reflections and do other updates here.
    // Because the script executes in edit mode, reflections for the scene view
    // camera will just work!
    public void OnWillRenderObject()
    {
        if( !enabled || !renderer || !renderer.sharedMaterial || !renderer.enabled )
            return;

        Camera cam = Camera.current;

        if( !cam )
            return;

        // Safeguard from recursive reflections.
        if( s_InsideRendering )
            return;
        s_InsideRendering = true;

        Camera reflectionCamera;
        CreateMirrorObjects( cam, out reflectionCamera );

        // find out the reflection plane: position and normal in world space
        Vector3 normal  = transform.up;
        Vector3 right   = transform.right;
        // Optionally disable pixel lights for reflection
        int oldPixelLightCount = QualitySettings.pixelLightCount;
        if( m_DisablePixelLights )
            QualitySettings.pixelLightCount = 0;

        UpdateCameraModes( cam, reflectionCamera );

        // Render reflection
        // Reflect camera around reflection plane
        Vector4     reflectionPlaneUp   = new Vector4 (normal.x, normal.y, normal.z, - m_ClipPlaneOffset);
        Vector4     reflectionPlaneRt   = new Vector4 (right.x,  right.y,  right.z,  0);

        Matrix4x4   reflectionUp        = Matrix4x4.zero;
        Matrix4x4   reflectionRt        = Matrix4x4.zero;
        Matrix4x4   reflectionSum       = Matrix4x4.zero;
        Quaternion  rotate              = transform.rotation * Quaternion.Inverse(SecondPortal.transform.rotation);

        CalculateReflectionMatrix(ref reflectionUp, reflectionPlaneUp);
        CalculateReflectionMatrix(ref reflectionRt, reflectionPlaneRt);

        //Step1 Move to BEGIN OF COORDINATES
        reflectionSum = Matrix4x4.TRS(transform.position, Quaternion.identity, new Vector3(1,1,1));
        //Step2 reflect from Normal and Right vectors
        reflectionSum *= reflectionUp * reflectionRt;
        //Step3 Rotate Camera on Difference Quaternion between 2 portals
        reflectionSum *= Matrix4x4.TRS(new Vector3(0,0,0), rotate, new Vector3(1,1,1));
        //Step4 Move to Other portal position
        reflectionSum *= Matrix4x4.TRS(-SecondPortal.transform.position, Quaternion.identity, new Vector3(1,1,1));

        //Apply all transformations on Portal camera
        reflectionCamera.worldToCameraMatrix = cam.worldToCameraMatrix * reflectionSum;

        // Setup oblique projection matrix so that near plane is our reflection
        // plane. This way we clip everything below/above it for free.

        Vector4 clipPlane = CameraSpacePlane( reflectionCamera, SecondPortal.transform.position, SecondPortal.transform.up, 1.0f );
        Matrix4x4 projection = cam.projectionMatrix;
        CalculateObliqueMatrix (ref projection, clipPlane);
        reflectionCamera.projectionMatrix = projection;

        reflectionCamera.cullingMask = ~(1<<4) & m_ReflectLayers.value; // never render water and system layers
        reflectionCamera.targetTexture = m_ReflectionTexture;
        reflectionCamera.Render();

        Material[] materials = renderer.sharedMaterials;
        foreach( Material mat in materials ) {
            if(mat.HasProperty("_PortalTex") )
                mat.SetTexture( "_PortalTex", m_ReflectionTexture );
        }

        // Set matrix on the shader that transforms UVs from object space into screen
        // space. We want to just project reflection texture on screen.
        Matrix4x4 scaleOffset = Matrix4x4.TRS(
            new Vector3(0.5f,0.5f,0.5f), Quaternion.identity, new Vector3(0.5f,0.5f,0.5f) );
        Vector3 scale = transform.lossyScale;
        Matrix4x4 mtx = transform.localToWorldMatrix * Matrix4x4.Scale( new Vector3(1.0f/scale.x, 1.0f/scale.y, 1.0f/scale.z) );
        mtx = scaleOffset * cam.projectionMatrix * cam.worldToCameraMatrix * mtx;
        foreach( Material mat in materials ) {
            mat.SetMatrix( "_ProjMatrix", mtx );
        }

        // Restore pixel light count
        if( m_DisablePixelLights )
            QualitySettings.pixelLightCount = oldPixelLightCount;

        s_InsideRendering = false;
    }

    // Cleanup all the objects we possibly have created
    void OnDisable()
    {
        if( m_ReflectionTexture ) {
            DestroyImmediate( m_ReflectionTexture );
            m_ReflectionTexture = null;
        }
        foreach( DictionaryEntry kvp in m_ReflectionCameras )
            DestroyImmediate( ((Camera)kvp.Value).gameObject );

        m_ReflectionCameras.Clear();
    }

    private void UpdateCameraModes( Camera src, Camera dest )
    {
        if( dest == null )
            return;
        // set camera to clear the same way as current camera

        dest.backgroundColor = src.backgroundColor;
        dest.clearFlags = src.clearFlags;
        if( src.clearFlags == CameraClearFlags.Skybox )
        {
            Skybox sky = src.GetComponent(typeof(Skybox)) as Skybox;
            Skybox mysky = dest.GetComponent(typeof(Skybox)) as Skybox;
            if( !sky || !sky.material )
            {
                mysky.enabled = false;
            }
            else
            {
                mysky.enabled = true;
                mysky.material = sky.material;
            }
        }
        // update other values to match current camera.
        // even if we are supplying custom camera&projection matrices,
        // some of values are used elsewhere (e.g. skybox uses far plane)
        dest.farClipPlane = src.farClipPlane;
        dest.nearClipPlane = src.nearClipPlane;
        dest.orthographic = src.orthographic;
        dest.fieldOfView = src.fieldOfView;
        dest.aspect = src.aspect;
        dest.orthographicSize = src.orthographicSize;
    }

    // On-demand create any objects we need
    private void CreateMirrorObjects( Camera currentCamera, out Camera reflectionCamera )
    {
        reflectionCamera = null;

        // Reflection render texture
        if( !m_ReflectionTexture || m_OldReflectionTextureSize != m_TextureSize )
        {
            if( m_ReflectionTexture )
                DestroyImmediate( m_ReflectionTexture );
            m_ReflectionTexture = new RenderTexture( m_TextureSize, m_TextureSize, 16 );
            m_ReflectionTexture.name = "__PortalReflection" + GetInstanceID();
            m_ReflectionTexture.isPowerOfTwo = true;
            m_ReflectionTexture.hideFlags = HideFlags.DontSave;
            m_OldReflectionTextureSize = m_TextureSize;
        }

        // Camera for reflection
        reflectionCamera = m_ReflectionCameras[currentCamera] as Camera;
        if( !reflectionCamera ) // catch both not-in-dictionary and in-dictionary-but-deleted-GO
        {
            GameObject go = new GameObject( "Portal Refl Camera id" + GetInstanceID() + " for " + currentCamera.GetInstanceID(), typeof(Camera), typeof(Skybox) );
            reflectionCamera = go.camera;
            reflectionCamera.enabled = false;
            reflectionCamera.transform.position = transform.position;
            reflectionCamera.transform.rotation = transform.rotation;
            reflectionCamera.gameObject.AddComponent("FlareLayer");
            go.hideFlags = HideFlags.HideAndDontSave;
            m_ReflectionCameras[currentCamera] = reflectionCamera;
        }
    }

    // Extended sign: returns -1, 0 or 1 based on sign of a
    private static float sgn(float a)
    {
        if (a > 0.0f) return 1.0f;
        if (a < 0.0f) return -1.0f;
        return 0.0f;
    }

    // Given position/normal of the plane, calculates plane in camera space.
    private Vector4 CameraSpacePlane (Camera cam, Vector3 pos, Vector3 normal, float sideSign)
    {
        Vector3 offsetPos = pos + normal * m_ClipPlaneOffset;
        Matrix4x4 m = cam.worldToCameraMatrix;
        Vector3 cpos = m.MultiplyPoint( offsetPos );
        Vector3 cnormal = m.MultiplyVector( normal ).normalized * sideSign;
        return new Vector4( cnormal.x, cnormal.y, cnormal.z, -Vector3.Dot(cpos,cnormal) );
    }

    // Adjusts the given projection matrix so that near plane is the given clipPlane
    // clipPlane is given in camera space. See article in Game Programming Gems 5 and
    // http://aras-p.info/texts/obliqueortho.html
    private static void CalculateObliqueMatrix (ref Matrix4x4 projection, Vector4 clipPlane)
    {
        Vector4 q = projection.inverse * new Vector4(
            sgn(clipPlane.x),
            sgn(clipPlane.y),
            1.0f,
            1.0f
        );
        Vector4 c = clipPlane * (2.0F / (Vector4.Dot (clipPlane, q)));
        // third row = clip plane - fourth row
        projection[2] = c.x - projection[3];
        projection[6] = c.y - projection[7];
        projection[10] = c.z - projection[11];
        projection[14] = c.w - projection[15];
    }

    // Calculates reflection matrix around the given plane
    private static void CalculateReflectionMatrix (ref Matrix4x4 reflectionMat, Vector4 plane)
    {
        reflectionMat.m00 = (1F - 2F*plane[0]*plane[0]);
        reflectionMat.m01 = (    -2F*plane[0]*plane[1]);
        reflectionMat.m02 = (    -2F*plane[0]*plane[2]);
        reflectionMat.m03 = (    -2F*plane[3]*plane[0]);

        reflectionMat.m10 = (    -2F*plane[1]*plane[0]);
        reflectionMat.m11 = (1F - 2F*plane[1]*plane[1]);
        reflectionMat.m12 = (    -2F*plane[1]*plane[2]);
        reflectionMat.m13 = (    -2F*plane[3]*plane[1]);

        reflectionMat.m20 = (    -2F*plane[2]*plane[0]);
        reflectionMat.m21 = (    -2F*plane[2]*plane[1]);
        reflectionMat.m22 = (1F - 2F*plane[2]*plane[2]);
        reflectionMat.m23 = (    -2F*plane[3]*plane[2]);

        reflectionMat.m30 = 0F;
        reflectionMat.m31 = 0F;
        reflectionMat.m32 = 0F;
        reflectionMat.m33 = 1F;
    }

```

# Answer
So after much working I found out this is a bug with Unity. It happens in their Deferred Lighting -\> RenderingToTexture pipeline. What's happening is they are cutting it to only show the first pass.

I'll be filing a bug report to Unity, and hopefully this gets fixed soon. As a simple work around I'm just setting the portal camera to forward rendering path, it's still missing shadows, but at least it shows lights now.
> 3 votes

---
Tags: c#, unity, lighting, shadows, deferred-rendering
---


# Question
Title: Timing - use individual timer for every task or global timer?
I'm writing a game, where a player controls a spaceship. It regenerates energy over time. So I need to make a little timer that adds certain amount of energy to the pool per second. My enemies also shoot at me, activate different abilities. I figured I can use separate timers for these too. But I see how this can quickly go out of hand, since I have different engines with different energy regeneration rates - will I need to replace the timer every time? Or if I have different energy - I have to manually track all the timers and set them anew.

I thought, maybe I can use some global singleton method that can handle all the timing in my game? It can update everything in the game, and when something new happens (like new enemy spawning) I can just send my singleton information about that object and it will handle all the timing for it?

Is this a good approach? Can I read up something about this somewhere? Maybe you have some experience with this?

# Answer
> 5 votes
Given the options in your question, separate timers would be the best approach.

I'm not sure what your implementation of the "timers" is but you can get a major performance increase and simplify things by using a different approach. Rather than using timers (as in stop-watch type timing) you could use time stamps that represent the expiration of a cooldown and to determine if the cd has expired, you would check against the time from the physics engine during physics engine ticks or update calls. This way you aren't managing a whole bunch of individual timers and are simply maintaining a series of time values to represent the timer end times.

Would this work for your scenario?

# Answer
> 1 votes
Many individual timers can cause race conditions. Set one timer to 50 ms, 10 ms later set another timer to 40 ms. Which one will fire first? Often there is no way of knowing, and the result may be different from one run to another due to minor performance variations. Often it is not an issue, but bugs caused by race conditions can be really hard to track.

The most reliable way of keeping time is to hang everything in your game on the same update rate, then measure all other timing relative to that update rate, and have a well defined order in which events are handled when they fall in the same "tick". Performance variations may still cause small deviations from that update rate, but as it affect everything equally the order of events remain the same.

For instance you may choose to run 120 updates per second, if you want a ship to move 10 km/s you would give it a speed of 83 metres per update, and if you would like a ship to fire every 1.5 seconds you would make it fire every 180ᵗʰ update.

You can loop through every object on every update and decrease their respective timers, even a phone is too fast for that approach to cause any performance issues.

# Answer
> 0 votes
It seems you're spending too much of your mental and motivational resources attempting to circumvent a problem that will likely never realize. Are you planning on having 10's or 100's of thousands of timers simultaneously? Or will it be a handful of timers for a handful of entities?

If the latter, which would be nearly certainly the case for the vast majority of games, whatever method you use (as long as it's effective) is fine. Specifically, individual timers is good enough. Don't optimize for any process before you encounter a problem unless you know (likely from experience) that you'll have performance issues.

Remember that your internal resources, that you spend to create the game, are just as or far more valuable than system resources. The time you spend solving non-problems is more of a concern than unknown or very small performance gains.

# Answer
> 0 votes
I would say, that you could use a single timer for all of these. If I don't recall wrong, Minecraft uses a system very similiar to this. Everything that needs a cooldown(Like redstone), uses "ticks". Every second is composed of 20 ticks. The game checks for the number of ticks to calculate timing.

Applied to your situation would be like this: You could have a single global timer that fires a specific times a second(20 times in above example). And for every tick, you could add an engine-specific amount to energy pool. For example, a basic engine adds 1 energy for each tick, while a HYPER-ULTRA-OVERCLOCKED engine adds 999 energy each tick. Hope this helps.

---
Tags: cocos2d-iphone, timing, realtime
---


# Question
Title: How to correctly create bullet rigid from custom .mesh in Ogre?
Being new to 3d programming and bullet physics in particular, I am wondering how a 3d model or the mesh generated out of it effects the accuracy of bullet physics simulation.

I have written a small Ogre 3d application in C++, including/using bullet for physics. In a small scene I add a plane as ground and three boxes (simple blender objects that come with Ogre) that have their initial position a bit over that ground. So after starting the application those three boxes fall down until they hit the ground plane, where they move a bit, depending on their initial height and rotation, until they come to a halt.

Watching that scene the bullet physics simulation looks very accurate and realistic, also the boxes seem to touch the ground very exactly.

Ok, then I have created a box model in Sketchup 8 and exported it to an Ogre .mesh file. Then I use this model instead for those three boxes in my scene. The C++ code itself is not changed at all (except that I load the new .mesh file for the boxes).

However, even though on the screen those new box models look exactly as the original ones, their movement is not correct any more. They fall to the ground plane fine, but then they move very weird, it looks not as realistic as before. Even worse, after they have stopped their movement those three boxes now "float" a bit over the ground plane, they do not touch it. I can also see their shadow now below the box on the plane, so they are really not touching the ground plane.

**TL;DR:** *Scene with three boxes, falling down to the ground, simulated by bullet. That works fine with default Ogre (blender) .mesh files for the boxes. But with custom Sketchup models (.mesh files) instead for the boxes, but the same code, the bullet simulation does not work correctly any more.*

My question is: how does the mesh of a model impact the accuracy of bullet?
And: what can I do to solve that issue with my custom Sketchup models?

PS: I load the .mesh file and convert it to a bullet rigid body as following:

```
m_pSceneMgr->createEntity("Cube1", "Cube.mesh");
...
BtOgre::StaticMeshToShapeConverter converter(m_pSceneMgr->getEntity("Cube1"));
btCollisionShape* colShape = converter.createBox();

```

# Answer
Found the solution to my problem. I simply needed to set model's origin in Sketchup to its bounding box's center, now bullet works correctly in my scene again :)
> 2 votes

# Answer
I am not a Ogre user, but I really think your problem is related to the createBox() call.

Since you loaded your later cube from a mesh file, it is a regular convex mesh, not necessarily interpretable as a box by BtOgre. Calling createConvex() instead would probably fix it.

This is because the loaded cube would be now treated as a mesh, which happens to be a box.
> 0 votes

---
Tags: physics, models, 3d-meshes, bullet-physics
---


title: Farseer: Ball is not getting slower

text:
# Question
Title: Farseer: Ball is not getting slower
The ball is not getting slower when it rolls over a straight platform. I added friction but that changed nothing, the ball still gets not slower. I want that the ball gets slower and slower and stops rolling after a certain time. Like in real life. How can I do that?

In addition, the ball jumps weird when it touches two platforms at the same time. Is there a possibility to avoid that weird jumping?

Jumping ball video: http://www.vidup.de/v/p2DDO/

```
public class Game1 : Microsoft.Xna.Framework.Game
{
    GraphicsDeviceManager graphics;
    SpriteBatch spriteBatch;
    World world;
    Body rectangle, rectangle2, rectangle3, rectangle4, rectangle5, ballcircle;
    Texture2D rectangleSprite, ballSprite;

    private static float _displayUnitsToSimUnitsRatio = 100f;

    public static Vector2 ToDisplayUnits(Vector2 simUnits)
    {
        return simUnits * _displayUnitsToSimUnitsRatio;
    }

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

    protected override void Initialize()
    {
        base.Initialize();
    }

    protected override void LoadContent()
    {
        spriteBatch = new SpriteBatch(GraphicsDevice);
        ballSprite = Content.Load<Texture2D>("ball");
        rectangleSprite = Content.Load<Texture2D>("tile");

        if (world == null)
        {
            world = new World(new Vector2(0, 1));
        }
        else
        {
            world.Clear();
        }

        ballcircle = BodyFactory.CreateCircle(world, 0.25f, 1.0f);
        ballcircle.BodyType = BodyType.Dynamic;
        ballcircle.Position = new Vector2(2.76f, 0f);
        ballcircle.Restitution = 0.5f;
        ballcircle.Friction = 0.3f;

        rectangle = BodyFactory.CreateRectangle(world, 1.50f, 0.50f, 1.0f);
        rectangle.BodyType = BodyType.Static;
        rectangle.Position = new Vector2(2.96f, 1.16f);
        rectangle.Rotation = -0.3f;
        rectangle.Friction = 0.9f;
        rectangle.CollisionCategories = Category.Cat5;

        rectangle2 = BodyFactory.CreateRectangle(world, 1.50f, 0.50f, 1.0f);
        rectangle2.BodyType = BodyType.Static;
        rectangle2.Position = new Vector2(1.0f, 1.80f);
        rectangle2.Rotation = 1.0f;
        rectangle2.Friction = 0.9f;
        rectangle2.CollisionCategories = Category.Cat5;

        rectangle3 = BodyFactory.CreateRectangle(world, 1.50f, 0.50f, 1.0f);
        rectangle3.BodyType = BodyType.Static;
        rectangle3.Position = new Vector2(5.1f, 4.80f);
        rectangle3.Friction = 0.9f;
        rectangle3.CollisionCategories = Category.Cat5;

        rectangle4 = BodyFactory.CreateRectangle(world, 1.50f, 0.50f, 1.0f);
        rectangle4.BodyType = BodyType.Static;
        rectangle4.Position = new Vector2(3.6f, 4.80f);
        rectangle4.Friction = 0.9f;
        rectangle4.CollisionCategories = Category.Cat5;

        rectangle5 = BodyFactory.CreateRectangle(world, 1.50f, 0.50f, 1.0f);
        rectangle5.BodyType = BodyType.Static;
        rectangle5.Position = new Vector2(6.6f, 4.80f);
        rectangle5.Friction = 0.9f;
        rectangle5.CollisionCategories = Category.Cat5;
    }

    protected override void Update(GameTime gameTime)
    {
        float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;
        world.Step(Math.Min(elapsed, (1f / 60f)));
        KeyboardState kbState = Keyboard.GetState();

        base.Update(gameTime);
    }

    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.CornflowerBlue);
        spriteBatch.Begin();
        spriteBatch.Draw(ballSprite, ConvertUnits.ToDisplayUnits(ballcircle.Position),
                                       null,
                                       Color.White, ballcircle.Rotation, new Vector2(ballSprite.Width / 2.0f, ballSprite.Height / 2.0f), 1.0f,
                                       SpriteEffects.None, 0f);

        spriteBatch.Draw(rectangleSprite, ConvertUnits.ToDisplayUnits(rectangle.Position),
                                        null,
                                        Color.White, rectangle.Rotation, new Vector2(rectangleSprite.Width / 2.0f, rectangleSprite.Height / 2.0f), 1f,
                                        SpriteEffects.None, 0f);

        spriteBatch.Draw(rectangleSprite, ConvertUnits.ToDisplayUnits(rectangle2.Position),
                                        null,
                                        Color.White, rectangle2.Rotation, new Vector2(rectangleSprite.Width / 2.0f, rectangleSprite.Height / 2.0f), 1f,
                                        SpriteEffects.None, 0f);

        spriteBatch.Draw(rectangleSprite, ConvertUnits.ToDisplayUnits(rectangle3.Position),
                                        null,
                                        Color.White, rectangle3.Rotation, new Vector2(rectangleSprite.Width / 2.0f, rectangleSprite.Height / 2.0f), 1f,
                                        SpriteEffects.None, 0f);

        spriteBatch.Draw(rectangleSprite, ConvertUnits.ToDisplayUnits(rectangle4.Position),
                                        null,
                                        Color.White, rectangle4.Rotation, new Vector2(rectangleSprite.Width / 2.0f, rectangleSprite.Height / 2.0f), 1f,
                                        SpriteEffects.None, 0f);
        spriteBatch.Draw(rectangleSprite, ConvertUnits.ToDisplayUnits(rectangle5.Position),
                                       null,
                                       Color.White, rectangle5.Rotation, new Vector2(rectangleSprite.Width / 2.0f, rectangleSprite.Height / 2.0f), 1f,
                                       SpriteEffects.None, 0f);
        spriteBatch.End();

        base.Draw(gameTime);
    }
}

```

# Answer
> In addition, the ball jumps weird when it touches two platforms at the same time. Is there a possibility to avoid that weird jumping?

Nope your going to get that behavior with 2 platforms. You should combine them together into 1 shape. If the shape is more complex you can create a polygon that encompasses the entire area.

Anyways friction is going to take a very very long time to stop a perfectly round object. However, you can apply `angularDamping` to the object which will continually apply force with the goal of making the object stable.

A really good resource is the Box2D Manual and iforce2d.
> 1 votes

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


# Question
Title: XNA spritebatch.Draw: Which part gets colored by the color parameter?
Which part gets colored and how can I control it? I have a rounded block and my goal is to have the center filled with a certain color chosen by that parameter. Here's the picture:

When I draw it with Color.Red for example, just nothing happens. Simply creating the texture in these colors I need won't help, I want to create the colors very dynamic. That's a very simply texture but I also want to apply it on harder ones.

The center is transparent already.

# Answer
> 2 votes
What you would do in this case, is draw a colored rectangle behind this texture first, and then draw this texture on top of the colored texture. This is assuming the center portion of your graphic is transparent.

```
SpriteBatch.Draw(BlankTexture, new Rectangle(Area, Of, Your, Texture), null, YourColor, 0, Vector2.Zero, SpriteEffects.None, 1);
SpriteBatch.Draw(YourTexture, new Rectangle(Area, Of, Your, Texture), null, Color.White, 0, Vector2.Zero, SpriteEffects.None, 0)

```

Just make sure your BlankTexture is white, and it should draw to whatever color you specify in your Spritebatch draw call.

# Answer
> 2 votes
> Which part gets colored and how can I control it?

All of it and you can't unless you make your own shader.

> I have a rounded block and my goal is to have the center filled with a certain color chosen by that parameter.

Tinting will not solve this problem. What you want is *masking* which was covered pretty thoroughly here.

---
Tags: xna, c#, 2d, textures
---


# Question
Title: How do I recreate this 3D "flying through space" effect resembling a tunnel?
On the *"Final Destination"* stage. in *"Super Smash Bros. Brawl"* and *"Super Smash Bros. Melee"*, the players fight on a platform that is seemingly moving through space.

I see particle effects, but I don't understand how they made the clouds, or the rest of it. I'm currently working on a breakout-clone in Unity3D, and would like to create a similar background for my game.

How can this effect be produced? How can a texture be made to fly towards the camera endlessly / seamlessly like that?

# Answer
> 5 votes
This effect is called Tunnel effect and has been popular in Demoscene. Basically it's a texture mapped infinite cylinder. The camera is moving inside the cylinder or the camera stays still and the cylinder is moving. Here is a video of this effect without alpha blending to make it more obvious and the source code for it.

Basic idea was to raytrace the cylinder into a look-up table, which can be used to render it very fast with arbitrary texture, where the offset can be animated. This technique is not limited to just cylinders, but is more generally called Plane deformations.

With current GPUs you can easily calculate the effect also in real-time without the pregenerated look-up table. Here is one such example using WebGL.

# Answer
> 2 votes
I don't know much about Untiy but I know how effects like that are produced. They take randomly generate particles around the area, I'd guess they used Perlin Noise. And in each update, if the particle is no longer visible, it's deleted to make more room for new particles. This should produce the effect you are looking for.

Here are a few links on Perlin Noise:

I also recommend taking a look into Simplex Noise. Pretty much a newer version of Perlin Noise.

---
Tags: unity, animation
---


# Question
Title: How should a programmer get started with creating 2D Sprites?
I am a programmer. Given a sprite sheet, I can code game as per the requirements. But I do not know how to create these sprites. I use Cocos2D. And I do not know where to begin. I have never done anything art-related before. I am aware of TexturePacker. But it only packs already created sprites. So how do I get started with creating 2D sprites? Are there any dedicated softwares for this purpose? Main main concern is about creating assets for Retina Displays.

# Answer
> 10 votes
Pixel art is a complex field. Many people start with tiles and then expand to animated sprites.

A good tutorial I can recommend is "So you want to be a Pixel Artist" by Tsugumo.

You don't need any special software. Any raster-based image manipulation program will do - for a beginner even MSPaint.

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


# Question
Title: How to create a font from an image for a game?
I found a font in a free pack of sprite as an image:

I'm wondering what would be the best way to use it in a game?

Is there tools to create a font from this image? Do i have to code it myself? I think of using this only for area with few text (like menus) so maybe a simple system converting a string to a sequence of image representing letters would be enough and it's not worth trying to use a complex font system?

What do you think?

# Answer
> 4 votes
Do you know how to implement sprites? If yes, then drawing text from a character sheet is easy: just treat each character as a sprite and draw them one after the other.

The details depend on the font you have and on how fancy you want your typography to be. Obviously, the simplest case would be a monospace font, where each character is a constant-size rectangle.

The font shown in your question appears to have variable character widths, which just means that you need to have a table giving the width of each character. If you already know how to work with variable-size sprites, this shouldn't be any more complicated. Just keep track of the current coordinates of the end of the text, and add the width of each character to the x-coordinate as you draw it.

One minor complication is that, if you want to draw that can wrap over multiple lines, you may want to make your drawing routine split the text into words and calculate the width of each word before drawing it, in order to check whether it fits in the remaining space. (Of course, there are even fancier microtypographical tricks you can do, like non-greedy line length optimization and dynamically adjusting word and character spacing to justify both margins, but those are probably overkill for your needs.)

Also, for fonts with less "blocky" shapes than the one in your example, you may want to implement kerning to make letter combinations like `AV` look nicer. A basic way to do this is to just calculate the minimum distance between two non-transparent pixels in a letter pair, and then move the letters to set this distance to the desired value. In practice, to improve performance, you may want to do this using downscaled bitmaps, or even a simplified model where each letter is first cut into a small number of horizontal slices, and each slice is then mapped to a pair of numbers giving the position of the leftmost and rightmost non-transparent pixel in the slice.

For even fancier effects, like emulation of hand-written calligraphic text, you could implement things like ligatures and context-dependent letter form variants (which are actually pretty simple to implement, basically just a lookup table mapping pairs of letters to the appropriate variants; the hard work is in drawing the ligatures to begin with), but you probably don't need any of that stuff. For most purposes, just drawing simple rectangular character blocks in a row is more than good enough.

# Answer
> 1 votes
Tool to create a bitmap font from a true type font there is a list of tools. Usually with this bitmap there is a file describing separate letters coordinates inside bitmap, so you generate font with some program. Then you parse that describing file, many tools provides their own parsers. So your task is to render string from separate rectangles to screen.

```
foreach letter in string
  get letter rectangle
  render_sprite (font_sprite, letter_rectangle, current_letter_index*letter width)

```

---
Tags: 2d, fonts
---


title: LibGDX GestureDetector touchUp

text:
# Question
Title: LibGDX GestureDetector touchUp
I am using to `GestureDetector` to detect drag gesture and determine vector based on position my finger first touched the screen and position when my finger left the screen. I already know that I can get coordinates where my finger touched the screen using `touchDown()`, but as far as I know there is no `touchUp()` in `GestureDetector`.

I tried to acieve this using `fling()`, but the problem with fling is that it has to be quick, otherwise it is not counted as fling.

`pan()` would be good, but it doesn't tell you if your finger left the screen.

So is there a way to detect **touchUp**? Or is there maybe another/better way to achieve what I want?

# Answer
I don't use GestureListener, but rather track fingers in my own InputProcessor overrides. This allows huge flexibility, and gives me a rich set of input data, without worrying about some of it being stolen by another listener. I can't make out exactly what you're trying to accomplish, but by doing something similar, you can do just about anything.

The designers did a good job on the interface, so with just a bit of creative calculation and keeping track (in class-level variables) of things, you can implement just about anything.

For instance, I implement an On-Screen virtual D-Pad. Where I treat the first touch via overridden touchDown() to be the origin of the D-Pad, storing the origin and the "pointer" (finger id) in class-level vars. When the class is initialized, the finger Id is set to -1, so I can easily check uninitialized state.

Then, using those state variables, and processing touchDragged() and touchUp(), I can tell when the user is dragging around, calculating a "heading vector" as the delta from the stored origin to the current screenX and screenY passed into touchDragged(). I can tell when another finger is tapped (which I treat as an "action button").

My current game doesn't utilze fixed-position controls, rather wherever the user wants to touch on the screen becomes the origin of the D-Pad until that finger is raised, then the origin becomes wherever they touch again (likely a different place than previously). This is to avoid controls getting in the way of in-game action.

For instance: It's easy to implement a radius of "dead spot" around the origin to filter of superfluous jitter around the origin. By using the pythagorean theorem to calculate the distance from the origin to the current screenX, screenY, and ignoring values with a distance less than some value.

It would be easy to implemnt a follower that just cached the screenX, screenY at each call into touchDragged(), and compared that cached value to the current value, so you could derive a detla-vector.

Good luck!
> 3 votes

# Answer
Since the `GestureListener` consumes all its `InputProcessor` events to transform basic events into gesture events. The best way would probably be implementing a separated `InputProcessor` to catch the `touchUp()`.

You instatiate a new `InputMultiplexer` and plug it to the applications instead of the Gesture Listener, then you plug your new `InputProcessor` and the `GestureListener` to the multiplexer.

Gesture Detection
Event Handling (also a bit over `InputMultiplexer`)
> 0 votes

---
Tags: libgdx
---


# Question
Title: How to handle scaled aspect ratio multiplayer player coordinates
I'm building a cross platform multiplayer game. I'm using pixel graphics and starting at a small `256x144` `16:9` aspect ratio That gets scaled up to larger `16:9` resolutions. The graphics look ok however the movement is off. I'm publishing the players `x,y` coordinates and having other clients subscribe and render the entity based on these. This works in the case of same resolution clients however if the client is at a different scale the movement is off. It does seem consistent though when moving to a 0,0 position.

I've tried taking the published coordinates and applying the scale of the local client to them which seems more accurate. How can I equalize the coordinates across many clients?

# Answer
Separate your screen coordinates from your world coordinates. Pick a coordinates system that will accurately represent your position with enough detail. For example, if you're using a `256x144` `int` coordinate system for your positions, you only have 144 different positions available to you, even when the screen size can display 1080.

You may want to use a floating point coordinate system for more accuracy across larger screens. Whatever coordinate system you use, you'll need to scale it appropriately to the screen size just like you do for your graphics.
> 2 votes

---
Tags: multiplayer, coordinates, cross-platform, aspect-ratio
---


# Question
Title: How do I move a sprite to the mouse position?
So, I'm trying to make my sprite walk to the X-coordinate of my mouse click. This is my code:

```
currentMouseState = Mouse.GetState();
            MouseState mouseState = Mouse.GetState();
            if (lastMouseState.LeftButton == ButtonState.Released && currentMouseState.LeftButton == ButtonState.Pressed)
            {
                int mouseposx = mouseState.X;
                if (playerPosition.X < mouseposx)
                    {
                        playerPosition.X += 3;
                    }
                if (playerPosition.X > mouseposx)
                    {
                        playerPosition.X -= 3;
                    }
            }`

```

The problem is that the sprite will walk only 3 pixels and then stop. If I use while instead, like this:

```
  currentMouseState = Mouse.GetState();
            MouseState mouseState = Mouse.GetState();
            if (lastMouseState.LeftButton == ButtonState.Released && currentMouseState.LeftButton == ButtonState.Pressed)
            {
                int mouseposx = mouseState.X;
                while (playerPosition.X < mouseposx)
                    {
                        playerPosition.X += 3;
                    }
                while (playerPosition.X > mouseposx)
                    {
                        playerPosition.X -= 3;
                    }
            }

```

it will simply teleport to the X-coordinate instead. I tried adding a delay using Thread.Sleep(ms), but that just made it freeze and then teleport anyway.

So, what should I do?

EDIT: This is the new code, by Byte56.

```
currentMouseState = Mouse.GetState();
            MouseState mouseState = Mouse.GetState();
            if (lastMouseState.LeftButton == ButtonState.Released && currentMouseState.LeftButton == ButtonState.Pressed)
            {
                if (playerPosition.X - mouseState.X < 3)
                {
                    playerPosition.X = mouseState.X;
                }
                else if (playerPosition.X < mouseState.X)
                {
                    playerPosition.X += 3;
                }
                else if (playerPosition.X > mouseState.X)
                {
                    playerPosition.X -= 3;
                }
            }

```

edit3:

```
 void update()
        {
            // Check if the player has reached the target, if not, move towards it.
            if (playerPosition.X - playerTarget.X < 3)
            {
                playerPosition.X = playerTarget.X;
            }
            else if (playerPosition.X > playerTarget.X)
            {
                playerPosition.X -= 3;
            }
            else if (playerPosition.X < playerTarget.X)
            {
                 playerPosition.X += 3;
            }

        }

```

and

```
 currentMouseState = Mouse.GetState();
            MouseState mouseState = Mouse.GetState();

            if (lastMouseState.LeftButton == ButtonState.Released && currentMouseState.LeftButton == ButtonState.Pressed)
            {
                // This will give the player a target to go to.
                playerTarget.X = mouseState.X;
            }
            update();

```

# Answer
Using a `while` loop inside your game loop is a basic no-no. Think about how the code is being executed and you'll realize why it just teleported or was frozen and then teleported. (hint: how much of that code do you think is run before the next time your graphics are updated?)

You want to have a target position, then on each iteration of your game loop check to see if your character has arrived at the target position. If it hasn't arrived yet, move it slightly closer.

```
if (lastMouseState.LeftButton == ButtonState.Released && currentMouseState.LeftButton == ButtonState.Pressed)
{
    targetPosition.set(mouseState.X, mouseState.Y);
}

if (Math.Abs(playerPosition.X - targetPosition.X) < playerSpeed)
{
   //handle the case where we're very close and would over shoot the position by moving
   playerPosition.X = targetPosition.X;
}
else if (playerPosition.X < targetPosition.X)
{
    //we're at a position less than the target, add to our position
    playerPosition.X += playerSpeed;
}
else if (playerPosition.X > targetPosition.X)
{
    //we're at a position greater than the target, subtract from our position
    playerPosition.X -= playerSpeed;
}

```

Remember that computers only do exactly what you tell them.
> 8 votes

# Answer
You need a variable that stores the position that was clicked ( the target of the object. ) This position could be set when you check the rest of your input like this

```
MouseState mouseState = Mouse.GetState();
if (lastMouseState.LeftButton == ButtonState.Released && currentMouseState.LeftButton == ButtonState.Pressed)
{
    // This will give the player a target to go to.
    playerTarget.X = mouseState.X;
}

```

Now we have the position the object is supposed to go to. Now we need to move it towards it. We need to do this every iteration of the main loop, but outside of the code that checks the input. It is useful to put this in a separate function.

```
 void update( )
 {
     // Check if the player has reached the target, if not, move towards it.
     if (playerPosition.X < playerTarget.X)
     {
         playerPosition.X += 3;
     }
     else if (playerPosition.X > playerTarget.X)
     {
         playerPosition.X -= 3 ;
     }

 }

```

This function works just like your function, but it will be execute ever frame regardless of pressed buttons. Now all you have to do is add a function call to this function in your main loop :

```
 update ( );

```
> 2 votes

# Answer
Could this be causing your issues?

```
if (lastMouseState.LeftButton == ButtonState.Released && currentMouseState.LeftButton == ButtonState.Pressed)

```

You are saying here:

If the left mouse button was released AND is being pressed currently;

This seems like contradicting actions, mouse buttons are usually pressed first, then released to signify a singular action (or continuously pressed to signify on-going action(s)). Perhaps what you are looking for is here is:

If the left mouse button was released OR is being pressed currently;

```
if (lastMouseState.LeftButton == ButtonState.Released || currentMouseState.LeftButton == ButtonState.Pressed)

```

Try that out and see what it does to your teleporting and short-stops.
> -2 votes

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


# Question
Title: Relevant file paths for reading in from a file?
Working on something in XNA, need to be able to read in data from a text file for something.

Trying to figure out how I can shorten this pathname down, so instead of it always checking there, it just checks in the directory where the actual program is.

I tried doing "\Data\Zone\\"+filenamestring+".txt" as my path but it didnt work.

What I have that works:

```
Sub loadFromFile(ByVal fileNameString As String)
        If System.IO.File.Exists("C:\Users\user\documents\visual studio 2010\Projects\asdf\asdf\asdf\Data\Zone\" + fileNameString + ".txt") Then
            MsgBox("It found it.")
        Else
            MsgBox("Could not find it")
        End If
End Sub

```

While this works, unfortunately this will probably only work on my machine. How do I shorten the file path so its flexible and relevant to the directory where the program is actually located at?

# Answer
> 3 votes
Beware that there are multiple ways of getting the **relevant directory**:

1. The `Environment.CurrentDirectory`(MSDN) gives you the **working directory** of the app. That is not always what you want. For example, you call the .exe of your game from C:\\, and the working directory will be C:\ not the one where the .exe resides
2. `AppDomain.CurrentDomain.BaseDirectory`(MSDN) or `Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)`(MSDN) will give you the **executable's directory**. That is the directory where the executable resides.

The following is an example:

```
C:\Users\Me>D:\TestPaths\bin\Debug\TestPaths.exe
Environment.CurrentDirectory= C:\Users\Me
AppDomain.CurrentDomain.BaseDirectory= D:\TestPaths\bin\Debug\
Assembly.GetExecutingAssembly().Location= D:\TestPaths\bin\Debug

```

If you want just to read data that accompaniates the executable (like Content), then I'd suggest using the second approach (executable's directory)

# Answer
> 0 votes
I found a solution after a bit of research on Stack Overflow:

https://stackoverflow.com/questions/5745911/relative-path-names-vb2010

This seems to have done the trick for now.

---
Tags: software-engineering
---


title: Slow glReadPixels

text:
# Question
Title: Slow glReadPixels
I have implemented a lense flare for my game, and it looks great. The first draft used individual sprites each with its own draw call. This was very slow, so I reengineered it to use a single draw call, expecting it to be much faster. It's not.

I realise now that it is the call to glReadPixels that is the culprit. I have read that the function is slow, especially for reading the depth buffer, but I am reading only a single pixel. And my drawing goes from about 2ms to 15ms (although I'm not sure I trust my timings).

I know that glReadPixels stalls, because it has to wait for all previous operations to finish. Another point is that I would like to port my game to mobile devices at some point, and it's even worse there, perhaps impossible using the depth reading technique.

So my question is, is there a way to speed it up. For example, can I refactor things so that I only do the test at the very end, or perhaps use last frame's data. This is tricky because I have a splitscreen game and use offscreen buffers. Or should I just bite the bullet and implement raytracing. I can do this and my geomentry is simple and static, so fairly easy to use a kdtree or something, but I'd rather not if I don't need to. Thanks

# Answer
You might want to use double buffering for the FBO and a Pixel Buffer Object to read the depth from the previous frames depth map to get rid of any CPU stall, as in your case it shouldn´t be a problem if it is a frame behind.

I currently have the same problem and I can´t use double buffering as it would mess everything up a lot, but from profiling and playing around with it, I am quite sure that the problem actually is the CPU stall, as for example simpler shaders will improve the performance a lot. I don´t know what is happening, but (at least with double buffering and multi threaded rendering) it seems as if rendering is usually a frame behind and the moment you call glReadPixels it has to finish rendering of the previous frame and then render the current frame while the CPU is waiting the whole time (I am probably completely wrong, but I didn´t find any usefull information for my issues and working on OSX I unfortunately don´t have any good OpenGL profiling tools available).
> 1 votes

---
Tags: opengl, depth-buffer
---


# Question
Title: Aim prediction along a parabola - How to make a Tower Defence Mortar aim accurately
I am building a very basic tower defence game in Unity3D where one tower is your standard long range mortar/artillery.

I want the projectile it fires to follow a parabola curve to make its movement seem like a mortar. This movement is not dependant on any physics (as I can make a projectile follow a curve but I could implement the Unity3D physics if the method used would benefit from it.

My question is: What technique should I use to ensure the projectile hits the locked unit whilst taking into account that the unit is moving along a possibly non linear path (defined with my A\* implementation.) I have not implemented any code as of yet as I wanted to consult the masses for any wisdom you can provide!

My initial idea was to fix the time the projectile would take along its parabola curve (regardless of distance) and try and track the position the unit would be at after this time delay. Is this along the right lines or are there alternative methods to consider when aiming a projectile that follows a curved path instead of a linear one?

Thank you for your time.

# Answer
> 2 votes
As Almo's comment mentions, your last paragraph is a pretty solid approach to the problem.

If you'd like one that requires less calculation however, another solution (provided you already have a method to hit a stationary target with a mortar shell) is to launch at and store the target's position in the world. Then, while the shell is in the air, make the shell's position equal to the position of the shell along the original arc plus the difference between the enemy's current position and the position when you launched.

This method means you don't need to know where the character is going to go as even if a player or random number generator was controlling the unit it will still hit with 100% accuracy (though it might look like the shell is cheating if the enemy attempts to quickly dodge and has high speed)

---
Tags: unity, tower-defense, aiming
---


# Question
Title: How can a desktop Java game be distributed without a Java runtime dependency?
Is it possible to turn a Java application into a standalone package that runs "out of the box"? The end user should not be required to install any Java JRE, nor should the installer contain a JRE and install it for the user.

The final distribution should contain a native executable (hopefully one for each of Windows, Mac and Linux) along with the regular data files and any extra JARs if needed. I'm not looking for a "one file" solution specifically -- I'd actually like data files to be unobfuscated.

How can this be done?

# Answer
> 8 votes
> The main point is that the end user should not be required to install any Java JRE, nor should the installer contain a JRE and install it for the user

You can use Java source/bytecode to machine code compilers. There are Excelsior JET for Windows and Linux (requires license) and GNU Compiler for Java which is old.

If it's ok to contain Java with your game without installing it, then you can probably package Java Runtime with your game and use a start script to set `JAVA_HOME` to your JRT location prior to launching the game.

**EDIT:** (comment response) Using the second option, you will still need different builds for different platforms using the appropriate Java runtime for that platform.

**EDIT2:** Aslo see Dmitry's recent comment.

# Answer
> 1 votes
For Mac, see the Oracle documentation for packaging a Java app for Mac. They've set up Java 7 so that you can bundle the runtime into an application bundle containing your jar files (.app is a folder treated as executable really), which is required for distribution on the Mac App Store. Basically, the .app bundle does mostly the same as what Eren's JAVA\_HOME answer suggests, but is packaged as a "native" Mac app.

For distributing without the Mac App Store, you can get away with not signing the app, telling your Mountain Lion users that they can get around Gatekeeper by right-clicking (or ctrl+click) on your app and clicking on "Open" when they first open the app. This will still warn them that the app is not signed, but it will allow them to open it anyway, and then allow them to double click on the app for subsequent opens.

(side note: you could also get away with Linux-style marking of shell scripts as executable and then construct a .app bundle around that. NetBeans does this on Mac and Linux, though without a bundled JRE/JDK)

---
Tags: java, distribution
---


# Question
Title: Which key bindings to use for switchable primary and secondary attacks?
I am making a game in which the player can have a primary and secondary weapon (like an ability). These are my current planned key bindings:

```
 Action | Effect
-----------------
 Click  | Shoot primary weapon
 WASD   | Move
 Space  | Use ability (secondary weapon)
 Q      | Previous primary weapon
 E      | Next primary weapon
 ???    | Previous/Next ability (secondary weapon)

```

I am trying to think of a way to switch the secondary weapon. Here are some options I have thought of and why I have rejected them:

* scroll wheel
    + some mice don't have scroll wheels
* `R` / `F`
    + awkward, also primary weapon switch is horizontal and this is vertical
* `shift` / ???
    + cannot think of another key

So, what is a good key binding for switching a secondary attack?

# Answer
* Scroll wheel
* (Shift|Alt|Ctrl)+Q/(Shift|Alt|Ctrl)+E
* TAB (just cycle to next if you don't have too many abilities)
* Forward/Back buttons on mouse (not universal)
* Right click with on screen "command rose"
* Space/Tab to cycle
* TAB to switch modes, Q/E switches weapons in mode 0, Q/E switches abilities in mode 1
* Shift/Tab to cycle
> 2 votes

---
Tags: input, keyboard
---


# Question
Title: How do I make a tile passable in one direction only?
I want that my character can jump through some of the tiles, like Mario does in this video: http://www.youtube.com/watch?v=zIPYzbNrNhc

In this video, Mario jumps **up** through orange platforms, but does not fall **down** through them.

How can I do that with Farseer?

# Answer
If you look at the Velcro Physics (formerly Farseer Physics) code, you'll find an example called `OneSidedPlatformTest`. Inside this test is the code required to create Fixtures that act in the manner you're requesting.

Essentially, you override the `PreSolve` function in the following way:

```
protected override void PreSolve(Contact contact, ref Manifold oldManifold)
    {
        base.PreSolve(contact, ref oldManifold);

        Fixture fixtureA = contact.FixtureA;
        Fixture fixtureB = contact.FixtureB;

        if (fixtureA != _platform && fixtureA != _character)
        {
            return;
        }

        if (fixtureB != _platform && fixtureB != _character)
        {
            return;
        }

        Vector2 position = _character.Body.Position;

        if (position.Y < _top + _radius - 3.0f * Settings.LinearSlop)
        {
            contact.Enabled = false;
        }
    }

```

This relies on testing the top of the platform against the position of the character. Assuming the position of the character is at its feet, no collision is returned when the feet are not near the platform.

This method may work for you, but once you've implemented this override, it should be trivial to change the detection method to other strategies. For example, you could test the direction the character is traveling and only apply collision if the character is above the platform and not moving up.
> 7 votes

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


# Question
Title: How can I define areas filled with water?
I would like to enhance my little game engine with nice looking water simulation. To start working on that I need to find a proper way to represent water in the game. Unfortunately I don't know much different representations, so I'll ask you. There is a similar question I asked some time ago. But since I hadn't formulated the issue clearly, the answer is correct but not what I was looking for.

In some games, water is just defined by a height level. For example everything under the height of zero is underwater. I saw this representation in (mostly older) games. The problem is that I'd like caves in the outdoor world which aren't flooded and different water levels for each lake and sea.

Another, more precise, representation of the occurrence of water are particles. Every water drop is stored as a point in world space. To render them, I could use techniques like metaballs so that they build a single mesh. This representation would be great for realism since I could easily calculate dynamics among them. Sadly no machine could calculate a ocean of metaballs in real time.

Are there other ways of representing water in an engine? I would like to have dynamic lakes, so defining water area by a static geometry is no option. For example if the player modifies the terrain to widen a lake, the water should fill that bay and the overall water level of that lake should slightly decrease.

# Answer
> 3 votes
I cannot say what is commonly used, but my first thought would be to use a particle system with particles of varying sizes representing water of various volumes. The top of the water would use smaller particles to form the undulations of the surface and waves, the water nearest the player would use the smallest particles to simulate splashes and small undulations, while the further or deeper the water would be, the larger the particles. This would allow for a dynamic number of particles simulating water of any size, dynamics of the water as it changes, and some reasonable and controlled performance level.

I can see problems with this implementation, but it certainly seems like a relatively simple and "good enough" solution that a viewer/player would be doubtful to ever notice deviations in the simulation.

# Answer
> 2 votes
If you were using a voxel-based terrain, you could, in addition to storing the density of ground per voxel, you could also store a water value that is clamped between `0` and `1 - groundDensity`. Drawing the water would be as simple as running a marching cubes pass over the water values. Simulating the water would be a little more difficult, but the basic premise is that you want to solve the system such that:

1. Below-surface water should fill up the remainder of the voxel
2. Surface-level water should have the same total density, `groundDensity + waterDensity`, as its neighbours
3. Water may be displaced to any voxel immediately adjacent and below it, provided that the neighbour's total density is less than its total density

The ideal algorithm would run in a compute shader, one execution path per voxel. If you wanted to get fancy, you could also store the water's velocity within that voxel for additional simulation effects: for example, attempting to distribute an amount of water proportional to the velocity to the cells "pointed to" by the velocity vector. This velocity data could also be used to move the waves, draw rapids, etc.

---
Tags: 3d, data-structure, water
---


# Question
Title: How to create adjustable formula for RPG level up requirements?
I'm trying to create a formula that can be modified simply by changing two values: number\_of\_levels, and last\_level\_experience. This is to enable people modding the game to change the levelling requirements.

I've got it so that I can specify the number of XP needed for the last level up, but I want to be able to control the XP needed for the first level up, which in this case can differ wildly. For example, if I have 40 levels, and 1,000,000 XP for the last level, the first level up requirement is then 625. But if I change the levels to 80, the first level up becomes 156. In both cases, the last level needs 1,000,000.

There must be some way to get the computer to work out a suitable curve given just these two basic values.

```
#include <iostream>

int main()
{
    int levels = 40;
    if (levels < 2) levels = 2;

    int experience_for_last_level = 1e6;
    float fraction = 1.0 / levels;

    {
        int i = 0;
        float fraction_counter = fraction;
        int counter = levels;
        int total = 0;

        for (i = 1; i <= levels; ++i, fraction_counter += fraction, --counter)
        {
            int a = static_cast<int>(fraction_counter * experience_for_last_level / counter);

            std::cout <<"Level "<<i<<":  "<<a<<" ("<<counter<<")"<<"\n";

            total += a;
        }

        std::cout << "\nTotal Exp: " << total;
    }
}

```

Output:

```
Level 1:  625   (40)      Level 15: 14423  (26)      Level 29: 60416  (12)
Level 2:  1282  (39)      Level 16: 16000  (25)      Level 30: 68181  (11)
Level 3:  1973  (38)      Level 17: 17708  (24)      Level 31: 77499  (10)
Level 4:  2702  (37)      Level 18: 19565  (23)      Level 32: 88888  (9)
Level 5:  3472  (36)      Level 19: 21590  (22)      Level 33: 103124 (8)
Level 6:  4285  (35)      Level 20: 23809  (21)      Level 34: 121428 (7)
Level 7:  5147  (34)      Level 21: 26250  (20)      Level 35: 145833 (6)
Level 8:  6060  (33)      Level 22: 28947  (19)      Level 36: 179999 (5)
Level 9:  7031  (32)      Level 23: 31944  (18)      Level 37: 231249 (4)
Level 10: 8064  (31)      Level 24: 35294  (17)      Level 38: 316666 (3)
Level 11: 9166  (30)      Level 25: 39062  (16)      Level 39: 487499 (2)
Level 12: 10344 (29)      Level 26: 43333  (15)      Level 40: 999999 (1)
Level 13: 11607 (28)      Level 27: 48214  (14)
Level 14: 12962 (27)      Level 28: 53846  (13)

```

# Answer
Though there are infinitely many ways to choose them, it is common for leveling curves to follow a **power rule** such as the following one:

```
f(level) == A * exp(B * level)

```

The major advantage of this formula can be easily explained: for a given rule, there is a fixed value N such that **each level costs N percent more than the previous one**.

Your initial variables add the following restrictions:

```
f(1) - f(0) == experience_for_first_level
f(levels) - f(levels - 1) == experience_for_last_level

```

Two equations, two unknowns. This looks good. Simple maths give `A` and `B`:

```
B = log(experience_for_last_level / experience_for_first_level) / (levels - 1);
A = experience_for_first_level / (exp(B) - 1);

```

Resulting in the following code:

```
#include <cmath>
#include <iostream>

int main(void)
{
    int levels = 40;
    int xp_for_first_level = 1000;
    int xp_for_last_level = 1000000;

    double B = log((double)xp_for_last_level / xp_for_first_level) / (levels - 1);
    double A = (double)xp_for_first_level / (exp(B) - 1.0);

    for (int i = 1; i <= levels; i++)
    {
        int old_xp = round(A * exp(B * (i - 1)));
        int new_xp = round(A * exp(B * i));
        std::cout << i << " " << (new_xp - old_xp) << std::endl;
    }
}

```

And the following output:

```
1 1000          9 4125          17 17012        25 70170        33 289427
2 1193          10 4924         18 20309        26 83768        34 345511
3 1425          11 5878         19 24245        27 100000       35 412462
4 1702          12 7017         20 28943        28 119378       36 492389
5 2031          13 8377         21 34551        29 142510       37 587801
6 2424          14 10000        22 41246        30 170125       38 701704
7 2894          15 11938        23 49239        31 203092       39 837678
8 3455          16 14251        24 58780        32 242446       40 1000000

```
> 72 votes

# Answer
Don't forget to round the numbers after you figured out your curve. It doesn't make much sense to tell the player he needs 119,378 experience points to reach the next level — because the person would always understand it as "roughly 120,000". Thus you will be better off doing the rounding yourself, and presenting "clean" results to your players. For example the following code (which extends upon the Sam Hocevar's) will attempt to round up to ≈2.2 significant digits (obviously that constant can be tweaked as you want):

```
from math import exp, log

levels = 40
xp_for_first_level = 1000
xp_for_last_level = 1000000

B = log(1.0 * xp_for_last_level / xp_for_first_level) / (levels - 1)
A = 1.0 * xp_for_first_level / (exp(B) - 1.0)

def xp_for_level(i):
    x = int(A * exp(B * i))
    y = 10**int(log(x) / log(10) - 2.2)
    return int(x / y) * y

for i in range(1, levels+1):
    print( "%d:  %d" % (i, xp_for_level(i) - xp_for_level(i-1)) )

```

The output is:

```
1:  1000     9:  4200     17:  17100    25:  70000     33:  287000
2:  1190    10:  4900     18:  20300    26:  84000     34:  340000
3:  1420    11:  5900     19:  24200    27:  100000    35:  420000
4:  1710    12:  7000     20:  28700    28:  119000    36:  490000
5:  2030    13:  8400     21:  34000    29:  142000    37:  590000
6:  2420    14:  10000    22:  42000    30:  171000    38:  700000
7:  2870    15:  11900    23:  49000    31:  203000    39:  840000
8:  3400    16:  14200    24:  59000    32:  242000    40:  1000000

```
> 17 votes

---
Tags: c++, rpg, mathematics, progression
---