# Question
Title: How do I simplify terrain with tunnels or overhangs?
I'm attempting to store vertex data in a quadtree with C++, such that far-away vertices can be combined to simplify the object and speed up rendering.

This works well with a reasonably flat mesh, but what about terrain with overhangs or tunnels? How should I represent such a mesh in a quadtree?

After the initial generation, each mesh is roughly 130,000 polygons and about 300 of these meshes are lined up to create the surface of a planetary body. A fully generated planet is upwards of 10,000,000 polygons before applying any culling to the individual meshes. Therefore, this second optimization is vital for the project.

The rest of my confusion focuses around my inexperience with vertex data: How do I properly loop through the vertex data to group them into specific quads? How do I conclude from vertex data what a quad's maximum size should be? How many quads should the quadtree include?

# Answer
> 2 votes
After reading a lot about this over the years, the advice that I see the most is to avoid doing it at all.

It might not feel like good advice at first, but the arguments are that the performance gains you get for making this kind of structure is totally overshadowed by the potential performance gain you would get by simply chopping your model into cubes at coarse resolution and doing basic culling. The reason is that modern GPUs are so efficient that they will render amazing amounts of geometry in the same time the CPU would use to be smart about it. To feed the GPU from an advanced structure vs. a simple flat format will incur all sorts of penalties in extra memory usage, memory fragmentation, cache misses etc.

EDIT: I decided to add some more tips for you after reading your question more thoroughly.

I have actually made such an engine myself, and my approach was this:

1. Define a deterministic density function like this: `float densityFunction(vec3 &point);` that returns the density at the given point in space. It should be fairly fast. There exist many such functions that you can use out there, and they can often be combined for interesting results. TIP: Make sure they are continuous, that means that they don’t have any abrupt changes in the density. The "deterministic" and "fast" parts ensure that you can calculate this a lot on the fly, which is the key here.
2. Generate an isosurface based on this density function based on some triangulation algorithm such as marching cubes. You should be able to pass your density function as input, and also you need to be able to specify the corners of a bounding box, and a resolution which basically states how many levels of subdivision you want to trangulate per axis. `void generateIsoSurfaces( func &densityFunction, std::vector<float> &vertices, std::vector<int> &indices, vec3 &low, vec3 &high, int resolution);`
3. Keep track of your "camera" during rendering, and divide the world into cubic chunks of a set size that makes sense. For each visible cube, pass its bounding box and resolution to the triangulation function. The resulting vertices/indices can then be rendered with your favourite graphics subsystem such as OpenGL (or some engine on top of that).
4. To avoid regenerating everything over and over which will be expensive, make sure to keep each chunk of vertices in memory in a pool. Whenever a chunk is outside the view for a predetermined amount of time (or memory gets low) you free the data. If you get really fancy like I did, you can persist the result on disk. Just make sure reading/writing to disk is faster than regenerating it first.

This way to do things is rather elegant, and has many upsides:

* The density functions can be made as interesting and complex as you like and the engine will cope with them like any other density function.
* The rendering is fast because you are in effect just making polygon soups in a native format for the graphics subsystem
* Tweaking performance is really easy. Just change the resolution, bounding box size, chunk pool size etc to balance rendering between CPU and GPU. In my system I also made an adaptive LOD system so that when the chunks went far away from the camera, a new "less complex" version of the chunk was generated. I operated with resolutions in powers of two so that the poly-count will quadruple between levels. This might generate artifacts such as popping and mismatches at the boundaries between chunks of different levels of detail. In my application this was not important.
* The density function can be used by other parts of the game, such as physics, and it can be much simpler to use than having to work with the polygons. You can simply use newtons method to probe for where a vector hits the "surface" of the density function, and calculate the normal on that surface by simply doing this 3 times in close proximity.
* You can use the density function for procedurally generating shader or textures for the surface.
* Using this landscape engine for multiplayer games is feasible even when you want to use lock-step or similar algorithm for synchronizing game state since it can be made to be portably deterministic (two computers will get the exact same result when calculating the same density function).
* Generation of cubes is very scalable so you can easily leverage multiple cores in a modern computer. I did this by keeping around one thread per core that I feed with work.

There you go. Hope this was helpful!

# Answer
> 0 votes
Well you always have voxel based terrains (look into Marching Cube and Marching Tetrahedron methods). This allows you to put data on the range of only a single byte into each voxel then the algorithm will reconstruct itself. Going from data to mesh is very, very easy once you understand the algorithm. Going from mesh to voxels is a bit more difficult but possible. To do overhangs you need octrees or some other 3d data type ... you just do.

Also if you are doing stuff in patches you need to make an algorithm for patching your terrains together if you want to operate on them independently.

So something like

```
class Patch
{
  //If Z is equal to 1 or 0 you evaluate it like a piece of a quadtree
  //else evaluate it as a octree
  private:
  int dimX, dimY, dimZ;
  float scale; //Scale of each unit of the dataset so we can map
               //to real world coordinates.
  int sizeXY; //getting Z slice is dimZ*sizeXY;
  byte* values; //Assuming you use marching cube algorithm
  public:
  //Getters / Setters
};

//Convient thing about marching cube is it guarantees
//alignment of your patches if aligned patches have same resolution!
//Warning: Your terrain will follow the same
//general flow but it probably won't be the exact same.
class MarchingCubeConverter
{
   //Map of byte value to vertex coords. You can get this
   //From white-papers
  public:
       //Converts a given mesh specified by some coordinates to a voxel
       //format with a given resolution and scale.
       static void BuildPatch(Mesh* mesh,vec3 limits,dim3 resolution);
       //Converts voxel data to a 3d mesh
       static void BuildMesh(Patch* patch,Mesh* mesh);
};

```

Other option is if you don't want to do marching cube is to create your own quadtree structure that can be an octree if the data needs the 3rd dimension. Look at the patch class above and just when moving across the structure test for the Z dim to decide what you do with it. If you don't do marching cube though you would be saving overhands and stuff into a single unit of your quadtree. You only need that 3rd dimension if you plan on splitting the mesh along that 3rd dimension.

Psuedo-code for patching your terrain assuming you only care about 2 dimensional break-up. Should be straightforward to implement to the third dimensions.

```
void PatchTerrainMesh(QuadTreeNode<Patch>* node,Mesh* mesh,
                      int VertexPatchLimit)
{
    //Test if the x-y dimensions are within your xy extents
    //return the number of vertices that are within that limit.
    int Vertices = FindContainedVertices(mesh,(*node)->extents);
    if(Vertices > VertexPatchLimit)
    {
      node->subdivide(); //We now have 4 patches with appropriately divided extents

      PatchTerrainMesh((*node)[0],mesh,VertexPatchLimit);
      PatchTerrainMesh((*node)[1],mesh,VertexPatchLimit);
      PatchTerrainMesh((*node)[2],mesh,VertexPatchLimit);
      PatchTerrainMesh((*node)[3],mesh,VertexPatchLimit);
    }
    else
    {
       ExtractPatchFromMesh(node,mesh);
    }
}

void ExtractPatchFromMesh(QuadTreeNode<Patch>* node,Mesh* mesh)
{
   //This is the hard part but i'll give some psuedo code to help.
  //Need to actually get the vertices you need
  vector<int> containingVertices = BuildContainingIndexList(mesh,node->extents);

  Line boundaries[4];

  ConvertExtentsToBoundaryLines(&boundaries,node->extents);

  for(int i = 0;i < containingVertices.size();++i)
  {
        for(int j = 0;j < mesh->indices.size();++j)
        {
            if(containingVertices[i] == mesh->indices[j])
            {
              int start = j - j % 3; //Need the start of the triangle
              Triangle tri = Triangle(mesh->vertices[start]
                                     ,mesh->vertices[start + 1]
                                     ,mesh->vertices[start + 2]);

              int intersection = TriangleBoundaryIntersection(&tri,boundaries))
              switch(intersection + 1)
              {
                 case 0:
                      //Add tri to list, no collision
                      break;
                 case 1:
                   //need to subdivide the triangle based on
                   //line [0]
                   break;
                 case 2:
                    //need to subdivide the triangle based on
                     //line [1]
                   break;
                   //etc....
              }

            }
        }
  }
}

```

---
Tags: terrain, data-structure, vertex, level-of-detail, quadtree
---


# Question
Title: How do I add a method to a class without editing the source file?
I am trying to add a method to a Minecraft source file, but I have to figure out how to do it without actually editing the source files, as it would be illegal to redistribute Minecraft's source files with the mod I am creating.

I need to add the method `setInPortalZub()` to the `EntityPlayer` class located in `net.minecraft.entity.player`. I am using the MCP/Minecaft Forge API. I have tried creating an `EntityPlayer` instance, but I'm not exactly sure how to make this work.

# Answer
Only way to change a class without extending it (or without access to the source) is by using reflection. For java there is the rather comprehensive Java Reflection API that is made for this task. It might be a bit daunting at first.

Anyway the operation you are looking for is called injection. Here is an example of injecting a method into the class at runtime.
> 1 votes

# Answer
Actually, if you don't need to change any of the minecraft core functionality, I would recommend using a mod API such as Minecraft Forge. It allows you to listen to player events and add blocks/entities. However, if you do need to edit core minecraft functionality, use the Mincraft Coder Pack, or MCP, it allows you to decompile minecraft, as well as recompile and obfusicate the code, and it will give you the compiled files that were modified, if you do that, then you can just, give them those files to put in the minecraft.jar
> 0 votes

# Answer
Extend the class, then make your own method on the extension

```
MyClass extends TargetClass
{
  void myMethod();
}

```
> 0 votes

---
Tags: minecraft-modding, modding, code-reflection
---


# Question
Title: Creating a black light (ultraviolet) shader?
I am interested in the algorithm for color picking that would ideally allow to choose what color range will be highlighted and what color range will be faded.

I can sort-of understand how to make it look like black light effect, but I wonder if there is actual research out there on how to make it properly. What is the technique for rendering a black light effect?

Another question is highlights: How do you handle highlights? Do you ignore them completely or link their power to the luminess color of the surface?

# Answer
> 2 votes
To answer your 2 somewhat unrelated questions:

**#1**

