# Question
Title: How can I support objects larger than a single tile in a 2D tile engine?
I´m currently working on a 2D Engine containing an isometric tile map. It´s running quite well but I'm not sure if I´ve chosen the best approach for that kind of engine. To give you an idea what I´m thinking about right now, let's have a look at a basic object for a tile map and its objects:

```
public class TileMap {
   public List<MapRow> Rows = new List<MapRow>();
   public int MapWidth = 50;
   public int MapHeight = 50;
}

public class MapRow {
   public List<MapCell> Columns = new List<MapCell>();
}

public class MapCell {
   public int TileID { get; set; }
}

```

Having those objects it's just possible to assign a tile to a single MapCell. What I want my engine to support is like having groups of MapCells since I would like to add objects to my tile map (e.g. a house with a size of 2x2 tiles). How should I do that? Should I edit my MapCell object that it may has a reference to other related tiles and how can I find an object while clicking on single MapCells? Or should I do another approach using a global container with all objects in it?

# Answer
I am going to talk about design and performance.

# Performance

## contenance

What you have right now is called a Jagged Array, it is flexible but not really serving any purpose here.

My opinion on that is that you should store objects (tiles) that have an existence into your world, as part of an array to reduce heap waste, memory fragmentation, increase locality, reduce indirection and totally avoid reference overhead. Unfortunately for you, you appear to be using java or C# which will not permit you to control any of these aspects. Jave/C# references are faster than C++ shared\_ptr but slower than raw-pointers, and definitely even slower than in-place objects. Allocation has demerits and since in java/c# evreything has to be allocated individually you kind of are in a tough luck situation. But don't get me wrong, until your game becomes dual head 4k resolution and has to manage immense and rich terrains, today's desktop machines are not going to be bothered by these details.

## research

1. iteration: Normally you need 2 things in games : fast iteration and fast locality-based access. Fast iteration is the best with memory contiguous containers, like I said before, e.g. `std::vector`, in java/C# you can't avoid the fact that your containers will all store references anyway so you loose in-place objects advantage for iteration. Iteration is useful when you absolutely need to consider all elements, like the logical update of a living entity, to run its IA routine. Or for animation of decors elements to update their current frame, even though this is discussable, animation update could be done during rendering because it could be decided that animation serves no purpose if the tile is off-screen, in which case the second approach will suffice, the research approach.
2. fast locality-based access. This is the most useful and most common access way for any game object, be it a decor tile or a living entity. You must be able to retrieve a list of stuff that overlaps some arbitrary region, quickly. For this purpose, either data must be stored in a grid, a full matrix where a dual index i,j indicates tile position, and each cell can be either empty of bear a cell. you need to allocate a huge base grid for this method, but it is the fastest because locality-based is instantaneous. You just have to take your pixel coordinate, add the screen view offset, divide by tile size, round to next smaller integer and you've got your direct index in the container. This is impracticable in cases of very large worlds. In such cases some people would use a quad-tree. I prefer to use a hash map. Just create a hashing function for a pair of integers (vector2) and store your tile ids this way. Access is almost constant and no games with pointers going to children nodes, especially with open address hash maps which are preferable for gaming environments, because they don't fragment the memory and are more efficient if the sizing is known in advance.

Store ids (indices) into your space partitionning structure, this way you get the main store which is just an array, and the locality-based store which stores ids into the main array.

If you have to delete something in your world, just keep a parallel array to store indices of the holes. This would be called the freelist. Some people prefer to swap the element to erase with the last element in the array, and pop back. This is also great but people already holding a pointer/reference/index to the last object must be updated, this can be difficult. notably your space partitionning structure is holding indices so this would have to be updated at least. In this regard, the freelist approach is simpler and fast. Next time you want to add an object just pick the last index in the freelist and pop it back. If you add too many objects in your world and the main array becomes full, crash the game immediately, find a new appropriate size and re-hard-code the new size. dynamic resizing is not desirable, gameing scenarios are well controlled, you just need to execute "profile" runs to determine how much of a max limit is acceptable. If your engine is to be shipped to clients for whom you do not know with what kind of scenarios they will use it, then make this constant appear in the build settings. (like some CMake variable) and document it well.

# Design

In terms of design, your jagged array has maintenance problems, because it forces repetitive code to follow the double indirection in terms of rows and columns which helps no one really. the linear approach has the advantage of being flexible, if it must be changed into a hash map, indices can still serve as identifiers so other systems wont be affected. or ever crazier, a streaming-able virtual container. indices could be loaded on the fly in a world where (infinite?) roaming is necessary so the container could be particularly complicated but identifiers create a nice loose coupling in this sense.

Also when you deserialize, you don't have to think about row column order, you just push to the array in whatever order fate decides and it would be cool. locality access is accelerated by a different structure anyway. good luck
> 4 votes

# Answer
Ignoring the fact your using lists for data that looks like array's..

Just store TileID in multiple row,cells for were it's is placed.

That way if your doing some find closest/A\* any edge/side will be found.

If your wanting there to be a primary cell, negate the minor cells, so you don't double count in a area search function, but still know it's type. And given your using an int for TitleID your not losing anything from your ID space.
> 3 votes

---
Tags: 2d, tilemap
---


# Question
Title: Delta times and frame lag in the game loop
Let's say we have a standard gameloop like this, in pseudocode:

```
while (true) {
    dt = GetDeltaTime();
    Update(dt);
    Render();
}

```

Here `Update(dt)` either uses a true variable timestep, or it determines how many cycles of a fixed timestep physics loop to execute based on `dt`.

Now say we have the common case where we have mostly constant framerate except for infrequent single-frame hiccups, so let's say we have `dt` values like

1/60, 1/60, 1/60, 1/6, 1/60, 1/60, ...

By the time our `GetDeltaTime()` detects the larger timestep in the fourth frame, we have already rendered and presented the fourth frame! So one frame will already have been rendered with a wrong (too small) timestep no matter what we do.

So if we now use the larger `dt=1/6` to render the fifth frame, my understanding is that we artificially create a *second* frame where a wrong timestep is used, this time a too large one. I wonder if this problem is acknowledged anywhere. Wouldn't it be better, say, to use the averaged `dt` over the previous few frames to combat this?

---

Here are some pictures to illustrate what I mean. I use the example of an object moving along a fixed axis with a constant speed, and using a variable timestepping scheme. The problem is essentially the same with fixed timesteps, though.

The plots have time on the x-axis, and the object position on the y-axis.

Let's say the object moving at 1 unit/s, and framerate is 1 Hz. This is the ideal situation.

Now let's say we have a frame where the time interval is 2 instead of 1. With a classical dt-based scheme, we get this:

So we have one frame where the velocity is perceived too low, and one where it is perceived too high and which corrects for the velocity in the previous frame.

What if we instead, say, always use a constant (or very slowly changing) dt? We get this:

The perceived velocity seems smoother using this approach to me. Of course, the object position is now not the "true" one, but I think humans perceive abrupt changes in velocity more clearly than such small positional offsets. Thoughts?

**UPDATE:**

At least Ogre can do this: http://ogre.sourcearchive.com/documentation/1.6.4.dfsg1-1/classOgre\_1\_1Root\_1f045bf046a75d65e6ddc71f4ebe0b2c.html So I guess I just got downvoted for people not understanding my question, which is rather frustrating.

# Answer
> 6 votes
To expand a bit on my comments in Shadows In Rain's answer:

If you're using variable timesteps, you shouldn't encounter this issue at all, unless you still cut it down to `n` updates in some way.

If you're using fixed timesteps, then you might hit that "stuttering" problem purely based on timing.

The problem is that - based on timing - you might draw a scene right before updating or just after an update has happened. Due to this animations (or movements) might not appear as fluent as they should, because they're essentially not constant at all.

Imagine a simple update loop like the on in Shadows In Rain's answer:

```
tick_rate = 1.0 / 66; // 66hz
adt = 0.0; // accumulated delta time
while(!quit) {
    adt += GetDeltaTime();
    if(adt >= tick_rate) {
        adt -= tick_rate;
        Update(tick_rate);
    }
   Render(adt);
}

```

There's nothing wrong with this code and it's running perfectly fine. Also, based on framerates and the number of updates per second, this will be as smooth as it can get.

However, as you lower the rendering framerate, you might suddenly notice stuttering, even if you're rendering at 60 FPS.

For simplicity, let's assume your game updates its state 60 times per second and your rendering is limited to 60 FPS as well (slowing the loop down to this rate, either through vertical synchronization or by being busy doing the actual rendering).

So you've got a ball that is moving at 1 pixel per update. That means, in a perfect world, it should move 60 pixels per second, one pixel per frame.

So theoretically, every 16.67 ms the ball moves by 1 pixel. As long as this is true, the animation will appear as smooth. However, let's assume in one iteration your accumulated time is only 16.60 ms. This means there won't be any update.

The result: The ball won't move for one frame (since no update happened). The next frame there might be two updates happening at once (since the accumulated time is now 34.03 ms) and now the ball moves by two pixels between frames.

Things like this might appear as some kind of "micro-stuttering". This can be hard to notice, but depending on your actual game layout it might be pretty obviousy.

Can you fight it? Yes, but it's a bit tedious based on how your draw/update your game.

You'll have to keep the previous screen's state (just taking a screen capture won't be enough; this isn't about blending two images).

In our example, you always keep the position of the ball during the last calculated frame.

To determine the actual position for drawing, you'd then use something like this:

```
drawing_x = old_x + (current_x - old_x) * f;

```

Where `f` is a factor between 0 and 1 based on how much time is in your accumulator:

```
f = adt / tick_rate;

```

So, the less time left till the next update, the further your ball's position will be drawn.

This will essentially introduce a one frame lag, which should be hardly noticeable. But at the same time it should help smoothen out your perceived framerate.

Keep in mind that there might be other factors causing minor stutters as well, e.g. the actual window manager presenting the window or some driver or hardware feature (like "adaptive vertical sync").

Before I finish, I'd like to get back to one statement from above: *just taking a screen capture won't be enough; this isn't about blending two images*

Actually, this isn't 100% true. If you can, you can also include some kind of motion/movement blur. This should also help with hiding slight stutters, especially for tiny movements, since it will be a lot harder to follow exact outlines or movements. Of course this is not an option for every use case, but it might be something to think about.

---

Update since you've added those graphs:

I think it's important to note that you'll have to identify where you're running slow and/or causing delays so you no longer update just-in-time.

In your second graph, you obviously take too much time to update your game logic, so you miss out one frame.