To pick which color range to fade out in a fragment shader I would first calculate the actual color of that fragment in the usual way. Then I would convert that to HSL colorspace. Then I would compare the H part (hue) to a constant and if it was too far away from that constant i would set the color of the fragment to black. You could also fade towards black based on the distance between the color and the constant for a less abrupt effect.

**#2**

When you go to the club dance floor to bust a move you might not think about the fact that UV light is invisible to us. The only reason we see it is because of an effect called fluorescence, which roughly means that "some materials, when they receive rays of UV light convert that light to another (visible) frequency.

Thus, to render UV light you will probably need an extra color component in your UV active textures and light sources. This is because our eyes preceive colors by separating it (roughly) into the amount of red, green and blue that is in the light, and there is no provision for unseen light in traditional graphics engines. I would investigate if using the alpha channel for this would be feasible in your case (of course this means that it cannot be used for transparency).

I would then paint a "UV mask" and save it as the alpha channel in my texture. Lets assume you have a wood texture for the walls of a basement and then in the alpha channel you make a "REDRUM" in bold letters. Next you create two light sources to your fragment shader, one with UV=0.0 and one with UV=1.0 (UV being your custom light parameter).

To calculate the amount of blue light contributed to the visible light you would do fragment.b+=fragment.a\*light.uv; //.a is uv, remember?

If you want different colors for the fluorecence, you would need more than one color channel added.

---
Tags: hlsl, lighting, graphic-effects
---


# Question
Title: Dynamic thruster balancing of space ship
The space ships in my game a meant to be player-built with an arbitrary amount of thrusters attached anywhere with any rotation. I currently have some dirty code to rotate the ship to a given angle (accelerating and decelerating).

Here's an example of a symmetrical ship facing where the red line points, being told to rotate left.

However, as you would imagine, depending on where the player has put the thrusters, sometimes undesired linear forces are affecting the ship. In this case, the ship starts moving forward.

I'm elaborating on whether it's possible to find the maximum thrust a thruster can apply to cause no linear velocity. (In the above case that would be none since there's nothing to counteract the forces from the rear thrusters, and the front ones kill eachother).

What I've come up with so far is a formula to determinate the "turn efficiency" e.g. how much rotation is caused in relation to linear movement.

a - position vector to thruster a b - position vector to thruster b v1 - force from thruster a v2 - force from thruster b

efficiencyDelta = a.cross(v1) / |v1| - ( a.cross(v1) + b.cross(v2) ) / |v1 + v2|

, basically "a.cross(v1 * t) / |v1|" is supposed to be the turn efficiency. And then we subtract it by the turn efficiency of the thrusters combined, to see if firing the new thruster is worth it.

Problem arises when I realize that thrusters aren't surposed to be on/off, but can vary their thrust from 0 to 1. And how to go about when the player wants the ship to go forward. Ofcourse, there would need to be a balance of how much to rotate/move.

I'm no rocket scientist so I'm hoping there's someone who can tell me if it's even possible to calculate the throttle of each thruster this way and give me a push in the right direction.

Thank you for taking the time! / Kim

# Answer
I will assume that you have physically correct motion for your ship, as otherwise this analysis will not hold. You need something stronger than efficiency to solve this problem properly.

Each thruster will produce two effects on the motion of the ship: linear and angular. These can be considered independently. If the thruster produces a force `f` in a direction `dir`, and is offset from the center of mass by a vector `r` (not geometric center or the center of the sprite!), then the effect on the linear component is:

```
t = f * dir // f is a scalar, dir is unit length

```

The effect on angular velocity is given by the torque:

```
tau = f * <dir.x, dir.y, 0> CROSS <r.x, r.y, 0> // cross product

```

`t` is an force vector (i.e. the linear thrust). `tau` is a signed scalar which, when divided by the mass moment of inertia, will give the angular acceleration. It is important that `dir` and `r` are both in the same coordinate space, i.e. both in local coordinates or both in world coordinates.

The overall linear acceleration of the ship is given by the sum of the `t`'s for each thruster divided by the ship's mass. Similarly, the angular acceleration is just the sum of the torques divided by the mass moment of inertia (which is another scalar). **The ship will not turn if the total torque is zero. Similarly, it will not move if the total thrust is zero.** Recall torque is a scalar but thrust (the sum of the `t`'s) is a 2D vector.

The point of this exposition is that now we can write our problem as a Linear Program. Say first we want our ship to *turn* without *moving*. We have a variable for each thruster, $x\_1, x\_2, ...$, which is the amount of thrust that thruster will provide. One set of constraints is:

```
0 <= x_i < fmax_i  //for each i

```

where `fmax` is the maximum force for that thruster (this lets us have stronger or weaker ones). Next, we say that both equalities:

```
0 = Sum_i  x_i * dir_i.x
0 = Sum_i  x_i * dir_i.y

```

This encodes the constraint that we will not apply a linear acceleration, by saying the total thrust is zero (thrust is a vector, so we just say each part is zero).

Now we want our ship to turn. Presumably we want to do so as quickly as possible, so we want to:

```
max (Sum_i  x_i * c_i)
where c_i = <dir_i.x, dir_i.y, 0> CROSS <r_i.x, r_i.y, 0>

```

Solving for the `x_i`'s while satisfying the inequalities and equalities above, while maximizing the summation above, will give us the desired thrust. Most programming languages have a LP library available for them. Just put the above problem into it and it will produce your answer.

A similar problem will let us move without turning. Say we re-write our problem in a coordinate system in which we want to move in the positive x direction. Then the constraints are:

```
0 <= x_i < fmax_i  //for each i
max Sum_i  x_i * dir_i.x
0 = Sum_i  x_i * dir_i.y
0 = (Sum_i  x_i * c_i)
where c_i = <dir_i.x, dir_i.y, 0> CROSS <r_i.x, r_i.y, 0> // as before

```

With the constraint that the thrusters can only produce thrust in a single direction, there are going to be limits to the kind of rotations and linear velocities that you will be able to achieve. This will manifest as the solution being `0 = x_1 = x_2 = ... = x_n`, which means you won't ever get anywhere. To mitigate this, I suggest adding a pair of small, weak (say 5%, or 10%) thrusters for each player placed thruster at 45-degrees on either side. This will give the solution more flexibility, because these can be used to counteract weak secondary effects of the main thrusters.

Finally, for up through maybe 100 thrusters, the solution to the LP is fast enough to be done per frame. However, because the solution does not depend on location or the current state, you can precompute the solution for each reasonable controller input combination whenever the shape changes (this includes adding non-thrusters which change the moment of inertia or the mass of the ship, because then the thrusters are in a different location relative to the center of mass!). This is 24 possibilities (i.e. 8 directions times {left spin, no rotation, right spin}).
> 8 votes

# Answer
My first thought was a purely empirical solution, that is simulate the rig in a sandbox environment for varying degrees of thrust to work out how it behaves. Instead of balancing a lot of complex math in the search for a deterministic solution you can reach it numerically for example using newtons's method. Example:

Range for thrust is 0 to 1000 where 1000 is ALOT.

**Step #1**

Simulate with trust (0+1000)/2=500. Result: too much trust

**Step #2**

Range is now 0 to 500 Simulate with trust (0+500)/2=250. Result: too much trust

**Step #3**

Range is now 0 to 250 Simulate with trust (0+250)/2=125 Result: too little trust

**Step #4**

Range is now 125 to 250 Simulate with trust (125+250)/2=187.5 Result too much trust

**Step #5** Range is now 125 to 187.5 Simulate with trust (125+187.5)/2=156.25 Result is too little trust

**Step #6** Range is now 156.25 to 187.5 Range is below threshold of 35 which means that it is a good enough estimate

Final result= (187.5+156.25)/2 = 171.875
> 1 votes

---
Tags: 2d, ai, vector, balance, steering-behaviors
---


# Question
Title: How can I procedurally generate the right difficulty of enemy waves?
I'm programming a space-shooter mobile game with a sandbox gameplay style similar to *Defender*'s. The player faces infinite waves of enemies moving towards his ship. The game has many upgrades the player can buy to increase his ship's strength.

It is important that the difficulty of each level matches the player's skill and strength. This includes setting the right number of enemy waves per level and the number and toughness of the enemies in them. This must be done procedurally, since the game has no predefined set of levels laid out by a designer.

I'm interested in straightforward solutions with more or less the desired effect, simple enough to quickly implement and test.

How should I approach this?

# Answer
## The balance

I don't think there are **shortcuts to balancing the game**, it takes time and **experimentation** to find the best settings. You can increase the level of difficulty differently depending on how good the player is. The game will correct the difficulty to **match the player skill**. For example, the more lives he has the faster it gets harder. But I don't really think it is really a good idea, this kind of *"mario kart"* thing can be very **frustrating**. Even more in single player game.

## Automate level creation

I can think of two differents way to acheive this. In both you keep a variable that correspond to **the level of difficulty**. You **increase** it as time passes. You can then create monsters depending on this variable, the number of them and their strengh. I will call this variable `diff` for the rest of the answer.

**1) Random monster, random position** (easier)

Each monster has a **time before spawning**, which is influenced by `diff`. It can be randomized to make it better looking. The position of the monster can just be randrom on the Y axis outside the view. For example, if the time is in ms.

```
fullTimeBeforeSpawn_monsterA = 200+1000/diff + random_between(-100,100);

```

When `diff` equals 1 a monster A spawns every 1.2 second and when it is equal to 1000 a monster A spawns every 0.2 second.

They can also have a **window of diff where they can be created**, for example monster C will not be created if spawn is inferior to 500. That will make the harder monsters arrive has the time passes.

**2) Paterns increasing in difficulty** (harder)

Another way could be to make patterns. You then **randomly choose between the patterns**. And just like the monsters, you can make them pickable for certain value of diff.

For example you can decide to have a pattern like on the following image. The red lines spawns a kind of monster and the blue line spawns another kind (They are still created outside the view).

The number of monster will depend on `diff`. Their position will be calculated to be at **regular interval** on the lines.

```
numberOfEnnemy_blueLine = 3+diff/10 // will never be 0
numberOfEnnemy_redLine = diff*diff/1000 // will increase faster than the blue
                                         // there will be more blue than red at the
                                         // beginning and more red than blue at the end

```

The dots represent where the enemies are created.

**3) Why not both ?**

In my opinion it looks better when these two options are **used together**. It gives the feeling that the main, strong and slow army is marching toward you while there are smaller and faster ennemies that need to be taken care of.

## In fine

I know you were looking for an easy and fast solution, but in case somebody else is interested I developed my answer a bit further. There are a lot of ways to automate the creation of ennemies. **Your system can balance itself** if the difficulty is increased differently if the player is *good* or *not* but there will always be settings to choose. However, the balance doesn't have to be perfect the player can adapt.
> 7 votes

# Answer
The problem with adaptive difficulty is that games live from problems the player "overcomes". If you analyze the strength of the player then that is very linear and predictable. Either it is too easy all the time or too hard.

I would suggest the opposite: Instead of changing the wave difficulty depending on the player strength let the player adapt to the difficulties ahead. Generate one difficulty progression at the start of the game and let the player know it in advance. If in 2 waves enemies will come that are resistant against arrow towers, tell the player. He will than be able to change his strategy accordingly. Add a user select-able difficulty level and you should have a game that is enjoyable for both "hardcore" gamers and "casuals".

How you generate that wave progression is a different question and will require a lot of tweaking values until you get a satisfying result. I would suggest first putting down some "milestones" and then interpolating between them.

E.g.

* Wave 1 is a few of small mobs
* Wave 5 is a bunch of small mobs with a few special mobs mixed in
* Wave 7 is a huge amount of the special mobs
* Wave 10 is a random boss with both small mobs and special mobs mixed in.

After you have defined a progression like that by hand or procedurally you can calculate the waves in between, for example Wave 3 would be a few more small mobs and a single special mob.
> 4 votes

# Answer
PCG is hard to get right. There are always balance issues, because you always have a variety of gamer types (casual, hardcore, etc.) to balance between.

Since other answers are deep and technical, I'm going to provide a simple answer, inspired by the game "Warning Forever": **keep track of what types of enemies kill your player and spawn more of that.** Also keep track of what types get slaughtered by the player, and spawn less of that.

For example, imagine you have three types of monsters (`A`, `B`, and `C`). In the first wave, you spawn ten of each. At the beginning of the next wave, you notice that:

* Monster `A` had the longest average lifetime (13 seconds)
* Monster `B` caused the most player deaths (2)
* Monster `C` is not significant statistically

Based on this, next wave, you might change the distribution to 40% `A`, 35% `B`, and 25% `C`.

This provides a procedurally-generated, but highly customized form of gameplay: players will see something different depending on their skill, and they can change their strategy from game to game. It could quickly become frustrating though, if they always have the same gameplay style.
> 4 votes

# Answer
You can always implement a "ratings system" for the player.

PlayerRating is calculated by the following

* Ship Upgrades
* Kills
* Deaths
* Score
* Shots fire / hit

You have a max rating, say 100, that corresponds with the hardest enemies.

You start the game at 0.