To fight this, you could drop a frame (usually described as frame dropping; pretty popular for emulators), or you try fighting this by constantly updating your accumulator, even while doing the updates (it's important to note that on very fast computers you'll have to ensure that you don't always just add 0 due to rounding or whatever):

```
tick_rate = 1.0 / 66; // 66hz
adt = 0.0; // accumulated delta time
while(!quit) {
    adt += GetDeltaTime();
    if(adt >= tick_rate) {
        adt -= tick_rate;
        Update(tick_rate);
        adt += GetDeltaTime(); // this is an additional update of the accumulator
        // here you'd want to count the iterations to ensure
        // you don't update forever and can't catch up!
    }
   Render(adt);
}

```

Of course this isn't possible for dynamic timesteps, so there'll always be some slight delays or lags. Don't think there's any effective way to fight that in all possible situations.

# Answer
> 0 votes
Do not rely on framerate if you want truly fixed timesteps for game logic, physics, etc. To keep rendering alive between updates, roughly extrapolate game state.

```
tick_rate = 1.0 / 66; // 66hz
adt = 0.0; // accumulated delta time
while(!quit) {
    adt += GetDeltaTime();
    if(adt >= tick_rate) {
        adt -= tick_rate;
        Update(tick_rate);
    }
    // remaining adt now means how rendered image must be ahead of game state
    // use it as extrapolation factor
    Render(adt);
}

```

Relevant: When should I use a fixed or variable time step?

# Answer
> 0 votes
I know exactly what you mean. Delta time gives us how much time to add to the simulation so that in-game seconds match real life seconds over time. However, it doesn't give us the time at which the frame is shown to the player, as rendering on the upcoming frame could overrun and be displayed a frame late.

In the delta time graph you're back where you should be after two frames. In your possible solution you're always one frame behind after the drop. A faster machine would update more than a slower one and therefore be at an advantage in multiplayer games - you would be able to move further per real life second if you didn't drop frames for example.

The only solution is to vsync, use a fixed update interval, and *guarantee* your game can render in a frame. This is why old (70's/80's) arcade games were smoother than current video games.

---
Tags: game-loop, timing
---


title: Entity System with C++

text:
# Question
Title: Entity System with C++
I'm working on a game engine using the Entity System and I have some questions.

## How I see Entity System :

**Components** : A class with attributs, set and get.

1. Sprite
2. Physicbody
3. SpaceShip
4. ...

**System** : A class with a list of components. (Component logic)

1. EntityManager
2. Renderer
3. Input
4. Camera
5. ...

**Entity** : Just a empty class with a list of components.

## What I've done :

Currently, I've got a program who allow me to do that :

```
// Create a new entity/
Entity* entity = game.createEntity();

// Add some components.
entity->addComponent( new TransformableComponent() )
            ->setPosition( 15, 50 )
            ->setRotation( 90 )
        ->addComponent( new PhysicComponent() )
            ->setMass( 70 )
        ->addComponent( new SpriteComponent() )
            ->setTexture( "name.png" )
            ->addToSystem( new RendererSystem() );

```

## My questions

1. Did the system stock a list of components or a list of entities ?
2. In the case where I stock a list of entities, I need to get the component of this entities on each frame, that's probably heavy isn't it ?
3. Did the system stock a list of components or a list of entities ? In the case where I stock a list of entities, I need to get the component of this entities on each frame, that's probably heavy isn't it ?

# Answer
> 3 votes
The system contains a list of components. Components that have dependencies can contain referenced to those dependencies, linked up when the component is added (e.g., physics depends on transform).

Note that as Conner pointed out, the aetup you have is not an "entity system" since you have an Entity class with a list of child components, but more of a general component based design. Somewhat subjective, but I'd lean towards keeping what you have, as there are various excellent uses for having that container game object (being able to list all components on a game object for an editor or serialized, having a place to store game object flags, fast lookup/validation of game object IDs, etc.), and there are plenty of cases where putting logic in a component is both simpler and faster and easier to maintain than trying to move everything into a system (e.g. Behavior components that directly modify what a game object does, rather than simply providing data to systems). Avoid the academically pure entity system and focus on solutions that actually get useful work done the easiest and most efficient way possible.

# Answer
> 2 votes
EDIT: Definitely check out Sean's post and take his advice. I merely meant to answer what a "true" entity system is, but you should definitely do what works for you. As they say, "If your entity system's architecture ain't broke, don't fix it."

---

> Did the system stock a list of components or a list of entities ?

Typically, a system should maintain a list of entities *that it is interested in*. Also, you mention that your entities maintain a list of components. Ideally (or typically) the components are *associated* with the entity, but they are not a *property* of the entity. I.e. maintain a world list of components and their associations.

> In the case where I stock a list of entities, I need to get the component of this entities on each frame, that's probably heavy isn't it ?

It's not as slow as you might think. Ideally, you can create a sort of "mapper" that will do fast retrieval of a component.

---

An implementation of an entity system that I believe adheres to good design is the Artemis Entity System. It's written in Java, but it's also open-source, and well-documented. You can see the source here.

# Answer
> 0 votes
1) Entities. Components should be unique to every entity, and added on creation, before adding the entity to the engine itself, though the engine should be capable of creating entities via some kind of logic system.

2) Do not attempt to copy data from every entity each frame. It is indeed a heavy operation, once you begin dealing with hundreds or thousands of entities. Copying once, allowing continued access is a better approach. My approach was for each system to store proxies of the entity, which stores only components which each system is interested in. (Movement system doesn't care about graphics, physics or logic, only position and velocity, so only needs a proxy with access to those two components).

3) This question seems like the same as 2), so I'll simply expand a little. Each system gets a unique proxy type, which contains the relevant components. You can either have the system implement methods which access and operate on those proxies, or have the proxies themselves implement the logic. I chose the latter. The benefit to this is that with minor modifications, I can have my systems multi-threaded, in that control over component access can be done within each proxy node using a mutex, preventing concurrent access to those components. You may choose to avoid multi-threading (it's certainly not always necessary), but It's still good software design to include abstraction layers in your code.

In this way, Entities only need be added or removed to each system, and only the core engine actually maintains the entities themselves. Storing multiple collections of entities is unnecessary and wasteful.

When an entity is added to each system, it can check if the entity has the components it requires, and if not, the entity is simply ignored. If it does, then a proxy is created, and the relevant components are extracted from the entity and stored in the proxy for later access.

---
Tags: c++, architecture, entity-system
---


# Question
Title: How can I simplify this code to compute the shortest rotation between two angles?
The following code will find the shortest rotation (in radians) (from pi to -pi) that I need to apply to `from` to leave me with `to`.

```
Scalar rotationBetween(Scalar from, Scalar to)
{
    Scalar fromMod = std::signbit(from) ?
        pi * 2 + std::fmod(from, pi * 2) : std::fmod(from, pi * 2);
    Scalar toMod = std::signbit(to) ?
        pi * 2 + std::fmod(to, pi * 2) : std::fmod(to, pi * 2);

    Scalar rotation = toMod - fromMod;

    if(rotation > pi)
        return rotation - 2 * pi;
    else if(rotation < -pi)
        return 2 * pi + rotation;
    else
        return rotation;
}

```

`Scalar` is a c++ `float`.

Can I simplify this? I feel like this is far too much logic to do something so simple.

# Answer
To get a value inside `[-pi,pi]`, you can add `pi`, do `fmod`, and subtract `pi` again. Here is one way that works. Unfortunately you still need to somehow test whether `from - to` is positive or negative before calling `fmod`:

```
Scalar rotationBetween(Scalar from, Scalar to)
{
    return (from > to) ? -pi + std::fmod(from - to + pi, pi * 2)
                       :  pi - std::fmod(to - from + pi, pi * 2);
}

```

If you are *absolutely sure* that `from` and `to` are in `[-2pi,2pi]`, then this simpler version will work:

```
Scalar rotationBetween(Scalar from, Scalar to)
{
    std::fmod(from - to + 5 * pi, pi * 2) - pi;
}

```

Finally, if you just want short code and don’t care about performance, this can be interesting:

```
Scalar rotationBetween(Scalar from, Scalar to)
{
    return 2 * std::atan(std::tan((from - to) / 2);
}

```
> 4 votes

# Answer
I think the following should do the trick.

(**Edit:** as pointed out in the comments, this gives the unsigned rotation).

```
Scalar rotationBetween(Scalar from, Scalar to)
{
   //Calculates the two possibilities, and take the smallest
   Scalar difference = std::min(
      std::fmod(from - to, pi * 2),
      std::fmod(to - from, pi * 2));

   //takes the above that is in the range 0 to 2*pi
   //and brings it in the range -pi to pi
   if (difference > pi)
      difference -= 2 * pi;

   return difference;
}

```
> 0 votes

---
Tags: c++, mathematics, rotation, floating-point
---


# Question
Title: Should I assign a unique ID to individual units of game currency?
I am currently making a MMORPG.

At the moment, I am working on the currency part of the game but I'm confused whether I should assign a unique serial number for every unit of the currency generated.

I'm hoping to use this system to trace any misuse of the virtual currency but is this a common practice and if not, would this be a good idea on operational and / or performance point of view?

# Answer
It's unlikely to make sense.

When I get 100 Zorkmids from Player A and 100 Zorkmids from Player B, I have 200 Zorkmids.

When I then pay 50 Zorkmids to Player C, will C get them from the Zorkmids I got form A or those I got from B? Do I have control over this? Does it even matter? A Zorkmid is a Zorkmid.

It definitely doesn't matter for real-world banks and accountants which all trace the transaction history of accounts, not the transaction history of individual units of currency. It is still possible to identify misuse that way.

That being said, I could *imagine* a game which treats individual coins as inventory items, so when you trade with someone, you have to make sure you have spare-change. This would allow some interesting features, like marking, enchanting or counterfeiting coins. In that case it would make sense to trace each coin individually. But I can't think of any game which actually does that.
> 26 votes

# Answer
No, you shouldn't.

While you should build systems that can allow you to track currency transactions (especially if that currency is a real-money obfuscator), you don't need to track every *individual* unit of that currency. The thing you are interested in tracking is the aggregate movement of funds, particularly in large volumes (as this could be an indicator of potential external/unsanctioned real-money transactions). Tracking individual units of currency doesn't help with that (in fact it may hurt), and only complicates the upkeep of the relevant data by requiring you to generate lots of IDs and store relatively massive volumes of information in your database.

There is some value to this idea for real-money obfuscator currencies (that is, thing you buy with real-world money that are used to purchase in-game content, such as the gems in Guild Wars 2). In particular, this desire might arise in order to disambiguate between units of currency introduced into the economy for "free" versus those that were introduced via an actual real-world transaction. Generally you can only ultimately recognize revenue on the latter, so it's important to keep them distinct.