Ship upgrade/power ups - If you gain "ultra blaster" it adds on 10 to your score. If you lose that powerup it subtracts 10. Kills / Misses (If you're in a side scroller etc) can add up to 10. Deaths - the more deaths divided by a percentage can LOWER your score...you aren't as good. High score + 10...if you are scoreing high, you are a better. Shots that actually hit / shots that miss. If you aim better you are better? (subjective) There are many variables you can put in your game to help calculate. So this number floats around and you can can generate your waves of enemies off this score.

If you have 10 different enemy ships:

PlayerRating \< 11 enemy tier 0
PlayerRating \< 21 enemy tier 1
PlayerRating = max Super Boss.
> 1 votes

---
Tags: procedural-generation, tower-defense, difficulty
---


# Question
Title: What are the security implications of this method of tracking countdowns?
Consider a multiplayer (client/server) game where you initiate the construction of some building. Let's assume construction will complete after 60 minutes.

My plan for dealing with this information is as follows, but I'm not sure if it is secure:

* Client initiates construction of building (60 mins)
* Server accepts request (resource requirements are met)
* Server stores the building task for that player and a completion time-stamp (now + 60 mins)
* Client begins a countdown (60 mins)
* If client re-connects, the completion time-stamp is retrieved from the server and the remaining time is calculated by the client
* When the client counter hits 0, it asks the server for an update
* While retrieving the data to send for an update, the server notices that the time-stamp has expired and makes the necessary updates
* Server response includes newly constructed building

I thinkit is secure since the completion time and resource calculations are all on the server side; however, is there a security problem that I haven't foreseen?

# Answer
The security implication you are worried about is a 10 year old changing the clock on their device to cheat the system. My daughter when she was 5 learned how to change the time on her iPod to get a new batch of coins in Coin Dozer. So it is a valid concern. But you have to count the cost. My goal is to reduce cheating by making it harder. To me it's not worth a lot of extra server processing to try to make a 100% system. And that's impossible anyway.

As Lex said, timers isn't the way to go. If you have 1000 users each building 5 things you're going to be running 5000 timers on the server? NO. What if you have 100k users. Use MATH! This is how I would do it:

1. Client occasionally gets game economics table from the server which includes time to complete building of each object type. This way you can change the economics after the game is released if you determine that an adjustment is needed or to stimulate sales.
2. Client also gets the time from the server on boot or entering foreground if it can and stores the offset between server time and client time. From then on server time can be estimated using client time.

Also if the device/client is offline the game still should be playable. Don't screw the 10 year old just because you're worried about cheating. Update the offset regularly and when you can, but if you can't use the last stored one. And look for cheaters by seeing if the time goes backwards or if the offset changes a lot. You can always put in code to require a server check only if it determines that cheating was attempted.
3. User initiates construction of a thing that takes D time according to the table.
4. If your device doesn't allow time changing without exiting and re-entering the app, you don't need to check the server time per new construction. (The iPhone can't without jailbreak) Just use the offset to estimate the server time (S).
5. Store the target time (T) when construction will be completed - client side. Checksum or hash or something to protect hacking that time if you want.
6. You can then calculate % complete using your estimated server time, the duration to build from the table, and the stored target completion time.

% complete = D-(T-S) / D. If this is more than 1.0 construction is complete.
7. Then if you want to store all this activity on the server, queue up messages to tell the server after the fact.
8. Alternatively you can check the server time repeatedly instead of estimating it, but it's going to bog the server down and cause lag on the game and then people will stop playing.

Lessons I've learned:

Do as much processing on the device or console as possible. Cause you only have 1 server and you might have 10k or 1m clients. Don't design so that your server can only handle the processing if you're game isn't successful. "If we're successful we'll buy more servers" isn't a winning idea.

Security to prevent cheating in a game is important, but reasonable security is enough. If your game is so popular that 1000's of people are cheating it - you'll be making money.

I use weird proprietary security algorithms. Hackers are better at cheating standard methods than something weird you just thought up.
> 3 votes

# Answer
Badweasel correctly pointed out that this solution would require excessive resources for little effect, but you have asked for what security issues remain on your solution.

Let's look at the typical avenues for cheating, more or less by order of difficulty:

* Change a user-editable value like the system clock. OK, This is what your algorithm is intended to protect against.
* Directly edit the game's saved file/data files. Works if the player is just changing the time-to-completion, but not if he sets the building to be already complete.
* Direct memory access, through a trainer or similar program. Easy on Windows, harder on Unix/OSX. No effect.
* Spoof entry/exit packets; change data packets as they leave/enter your network. Protects vs. outcoming, doesn't protect vs. incoming.
* Spoof client; fake client program sends data to your server. May make things worse, as it opens your system to DDoS-like attacks.
* Spoof server; redirects your server's IP to a fake server that sends custom packets to your application. No effect.

I've probably missed a few common cheat methods, but you can see how you've barely dented the problem.
> 1 votes

---
Tags: client-server, security
---


# Question
Title: Multiple colored textures vs Color Overlay
Let's say we're using DirectX 9/10/11. In our game we have a character wearing armor.

The armor has 50 different color variations. So, if armor is red, the first method would load the red texture from file. The second method would display the 1 base texture, with a red overlay.

Code wise the overlay armor would just contain an extra flag that would specify color.

Is it faster / more efficient to load different textures in? Or, is it faster / more efficient to color the texture on the fly?

I'm not aware if there is some huge overhead for dropping a tint over a texture...

# Answer
Technically, using overlays would require **less memory**, and loading all the different textures would require **less computing** every frame. Knowing which one is more efficient can be difficult because it depends on the circumstance, on what you *prefer*.

However, **textures are really big and overlays may use hardware acceleration which is very fast**. So I would recommend the use of **overlay**.

I didn't manage to find the info about DirectX 11. I can't find the documentation. I found that Direct 3D uses hardware to perform the overlay operations. If someone has the info please edit my answer.
> 0 votes

# Answer
Since i cant add a comment ( i dont have 50 reputation) i post this: if i have understand the question and you have to change all the color of the armor you can simple change pixel color in pixel shader passing a value in a costant buffer (es pixel.color.r\*=1.5, make sure you aren't using a float render target view). if you change just a part of your texture (ex the cloack of the armor) render first the armor and then a white overlay(1.0f,1.0f,1.0f,1.0f) and multiply it by a color passed with a constant buffer. I think it isn't a good idea load 50 textures for the same oject.
> 0 votes

---
Tags: textures, directx11
---


# Question
Title: Include Box2D libraries to a cocos2d project (iOS)
I have a problem including box2D to my cocos2d project. I've tried different ways to do it with no success. This is what I've done:

* I downloaded Box2D (Box2D\_v2.2.1) to my project directory.
* Dragged the Box2D directory (which includes -\> /Box2D.h, /Collision, /Common, /Dynamics, /Rope) to my Xcode project (from Finder to Xcode)
* Then I added #include "Box2D.h" to my .h file and got many errors... Here is where I started my research :P
* I went to Project Settings and edited the attribute **Header Search Paths** (contained in the **Search Paths** section) specifying the path of Box2D. At this point, I builded the project and I got *less errors*.
* After that, I renamed my **.m file** to **.mm** (I think this is because Box2D is written in C++ and with this, the compiler can treat it as it is). Still got errors.
* Then I tried changing the attribute **Always Search User Paths** (contained in Project Settings -\> Search Paths) from **YES** to **NO**. Still got errors.
* As my last option I tried changing the attribute **Compile Sources As** (contained in Project Settings -\> LLVM GCC 4.2 - Language) from **According to File Type** to **Objective-C++**.

By now I'm frustrated xD. I have 203 errors and most of them are in the .h files contained in the Box2d engine.

**b2Timer.h** \- Expected '=', ',', ';', 'asm' or '**attribute**' before 'b2Timer'

**b2Distance.h** \- Expected specifier-qualifier-list before 'b2DistanceProxy'

**b2Math.h** \- Cfloat: No such file or directory

And so on...

Thanks!!!

# Answer
You need to use the Cocos2D binding provided, never the Box2DLibrary as-is. If you have already starter your project without it the best thing I can recommend is either start a new template with Box2D included this time and import all the code (less painful than expected) or hardlinking "box2d.h" already included in the cocos2d folder "cocos2d-iphone\external\Box2d"
> 1 votes

# Answer
If you followed the procexdure in here: http://www.cocos2d-iphone.org/wiki/doku.php/prog\_guide:lesson\_1.\_install\_test

and installed the cocos2d, it would have added cocos2d-box2d and cocos2d-chipmunk templates that comes in new project window of xcode.

By creating projects this way, all the libraries are integrated and setup by default.
> 0 votes

# Answer
If all its wrong, you may create a new project directly from box2D, and migrate everything. It's the last thing I can think of. You have made everything already so this is a last resort. It might work.
> 0 votes

# Answer
You need brew to install cmack, then use it to install Box2D.
> -2 votes

---
Tags: box2d, cocos2d-iphone, ios, cocos2d
---


title: Background Sprite Setting

text:
# Question
Title: Background Sprite Setting
For my 2d game, I want to set background image. So that I am using multiple background images for that purpose.

But it can't set correctly on screen that illustrated in following image.

Also for setting background correctly, I am calculating camera orthographic size based current resolution and loading that sprite dynamically.

My camera inspector setting illustrated in following image.

My basic target is to display my background image in full screen without any bar. For example, If I have resolution of 600x1024 resolution and I am loading same resolution image then it should be display in full screen.

But you see that I can't able to get this result. So please some one help me to come out of this. If you want any more detail then I will provide at any time.

# Answer
> 1 votes
the best way to proceed is to use the gameobject Quad.

Assign the texture to the Quad you want to use as the background and scale it just enough to cover your viewport. This way you wont have to adjust according to the resolution and Unity will scale accordingly according to the screen res.

One more advantage is that Quad is basically a (kind of )2d Object in a 3d space with ability to move it in the game screen so it will be easy for you to position it accordingly. makes your designing easier and simpler :)

---
Tags: 2d, unity, sprites, camera
---


# Question
Title: Spaceship acceleration for following waypoints
I'm creating a turn based space ship strategy game with simultaneous turn resolution similar to Steam Birds. After all the orders are given, the ships run through a real time simulation where they rotate, accelerate and shoot each other.

The physics work similar to the old asteroids game. At the beginning of each turn the ships can be given a constant acceleration, they will then rotate into position so that their engines will be pushing them in the acceleration direction, and they will maintain the acceleration for the rest of the turn. Each ship has a maximum acceleration value based on their engine strength and mass.

I'm having trouble calculating the proper accelerations for the AI ships to get them to go where they need to go.

I had a diagram here, but this video makes it much more clear what I'm trying to do. This is a player controlled ship moving through some asteroids in the same way I need an AI ship to move.

I've got a ship moving through some obstacles, there are waypoints defined that will guide the ship through the obstacles. There are a couple of things I'm trying to calculate:

* I need to calculate how much the ship has to slow down to make a fairly tight turn so that it doesn't run into obstacles
* I need to calculate the acceleration to get the ship to change directions at the waypoint, again making sure that the turn is fairly tight
* Between the waypoints I would like the ship to accelerate to as high a speed as it can and still have time to slow down to make the turn

Any help here would be greatly appreciated. Thanks.

# Answer
> 7 votes
I'm going to assume that the rotation of the engine is purely visual, and the acceleration during any thrust is in a constant direction. (If we're accelerating in a rotating direction, the math for planning the trajectory gets a LOT more complicated very quickly, so I'd recommend turning off the thruster when turning, and just accounting for that as a linear segment in the path)

Quadratic Bézier curves are isomorphic to a point moving with constant acceleration, so you can think of this problem as a matter of **planning a quadratic Bézier spline** under certain constraints.

At the beginning of each turn, two of your control points are fixed, and you're making a choice for the third point (unless the ship is allowed to coast without acceleration for a span, that is - then add another two variables for pre-thrust and post-thrust drift)

Point A is where the ship begins this turn.

Point B is where the ship would be halfway through the turn if it were not thrusting. If one turn is T simulation-seconds long, then this is A + (T/2)\*v1, where v1 is the velocity of the ship at the start of the turn.

Point D (not part of the curve) is where the ship would end the turn with zero acceleration. It acts as an anchor for our choice of point C...

Now we get to choose point C, where the ship will be at the end of the turn. We can select any point in a radius of (T\*T/2)\*max\_acceleration of D. This ensures our max acceleration constraint is respected. Our velocity coming out of this turn will be parallel to C-B (specifically, it will be (C-B)\*2/T).

From this, a few things follow:

1. If we want to come out of the turn with a velocity in a particular direction (say, we've passed one waypoint and want to steer toward the next one), we can draw a line with that direction through point B. The part of that line that overlaps the circle around D includes all our options that put us on the desired trajectory, with the one furthest from B being the fastest option.
2. The turn is fully-contained within the triangle ABC, so we can check that triangle for collisions and re-plan as necessary.
3. If the radius of the circle is r = max\_acceleration * (T\*T/2), then the maximum angular change we can effect in one turn is:

180° if (T/2)\*v1.magnitude \<= r

asin(r/((T/2)\*v1.magnitude)) = asin(T * max\_acceleration/v\_1) otherwise

So, if you need to pivot through an angle of theta in one turn, slow down to (2 * r)/(T * sin(theta)).

If you're still n turns away from this rotation, then you can safely travel up to n*max\_acceleration*T faster than this limit and still slow down in time. If you're going faster than that, start braking.

Note that you can apply this recursively to get the AI thinking one or more steps ahead - any choice for point C this turn dictates A, B, and D next turn. So you can choose C this turn in such a way that the circle around next turn's D includes next turn's goal, and reject choices of C that take you too far off course even with a full turn to correct it.

There are still a lot of judgement calls for you to make in designing your AI, but I hope this provides a useful framework for making those decisions in a way that's appropriate for your game.

---
Tags: physics, vector, steering-behaviors
---


# Question
Title: Unity - Part of the sprite is covered in shadow
I have a sprite with **Transparent/Cutout/Diffuse** shader. Recieving shadows is turned on in SpriteRenderer. The light is a pointlight and I am using **deffered** rendering path.

However when I am above or right of the object, it is covered in shadow. When I am below or left of the object everything seem to work as it should.If I place the light in the center of the sprite, only a part of the sprite is lit up, the other part is covered in shadow.

Maybe it is something with normals? I need to get rid of the self shading effect.

## Shader

```
Shader "Transparent/Cutout/Diffuse" {
Properties {
    _Color ("Main Color", Color) = (1,1,1,1)
    _MainTex ("Base (RGB) Trans (A)", 2D) = "white" {}
    _Cutoff ("Alpha cutoff", Range(0,1)) = 0.5
}

SubShader {
Tags {"Queue"="AlphaTest" "IgnoreProjector"="True" "RenderType"="TransparentCutout"}
LOD 200

CGPROGRAM
#pragma surface surf Lambert alphatest:_Cutoff

sampler2D _MainTex;
fixed4 _Color;

struct Input {
    float2 uv_MainTex;
};

void surf (Input IN, inout SurfaceOutput o) {
    fixed4 c = tex2D(_MainTex, IN.uv_MainTex) * _Color;
    o.Albedo = c.rgb;
    o.Alpha = c.a;
}
ENDCG
}

Fallback "Transparent/Cutout/VertexLit"
}

```

I found out what unity uses for lambert lightning. Since I use deffered rendering so unity should use function with \_PrePass prefix. But the implementation of the actual lighning is implemented somewhere else and is it used for all materials, that looks like dead end.

## Custom Lightning

```
inline fixed4 LightingSLambert (SurfaceOutput s, fixed3 lightDir, fixed atten)
{
fixed diff = max (0, dot (s.Normal, lightDir));

fixed4 c;
c.rgb = s.Albedo * _LightColor0.rgb * (diff * atten * 2);
c.a = s.Alpha;
return c;
}

inline fixed4 LightingSLambert_PrePass (SurfaceOutput s, half4 light)
{
fixed4 c;
c.rgb = s.Albedo * light.rgb;
c.a = s.Alpha;
return c;
}

inline half4 LightingSLambert_DirLightmap (SurfaceOutput s, fixed4 color, fixed4 scale, bool surfFuncWritesNormal)
{
UNITY_DIRBASIS
half3 scalePerBasisVector;
half3 lm = DirLightmapDiffuse (unity_DirBasis, color, scale, s.Normal, surfFuncWritesNormal, scalePerBasisVector);
return half4(lm, 0);
}

```

# Answer
Unity's SpriteRenderer does not use normals by default. From the SpriteRenderer Component page in docs.

http://docs.unity3d.com/Documentation/Components/class-SpriteRenderer.html

"*SpriteRenderer uses a mesh combined of position, color and UV to render. Normal vector is not included. If normals are required, you can generate them in a vertex shader. See 'Custom data computed per-vertex' in Surface Shader Examples.*"

What you want is possible but is not what the SpriteRenderer is intended for. This code below adds normals to the surface shader which removes the immediate shading error by supplying a normal vector manually.

While this should work for your use case, it may be better to not use a sprite at all and use an actual MeshRenderer/Filter with a quad or plane.

(The example normals below work for having the light behind the sprite, assuming Y-up and Z-positive away from the camera)

```
Shader "Custom/SpriteLightWithNormals" {
Properties {
    _Color ("Main Color", Color) = (1,1,1,1)
    _MainTex ("Base (RGB) Trans (A)", 2D) = "white" {}
    _Cutoff ("Alpha cutoff", Range(0,1)) = 0.5
}

SubShader {
Tags {"Queue"="AlphaTest" "IgnoreProjector"="True" "RenderType"="TransparentCutout"}
LOD 200

CGPROGRAM

#pragma surface surf Lambert vertex:vert alphatest:_Cutoff

sampler2D _MainTex;
fixed4 _Color;

struct Input
{
    float2 uv_MainTex;
    float3 nrmls;
};

void vert(inout appdata_full v, out Input o)
{
    v.normal = float3(0,0,-1);
    v.tangent = float4 (1,0,0,-1);
    UNITY_INITIALIZE_OUTPUT(Input,o);
    o.nrmls = v.normal;
}

void surf (Input IN, inout SurfaceOutput o)
{
    fixed4 c = tex2D(_MainTex, IN.uv_MainTex) * _Color;
    o.Albedo = c.rgb;
    o.Alpha = c.a;
    o.Normal = IN.nrmls;
}

    ENDCG
}FallBack "Diffuse"}

```

Edit: I've updated the shader to support shadows.

```
Shader "Custom/SpriteLightWithNormals"
{
Properties
{
    _Color ("Main Color", Color) = (1,1,1,1)
    _MainTex ("Base (RGB) Trans (A)", 2D) = "white" {}
    [MaterialToggle] PixelSnap ("Pixel snap", Float) = 0
    _Cutoff ("Alpha cutoff", Range(0,1)) = 0.5
}

SubShader
{
    Tags {"Queue"="AlphaTest" "IgnoreProjector"="True" "RenderType"="TransparentCutOut" "CanUseSpriteAtlas"="True"}
    LOD 200

    CGPROGRAM

    #pragma surface surf Lambert alpha vertex:vert  alphatest:_Cutoff fullforwardshadows
    #pragma multi_compile DUMMY PIXELSNAP_ON

    sampler2D _MainTex;
    fixed4 _Color;

    struct Input
    {
        float2 uv_MainTex;
        float3 nrmls;
    };

    void vert(inout appdata_full v, out Input o)
    {
        v.normal = float3(0,0,-1);
        v.tangent = float4 (0,0,0,0);
        UNITY_INITIALIZE_OUTPUT(Input,o);
        o.nrmls = v.normal;
    }

    void surf (Input IN, inout SurfaceOutput o)
    {
        fixed4 c = tex2D(_MainTex, IN.uv_MainTex) * _Color;
        o.Albedo = c.rgb;
        o.Alpha = c.a;
        o.Normal = IN.nrmls;
    }

    ENDCG
}   }

```
> 1 votes

# Answer
It seems like a fair assessment that it has got something to with normals, but it is hard to know exactly given only the posted code. It looks like the sprite's normal is pointing down left, rather than towards the screen.

Given that the sprites seem to be located in the same plane as the light fixing this to be physically correct would actually make the sprites black all of the time, so I guess you better make some non-physical light. It should be possible to write a lighting shader that simply ignore normals, I think that would work well for your sprites.

I haven't got the full grasp of your code, but the following line has what looks like a calculation of lighting with regards to surface normals:

```
fixed diff = max (0, dot (s.Normal, lightDir));

```

If you simply set diff to 1 for sprites I suppose that it will work.
> 0 votes

---
Tags: unity, shaders, sprites, shadows, deferred-rendering
---


# Question
Title: How do I associate my objects to my meshes and other resources?
I am creating a simple 3D engine and I've run into a problem.

I have an array of objects

```
[Camera, Player, Player, MonsterA, MonsterB, MonsterA]

```

and a number of mesh files that I need to associate with these game objects

```
camera.obj, male.obj, female.obj, etc.

```

I pass the state of the world (the array of objects) to my renderer, and I would like to render each object with its associated mesh.

My question is: how / where do I tie these game objects to their meshes?

Should I keep them together as game objects?

```
eg. [(Camera, camera.obj), (Player, male.obj), ...]

```

Or should I have some sort of associative structure within my renderer? Or somewhere else entirely? This question also applies to textures as well. Basically, how do I connect the game objects to their assets?

# Answer
There's many ways to solve this. One way is, yes, to keep the resources attached to the game objects. Each game object would store a handle to its material and its mesh(es).

Another approach is to keep a separate hierarchy/list of scene nodes. Each game object would just hold a reference to the scene node that represents the object visually. The scene node would then be a small object that has just the visual data.

There's then all kinds of ways to structure that data. An instance of a model has a position and other state but the actual resources can be shared by all instances of that model. So you might have your object or scene node contain per-instance state and then refer to a `ModelTemplate` sort of object which in turn refers to a material and meshes. That is, each goblin might have a position and an animation matrix list and a reference to the goblin model, and the goblin model has a reference to the goblin textures and the creature shader and the skeleton structure information.

In general, just do the simplest thing you can that works. Your players don't care how fancy your graphics architecture is. They only care if your game is fun and pretty and doesn't crash or leak memory.
> 2 votes

# Answer
you can group the objects by needed mesh so you can batch the draw commands without needing to swap out the mesh buffer for each object

this eliminates the need for objects to know about how they are drawn
> 0 votes

---
Tags: architecture, assets
---


# Question
Title: How to make the images appear in a specific location?
How can I draw a sprite in a specific location of the screen using native Android 2D graphics API?

The image should stay in the location specified.

# Answer
**Answer**

Based on the Android API Reference on Canvas.drawBitmap(), I came up with this:

```
   ...

   private Bitmap bmp=null;

   //Called once at startup
   @Override
   protected void onCreate(){
         //Load a bitmap from a resource (file in drawable folder in your project)
         bmp = BitmapFactory.decodeResource(getResources(), R.drawable.my_drawable);
   }

   //Called every time a redraw is required
   @Override
   protected void onDraw(Canvas canvas) {
         //Clear background to black
         canvas.drawColor(Color.BLACK);
         //Draw bitmap
         float x=0.0f; //Distance from the left edge of the canvas
         float y=0.0f; //Distance from the top edge of the canvas
         //Draw
         canvas.drawBitmap(bmp, x,y, null);
   }

   ...

```

For a better more comprehensive example, please look at this.
> -1 votes

---
Tags: 2d, android
---


# Question
Title: Deferred lighting and point light volumes
I'm doing deferred point light shadow mapping and I am drawing my point lights using light volumes. Normally I access the position/diffuse texture/normals using this in the fragment shaders:

```
vec2 texcoord = gl_FragCoord.xy / UnifPointLightPass.mScreenSize;

vec3 worldPos = texture(unifPositionTexture, texcoord).xyz;
vec3 normal   = texture(unifNormalTexture, texcoord).xyz;
vec3 diffuse  = texture(unifDiffuseTexture, texcoord).xyz;

```

When doing directional lights, I just draw a fullscreen-rectangle, but when doing point lights I use light volumes - drawing a 3d sphere from the cameras point of view to limit the amount of fragments processed.

Does light volumes change the way I get the texcoord?

# Answer
> 3 votes
`gl_FragCoord.xy` just gives you the pixel coordinates where this instance of the shader is running, so getting the texture coordinate for full-screen textures this way should work fine regardless of what kind of geometry you're rendering - a full-screen rectangle or 3D light volume geometry.

---
Tags: opengl
---


# Question
Title: Collision intermittently fails when multiple bullets on screen
I'm building a very simple Java game where a player rectangle fires bullet rectangles at enemy rectangles. When a single bullet is on screen, it always correctly collides with enemies. When multiple bullets are on screen, they often go right through the enemies without triggering a collision. The only way to get the collision to work is to run very far away from the enemy; if the bullet travels a very far distance before hitting the enemy, the collision will work with multiple bullets on screen.

I tried writing a method to calculate a new rectangle that extends the colliding sprites' previous location to its current location, and then checking these extended rectangles for collisions, but to no avail.

Below are the methods I'm using in the sprite parent class to create these extended rectangles and to check for intersection:

```
public boolean movingIntersects(GameEntity g) {
    return this.getMovingRectangle().intersects(g.getMovingRectangle());
}

public Rectangle getMovingRectangle() {
    Rectangle r = new Rectangle();
    r.x = Math.min(x, prevX);
    r.y = Math.min(y, prevY);
    r.width = Math.abs(x - prevX) + width;
    r.height = Math.abs(y - prevY) + height;
    //System.out.println(this + " " + r);
    return r;
}

```

This is the code I'm using in the `actionPerformed` method to handle moving and managing the sprites. Variable p is the player, keys holds the keys being pressed, tm holds the Timer that triggers the actionPerformed:

```
public void actionPerformed(ActionEvent e) {
// pause game if necessary
if (keys.contains(KeyEvent.VK_ESCAPE)) {
    paused = !paused;
    keys.remove(KeyEvent.VK_ESCAPE);
}
if (!paused) {
    // Setup player movement
    p.movement = 0;
    if (keys.contains(KeyEvent.VK_W)) {
    p.movement |= GameEntity.UP;
    }
    if (keys.contains(KeyEvent.VK_S)) {
    p.movement |= GameEntity.DOWN;
    }
    if (keys.contains(KeyEvent.VK_A)) {
    p.movement |= GameEntity.LEFT;
    }
    if (keys.contains(KeyEvent.VK_D)) {
    p.movement |= GameEntity.RIGHT;
    }
    // Setup bullets
    p.framesToNextFire = Math.max(0, --p.framesToNextFire);
    if (p.framesToNextFire == 0) {
    Bullet b = new Bullet(this, 0, 0, 0, p.bulletSpeed);
    b.x = p.x + (p.width / 2) - (b.width / 2);
        b.y = p.y + (p.height / 2) - (b.height / 2);
    if (keys.contains(KeyEvent.VK_UP)) {
        b.movement = GameEntity.UP;
        p.bullets.add(b);
        p.framesToNextFire = p.coolDown;
    } else if (keys.contains(KeyEvent.VK_DOWN)) {
        b.movement = GameEntity.DOWN;
        p.bullets.add(b);
        p.framesToNextFire = p.coolDown;
    } else if (keys.contains(KeyEvent.VK_LEFT)) {
        b.movement = GameEntity.LEFT;
        p.bullets.add(b);
        p.framesToNextFire = p.coolDown;
    } else if (keys.contains(KeyEvent.VK_RIGHT)) {
        b.movement = GameEntity.RIGHT;
        p.bullets.add(b);
        p.framesToNextFire = p.coolDown;
    }
    }

    // Move GameEntities
    if (enemies.size() > 0) {
    // move player
    p.move(GameEntity.CONSTRAIN);
    // move enemies
    for (Enemy en : enemies) {
        en.move(GameEntity.CONSTRAIN);
    }
    // move bullets
    Iterator<Bullet> itB = p.bullets.iterator();
    while (itB.hasNext()) {
        Bullet b = itB.next();
        //System.out.println(b.x + ":" + b.y);
        if (b.move(GameEntity.REMOVE)) {
        itB.remove();
        }
    }
    // Check for shot enemies
    itB = p.bullets.iterator();
    Iterator<Enemy> itE = enemies.iterator();
    while (itB.hasNext()) {
        Bullet b = itB.next();
        while (itE.hasNext()) {
        Enemy m = itE.next();
        if (b.movingIntersects(m)) {
            m.health -= b.health;
            itB.remove();
            if (m.health <= 0) {
            int points = (int) (m.intelligence * m.speed * 100);
            System.out.println(m.intelligence + " + " + m.speed + " = " + points);
            score += points;
            itE.remove();
            }
            break;
        }
        }
    }

    // Check for dead player
    itE = enemies.iterator();
    while (itE.hasNext()) {
        Enemy m = itE.next();
        if (m.intersects(p)) {
        // Player is dead
        tm.stop();
        // Show score
        message = "Game Over";
        paused = true;
        // Reset game
        level = 1;
        score = 0;
        startLevel();
        tm.start();
        break;
        }

    }
    // Draw the screen
    repaint();
    } else {
    tm.stop();
    p.bullets.clear();
    repaint();
    level++;
    startLevel();
    tm.start();
    }
}
}

```

# Answer
The reason this code fails when you have more than one bullet is that for each bullet, you go through each enemy to check for a collision. The piece of code that initializes itE (the enemy iterator) is outside the bullet loop, so what is actually happening is that you are checking all the enemies on the first bullet only. Each check after that the enemy iterator is already at the end of the list, so you are not checking anything. Move the line: Iterator itE = enemies.iterator(); down to inside the while loop, and that should fix your first problem.

There is a second problem you are not seeing yet, which is that you remove any enemy you collide against from the list with the line itE.remove(). This means that each enemy can only get hit once per frame, even if multiple bullets hit it. Remove the line itE.remove() from your code, it is not required and will cause you problems.
> 2 votes

---
Tags: java, collision-detection
---


# Question
Title: Using Canvas instead of Scaleform in UDK
I'm working with Unreal Script, and I need to use Canvas instead of Scaleform to create a HUD. I've extended the game type from UTGame, and used bUseClassicHUD in the Default Properties section, but the default Scaleform HUD continues to appear. I know for certain that I have everything configured properly to load and run the scripts, but this one line just doesn't seem to have any effect.

```
DefaultProperties{

// Disable the scaleform (flash) HUD in the UTGame
bUseClassicHUD = true

// Initial score value
nScore = 0

// Initial time value
m_gameTimer = 30.0

```

}

Is there something else I need to include? I've done a reinstall (I'm using the July 2013 build), but to no avail.

# Answer
> 1 votes
After moving the opening curly brace onto the next line, the code worked as intended. I'm not sure why it has to be on a separate line here in particular, but it solved the problem.

# Answer
> 0 votes
Are you sure it's the scaleform HUD that's appearing? I'd try logging out the `newHUDType` parameter you're getting in `ClientSetHUD()`. If bUseClassicHUD is true, it looks like you should be getting the UTHUD class (granted, I have an older drop of UDK, so things may have changed in more recent builds.

---
Tags: udk, scripting, hud
---


# Question
Title: Smooth camera movement between followed objects
I have 2d game where my camera follows the player. Simplified, it copies the player position as its own.

Now I have some other object in the game, that I want to camera to follow. This is easy enough by not setting the camera's position with the player's, but with the position of the other object.

The problem is that this camera movement is instant. I'd like to have a more smooth transition (e.g. panning over the level to the given object).

How can I achieve this?

# Answer
You need to interpolate between the camera's position and the target position. It looks like libgdx has a `Vector2.lerp()` linear interpolation method that you can use, however if you want something that has a smoother ease in/out you'll need to use another method, which it seems you can do using `Vector2.interpolate()`. Call one of these methods every frame and your camera's position will move smoothly to the target position instead of snapping.
> 3 votes

# Answer
Since you are using lib gdx, this sound like a perfect use of the wonderful Tween Engine!

http://www.aurelienribon.com/blog/projects/universal-tween-engine/
> 0 votes

---
Tags: libgdx, camera
---


# Question
Title: who turn a moving agent to the specific coordinate
i have a moving agent in gis map that is going to the special Coordinate . with assumption that maximum angel of rotation is predefined, i want the agent turn into specified coordinate (in moving) and then go to that location, what i do for this work please help me.

# Answer
> 1 votes
Imagine that you would make a vector from the moving agent straight to the target location. Instead of using this new vector as your agent's path, you can update you path slightly every iteration with your angle rotation you mentioned, so that it eventually starts going straight to the location.

Algoritm in steps:

1. Make a vector from agent to target location
2. Check which direction gives the smallest angle to rotate to face the target location
3. Check to see if this angle is below (for example) 10 degrees.

4a. If it is, simply set the path to the vector you made in step one (to avoid zig-zagging)

4b. If not, rotate your initial path-vector in this direction with your angle rotation speed.

Granted that your rotation speed is low enough, this will make the agent take a smoother path towards the target location.

Depending on what framework you are working in, a "slerp" or "lerp" function might already be implemented which is very useful!

http://answers.unity3d.com/questions/13869/how-do-i-get-smooth-rotation-to-a-point-in-space.html

---
Tags: game-design
---


# Question
Title: How can I create or extrude a mesh along a spline?
Let's say, for example, that I have a working spline. I want to use this spline to create a mesh, but I'm not quite sure how to go about it. For example, I want to create a road along this spline. I can interpolate through the curve and generate my segments and use that. If I were just making a single straight line I could take the normal of that vector and extrude the endpoints to get the vertices for a quad and do it that way, but how should I handle the curve part? I can't just use the endpoints of one quad as the start of another because they won't line up at different angles.

What would be the proper way to extrude a spline into a mesh? I'm tagging this as Unity since that's what I'm using, though the answer I assume will be engine-agnostic.

# Answer
> 10 votes
Your idea is correct, you just have to work more on it.

Here is an article I wrote last year: http://blog.meltinglogic.com/2013/12/how-to-generate-procedural-racetracks/ It uses exactly what you described, and as you can see, the result is very good.

Here is the code which explains how the mesh was generated from the spline:

```
for(float i = 0; i <= 1.0f;)
{
    Vector2 p = CatmullRom.calculatePoint(dataSet, i);
    Vector2 deriv = CatmullRom.calculateDerivative(dataSet, i);
    float len = deriv.Length();
    i += step / len;
    deriv.divide(len);
    deriv.scale(thickness);
    deriv.set(-deriv.y, deriv.x);
    Vector2 v1 = new Vector2();
    v1.set(p).add(deriv);
    vertices.add(v1);
    Vector2 v2 = new Vector2();
    v2.set(p).sub(deriv);
    vertices.add(v2);

    if(i > 1.0f) i = 1.0f;
}

```

The idea behind this algorithm is, traverse through the spline by segments of `step` size, for each point on the spline, calculate its derivative, normalize it to get the normal, rotate it by 90°, then add two points to the vertice list: `splinePoint + normal` and `splinePoint - normal`. You'll have a stripe of vertices following the spline, you can easily generate it's indices, If you have problems generating those indices, just throw a comment and I'll edit the answer.

Some further clarifications:

* Derivative is the same as tangent, in case your engine words it differently;
* Incrementing `step / derivativeLength` to the `time` parameter is the right thing to do. Since the size of the spline differ from point to point, you must use this to keep going at a constant speed;
* With that being said, `step` parameter should be defined in World Units, not Spline Percentage. (That is, if you set step to 5 and your units are pixels, then each segment will be put 5 pixels apart, and not each 5% of the spline);
* Yes, `thickness` is some constant that you should fiddle around to find a good value. If your world units are pixels, then your mesh will be `2 * thickness` thick;
* If your engine doesnt support derivatives, try porting these: LibGDX Catmull Rom or LibGDX Bezier
* In case you want details on the implementation of catmull derivatives, it seems that OP have already did the awesome job of asking on Math.SE, so go read that!

---
Tags: c#, unity, 3d-meshes, splines
---


# Question
Title: Pokemon Black White 2 - Ground Tiles Directory?
I opened up Pokemon Black 2 in Tinke (https://code.google.com/p/tinke/) and I'm looking for the directory that contains the ground tiles. Here's a picture showing what tiles I'm after (http://fc01.deviantart.net/fs70/f/2013/166/e/4/pokemon\_black\___white\_tileset\_by\_rossay-d3a75aj.png). I've looked for ages, but I can't find these basic tiles. Thanks :D

# Answer
Some notes from the comments:

* Using Nintendo's official art work (ripping it and using it) is definitely a **violation of copyright.** (Your response was you're only using it for yourself.)
* Questions about "help me rip ... from game ..." are probably off-topic for this site.

What I really recommend, like your link, is to use custom tiles which other people made which are similar to what you want.

The Google image search for `tiles similar to pokemon black white` looks quite fruitful.
> 1 votes

---
Tags: tiles, modding, tilesets
---


title: Drawing geometry to an SDL_Texture?

text:
# Question
Title: Drawing geometry to an SDL_Texture?
As a direct result of this question that I asked a few days ago, I want to draw potentially-complex geometry to a SDL\_Texture or, I suppose, an SDL\_Surface. Ultimately, I want the foreground of a 2D platformer on this texture so that I cant draw a specific portion to the screen, as explained in the above link. Most of the geometry will be simple rectangles, but I would also like to draw slopes and possibly circles. Diving into OpenGL seems like a viable option at this point, but if I could avoid it, that would be grand.

# Answer
`SDL_SetRenderTarget(SDL_Renderer *renderer,SDL_Texture *texture)`

After calling this, any drawing functions using this renderer will be drawn into the specified texture, instead of to the screen. (Passing `NULL` for the texture will make subsequent drawing functions draw to the screen again)

Note that the texture must have been created using the `SDL_TEXTUREACCESS_TARGET` flag.

More details are available in the on-line documentation.
> 4 votes

---
Tags: c++, sdl, platformer, level-design
---


# Question
Title: How do I generate mipmap .png and model .obj files for LibGDX?
I'm playing a bit with LibGDX (OpenGL ES 2.0 wrapper for Android).

I found some sample code which used prepared files to load models and mipmap textures for them, e.g., at https://github.com/libgdx/libgdx/blob/master/demos/invaders/gdx-invaders/src/com/badlogic/gdxinvaders/RendererGL20.java it reads .obj file for the model and RGB565 format .png file to apply a mipmapped texture to it.

What is the best / easiest way for me to create these files?

I understand .obj files are generated by a bunch of tools (I installed Blender, Wings3D and Kerkythea so far), but which ones will be the most user friendly for someone unfamiliar with 3D modelling?

But more importantly, how do I produce a .png file with the mipmapped texture? The .png I looked at ( https://github.com/libgdx/libgdx/blob/master/demos/invaders/gdx-invaders/data/ship.png ) seems to include different textures for each of the faces, probably created with some tool. I browsed through the menus for the 3 tools I have installed but didn't find an option to export such a .png file. What am I missing?

# Answer
I've used Blender \+ GIMP for creating textures. After making the final model, select it, jump into edit mode, then press `u` (or *Mesh-\> UV Unwrap*, on the lower menu bar) and select *Smart UV Project* and click *OK*. Then change the editor type to *UV/Image editor* (Blue arrow).

**If nothing is displayed, make sure all faces are selected.**

Now on the lower bar click *UVs -\> Export UV Layout*. \[GIMP magic happens there\]. When you want to test testures, `Alt`+`r` refreshes, go back to 3D view and select *textured display mode* (red arrow).

I've read that the `obj` format isn't the best one for libgdx and that `g3db` is better. To obtain such a file, first download fbx-conv. In Blender click *File -\> Export -\> Autodesk FBX*, and save it in the folder with fbx-conv. then open command line\terminal and run:

```
fbx-conv.exe -f "filename.fbx"

```

**Note that you must add to assets both the .png and .g3db** I used AssetManager to load the model.
> 1 votes

---
Tags: textures, opengl-es, libgdx
---


# Question
Title: Should I use more than one panel in a java game ?
I' m creating a game in java, and it has this schema:

I use the `main class` to launch my game and I create a frame to add a panel, that is defined into `GamePanel` class.

```
public class MainFrame {

    private static final MainFrame mainFrame = new MainFrame();
    private final JFrame frame;

    private MainFrame() {
    frame = new JFrame();
    frame.setUndecorated(true);
    frame.add(new GamePanel());
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
    }

    public static final MainFrame getMainFrameInstance() {
    return mainFrame;
    }

    public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
        try {
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
        } catch (Exception e) {
            e.printStackTrace();
        }
        MainFrame.getMainFrameInstance();
        }
    });
    }

```

and the `game panel` class

```
public class GamePanel extends JPanel implements Runnable, KeyListener, MouseListener,   MouseMotionListener {

    private static final long serialVersionUID = 1L;

    // thread and game loop
    private Thread thread;
    private boolean running;
    private int FPS = 60;
    private long targetTime = 1000 / FPS;
    private long start;
    private long elapsed;
    private long wait;

    // mouse events
    private long mousePressed;
    private long mouseReleased;
    private long mousePressTime;

    // mouse pressed force
    public static int seconds = 0;
    // image
    public static BufferedImage image;
    private boolean firstCall = true;

    // game manager
    private GameManager gameManager;
    // renderManager
    private RenderManager renderManager;

    public GamePanel() {
    setPreferredSize(new Dimension(GuiDimension.WIDTH.getValue(), GuiDimension.HEIGHT.getValue()));
    setFocusable(true);
    requestFocus();
    }

    public void addNotify() {
    super.addNotify();
    if (thread == null) {
        addKeyListener(this);
        addMouseListener(this);
        addMouseMotionListener(this);
        thread = new Thread(this);
        thread.start();
    }
    }

    // prevent to be done all method.
    private synchronized void init() {
    image = new BufferedImage(GuiDimension.WIDTH.getValue(), GuiDimension.HEIGHT.getValue(), BufferedImage.TYPE_INT_RGB);
    gameManager = new GameManager(States.LOADING.getValue());
    gameManager.loadCurrentState(States.LOADING.getValue());
    renderManager = new RenderManager(gameManager);
    MainFrame.getMainFrameInstance().setCursor(CursorStatus.CUSTOMCURSOR.getValue());
    running = true;

    }

    public void run() {
    init();
    // game loop
    while (running) {
        start = System.nanoTime();
        gameManager.update();
        KeyInput.getKeyInputInstance().update();
        MouseInput.getMouseInputInstance().update();
        // refresh panel components
        repaint();
        elapsed = System.nanoTime() - start;
        wait = (targetTime - elapsed / 1000000) - 8;
        if (wait <= 0)
        wait = 6;
        try {
        Thread.sleep(wait);
        } catch (Exception e) {
        e.printStackTrace();
        }

    }

    }

    @Override
    protected void paintComponent(Graphics graphic) {
    super.paintComponent(graphic);
    Graphics2D graphic2D = image.createGraphics();
    // to best visualization of the shapes and all graphics components
    graphic2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    graphic2D.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    if (firstCall) {
        // for the first call of paintComponent()
        // i draw this after other thing
        graphic.drawImage(ImageLoader.LOADING, 0, 0, this);
        firstCall = false;
        // other graphic calls
    } else {
        renderManager.setRenderState(graphic2D);
        graphic.drawImage(image, 0, 0, this);
    }
    // clear graphics resources after use them
    graphic2D.dispose();
    image.flush();
    }

    public void keyPressed(KeyEvent keyEvent) {
    KeyInput.getKeyInputInstance().keySet(keyEvent.getKeyCode(), true);
    }

    public void keyReleased(KeyEvent keyEvent) {
    KeyInput.getKeyInputInstance().keySet(keyEvent.getKeyCode(), false);
    }

    public void mousePressed(MouseEvent mouseEvent) {
    MouseInput.getMouseInputInstance().setAction(MouseInput.getMouseInputInstance().getPRESSED());
    mousePressed = mouseEvent.getWhen();

    }

    public void mouseReleased(MouseEvent mouseEvent) {
    MouseInput.getMouseInputInstance().setAction(MouseInput.getMouseInputInstance().getRELEASED());
    mouseReleased = mouseEvent.getWhen();
    mousePressTime = mouseReleased - mousePressed;
    seconds = (int) ((mousePressTime / 1000) % 60);
    if (seconds <= 0) {
        seconds = 1;
    }
    }

    public void mouseMoved(MouseEvent mouseEvent) {
    MouseInput.getMouseInputInstance().setPosition(mouseEvent.getX(), mouseEvent.getY());
    ;
    }

    public void mouseDragged(MouseEvent mouseEvent) {
    MouseInput.getMouseInputInstance().setAction(MouseInput.getMouseInputInstance().getPRESSED());
    MouseInput.getMouseInputInstance().setPosition(mouseEvent.getX(), mouseEvent.getY());
    }

    public void mouseEntered(MouseEvent mouseEvent) {
    }

    public void mouseExited(MouseEvent mouseEvent) {
    }

    public void mouseClicked(MouseEvent mouseEvent) {
    }

    public void keyTyped(KeyEvent keyEvent) {
    }

}

```

Now, my game works pretty well but **is it correct to maintain only one panel for the game ?** I find this way easier and more convenient.

# Answer
> 3 votes
A single panel is the right way to go when using Java Swing to create a Java game. By using a panel, you basically ask Java: "Give me an area in the interface to draw my game on." You can then draw everything you need onto that panel.

I don't see any immediate use for having multiple panels. Even if you were to create a split-screen multiplayer game, you'll typically reserve multiple portions of a single panel to draw your different views. You don't want to adapt the structure of your game to the structure of the Java Swing framework.

An exception to this rule could be if you were to create an event-based game. For instance, if you were to create a minesweeper game, it would make sense to use a panel to render the field, several labels to render the score ... etc. As, the Minesweeper game world only advanced upon player input. It is thus event-based and could fit into the Java Swing framework.

But, as you are using a gameloop to update your game at a steady 60 frames per second pace, you'll want just a single panel and take care of all drawing yourself.

---
Tags: java, game-design
---


# Question
Title: How to implement fake 3D like distortion effects for a 2D side scrolling game?
I'm not certain of the proper terms to search on or even where to begin though I imagine it is some sort of post processing effect.

I've seen games like *I Wanna Be The Boshy* and *You Have To Win the Game* which manage to modify the perspective of 2D games to give a sort of 3D effect to them (see images below). Boshy basically makes it look like you are inside a tower (cylinder) while You Have To Win the Game distorts the image so that it looks like you are playing on an old CRT monitor, specifically the slightly rounded look.

* Is there a term for this effect?
* What is the standard way for implementing this effect (terminology)?
* How would I go about implementing such an effect in a high level engine / framework such as Unity or XNA/Monogame from a 20,000 foot view? (detailed code happily accepted but not necessary - I realize exact implementation details might vary but high level details on what needs to be done would be greatly appreciated)

**I Wanna be the Boshy**

**You Have To Win The Game**

# Answer
> 7 votes
This can be implemented as a post-processing kind of effect. (When using Unity/XNA/Dx/OGL/...)

# Geometry method

Start by creating a mesh that resembles the distortion effect you are looking to achieve. (e.g. model a half cylinder (or cone, sphere, cube, ...), make sure to set the texture coordinates). Render your 2D game as usual, but render the final result into a texture. Then, render the distortion geometry with the texture you just created. You can use the world/view/projection or modify the actual geometry/texture coordinates to control the strength of the distortion. (image 1 shows the regular 2D game, image 2 shows the same texture projected onto a sphere)

# Distortion method

Image processing tools often offer distortion effects that could emulate the projection (bit like optical illusions). For example, image 3 was generated using the bulge filter from Paint.Net

.

(You can find an implementation (OpenGL ES 2.0) of this distortion effect from the GPUImage project - see GPUImageBulgeDistortionFilter)

Depending on the implementation, either method might be faster or provide a better match to your desired result. As both implementations are fairly simple, you could try to implement both and see which one works best for you.

---
Tags: 2d, graphic-effects, post-processing
---


# Question
Title: Brighter pixels around area (OpenGL ES 2)
I'm trying to achieve an effect like in the image bellow. Basically I will have a 2D texture and I want a small area around a point (let's call it "light source") to be slightly better lit (i.e. be brighter). The light source will never move from its original position nor will it seem to "pulse" like the light of a fire for example. All the other areas further away will have some default brightness.

From my understanding, this can be done using a light map, but I was wondering whether it was possible to come up with a formula in the fragment shader of the texture below that changed the brightness of my pixels so that it is very bright around a particular point and quickly faded to a default value for the pixels further away. I tried working with something like this:

```
precision mediump float;
uniform sampler2D u_Texture;

uniform vec3 u_LightPosition;
varying vec3 v_Position;
varying vec2 v_TexCoordinate;

void main() {
    float dist = length(v_Position - u_LightPosition);
    gl_FragColor = (1.0 / (c + b * dist + a * dist * dist) + 0.15) * texture2D(u_Texture, v_TexCoordinate);
}

```

where `c`, `b` and `a` are hardcoded and adjusted by myself. However I wasn't able to find any combination of `c`, `b` and `a` that achieved an effect like the one from the image, because the brightness doesn't fade away quickly enough and it's very gradual. I think that's expected behaviour from a quadratic expression anyway, so my approach is clearly wrong and it's not a matter of adjusting `c`, `b` and `a`. What should I try then?

# Answer
> 1 votes
I think the easiest/fastest solution for this would indeed be a lightmap.

* Create a second texture, big enough to fit the whole screen.
* Clear it to black and render your lights into it using their actual color.
* Bonus: If you've got a wall or similar that should be in front of a light map, just draw it using black onto the lightmap.
* Once you're done with your scene, render the lightmap ontop your screen using multiplicative blending (so bright white in the light map means fully illuminated; bright red would mean a red light, etc.).

If you still prefer the shader approach, there are other functions you can use rather than a quadratic equation.

For example, you could try *1 - x4* multiplicative with your initial fragment color, but only if the distance is between "full brightness distance" and "full darkness distance".

---
Tags: opengl-es2, lighting
---


title: GLSL: Noise via texture

text:
# Question
Title: GLSL: Noise via texture
I am trying to access a texture in a fragment shader to overlay this texture over a certain area.

```
varying vec4 v_color;
varying vec2 v_texCoord0;

uniform sampler2D u_sampler2D;
uniform vec4 u_oldcolor;
uniform vec4 u_newcolor;
uniform vec3 u_noise;

void main(){

    vec4 color = texture2D( u_sampler2D , v_texCoord0 ) ;
    float threshold = 0.005f;
    if(color.r <= (u_oldcolor.r + threshold) && color.g <= (u_oldcolor.g + threshold) && color.b <= (u_oldcolor.b + threshold)
    && color.r >= (u_oldcolor.r - threshold) && color.g >= (u_oldcolor.g - threshold) && color.b >= (u_oldcolor.b - threshold)){
        color.rgb = u_newcolor.rgb + vec3(v_texCoord0, 0.1);
    }

    gl_FragColor = color ;

}

```

For every pixel the shader checks for a certain color and replaces it with a new color+v\_texCoord0.

Now I am want to bring in a third component: a noise texture to make it look like this:

I searched the web for a solution but I could not find anything helpful.

My questions: 1.Is this even possible to accomplish via a shader? 2.How to access the texture ?

I hope that my questions are clear and proper for this forum :) .

# Answer
To get noise in a shader you can:

a) Just calculate the noise in the shader

b) Simpler, use a (precalculated) noise texture. Just add another sampler and use it as you want.
> 2 votes

---
Tags: textures, glsl, noise
---


# Question
Title: how do I create a moving type of block like in Mario[box2d]
I want to create a block which only moves up and only when hit from below. I am trying out a distance joint and I read it can be used as a spring, is this the correct solution?

the way I have tried it is to create a block, and right underneath it I created a body and created a distance joint between these 2, however I do not see any type of spring physics, the block just falls down and acts like a rope joint.

```
DistanceJointDef j = new DistanceJointDef();
        j.type = JointType.DistanceJoint;
        j.frequencyHz = 4f;
        j.dampingRatio = .5f;
        j.bodyA = body;
        j.bodyB = body2;

```

my joint def.

edit: right now I am just using a pristmastic joint and so far it seems okay.

# Answer
> 5 votes
I tried it out in RUBE and the Prismatic joint works fine for me:

What you may not have realized is that you can set joint limits on the prismatic joint, which makes this a lot easier to set up.

You can tune this by playing with the mass of the block, and the linear damping. You might also want to set the coefficient of restitution to zero.

# Answer
> -1 votes
I don't know Box2D specifically, but using a physics simulation for this effect would be overkill. They certainly didn't use any physics calculations in Mario. :)
I would do this by linearly interpolating between the normal position and moved position.