However, you can track the information you need simply by storing the numbers in aggregate (total units in, total units out, for both 'free' and 'paid' instances of the currency). This goes along with the general idea that you want to track these things in aggregate, generally a the *transaction* level and not the current level, as it both tracks the data you really need *and* makes it easier to trace large chunks of funds as they disperse throughout your system.
> 6 votes

# Answer
Author's note: This answer made with the assumption that you are not doing trading while off network and then syncing back to the servers.

You do not need to track individual serial numbers of currencies specifically because any transaction between individual players must happen through your servers. In other words, your servers are the authoritative source on account balances. Your servers will not ask the user how much money he has. The clients attached to the servers ask the server "How much money does my player have" via an api call. This places an assumption that players aren't doing trading while off network and then syncing back to the server(s) \[Though that would be novel, I don't recommend it unless you'd like to spend a lot of time in theory\].

In the example of government currency, the only authoritative source is the currency when not attached to the account \[A man takes out $200, each bill is "signed" with a serial number that tags it so that others can determine if it's real(if they went through the hassle of doing so) to take it\]. When the bill is taken into a bank, there are ways for determining whether serial numbers have been marked as out of circulation, etc\]. But, your transactions are more similar to multiple users in a single branch transferring funds between accounts without ever seeing currency.

The main story to illustrate is just who is your authoritative source: I'll try to illustrate: A user wants to take out money from the atm. The user doesn't go to the branch and declare "I have $500, trust me, these are the serials". Instead he gives over the key \[account number / key\] and the branch /server can notify the user of his funds and allow him to take out currency while diminishing his balance. No matter what a user does to try to convince the bank "Really, I've got $500" unless the authoritative source (the server) verifies the balance, nothing will happen.

Cheers.
> 4 votes

# Answer
If you try to program a game simulation based on how the real world works then you are going to run into some big problems when it comes to how much information a computer can process.
Take for instance the following page which is an attempt to calculate how many atoms there are in a grain of sand.

http://www.thenakedscientists.com/forum/index.php?topic=6447.0

I've seen lots of problems like this from studying chemistry and physics and the ridiculously high number that the person on this page came to is in the ball park of what I've seen various teachers and textbooks come up with. -\> 78 000 000 000 000 000 000

Even if this is way off and you remove 6 of those zeroes then you will still have a number that is way too big for the average computer to handle at interactive rates. Especially when there are 1000's of these transactions taking place at any given time.

How could we possibly calculate and track the momentum, positions, velocity, instantaneous accelerations, field charges, etc, of every atom in every grain of sand on a beach if just one grain has 78 000 000 000 000 000 000 individual components. (Or even more if you consider the sub-atomic components.)

I once read an nVidia graphics programming document that stated something like the following.
Do what gives the best approximation of looks good because no one will really be able to tell if the simulation is not 100% accurate. Efficiency has to be taken into consideration.

The same applies for every type of game simulation even if it does not have to do with graphics. You should probably only do the bare minimum of what it takes to get things working. If you go all out here then you will bury the computer in complexity that it cannot handle.
You will also have to write and try and maintain code of this complexity.

You could give unique serial numbers to every unit of currency but you will use up all the computer's resources just on this one detail.

Maybe a better way to handle this is to give only 1 unique identifying for each transaction.

So player #1 pays player #2 $1000000.
If you give each dollar a unique identifier, many people's computers will start to have big problems, not to mention all the network traffic and the lag this will cause.

Or you can just create one value that represents the entire transaction.

uint transferFunds\_Player1ToPlayer2 = 1000000;

Even a 20 year old pocket calculator can handle something like this.
> 2 votes

---
Tags: mmo
---


# Question
Title: Centering a textbutton in a table libGDX
I have a few `Table`s spread across a `Stage`, now I have a problem. In one table, all the `TextButton`s are centered, while in a different one they aren't, like this:

```
Table 1           Table 2
XXXtextXXX        text
XXmoretxXX        moretext
XXXXtxXXXX        MoreTextHere

```

The problem is that as much as I try I can't seem to center them. In the first table I have only textbuttons in each row, while in the second one I have two rows with 3 textbuttons, which the rest are only one text button. this is the code:

```
        settingNames.bottom().left();
    settingNames.add(new TextButton("Resolution:", style));
    settingNames.row();
    settingNames.add(new TextButton("VSync:", style));
    settingNames.row();
    settingNames.add(new TextButton("FullScreen:", style));
    settingNames.row();
    settingNames.add(new TextButton("Borderless:", style));
    settingNames.row();
    settingNames.add(new TextButton("Force FPS:", style));
    settingNames.row();
    settingNames.add(new TextButton("Target FPS:", style));
    settingNames.setBounds(0, 0, Gdx.graphics.getWidth(),
            Gdx.graphics.getHeight());
    settingNames.debug();

    resPrevious = new TextButton("<", style);
    resText = new DynamicLabel(resHandler.getResolution(), labelStyleSkin);
    resNext = new TextButton(">", style);
    vsyncToggle = new TextButton("Off", style);
    fullscreenToggle = new TextButton("Off", style);
    borderlessToggle = new TextButton("Off", style);
    forceFPSToggle = new TextButton("Off", style);
    targetFPSPrevious = new TextButton("<", style);
    targetFPSText = new DynamicLabel("60", labelStyleSkin);
    targetFPSNext = new TextButton(">", style);
    fullscreenToggle
            .setColor(fullscreenToggle.getColor().r,
                    fullscreenToggle.getColor().g,
                    fullscreenToggle.getColor().b, 0); ---> Used this line to check how the textbutton looks.
    changeOptions.center().bottom();
    changeOptions.add(resPrevious);
    changeOptions.add(resText);
    changeOptions.add(resNext);
    changeOptions.row();
    changeOptions.add(vsyncToggle).fill(true, false);
    changeOptions.row();
    changeOptions.add(fullscreenToggle);
    changeOptions.row();
    changeOptions.add(borderlessToggle).fill(true, false);
    changeOptions.row();
    changeOptions.add(forceFPSToggle).fill(true, false);
    changeOptions.row();
    changeOptions.add(targetFPSPrevious);
    changeOptions.add(targetFPSText).center();
    changeOptions.add(targetFPSNext);
    changeOptions.setBounds(0, 0, Gdx.graphics.getWidth(),
            Gdx.graphics.getHeight());
    changeOptions.debug();

```

I added all the tables to a stage and display them, but can't figure what's wrong, I could really use help here...

# Answer
On the second table, you have two rows with three columns. If you want to center your others rows with these one, you have to set the horizontal size of the cell to three columns using the colspan method.

The "center" method will only center the widget inside it's own cell.

For example, your code should be :

```
changeOptions.center().bottom();
changeOptions.add(resPrevious);
changeOptions.add(resText);
changeOptions.add(resNext);
changeOptions.row();
changeOptions.add(vsyncToggle).colspan(3).center();
changeOptions.row();
changeOptions.add(fullscreenToggle).colspan(3).center();
changeOptions.row();
changeOptions.add(borderlessToggle).colspan(3).center();
changeOptions.row();
changeOptions.add(targetFPSPrevious);
changeOptions.add(targetFPSText);
changeOptions.add(targetFPSNext);

```

Currently this what you are doing :

```
# Cell 1 # Cell 2 # Cell 3 #
# Cell 1 #
# Cell 1 #
# Cell 1 #
# Cell 1 # Cell 2 # Cell 3 #

```

With the above code, you should obtain :

```
# Cell 1 # Cell 2 # Cell 3 #
#          Cell 1          #
#          Cell 1          #
#          Cell 1          #
# Cell 1 # Cell 2 # Cell 3 #

```

And that's why on the first table the problem doesn't occure cause you only have one cell per rows.
> 6 votes

---
Tags: java, libgdx
---


title: GLSL Sphere from Vertex

text:
# Question
Title: GLSL Sphere from Vertex
I am working on a particle simulation where we have a lot of spheres which can have different radii. Using this tutorial http://mmmovania.blogspot.de/2011/01/point-sprites-as-spheres-in-opengl33.html (see also code below) I was able to create a sphere from a point, but they all have the size from glPointSize(). Is it possible to extend this with a radius?

```
#version 330
out vec4 vFragColor;

uniform vec3 Color;
uniform vec3 lightDir;

void main(void)
{
    // calculate normal from texture coordinates
    vec3 N;
    N.xy = gl_PointCoord* 2.0 - vec2(1.0);
    float mag = dot(N.xy, N.xy);
    if (mag > 1.0) discard;   // kill pixels outside circle
    N.z = sqrt(1.0-mag);

    // calculate lighting
    float diffuse = max(0.0, dot(lightDir, N));

    vFragColor = vec4(Color,1) * diffuse;
}

```

Maybe of interest: I am using `#version 120` for my shaders. Or, is there a better way to do this?

So, combining the two answers I now have:

```
void
Draw::setGeometry(float* geometry, float* velocity, float* radius, GLuint size){
    this->_size = size;

    glGenBuffers(1, &_vertexData);
    glBindBuffer(GL_ARRAY_BUFFER, _vertexData);
    glBufferData(GL_ARRAY_BUFFER, _size * 3 * sizeof(float), geometry, GL_STATIC_DRAW);
    glBindBuffer(GL_ARRAY_BUFFER, 0);

    glGenBuffers(1, &_velocityData);
    glBindBuffer(GL_ARRAY_BUFFER, _velocityData);
    glBufferData(GL_ARRAY_BUFFER, size * 3 * sizeof(float), velocity, GL_STATIC_DRAW);
    glBindBuffer(GL_ARRAY_BUFFER, 0);

    glGenBuffers(1, &_radiusData);
    glBindBuffer(GL_ARRAY_BUFFER, _radiusData);
    glBufferData(GL_ARRAY_BUFFER, size * sizeof(float), radius, GL_STATIC_DRAW);
    glBindBuffer(GL_ARRAY_BUFFER, 0);

}

```

And the drawing method:

```
void
Draw::paint(GLenum mode){
    glBindBuffer(GL_ARRAY_BUFFER, _vertexData);
     glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
    glEnableVertexAttribArray(1);
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, 0);
    glEnableVertexAttribArray(2);
    glVertexAttribPointer(2, 1, GL_FLOAT, GL_FALSE, 0, 0);

    glDrawArrays(mode, 0, _size * 3 * sizeof(float));
    glDisableVertexAttribArray(0);
}

```

And the Vertex Shader:

```
#version 130

attribute vec3 position;
attribute vec3 velocity;
attribute float size;

uniform mat4 MVP;
uniform mat4 MV;

void main(){
   gl_PointSize = size;

   gl_Position = MVP * vec4(position, 1.0);
}

```

~~The problem is that when `gl_PointSize = 15` is set, they are drawn well. When I make it equal with size, then it looks like this: http://picpaste.com/Big\_particles-daIBnJCG.png~~

Works better now. Particles still getting bigger as they move along.

# Answer
Yes.

I would send the radius as an attribute. Which means you'll have to add it in your vertex shader, then pass it to the fragment shader as a varying.

I don't know how you're storing your attributes for the particles. But I usually do this in an array of structs. That way the data is interleaved per particle. So let's say you have something like:

```
typedef struct {
    vec3 vertex;
    vec2 texture;
    vec4 color;
} TexturedColoredVertex;

```

You'd add to it at the end:

```
    float radius;

```

Then when you're setting up the attribute data you're going to have something like:

```
glVertexAttribPointer(a_vertexPosition, 3, GL_FLOAT, GL_FALSE, sizeof(TexturedColoredVertex), 0);
glVertexAttribPointer(a_vertexColor, 4, GL_FLOAT, GL_FALSE, sizeof(TexturedColoredVertex), (GLvoid*) offsetof(TexturedColoredVertex, color));
glVertexAttribPointer(a_vertexTexCoord0, 2, GL_FLOAT, GL_FALSE, sizeof(TexturedColoredVertex), (GLvoid*) offsetof(TexturedColoredVertex, texture));

```

and you'll add:

```
glVertexAttribPointer(a_vertexRadius, 1, GL_FLOAT, GL_FALSE, sizeof(TexturedColoredVertex), (GLvoid*) offsetof(TexturedColoredVertex, radius));

```

There are of course other things like getting the location of that attribute along with all your others. But hopefully you get the idea.

Then in your particle emitter code just set the radius of each particle and it can even change over time or whatever happens with your particles.

Then in the vertex shader you'll have access to the radius of each particle via:

```
attribute vec3 a_vertexPosition;
attribute lowp vec2 a_vertexTexCoord0;
attribute lowp vec3 a_vertexColor;
attribute float a_vertexRadius;

```

Set up a varying and copy the radius to it. This gets it to the fragment shader. Just like you do with the vertex position.

I'm still on OpenGL 2.0, so I'm not using in/out yet. But it's all the same. Maybe in your version instead of claiming a `varying float v_radius` in both shaders you do `out float v_radius` in one and `in float v_radius` in the other.
> 4 votes

# Answer
Call `glEnable(GL_VERTEX_PROGRAM_POINT_SIZE);` You can then write to the built in variable `gl_PointSize` in your vertex shader. This affects the size of the quad that will be created for the point. If you have a vertex attribute to specify the size of each point you can simply set `gl_PointSize` from that. The point size is specified in device pixels.
> 2 votes

# Answer
After some 12 hours spent on the problem, the solution is a combination of the two before-mentioned solutions:

**Vertex Shader**

Thanks to GuyRT's answer, I added the gl\_PointSize to the Vertex Shader, which sets the size of the points. Look at his answer for more details.

```
uniform mat4 MVP;
uniform mat4 MV;

attribute vec3 position;
attribute float velocity;
attribute float radius;

varying float speed;

void main(){
   gl_PointSize = radius;
   speed = velocity;

   gl_Position = MVP * vec4(position, 1.0);
}

```

**Fragment Shader**

As pointed by badweasel in his answer, transferring from one kernel to another is fairly simple, no matter what version of GLSL you use. I did not color my particles by size in the end, but by velocity, but moving the data from one shader to another should be similar.

```
#version 130

varying float speed;

void main(){
    gl_FragColor = vec4(speed, speed, speed, 1.0);
}

```

All the fancy sprite stuff from above can be then copied here.

**Moving and updating the particles**

This was the actual problem where I got stuck in the end. After looking at https://code.google.com/p/opengl-tutorial-org/source/browse/tutorial04\_colored\_cube/tutorial04.cpp I came up with the following:

```
    //Somewhere in the class
    GLuint vboHandles[3];

```

**Init Method**

```
    //Declaring the buffers
    glBindAttribLocation(this->getProgram(), 0, "position");
    glBindAttribLocation(this->getProgram(), 1, "velocity");
    glBindAttribLocation(this->getProgram(), 2, "radius");

    glGenBuffers(3, vboHandles);

    glBindBuffer(GL_ARRAY_BUFFER, vboHandles[0]);
    glBufferData(GL_ARRAY_BUFFER, _memSize, geometry, GL_STATIC_DRAW);

    glBindBuffer(GL_ARRAY_BUFFER, vboHandles[1]);
    glBufferData(GL_ARRAY_BUFFER, _memSize / 3, velocity, GL_STATIC_DRAW);

    glBindBuffer(GL_ARRAY_BUFFER, vboHandles[2]);
    glBufferData(GL_ARRAY_BUFFER, _memSize / 3, radius, GL_STATIC_DRAW);

```

**Update method**

```
    //Updating positions
    glBindBuffer(GL_ARRAY_BUFFER, vboHandles[0]);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (GLubyte*) NULL);
    glBufferData(GL_ARRAY_BUFFER, _memSize, geometry, GL_STATIC_DRAW);

```

**Paint method**

```
    glBindBuffer(GL_ARRAY_BUFFER, vboHandles[0]);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
    glBindBuffer(GL_ARRAY_BUFFER, vboHandles[1]);
    glEnableVertexAttribArray(1);
    glVertexAttribPointer(1, 1, GL_FLOAT, GL_FALSE, 0, 0);
    glBindBuffer(GL_ARRAY_BUFFER, vboHandles[2]);
    glEnableVertexAttribArray(2);
    glVertexAttribPointer(2, 1, GL_FLOAT, GL_FALSE, 0, 0);

    glDrawArrays(mode, 0, _size);  //Mode is GL_POINTS
    glDisableVertexAttribArray(0);
    glDisableVertexAttribArray(1);
    glDisableVertexAttribArray(2);

```

So again, the answer is based on the two good given answers. For this specific problem, it was a bit harder to implement and combine. Improvements to the code are welcome.
> 0 votes

---
Tags: opengl, glsl
---


title: Self colliding cloth physics

text:
# Question
Title: Self colliding cloth physics
I've previously simulated cloth using Verlet integration but couldn't successfully get the cloth to collide with itself in an efficient way. The reason being is because I used a brute force algorithm to if check all the cloth points collided with each other.

My question is how could I efficiently check for collision between the cloth points? I thought of using some sort of tree structure but it doesn't really make sense in my head given that a lot of tree structures largely depend on spatial position or don't actually suit the cloth because they're better suited to static geometry(BSP).

Additional Info: The cloth is logically just a 2D array of points tied together by a constraint. The cloth is affected by wind and gravity and is also anchored in space at the two upper corner

# Answer
> 5 votes
Any easy way to do this is to form your cloth to approximate the surface as many small spheres. This will work if you have a fairly good particle size to edge-length ratio. To avoid a silly N^2 collision detection algorithm you can use a simple implementation of spacial hashing.

First lets talk about spatial hashing for a discrete point. You take it's position and determine its location in a grid. This "grid" is not a real grid, but an imaginary one. This is super easy given a single grid resolution parameter:

```
const float kGridResolution = 0.5f;
float x = position.x;
float y = position.y
int ix = int( x / kGridResolution );
int iy = int( y / kGridResolution );

```

Once the grid cell coordinates are found they can be hashed with a simple hash function:

```
int kNumberBuckets = 250;

int HashCoordinate( int x, int y )
{
  // Some large primes I pixed from prime-numbers.org
  int k1 = 0x6229ce95;
  int k2 = 0x4787048b;

  return (k1 * x + k2 * y) % kNumberBuckets;
}

```

Once the hash is finished the bucket index into a hash table can be computed with the modulo operator. From here it's just a matter of placing points into the grid and implementing chained resolution. Please note that it doesn't matter if two real-world grid cells map to the same hash table bucket -that's fine as we only want to detect collisions in world space, and do not care about particle lookup with the table. So even though there is a many to one mapping, we won't ever be going from hash to grid cell.

You'll want to use an integer array to represent your chains, instead of a dynamic linked list. This should work in roughly O( 1 ) time in practice, though if your table load factor is high this will deteriorate to O( n ).

To accommodate spheres you will want to find the region of buckets that the sphere overlaps and test the chains of each overlapped bucket. It can be sufficient to represent your sphere as an AABB for simplicity, and don't forget to take epsilon into account. Be careful and you can optimize this to make sure you don't redundantly test any bucket for a given discrete point when you loop over all overlapped grid cells.

Pseudo code in 2D for points (not spheres), no epsilon:

```
const int N = 1000;
int links[ N ];
int lists[ N ];
point insertedPoints[ N ];

void function ReportCollisions( void )
{
  // Clear the linked lists for each hash table bucket
  for ( int i = 0; i < N; ++i )
    lists[ i ] = ~0;

  int insertedPointCount = 0;

  for each point with index pointIndex
  {
    int x = point.x / kGridResolution;
    int y = point.y / kGridResolution;

    int bucket = HashCoordinate( x, y );

    // Look for collisions within this bucket chain
    for ( int i = lists[ bucket ]; i != ~0; i = links[ i ] )
    {
      pointInBucket = insertedPoints[ i ];

      if ( distSqr( pointInBucket, point ) == 0.0f )
        ReportCollision( /* put things in  here */ );
    }

    // Place each point into the table after testing for possible collisions
    insertedPoints[ insertedPointCount ] = point;
    links[ insertedPointCount ] = lists[ bucket ];
    ++insertedPointCount;
    lists[ bucket ] = insertedPointCount;
  }
}

```

An alternative to is to perform triangle to point tests. Each cloth particle will probably be approximated as a sphere for some error tolerance. If you want to get even fancier you can take the motion of a particle over a small time delta and attempt to perform continuous collision detection from particles to triangles. This would probably make use of capsule to triangle and time of impact tests. This is too detailed to cover here, but I felt at least mentioning the ideas is worthwhile.

---
Tags: collision-detection, 3d, physics
---


# Question
Title: Handling multiple lights of different types in GLSL
I want to be able to support multiple lights of different types (point, spot & directional). Note that I also want to be able to render transparent/translucent objects, which rules out deferred rendering.

This means that I will need a fixed upper limit on the number of lights. All of the implementations I have seen use a uniform array, for example:

```
struct PointLight
{
    vec3 color;
    float intensity;
    float radius;
};

uniform PointLight pointLights[8];

```

How can I best extend this to multiple types of lights? Two possible options are:

1. Create multiple uniform arrays, one for each type of light.
2. Define a struct that can be used for all three types of light and then have some way of differentiating the types of lights in the array (e.g. using start index and count uniforms or adding some kind of type flag to the struct).

Both have disadvantages. Both waste memory (although the first more so than the second) and the second either requires additional uniforms or flag checking.

What is the usual method for handling multiple lights of various types?

# Answer
> 3 votes
There is not **THE SOLUTION** when it comes to implement complex lighting. As a result I can not tell you the "usual method", but I can give you pointers in the direction.

First, you want to get rid of the notion, that you have one shader and render one pass and you are done. The way multiple lights are handled is by rendering one light at a time and the geometry it affects and then blending (`GL_ONE, GL_ONE`) it together.

The consensus basically is that for performance reasons you want to have as few if-conditions as possible in your shader. Here you will see often that one shader is used per light type. Then again this is hard to maintain and I for example use an integer.

But if you have add a global ambient term, for example, you can not add this term for each light. The correct solution here is to special pass for the global ambient term. The same is for emissive materials.

You mentioned translucent objects. The same problem you have with deferred lighting, you have it also with multiple passes. Each pass the object becomes more opaque. Although I have not yet tackled this problem (lighting + translucency), my approach would be to render the opaque objects normally. (Maybe even deferred.) And render the translucent objects into a framebuffer as if they where opaque and then blend that. The problem here is when the objects overlap. If overlap is probable you would have to render each translucent object on its own and blend them individually.

If this all works fine, you can look into shadows. One of the reasons why each light is rendered on it's own, is because if you add any form of dynamic lightmap, you would first "render" the light map and then the light.

So basically so lots of different shaders and many frame buffers and this is before doing fancy things like iradiance transfer or ambient occlusion.

---
Tags: opengl, glsl, lighting
---


# Question
Title: Simple Water surface simulation problems (GDC2008 Matthias Muller- Hello World)
Im attempting to implement a simple height field water surface simulation outlined in Matthias Muller's GDC 2008 talk. "http://www.matthiasmueller.info/talks/gdc2008.pdf"

I can't seem to see why it my implementation doesnt work. Could anyone help? Any advice or help would be much appreciated. The main processing loop is below The obstruction array is initialized as 1. And the source just adds 0.1f to a point.

```
void wave()
    {
        for( int i = 0; i<size ; i++)
        {
            height[i] += source[i];
            height[i] *= obstruction[i];
        }

        for (int i = 1 ; i<iwidth-1 ; i++)
        {
            for(int j = 1 ; j < iheight-1 ; j++)
            {

                velocityField[indexFind(i,j)] += (height[indexFind(i-1,j)] +
                                                  height[indexFind(i+1,j)] +
                                                  height[indexFind(i,j-1)] +
                                                  height[indexFind(i,j+1)])/4 - height[indexFind(i,j)];

                velocityField[indexFind(i,j)] *= dampening;

                height[indexFind(i,j)] += velocityField[indexFind(i,j)];

            }

        }
    }

    int indexFind(int x, int y)
    {
        return (x + iwidth*y);
    }

```

This is what happens (height field rendered as a texture on a plane)

This is the page from the link that outlines the algorithm

# Answer
The error is in the slide, the correct implementation is:

```
for (size_t i = 0; i < N; i++)
{
    for (size_t j = 0; j < M; j++)
    {
        size_t n = i * N + j;
        size_t a = i ==   0 ? i * N + j : (i-1) * N + j;
        size_t b = i == N-1 ? i * N + j : (i+1) * N + j;
        size_t c = j ==   0 ? i * N + j : i * N + (j - 1);
        size_t d = j == M-1 ? i * N + j : i * N + (j + 1);

        v[n] = (u[a] + u[b] + u[c] + u[d]) / 4.0f - u[n];
        v[n] *= 0.99;
        u[n] += v[i * N + j];
    }
}

```

Note the `=`instead of the first `+=`. To make something interesting you will need to add additional perturbation over time, since this only smooths out the waves.
> 3 votes

---
Tags: unity, simulations, heightmap, water
---


# Question
Title: Why don't top selling mobile games have localization?
For example: Plants vs Zombies 2, Angry Birds, Bad Piggies, Candy Crush Saga, Temple Run 2 and so on. These games are available in English only. These companies have huge resources; why don't they localize their games?

# Answer
> 6 votes
People might not translate because they think the follow things, that as noted is the comments may or may-not be true.

1. Translation costs lots of money to pay to have done
2. Take lots of support time if done via user supplied text
3. Takes lots of developer resource to implement
4. For free games that rely on Ad revenue, ad clicks are most likely near zero in non-English locations (based on my AdSense returns in non-English locals)
5. For paid games, will less people not playing due to missing language, verse gained customers minus opportunity cost for working on next game
6. You list games, and a large amount of the "text" might be in UI assets, not standard text, thus have a larger asset set to manage might be painful and make the large package larger

# Answer
> 2 votes
Perhaps it's because most people who have access to these technologies speak english nowadays, at least good enough to understand what's going on. I'd rather have a good game with more features rather than one translated in my native language. It wont really affect my decision on which game I'll choose.

# Answer
> 2 votes
Another explanation would be that most mobile games have a quite intuitive gameplay and require less text to be read by the player so most players are able to enjoy the game even if they have moderate english skills.

In these cases, translating the game isn't really worth it for reasons already mentioned by Simeon Pilgrim.

---
Tags: marketing, localization
---


title: Obstacle Avoidance With Walls in C#

text:
# Question
Title: Obstacle Avoidance With Walls in C#
I'm trying to do some obstacle avoidance. Yet somehow something is not going quite well. I've used the book "Programming Game AI by Example" to create a simular function in c# in combination with XNA.

This is what i'm doing right now:

```
public Vector2 ObstacleAvoidance(List<Obstacle> obstacles)
        {
            //the detection box length is proportional to the agent's velocity
            Owner.DetectionBox = Owner.MinDetectionBoxLength +
                                         ((Owner.Speed() / Owner.MaxSpeed) * Owner.MinDetectionBoxLength);
            //tag all obstacles within range of the box for processing
            TagObstaclesWithinViewRange(Owner);

            //this will keep track of the closest intersecting obstacle (CIB)
            BaseGameEntity ClosestIntersectingObstacle = null;

            //this will be used to track the distance to the CIB
            double DistToClosestIP = Double.MaxValue;

            //this will record the transformed local coordinates of the CIB
            Vector2 LocalPosOfClosestObstacle = new Vector2();

            foreach (Obstacle curOb in obstacles)
            {
                //if the obstacle has been tagged within range proceed
                if (curOb.Tag)
                {
                    //calculate this obstacle's position in local space
                    Vector2 LocalPos = HelperMethods.PointToLocalSpace(curOb.Position,
                                                           Owner.Heading,
                                                           Owner.Side,
                                                           Owner.Position);

                    //if the local position has a negative x value then it must lay
                    //behind the agent. (in which case it can be ignored)
                    if (LocalPos.X >= 0)
                    {
                        //if the distance from the x axis to the object's position is less
                        //than its radius + half the width of the detection box then there
                        //is a potential intersection.
                        double ExpandedRadius = curOb.BoundingRadius + Owner.BoundingRadius;
                        if (Math.Abs(LocalPos.Y) < ExpandedRadius)
                        {
                            //now to do a line/circle intersection test. The center of the
                            //circle is represented by (cX, cY). The intersection points are
                            //given by the formula x = cX +/-sqrt(r^2-cY^2) for y=0.
                            //We only need to look at the smallest positive value of x because
                            //that will be the closest point of intersection.
                            double cX = LocalPos.X;
                            double cY = LocalPos.Y;

                            //we only need to calculate the sqrt part of the above equation once
                            double SqrtPart = Math.Sqrt(ExpandedRadius * ExpandedRadius - cY * cY);

                            double ip = cX - SqrtPart;

                            if (ip <= 0.0)
                            {
                                ip = cX + SqrtPart;
                            }

                            //test to see if this is the closest so far. If it is keep a
                            //record of the obstacle and its local coordinates
                            if (ip < DistToClosestIP)
                            {
                                DistToClosestIP = ip;

                                ClosestIntersectingObstacle = curOb;

                                LocalPosOfClosestObstacle = LocalPos;
                            }
                        }
                    }
                }
            }

            //if we have found an intersecting obstacle, calculate a steering
            //force away from it
            Vector2 SteeringForce = Vector2.Zero;

            if (ClosestIntersectingObstacle != null)
            {
                //the closer the agent is to an object, the stronger the
                //steering force should be
                double multiplier = 1.0 + (Owner.DetectionBox - LocalPosOfClosestObstacle.X) /
                                    Owner.DetectionBox;

                //calculate the lateral force
                SteeringForce.Y = (float) ((ClosestIntersectingObstacle.BoundingRadius -
                                            LocalPosOfClosestObstacle.Y) * multiplier);

                //apply a braking force proportional to the obstacles distance from
                //the vehicle.
                double BrakingWeight = 0.2;

                SteeringForce.X = (float) ((ClosestIntersectingObstacle.BoundingRadius -
                                            LocalPosOfClosestObstacle.X) *
                                           BrakingWeight);
            }

            //finally, convert the steering vector from local to world space
            return HelperMethods.VectorToWorldSpace(SteeringForce,
                                      Owner.Heading,
                                      Owner.Side);
        }

```

When i'm seeing the wall i still go through it instead of changing directions. This has something to do with this specific line of code:

```
double ExpandedRadius = curOb.BoundingRadius + Owner.BoundingRadius;
if (Math.Abs(LocalPos.Y) < ExpandedRadius)

```

When i'm seeing the wall i should go into this if yet i'm not, and therefore going through the wall.

curOb = the wall and his boudingradius is 12.5. Owner = the player and his bounding radius is also 12.5. The LocalPos.Y value is something like 120 which is correct as the y position of the wall is at that exact location. How can i try to fix this so my player won't crash into walls?

Greets

EDIT

The Promised Picture - It should detect the wall and add it to closestIntersectionObstacle but it doesnt

# Answer
> 1 votes
As per your comment my reading was wrong. I thought LocalPos was relative to the player, because I assumed that's what `HelperMethods.PointToLocalSpace` was supposed to be doing. But if `LocalPos` is still world coords, then your description at the end of the question gives it away.

Your if statement:

```
if (Math.Abs(LocalPos.Y) < ExpandedRadius)

```

can be translated into English like so:

```
if the wall's vertical position on the screen is less than the bounding distance...

```

Comparing an absolute position to a relative distance shouldn't make much sense intuitively.

It should be asking if the *distance* between the player and the wall is less than `ExpandingRadius`.

```
double playerDistance = /* Calculate distance between player and wall */
if (playerDistance < ExpandedRadius)

```

---
Tags: xna, c#, steering-behaviors, collision-avoidance
---


# Question
Title: How can I manage complicated visual state over a simple model in puzzle games?
I've been encountering this design challenge making a few toys with Javascript (CreateJS, EaselJS)

The scenario is that you've got some sort of puzzle game with a simple game model. For a simple case, imagine a visual graph builder, where the model is a simple vanilla CS graph structure, maybe stored as nodes and edges.

However, you want to build a fancy interface for editing this graph structure, which introduces a *lot* more information. Colors, sizes, bezier curve control points for the edges, having a node "blink" during forming a connection, having the edited edge follow the mouse, etc.

How can I decouple the visual information from the raw model information? There's also a lot of state concerns. Some strategies I've employed:

Have an overall application state: ex. `{NO_ACTION, CONNECTING}`, where `CONNECTING` could store information about the selected node. Upon changing into the `CONNECTING` state after an event, I tell the node on which the connection was initiated to change into `INITIATE_CONNECTION` mode which, upon other things, causes the port to blink. Most of the ways I come up with to manage this feel hackish, dirty, and not abstracted.

I'm interested in resources or opinions about this type of scenario, and how I can better architect the application.

# Answer
> 1 votes
> How can I decouple the visual information from the raw model information?

More easily than you are probably thinking:

```
class ModelObject {
  ...
}

class VisualObject {
  ModelObject ModelReference;

  ...
}

```

As you note, the visual representation almost always only introduces *new* information, so it can be defined in terms of a reference to an existing model object (for any type of model object, be it a graph node, edge, puzzle piece, et cetera), plus it's extra properties. You then build your UI and interaction code around the visual API, which allows you to expose or derive all the interesting blink, color, node connection position, et cetera properties you want.

You will also need to keep a simple state machine in play in most cases, since in most cases the way you'd visually construct a new model instance requires more information than an UI can accept from the player all at once. For example, to return to your graph example, the player will probably first click somewhere to create a new node, and then click around to set some node properties and connect it to the rest of the graph. The model API, on the other hand, may not allow for that kind of multi-phase construction (for example, you may not be able to directly construct graph nodes, but rather need to ask the graph itself for a new node and supply *all* the relevant information, which you may not have from the user yet).

In that scenario, a simple state machine like you described works fine, and you may also need to have some idea of a "proxy" object that is under construction but not yet backed by an actual final model object.

In addition to the MVC pattern noted in the comments, there's also the MVVM pattern which you may want to look into. Both are useful, although with all patterns I recommend you avoid an overly dogmatic approach, because that's overkill (especially for games). By this I mean, don't decide to adopt MVC and then go around refactoring everything so you now have a "Sprite" and a "SpriteView" and a "SpriteController" and so on. The important parts of these patterns are the conceptual ways in which they are factoring responsibility and facilitating communication between the parties responsible for things.

# Answer
> 0 votes
I think you should check on Entity Framework. Particularly Ash framework and its Javascript port. Having a lot of information is ideal candicate to split these into components/entities. Then you can have systems that work over these entities. It's hard to give exact example when you haven't given any by yourself.

And for state management, you can combine this with FSM like MachinaJS.

---
Tags: game-design, architecture, javascript, puzzle, easeljs
---


# Question
Title: Act on Right Mouse Button click on Button
I want to be able to listen for a right mouse click onto a `TextButton`. Is this possible without removing the default `ClickListener` of the `TextButton`? If yes, how? Or should I use a different listener?

# Answer
This is actually really simple. All you have to do is add another `ClickListener` which listens for Right Clicks (the default only listens to left clicks). To do this all you have to do is this:

```
someButton.addListener(new ClickListener(Buttons.RIGHT)
{
    @Override
    public void clicked(InputEvent event, float x, float y)
    {
        //do whatever
    }
});

```

*Note that this also works for middle clicks (`Buttons.MIDDLE`)*
> 11 votes

# Answer
There are three main ways (that I know of) to obtaining input in LibGDX.
The first is as you said, changing the  `ClickListener`, the second will be setting the setting the current screen as an implementation of  `InputProcessor` , and the third will be obtaining the mouse click through a new class, or a sub-class to get the input.
I'll elaborate on each:

1. The first way: Changing the ClickListener. Pretty straight forward, lets say you have a text button named  `onOffSwitch`, if you'd want to recieve input on it, you'd write the following code:
`onOffSwitch.addListener(new ClickListener(){ });`
This will create a new `ClickListener` to use to recieve any input from the button.
When you use this you can add method like `enter` to see whenever the mouse is hovering over the buttton, or when the player is touching the button.
2. The second way: Setting a new `InputProcessor`, this will basically create an inputprocessor which will be your entire screen.
I don't recommend using this since it requires more than one methhod and is often not needed, all that's needed is a little digging around on how to get the listeners you need.
To implement this way, you need to make your class implement the `InputProcessor` and implement the needed methods.
3. The third and last way, which I assume is the one you'll use is the following:
To use this way you'll create a new instance of `InputProcessor` and apply it to `Gdx.input`:

```
class AwesomeGameClass {
public void init() {
    Gdx.input.setInputProcessor(new InputProcessor() {
        @Override
        public boolean TouchDown(int x, int y, int pointer, int button) {
            if (button == Input.Buttons.LEFT) {
                //check if the x and y coordinates are the same as your text button (using TextButton.getPrefWidth() & TextButton.getPrefHeight()) and if so then invoke the onMouseDown method.
                return true;
            }
            return false
        }
    });
}
private void onMouseDown() {
}

```

}