---
Tags: android, libgdx, box2d
---


# Question
Title: Resizing the window moves and stretches the texture
I have a basic screen with 3 TextureRegions rendered on the screen rendered with this code(Ignore the hardcoded numbers, bad decision I know will be replaced later):

```
Gdx.gl.glClearColor(0, 0, 0, 0);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
batch.draw(btnIdle, (Gdx.graphics.getWidth() / 2) - (169 / 2), 225);
batch.draw(btnIdle, (Gdx.graphics.getWidth() / 2) - (169 / 2), 150);
batch.draw(btnIdle, (Gdx.graphics.getWidth() / 2) - (169 / 2), 75);
batch.end();

```

and it renders like this:

But if I resize the window it becomes like this:

Why does the texture become like that when the window is resized and what are the solutions?

P.S. I am aware of this question and it does not solve my problem

# Answer
Figured it out, To actually get the resizing correctly a camera needs to be created:

```
OrthographicCamera camera;

```

and initialised in the create method:

```
camera = new OrthographicCamera(800, 480);
camera.position.set(800 / 2, 480 / 2, 0);

```

Then in the rendering method:

Set the projection matrix:

```
batch.setProjectionMatrix(camera.combined);

```

And update the camera:

```
camera.update();

```

And finally add this method:

```
@Override
public void resize(int width, int height) {
    camera.viewportWidth = width;
    camera.viewportHeight = height;
}

```