The code I got from here, and you can see what else there is there that I might have missed. HERE Except that you can read up on materials in the LibGDX github, which is located HERE Or look at the data concerning TextButtons in HERE
> 6 votes

---
Tags: libgdx, input
---


title: Is DXUT deprecated?

text:
# Question
Title: Is DXUT deprecated?
I'm starting on a new project and was thinking of using DXUT. On the Microsoft site though, this page says the content has moved to this page. And on that second page, which is an overview of DirectX components, there's no mention of DXUT.

Is DXUT deprecated now?

# Answer
DXUT was primarily used to drive DirectX samples, and really that's about all it was good for -- it was itself always shipped in the samples directory of the SDK.

Modern (that is, for Windows 8) samples seem to directly include "DirectXApp" classes that drive the basic equivalent functionality that DXUT provided. I don't believe DXUT itself has survived the transition because I don't see it in the samples directory linked off of the second page you provided.

But that's fine, since it wasn't really worth using for production applications.

EDIT: However, as of September 2013, as Chuck notes above, a standalone updated to DXUT can be obtained.
> 6 votes

# Answer
To the original question: DXUT has historically been the sample framework for the DirectX SDK. Officially the DirectX SDK is now deprecated, and along with it the D3DX utility library that DXUT used to use. Also, DXUT only works for Win32 desktop applications, and is not supported for Windows Store apps, Windows phone 8, Xbox One, etc.