Entire source code:

```
SpriteBatch batch;

OrthographicCamera camera;

Texture menu;

TextureRegion btnIdle;

@Override
public void create () {
    camera = new OrthographicCamera(800, 480);
    camera.position.set(800 / 2, 480 / 2, 0);
    batch = new SpriteBatch();
    menu = new Texture("menuSprite.png");
    btnIdle = new TextureRegion(menu, 831, 228, 169, 32);
}

@Override
public void render () {
    batch.setProjectionMatrix(camera.combined);
    Gdx.gl.glClearColor(1, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    camera.update();
    batch.begin();
    batch.draw(btnIdle, camera.position.x - btnIdle.getRegionWidth() / 2, 225);
    batch.end();
}

@Override
public void resize(int width, int height) {
    camera.viewportWidth = width;
    camera.viewportHeight = height;
}

```
> 1 votes

---
Tags: java, libgdx
---


# Question
Title: How do I efficiently display image tiles in Unity 4.3 free
I previously wrote a TileEngine with SFML that I would like to port to Unity3D 4.3, but have not found a way to draw a tile on the screen programmatically in Unity.

All I am looking for something akin to SFML's RenderTexture(), and **not** a plugin or something from the asset store.

I am using Unity 4.3's new 2D tools/workflow, and as such need a method that will work with the 2d viewport.