The GitHub version of DXUT is basically a cleaned up DXUT11 from the legacy DirectX SDK (June 2010). It no longer has any dependencies on the legacy DirectX SDK and can be built using just VS 2012 or VS 2013 with the Windows 8.x SDK. it includes some helper code (DDSTextureLoader, WICTextureLoader, ScreenGrab) from the DirectXTex/DirectX Tool Kit projects but otherwise is 'standalone'. I used this version of DXUT to scrub out the legacy DirectX SDK dependencies of a number of old samples.

DXUT was never really recommended for use for 'production' applications as it was primarily about making it easier to write samples, but some people found it useful as a the basis of their work.

See this blog post.

**NOTE** For simple projects and developer education, another option instead of using DXUT is to use DirectX Tool Kit which supports all the modern Microsoft platforms in combination with the Direct3D Game template.
> 9 votes

---
Tags: c++, directx
---


title: Matrix transformation

text:
# Question
Title: Matrix transformation
I have to find components of a matrix for 3D transformation. I have a first system in which transformations are made by multiplying: M1 = Scale x Rotation x Translation. I want to have the same transformations in an engine who compute like this: M2 = Scale x Translation x Rotation So when I enter the same values there's a problem du to the inversion of translation and rotation.

How can I compute the values in the last matrix M2 for having the same transformation?

Thanks

# Answer
If you multiply the translation vector by the inverse of the rotation matrix, you'll get an "anti-rotated" translation which you can use to swap the order. The "anti-rotated" translation will get turned back into the original translation when the rotation matrix is applied.

However, are you sure you understand correctly what the second engine is doing? Scale * Translation * Rotation makes no sense as a local-to-world transform, as objects would be rotated about the world origin rather than their own local origin. Perhaps this engine supports different scale and rotate pivots, and the translation you're seeing is from the scale pivot to the rotate pivot? That's the only reason I can think of to place a translation between a scale and a rotation.
> 1 votes

---
Tags: matrix, transformation
---


# Question
Title: XY Location scaling with varying density screens
I have a phone with resolution H=1280,W=720,Density=2
I have a tablet with resolution H=1216,W=800,Density=1.331

I drew a rectangle on my phone with corners Left,Top (-1.6,1.55), Right,Bottom (1.6,-1.65).
If I want to draw very similar rectangle on tablet (the gap of edges from screen ends look almost same), what would the formula be to calculate the four corners?

Given:
* The origin is always at center of screen. (because I don't know how to change it in Opengl ES 2.0 :-/ )

Shader code:

```
String vertexShaderSource = "attribute vec4 a_Position; uniform mat4 uMVPMatrix; void main() { gl_Position = uMVPMatrix * a_Position; }";
String fragmentShaderSource = "precision mediump float; uniform vec4 u_Color; void main() { gl_FragColor = u_Color; }";

```

OpenGL setup code:

```
@Override
public void onSurfaceChanged(GL10 gl, int width, int height) {
    this.W = width;
    this.H = height;

    glViewport(0, 0, width, height);

    //initialize rectangle...

    Matrix.setIdentityM(mProjMatrix, 0);
    Matrix.setIdentityM(mViewMatrix, 0);
    Matrix.setIdentityM(mMVPMatrix, 0);

    float aspect = width > height ? (float)width / height : (float)height / width;

    // Setup our screen width and height for normal sprite translation.
    // ortho is converting 3d to 2d - z is 0
    if (width > height) {
        Matrix.orthoM(mProjMatrix, 0, -aspect, aspect, -1, 1, 3, 7);
    } else {
        Matrix.orthoM(mProjMatrix, 0, -1, 1f, -aspect, aspect, 3, 7);
    }

    // Set the camera position (View matrix)
    Matrix.setLookAtM(mViewMatrix, 0,
                        0f, 0f, -3f, // eye
                        0f, 0f, 0f, // center
                        0f, 1f, 0f); // up

    // Calculate the projection and view transformation
    Matrix.multiplyMM(mMVPMatrix, 0, mProjMatrix, 0, mViewMatrix, 0);
}

@Override
public void onDrawFrame(GL10 gl) {
    glClear(GL_COLOR_BUFFER_BIT);

    // view transformation
    glUniformMatrix4fv(_uMVPMatrix, 1, false, mMVPMatrix, 0);

    m_vertexBuffer.position(0);
    glVertexAttribPointer(m_a_Position, POSITION_COMPONENT_COUNT, GL_FLOAT, false, 0, m_vertexBuffer);

    glDrawArrays(GL_LINE_LOOP, 0, 4);
}

```

I do not have any formula. Has anybody got any idea?

# Answer
> 1 votes
Okay, this worked for me.

I switched from \[-1,1\] range to \[-1,WIDTH\] and \[-1,HEIGHT\] range. This way, I used the pixel X,Y directly in my app, which always scaled correctly on both devices.

```
@Override
public void onSurfaceChanged(GL10 gl, int width, int height) {
    this.W = width;
    this.H = height;

    glViewport(0, 0, width, height);

    //initialize rectangle...

    Matrix.setIdentityM(mProjMatrix, 0);
    Matrix.setIdentityM(mViewMatrix, 0);
    Matrix.setIdentityM(mMVPMatrix, 0);

    //my app is in portrait mode
    Matrix.orthoM(mProjMatrix, 0, -1f, width, height, -1f, -1f, 1f);

    // Calculate the projection and view transformation
    Matrix.multiplyMM(mMVPMatrix, 0, mProjMatrix, 0, mViewMatrix, 0);
}

```

I chose -1 as the min range, because if I draw a rectangle of L=0,T=0,R=WIDTH,B=HEIGHT, I can see the full rectangle inside the screen at the border. This can be changed as per need.

Now, the objects drawn at specific XY pixel locations look exactly in the same ratio. However, this might not be true for *ALL* devices, as the resolutions differ.

---
Tags: android, mathematics, opengl-es2, geometry
---


title: Pathplanning A* Getting stuck in wall

text:
# Question
Title: Pathplanning A* Getting stuck in wall
I'm having a problem with my pathplanning.

I can plan a path and make my character follow it, that's not a problem. But when I plan a path around a wall, it takes the shortest way as A\* suggests, which is normally good. But the player I'm moving is not 1 pixel by 1 pixel, so it overlaps with the wall. My question, should I check for that during the calculation of the path created by A\* or should I do it somewhere later?

I thought it'd be wise to take the Player's width and height into account with the A\* calculation. But I don't know how I'm going to do that.

I hope you guys can help me out.

Here's my A\* search:

```
internal class SearchWithAStar
    {
    private SparseGraph _graph;
    private int _source, _target;
    private List<double> _costToThisNode;
    private List<double> _mgCost;
    private List<Edge> _shortestPathTree, _searchFrontier;

    public SearchWithAStar(SparseGraph graph, int source, int target)
    {
        _graph = graph;
        _source = source;
        _target = target;
        _shortestPathTree = new List<Edge>(_graph.NumNodes);
        _searchFrontier = new List<Edge>(_graph.NumNodes);
        _costToThisNode = new List<double>(_graph.NumNodes);
        _mgCost = new List<double>(_graph.NumNodes);

        for (int i = 0; i < _graph.NumNodes; ++i)
        {
            _shortestPathTree.Insert(i, null);
            _searchFrontier.Insert(i, null);
            _costToThisNode.Insert(i, 0);
            _mgCost.Insert(i, 0);
        }
        Search();
    }

    private void Search()
    {
        //m_FCosts = _costToThisNode
        //
        IndexedPriorityQLow<double> pq = new IndexedPriorityQLow<double>(_costToThisNode, _graph.NumNodes);
        pq.Insert(_source);
        while (!pq.Empty)
        {
            //get lowest cost node from the queue
            int NextClosestNode = pq.Pop();

            //move this node from the frontier to the spanning tree
            _shortestPathTree[NextClosestNode] = _searchFrontier[NextClosestNode];

            //if the target has been found exit
            if (NextClosestNode == _target) return;

            List<Edge> nodeEdges = _graph.GetAllEdgesFromNode(NextClosestNode);

            foreach (Edge edge in nodeEdges)
            {
                //calculate the heuristic cost from this node to the target (H)
                double HCost = Heuristic.Calculate(_graph, _target, edge.To);

                //calculate the 'real' cost to this node from the source (G)
                double GCost = _costToThisNode[NextClosestNode] + edge.Cost;

                //if the node has not been added to the frontier, add it and update
                //the G and F costs
                if (_searchFrontier[edge.To] == null)
                {
                    _costToThisNode[edge.To] = GCost + HCost;
                    _mgCost[edge.To] = GCost;

                    pq.Insert(edge.To);

                    _searchFrontier[edge.To] = edge;
                }

                    //if this node is already on the frontier but the cost to get here
                    //is cheaper than has been found previously, update the node
                    //costs and frontier accordingly.
                else if ((GCost < _mgCost[edge.To]) && (_shortestPathTree[edge.To] == null))
                {
                    _costToThisNode[edge.To] = GCost + HCost;
                    _mgCost[edge.To] = GCost;

                    pq.ChangePriority(edge.To);

                    _searchFrontier[edge.To] = edge;
                }
            }
        }
    }

    public List<int> GetPathToTarget()
    {
        var path = new LinkedList<int>();

        // if the target has not been set, then no path has
        // been found
        if (_target < 0)
            return path.ToList();

        // add the target node to the linked list
        var node = _target;
        path.AddFirst(node);

        // then add each node on the shortest path tree
        while ((node != _source) && (_shortestPathTree[node] != null))
        {
            node = _shortestPathTree[node].From;
            path.AddFirst(node);
        }

        // return the completed path as a List<>
        return path.ToList();
    }

```

And a picture for more detail about this "error": the guy should walk around the wall, not through the wall.

# Answer
> 4 votes
One thing you can do is not let the character travel diagonally when the path crosses the corner of a wall. The character is free to travel diagonally out on the open, but not next to a wall. This is done in your a\* algorithm.

# Answer
> 3 votes
Yes you should factor the size of the character into the A\* calculation. There are basically two ways you can either make your character larger, which complicates the computation. Alternatively you can make the wall wider and pretend your character has 0 width.

---
Tags: xna, c#, collision-detection, sprites, path-finding
---


# Question
Title: Graphics programming replicating the transition from Chrono Trigger inside the gate
I started playing this game for the first time lately and this really peaked my interest

You can see the transition in motion starting at ~12:08

There seems to be some interesting maths taking place in there. It would appear that there are two different views combined together. The blue ripples are rendered first in the background and then the purple oscillating waves appear to be rendered on some sort of pseudo 3D projection.

How exactly they came to this result however is beyond me and curiosity has got the better of me.

I don't expect a lot of people would know how this is especially done but if anyone has done some extensive graphics programming, perhaps they could enlighten me.

# Answer
> 11 votes
I tried to duplicate the effect by using shader.

Shader00 Center : https://www.shadertoy.com/view/XsXSz2

Shader01 Sides : https://www.shadertoy.com/view/4sXSz2

:) you could, as Byte56 said, set up three planes. A plane facing camera directly forward with Shader00, and then two plane with Shader01, perhapss as RandyGaul mentioned, top/bottom non uniformly scaled to give the illusion of depth.