# Answer
The following two guides programmatically create squares using a mesh, which is along the lines of what I was looking for.

http://studentgamedev.blogspot.no/2013/08/unity-voxel-tutorial-part-1-generating.html https://www.youtube.com/playlist?list=PLbghT7MmckI4qGA0Wm\_TZS8LVrqS47I9R
> 1 votes

---
Tags: c#, unity, tilemap, tiles
---


# Question
Title: Which Design Patterns Should I consider for Quest Management?
I am working on an fantasy RPG and I would like to get some ideas about how I am implementing Quests.

Quests in my game are very generic. The quest goal can be almost anything in the game. The goal can be: press a GUI button; pick up a certain object; kill a creature; steal an object; collect 10 items; walk to a certain location; etc. Therefor, quests need to be somehow tied to many other objects in my game.

I've been flirting with the Observer design pattern, but I'm not sure if this is the best approach.

Currently, my Quest Manager singleton is an observer, and it registers itself with many subjects. For example, I have a menu class with GUI buttons that has an EventHandler, and the Quest Manager registers with the menu class to have its own function called when a certain button is pressed. When the function gets called, the Quest Manager checks to see if the "Press the button" quest is in progress, and if it is, then that Quest becomes "Completed"!

Is this a good design or are there other design patterns that I should consider?

# Answer
It seems like you're on the right track, but I would change things up a little. Having the QuestManager know about specific quests (checking to see if the "press the button" quest is in progress, marking it as complete, etc), would quickly lead to the QuestManager being a big mess.

Instead, you could derive each quest from an IQuest interface and the QuestManager could contain/manage these quests. Your IQuest interface could have virtual functions like Activate, Update, Deactivate, and IsComplete (just some examples), which the QuestManager would call. In this case you would derive PressButtonQuest from IQuest, and the PressButtonQuest would do the things the QuestManager was responsible for in your example.
> 1 votes

# Answer
You may be interested in this question, which is similar, albeit about an achievement system (which is quite similar to a quest system).

In short:

* Store the state of your game world, including history, actions undertaken, etc.
* Iterate through all this history, and find certain conditions that meet your quest requirements
* Award quest completion accordingly.

In your example, you would have to store when each of these actions occur, as well as details about the events themselves:

* User presses a GUI button
* User picks up (certain) object(s)
* User kills creatures
* User steals objects
* User item count (`user collects 10 items`)
* Key locations walked to

You are probably already tracking some of this already (eg. items picked, objects stolen); you just now need to store extra info (what was stolen and when?)

If you have a quest like "User walks to the fountain in town X with a gold sword and gold shield," you can implement it by searching for these three events:

* User gets a gold sword
* User gets a gold shield
* User walks to location X (after the above two)

This is a pretty flexible, generic way, but the trade-off is that you're storing a bunch of extra data which, frankly, is a lot, and may not be useful outside of quests.
> 3 votes

---
Tags: design-patterns
---