They should, I believe, give sufficient 3D look to be convincing.

Both two shaders are not exactly the same as in your youtube link(also they are more of rough draft). However I believe these shaders can, hopefully, give you a place to start building your own version.

Tutorial : How to make a simple stripe pattern.

Each point in the plane has coordinate. Attempting to create a shader effect is basically visualizing 2D math onto the plane. Here let me introduce a simple example.

```
//This shader will visualize coordinates
vec2 uv = gl_FragCoord.xy / iResolution.xy;
gl_FragColor = vec4(uv.x,uv.y,0,1);

```

The color red will represent x coordinate and the green hue will represent y coordinate. For now, we want to create simplest shader effect; a stripe. We won't need uv.y value for this tutorial.

```
vec2 uv = gl_FragCoord.xy / iResolution.xy;
gl_FragColor = vec4(uv.x,0,0,1);

```

You can see that red hue gets intense as it directs to the right side. That's because x value of the coordinate gets higher as you move to the right side; the left end x coordinate starts from 0 and the right end x coordinate is 1.

Since we have this basic understanding let's try something "intuitive"

```
vec2 uv = gl_FragCoord.xy / iResolution.xy;
float color = 0.0;
if(uv.x < .5 ) color= 1.0 ;
gl_FragColor = vec4(color,0,0,1);

```

There you have a stripe pattern. Wait... that doesn't look quite right. Yes this is just red and black. Stripe pattern is consist of more than just two color sections. There...!

```
vec2 uv = gl_FragCoord.xy / iResolution.xy;
float color = 0.0;
if(uv.x < .2 ||(uv.x >.4 && uv.x < .6) || (uv.x > .8 && uv.x <1.0 )) color= 1.0 ;
gl_FragColor = vec4(color,0,0,1);

```

but what if we want to make N number of stripe?

What I am attempting to display is that if you try to approach shader programming with more of traditional programming "logic" then you are likely to fail. When it comes to shader, it's all about math.

Speaking of math, what's the pattern that most resembles "stripe" pattern? In other words, what's the equation that looks like stripes? Yes. Y = sin(X). However our X value ranges from 0.0~1.0 If we want to use Y = sin(X) we want our x value to range from 0.0 ~ 6.28(which is roughly 2 PI)

```
vec2 uv = gl_FragCoord.xy / iResolution.xy;
float x = uv.x * 2.0 *PI;
float y = sin(x);
gl_FragColor = vec4(y,0,0,1);

```

We now have "stripe" in terms of pattern generated by an equation. Why should we take this approach? Not only can this be faster, but also it eliminates the need of writing ugly "if" conditions to have N number of stripe. If we wanted to have more than one stripe, we could simply extend the pattern by increasing the maximum X value further.

```
vec2 uv = gl_FragCoord.xy / iResolution.xy;
float x = uv.x * (2.0 *PI * 10.0); //ta dan!
float y = sin(x);
gl_FragColor = vec4(y,0,0,1);

```

You might say this shader doesn't produce the perfect stripe like from early shader, but really, all you need to do is write more fitting equation!

```
vec2 uv = gl_FragCoord.xy / iResolution.xy;
float x = uv.x * (2.0 *PI * 10.0);
float y = sin(x) / abs(sin(x) );
gl_FragColor = vec4(y,0,0,1);

```

Weeee~~~

Next : How to make a wavy stripe pattern.

---
Tags: graphics, graphics-programming
---


title: Generating tile map

text:
# Question
Title: Generating tile map
I am programming a tile based game and I have some basic tiles (grass, dirt, etc..), but I can't figure out how to make good random map generation, because when I do some really random selection, if the tile should be grass/dirt, I get this:

I understand why this is happening, but what I want is to create some random continuous areas of grass or dirt. Something that would make more sense, like this:

# Answer
What you could do is randomly generate a Voronoi map like this:

1. Picking random `center points` (see the black dots) and randomly decide if they are grass or dirt.
2. Then for over all tiles, check if it's closest to a `center point` of dirt or a grass.
3. Done!

If what you did previously is "flip a coin" for each tile (noise), generating a Voronoi diagram will provide a much better result.

You could improve on this by dividing the `center points` into `islands` with an algorithm that:

1. Picks a small group of `centers points` and designates them as `leaders`.
2. Iteratively adds a random adjacent undecided center point each turn.
3. Done!
> 25 votes

# Answer
You could use perlin noise, which is normaly used for heightmap generation. Perlin noise in games

Then you could use the heights as an adviser, how high the chance of grass/dirt occuring in one region of the map is.

Example (Perlin noise values from 0-256): If the value is over 200 the chance that grass is placed is 80% (dirt 20%). If the value is between 100 and 200 the chance that grass is placed is 50% (dirt also 50%). If the value is under 100 the chance that grass is placed is 20% (dirt 80%).
> 25 votes

# Answer
http://gamedevelopment.tutsplus.com/tutorials/generate-random-cave-levels-using-cellular-automata--gamedev-9664

here is my version of the cellular automata method start by filling the grid with random then run these cullular automata rules on it a couple times

* If a living cell has less than two living neighbours, it dies.
* If a living cell has two or three living neighbours, it stays alive.
* If a living cell has more than three living neighbours, it dies.
* If a dead cell has exactly three living neighbours, it becomes alive.

and it ends up looking like a cave

the index can be converted to the x&y position and back with this code

```
public int TileIndex(int x, int y)
{
    return y * Generator.Instance.Width + x;
}
public Vector2 TilePosition(int index)
{
    float y = index / Generator.Instance.Width;
    float x = index - Generator.Instance.Width * y;
    return new Vector2(x, y);
}

```

i just return a list of bools because i use this list for many things: caves, trees, flowers, grass, fog, water you can even combine multiple lists in different ways here i first remove all smaller caves then union two random lists

```
private int GetAdjacentCount(List<bool> list, Vector2 p)
{
    int count = 0;
    for (int y = -1; y <= 1; y++)
    {
        for (int x = -1; x <= 1; x++)
        {
            if (!((x == 0) && (y == 0)))
            {
                Vector2 point = new Vector2(p.x + x, p.y + y);
                if (PathFinder.Instance.InsideMap(point))
                {
                    int index = PathFinder.Instance.TileIndex(point);
                    if (list[index])
                    {
                        count++;
                    }
                }
                else
                {
                    count++;
                }
            }
        }
    }
    return count;
}
private List<bool> GetCellularList(int steps, float chance, int birth, int death)
{
    int count = _width * _height;
    List<bool> list = Enumerable.Repeat(false, count).ToList();
    for (int y = 0; y < _height; y++)
    {
        for (int x = 0; x < _width; x++)
        {
            Vector2 p = new Vector2(x, y);
            int index = PathFinder.Instance.TileIndex(p);
            list[index] = Utility.RandomPercent(chance);
        }
    }
    for (int i = 0; i < steps; i++)
    {
        var temp = Enumerable.Repeat(false, count).ToList();
        for (int y = 0; y < _height; y++)
        {
            for (int x = 0; x < _width; x++)
            {
                Vector2 p = new Vector2(x, y);
                int index = PathFinder.Instance.TileIndex(p);
                if (index == -1) Debug.Log(index);
                int adjacent = GetAdjacentCount(list, p);
                bool set = list[index];
                if (set)
                {
                    if (adjacent < death)
                        set = false;
                }
                else
                {
                    if (adjacent > birth)
                        set = true;
                }
                temp[index] = set;
            }
        }
        list = temp;
    }
    if ((steps > 0) && Utility.RandomBool())
        RemoveSmall(list);
    return list;
}

```
> 9 votes

# Answer
Select a point on the map. Place desired tile type with a base value such as 40. Keep track of where you placed your newly desired tile. Add the starting point to a list.

For each point in this list, you visit all neighbours. While you have enough power left (started at 40) add a desired tile and add it to the list to be visited. Give the new tile less power, determined by you. Easiest = random lowering. After you visited the tile from the list, remove it. Start over again by visiting any unvisited but created tiles.
> 7 votes

---
Tags: tiles, procedural-generation, tilemap, random
---


# Question
Title: Restarting a libGDX game to apply changes to resolution
How can I restart a LibGDX game to apply certain changes to the game such as changes to the resolution (going from 1920X1080 to 1280X720), or changing full screen.
Granted the `resize(int width, int height)` can help with the resolution change, but I need to change other settings as well so I rather restart the game and continue from the options menu instead of forcing the user to manually exit the game and then restart it.

# Answer
After 3 days of working I managed to work around it, I created this git repository so people can use it, it says everything there. Git Repository Enjoy, those who need it.

EDIT: Not the solution.
EDIT: The solution is located here.
> 3 votes

---
Tags: java, libgdx
---


# Question
Title: How to make a projectile align correctly with the entity that shot it
I'm developing a 2D game. In the game, all entities can rotate 360 degrees. Each entity holds an `angle` value, and every frame it is drawn rotated around it's center by it's current angle value. For example:

An entity can 'shoot' another entity, a projectile. The `Projectile` is instantiated with a position and an angle. The position is calculated like so:

```
radius = entity.width / 2
angle = entity.angle
projectileX = entity.centerX + cos(angle) * radius
projectileY = entity.centerY + sin(angle) * radius

```

Example positions this calculation gives:

The angle the `Projectile` is instantiated with is the angle of the entity creating it. So if the entity's current `angle` value was `45`, the angle of the new `Projectile` is going to be `45`.

All of this creates a problem. I will demonstrate the steps leading to this problem:

**1-** An entity decides to shoot a `Projectile`. It's position is calculated like shown above.

**2-** A new `Projectile` is added to the game. It is instantiated with the position calculated in the previous step and with the `angle` of the entity instantiating it, for this example `45`.

**3-** Every frame, each entity is drawn rotated around it's center by it's current `angle` value.

The `angle` of the new `Projectile` is `45`, so it is drawn rotated around it's center by `45` degrees.

As you can see: after the rotation, the `Projectile` is no longer aligned correctly with the entity that created it. They are both rotated by the same angle, but the `Projectile` isn't 'pointing from the center' of the entity. It seems like it 'moved' a little to the side.

To clarify:

**My question: how can I make the `Projectile` align correctly with the entity that created it?** How can I make it still 'point from the middle' of the entity that created it, and not mess this up when rotating it around it's center?

# Answer
> 5 votes
Rather than rotating the projectile about its own centre, then translating it to the end of the cannon, you could translate it first *and then* rotate the projectile using the origin of the tank (the tank's centre, in this case) by the tank's rotation.

Here is how to rotate a point around another point in c++. (C# version)

Following that:

```
projectile.position = tank.position + cannonOffset;
projectile.position = rotatePoint(origin: tank.position,
                                  point: projectile.position,
                                  angle: tank.rotation);
projectile.rotation = tank.rotation;

```

Part of the reason for doing it this way is that you can make cannonOffset any relative position to the source entity. So if there is a gun on the front side (1,-1 instead of 2,0), this will still work.

# Answer
> 4 votes
I would instantiate the Projectile at the (x,y) location of the Entity and then move it in the direction of the Entity by radius distance. In code, that would go:

```
projectileX = entity.x + cos(entity.angle) * radius;
projectileY = entity.y + sin(entity.angle) * radius;

```

Then add your projectile to the game world and send it off!

---
Tags: 2d, mathematics, geometry
---


# Question
Title: Why do some game titles differ between localisation versions?
I had previously asked this on Arqade but it seems it was off-topic, hopefully this network is a better place to ask.

---

I've noticed that for a number of games, different localisation versions sometimes differ in the titles. A notable example are the Professor Layton series, in which the Diabolical Box, Unwound Future, and Last Specter are named as Pandora's Box, Lost Future, and Spectre's Call in the European versions (respectively). I can see how the Japanese names would differ (e.g. "Mask of Miracle" instead of "Miracle Mask") due to it being a different language, but I can't understand why the English titles for the European versions should have different names from the US versions.

What makes the situation even more confusing is that the Curious Village, Miracle Mask, and Azran Legacy aren't subject to this and have the same names in both the European and US versions.

Can anybody enlighten me as to why developers/publishers do this? To my knowledge the games are more or less identical in every other way, apart from British/US English spelling differences (and the exclusion of the London Life minigame in the Spectre's Call). Another example would be Luigi's Mansion: Dark Moon, known as Luigi's Mansion 2 in Europe, which again makes no sense to me.

# Answer
This is not a phenomenon limited to games; it also occurs in other media. There are a variety of reasons it might happen (which apply equally well to games and non-games):

* Preparing a game for release in another country isn't just a matter of *translation*; sometimes the name of a title, character, item, what-have-you needs to be changed to fit better with the culture idioms and expectations of the target country (the US publisher for the Harry Potter series thought that children wouldn't want to read a book with "philosopher" in the title).
* In the case of numbered titles, intervening numbers may not have been released in all countries (as with the early Final Fantasy games in the US).
* Legal issues, such as trademarks and such, that differ between countries may prevent the use of one name and thus force a name change.
* Names may be changed to capitalize on the success of other names; for example, Doki Doki Panic (although this is perhaps a borderline example, since art assets were altered as well).
* Sometimes the developer or publish just plain *wants* to, for one reason or another (see the difference in the title of The Golden Compass in the US and UK).
> 3 votes

---
Tags: publishing, localization
---