# Question
Title: Converting hexagon grid coordinate system
I have been building a RTS game based on a hexagon grid in JavaScript and I stumbled across a problem regarding the coordinate system. I have been trying to implement an A-star system to find paths, but it seems that a horizontal hex grid could cause some problems so far when it comes to odd and even.

It was made horizontal as it is the way it is rendered to make all graphics not overlapping improperly.

So now to my question after some digging on the web. How do you convert between horizontal and 60 degrees coords?

I have tried this code, but it's not good enough, and I'm stuck at what I'm missing for my two functions `GetWorldXpos` and `GetWorldYpos`.

```
function DrawHex(context, hexagonData, isEven, x, y)
{
    var heightValue;

    heightValue =  GetIntNoDecimals(hexagonData.heightValue); //parseInt(hexagonData.heightValue, 10);

     //sets up so if the height of sea-levels is achived it should be equal level
    heightValue = CheckForLakeLevel(heightValue);

     //Gets color code depengin on height
     var colorCode = GetColorCode(heightValue, hexagonData.heightValue);

    if(isEven){
        //creates and draws object
        var hex = new HexagonObj(GetLargeMapXpos(x), GetLargeMapYpos(y), GetWorldXpos(x + 1, y), GetWorldYpos(x, y));
        hex.Draw(context, 0.99, lmapData.spaceing, colorCode, (heightValue), 0);

        //Adds data for usage how to draw other worl dependent objects
        lmapHeightData.push(new LargeGridData(GetLargeMapXpos(x), GetLargeMapYpos(y), GetWorldXpos(x, y), GetWorldYpos(x, y), heightValue));
    }
    else
    {
        //creates and draws object
        var hex = new HexagonObj(GetLargeMapXpos(x), GetLargeMapYpos(y) + lmapData.spaceing, GetWorldXpos(x, y), GetWorldYpos(x, y));
        hex.Draw(context, 0.99, lmapData.spaceing, colorCode, (heightValue), 0);

        lmapHeightData.push(new LargeGridData(GetLargeMapXpos(x), GetLargeMapYpos(y) + lmapData.spaceing, GetWorldXpos(x, y), GetWorldYpos(x, y), heightValue));
    }
}

//Gets what is the coordinate to be drawn on screen
function GetLargeMapXpos(x)
{
    var lgX = ((lmapData.posX + lmapData.spaceing) * x) + lmapData.areaPosX + lmapData.correctionX;
    return lgX;
}

//Gets what is the coordinate to be drawn on screen
function GetLargeMapYpos(y)
{
    return (lmapData.posY * y) + lmapData.areaPosY + lmapData.correctionY;
}

//Gets what is the coordinate for current hexagon
function GetWorldXpos(x, y)
{
    return (x + lmapData.cameraPosX) - ((y + lmapData.cameraPosY) * 2);
}

//Gets what is the coordinate for current hexagon
function GetWorldYpos(x, y)
{
    return y + lmapData.cameraPosY + (x + lmapData.cameraPosX);
}

```

Any suggestions?

# Answer
> 9 votes
Before I answer the question you already asked, some notes:

You *can* use A\* with the original grid system you are using. The key things you need are neighbors and distance (for the heuristic). For neighbors with your grid system, you need to do something different for even and odd columns (as you mention); here's how:

```
neighbors =  [
   [  [+1, +1],  [+1,  0],  [ 0, -1],
      [-1,  0],  [-1, +1],  [ 0, +1]  ],
   [  [+1,  0],  [+1, -1],  [ 0, -1],
      [-1, -1],  [-1,  0],  [ 0, +1]  ]
];
parity =  x & 1;
d = neighbors[parity][direction];
return Hex(x + d[0], y + d[1]);

```

For distances, the simplest thing to do is to convert from your coordinate system to a 3-axis form and then get distances with that. So that brings us to coordinate conversion.

In my guide to hexes, I call your coordinate system “even-q” because the even columns(q) are pushed down. (Note: in my guide I call hex coordinates `q,r` to distinguish them from 3-axis coordinates `x,y,z` but since you use `x,y` in your code I'll use `xx,yy,zz` for 3-axis in this answer.) You can convert your `x,y` to 3-axis `xx,yy,zz` with this:

```
xx = x
zz = y - (x + x&1) / 2
yy = -xx-zz

```

Once you've converted both the source and destination to the `xx,yy,zz` form, you can get distances easily:

```
distance = (abs(xx1 - xx2) + abs(yy1 - yy2) + abs(zz1 - zz2)) / 2

```

To answer your actual question, once you have the `xx,yy,zz` form, take a look at the 3-axis system below; I think `-zz,-yy` will give you what you want:

# Answer
> 2 votes
Consider this:

```
public sealed partial class HexCoords {
  static HexCoords() {
    MatrixUserToCanon  = new IntMatrix2D(2, 1,  0,2,  0,0,  2);
    MatrixCanonToUser  = new IntMatrix2D(2,-1,  0,2,  0,1,  2);
  }
  protected HexCoords(CoordsType coordsType, IntVector2D vector) {
    switch(coordsType) {
      default:
      case CoordsType.Canon: _vectorCanon = vector;  isUserNull  = true;  break;
      case CoordsType.User:  _vectorUser  = vector;  isCanonNull = true;  break;
    }
  }
  protected static IntMatrix2D MatrixUserToCanon;
  protected IntVector2D VectorCanon {
    get { return !isCanonNull ? _vectorCanon : VectorUser * MatrixUserToCanon; }
    set { _vectorCanon = value;  isUserNull = true; }
  } IntVector2D _vectorCanon;
  bool isCanonNull;

  protected static IntMatrix2D MatrixCanonToUser;
  protected IntVector2D VectorUser {
    get { return !isUserNull  ? _vectorUser : VectorCanon  * MatrixCanonToUser; }
    set { _vectorUser  = value;  isCanonNull = true; }
  } IntVector2D _vectorUser;
  bool isUserNull;
}

```

with these utility classes:

```
public struct IntMatrix2D : IEquatable<IntMatrix2D> {
  public static IntVector2D operator * (IntVector2D v, IntMatrix2D m) {
    return new IntVector2D (
      v.X*m.M11 + v.Y*m.M21 + m.M31,  v.X*m.M12 + v.Y*m.M22 + m.M32,  v.W*m.M33
    ).Normalize();
  }
}

public struct IntVector2D : IEquatable<IntVector2D> {
  public int X { get; private set; }
  public int Y { get; private set; }
  public int W { get; private set; }
  public IntVector2D(int x, int y, int w) : this() {
    X = x;      Y = y;      W = w;
  }
  public IntVector2D Normalize() {
    var x = (X >= 0) ? X : X - W;
    var y = (Y >= 0) ? Y : Y - W;
    return new IntVector2D(x/W, y/W);
  }
}

```

For this purpose **canonical** coordinates have origin in the upper-left, with y-axis running vertically downwards and x-axis running at 120 degrees up and to the right. **User** coordinates are from the same origin, with y-axis running vertically downwards and x-axis running horizontally to the right, zigging down and then up from the origin.

I have implemented this and assorted other utilities for Hex-Grid manipulation in an open source library (MIT license) here on GitHub.

---
Tags: 2d, javascript, coordinates, hexagonal-grid
---


# Question
Title: Best way to go with 3D dungeon crawler generation
I'm trying to prototype a little 3D dungeon crawler. That is, the same system as any rogue-like : A map with little rooms, linked by hallways.

But in 3D. The world is still in blocks, but I can go up and down. This game is a nice exemple of what I want. I still want the world to be mostly flat (for exemple every room could be at the same height) but I need some little up-and-downs in the rooms, or the hallways between them.

I already tried 2D dungeon generation with no precise algorithm (just by myself) but I think this time it would be best to have some nice algorithm and a good workflow about it.

So I need help about this :

* A nice 3D generation
* What data structures should I use to store my levels ?
* How should I then create it ? I'm on Unity, and for now I am associating an enum to prefabs for each type of map blocks, and then I instantiate every case. Is it a good way of doing this ?

# Answer
> 1 votes
If you already have code that generates rooms connected with hallways in 2D simply update your code to do this:

Each generated room gets a random height (pretty obvious right?). I would try with picking from a list of predefined height values or simply pick a random value from a good interval. Then proceed as usual - connect the rooms with hallways, but this time you will have to account for the height difference.

Connecting the rooms should be easy - if you went with the predefined heights approach it will be even easier. What I would do would simply build the hallway from one room to another, each step (cell of your map) getting as close to the target elevation as possible.

So if room A has exit at (0,0,0) and room B entrance at (2,4,3) then each step of building the hallway will place the next block as close to the target as possible:

Step 1: (0,0,0) Step 2: (1,1,1) Step 3: (2,2,2) Step 4: (2,3,3) Step 5: (2,4,3)

This is the simplest approach and the easiest to do, but might not get the prettiest results. Try experimenting to see what works best for you.

---
Tags: 3d, unity, procedural-generation, roguelikes
---


# Question
Title: How can I draw a small bitmap on a larger bitmap at a particular position? (Canvas / SurfaceView)
I'm building a game that requires additive blending of colours for certain bitmaps. Say I have 4 different types object, there are maybe ten of each type on the screen with each type having a distinct colour. If these objects overlap I want to perform additive blending on the overlapping portions. After doing some research on the subject I came across this thread about drawing and additive blending. It has lots of useful information, but it's not using bitmaps. Then I found another thread about blending pixels from two bitmaps which is also helpful, but is based on same sized bitmaps.

So my solutions to solve this problem is to create four temporary bitmaps, one for each object type / colour, with each of these bitmaps being the same size as the device screen. I want to draw all objects of each colour onto the relevant bitmap, so all the blue objects on one bitmap, all the orange objects on another and so on. Then when all for bitmaps are ready I'll perform additive blending on the four bitmaps of the same size as per the link above. then draw the result on the canvas.

My only problem is I'm not sure how to position the smaller bitmaps correctly on the larger one. Can anyone advise me on how I might proceed with this?

# Answer
OK, my lack of understanding of Paint objects and how filtering works let me to make some incorrect assumptions about how straight forward this might be.

I have figured it out in the end anyway.

To do additive blending you need grey scale images that represent each channel of colour: alpha, red, green and blue.

Gimp has the functionality to separate images into these individual colour channels. Once separated, I add them to my project resources and, as suggested above, create temporary bitmaps the same size as the screen, a paint object and a canvas for each colour and the alpha channel. For each paint I add the corresponding grey scale image to a BitmapShader (with Mode set to CLAMP) and set it to the paint. I also add a new PorterDuffColorFilter to each paint set to the corresponding colour, and multiply mode. Here's what the red channel looks like:

```
    redPaint.setShader(new BitmapShader(redTempBmp, TileMode.CLAMP,
            TileMode.CLAMP));
    redPaint.setColorFilter(new PorterDuffColorFilter(Color.RED,
            Mode.MULTIPLY));
    redPaint.setXfermode(new PorterDuffXfermode(Mode.SCREEN));

```

For the alpha channel (after some research) I discovered bit shifting the colour pixels (from my grey scale alpha image) into the alpha channel will result in the correct alpha levels. I found a method online to do this. here's the code:

```
private Paint getAlphaBitmap(int width, int height, Bitmap alphaTempBmp) {

    int pixelCount = width * height;
    int[] alphaPixels = new int[pixelCount];
    alphaTempBmp.getPixels(alphaPixels, 0, width, 0, 0, width, height);
    for(int i = 0; i < pixelCount; i++){

        alphaPixels[i] = alphaPixels[i] << 8;

    }
    alphaTempBmp.setPixels(alphaPixels, 0, width, 0, 0, width, height);
    Paint alphaPaint = new Paint();
    alphaPaint.setAntiAlias(true);
    alphaPaint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));
    return alphaPaint;
}

```

From this point, in my draw method I can just draw 3 rectangles, each the size of the screen using the above paints to get the desired additive blending results. After that I draw the alphaBitmap on top and the job is done.

There is one more factor to take into consideration. When using software to split an image into separate channels, on the resulting alpha bitmap clear areas appear black. For my purposes this didn't work as I needed to draw the sprites onto the temp alpha bitmap in order to generate a screen sized alpha bitmap. This means if any images overlap then the black representing the clear parts of the image overwrite the coloured parts on the image beneath it. So, I drew my sprites as I wanted them, and rendered them in grey scale without any alpha channel. I then created the alpha channel separately and made sure it contained only white/grey without any black. The results work quite well. Now however, I have another problem - the code is quite slow, I hope multi-threading will sort the issue, otherwise I'm back to square 1.

EDIT: This is way to slow to use for any sort of animation. Needs to be applied using OpenGL.
> 1 votes

---
Tags: 2d, android, textures, html-canvas, blending
---


# Question
Title: Is there a centralized achievement system for browserbased onlinegames
I plan to implement missions with achievements (or rewards/badges) in my online space browser game spacetrace.

I want somehow connect that to an existing online achievement platform for browser-based HTML5-games?

There are some online platforms that lets users show their achievements in several games they have reached like GameCenter, OpenFeint, Steam, PlaystationNetwork and Scoreloop

But is there a great community for browser-based onlinegames too?

clay.io looks quite promising.

Which is the most used platform that I should implement the achievements on?

# Answer
> 4 votes
Kongregate have an achievement system. It works a lot like Steam, so you can get multiple achievements from different games on different platforms (Flash, Unity, etc.) and you can show them off.

Sign up for an account and play a game that has achievements to see how it works. Kongregate is also an incredibly popular online community, so your game will also get lots of exposure.

**UPDATE** Here is a link to Kongregate's API section for developers. Completely slipped my mind to include the link. That should help you out with implementation.

# Answer
> 4 votes
Google has announced its Google Play game services which offer

* Achievements
* Leaderboards
* Cloud Save
* Matchmaking

across Android, iOS, and web (via RESTful apis).

# Answer
> 3 votes
Disclaimer: I am a co-founder of Clay.io (mentioned in question).

Since January we've added search and made the site a bit less cluttered, here are some useful links to look through.

Developer Info Page
Documentation
Achievements Documentation

I hope this helps. You hit the nail on the head for the platforms we're emulating, only for HTML5 games. One more that's similar is Mochi Media (for Flash Games). As mentioned, Kongregate and now Google Play are alternatives.

---
Tags: browser-based-games, achievements, community-management
---


# Question
Title: Using a programmable pipeline in a game engine
As a learning experience, I'm developing my own 3D game engine using OpenGL. I'm a little confused as to how to implement my rendering engine such that it uses a programmable pipeline while still being responsible for projecting and displaying vertices correctly.

Let's say my engine has a simple vertex shader that uses projection and modelview matrices to project a vertex in 3D space. How do I use the engine's vertex shader while still allowing the programmer to provide his/her own vertex shader for other calculations in their game? What is the normal approach here?

# Answer
> How do I use the engine's vertex shader while still allowing the programmer to provide his/her own vertex shader for other calculations in their game? What is the normal approach here?

There is no normal approach because engines generally don't let you do that.

Generally speaking, engines take one of two approaches: either the user provides *none* of a shader or *all* of a shader. Never *parts* of a shader.

Engines that allow the user to provide shaders will establish some form of convention for communication between the application and the shader. They'll say that the position must be named "position" or whatever, and you're expected to provide vertex shaders with that attribute name. The various transformation matrices will similarly have specific uniform names and types, and the user providing the shader must adhere to those names and types.

Some engines allow you to create shaders from raw components via some system. But even there, it's the *system* that's creating those shaders. If that system has some mechanism for inserting user-provided fragments of code, then it will be specific to that system, and it likely won't be in GLSL anymore. And even then, those fragments will have to adhere to a specific convention based on the needs of that system.

In any case, if you're truly writing an engine for *yourself* or a single team that you're supporting, you really shouldn't bother with this. Just use shaders directly.
> 3 votes

# Answer
Higher-end engines typically use a higher-level abstraction than an individual shader.

Simpler games just allow each model/material to specify shaders and then to use HLSL includes or the like to allow all common code to be easily reused. You'll need a bit of discipline in applying the shader includes properly and it can be a bit repetitive sometimes, but so long as you don't have a really huge number of different materials (most hobby/student games won't), you should be okay.

The higher-level abstraction are generally built around a concept of shader pieces that can be assembled into complete shaders. For example, the engine would provide some shaders for deferred shading vs simple pass-thru. A material could specify a BRDF which maps to a small piece of shader code and metadata. The engine/tools look at the BRDF fragment and inserts the necessary code into the pixel shader to do the calculations and inserts the correct attribute code into the vertex shader, binding the final generated shaders to the runtime material definitions. This is non-trivial to implement for someone just beginning at games.

Some engines go so far as to use a visual material definition language and generating the shaders from that. This is a *lot* of work, though.
> 2 votes

---
Tags: opengl, architecture, graphics, glsl
---


title: "Car" movement in 2D dimension

text:
# Question
Title: "Car" movement in 2D dimension
I am searching for a simple tutorial how to add arcade car physics for my game.

Exactly same user units behaviour i found in next games:

**Tank Hero: Laser Wars**

**Death Worm:**

Video: http://www.youtube.com/watch?v=tbJbvPwYT\_I

Any good tutorials with simplified physics? Because if I understand this issue correctly I don't need any complex car physics to add unit behaviour like presented in those games.

# Answer
Since I researched this in the past, I will post some code I had converted previously that may help you. This is basically the bare minimum of what you can do to achieve this effect. You will most likely want to add damping, and effects such as braking etc. It also works on a system where you only have two tires, one in front and one in back.

The code can be extended to add the two extra tires, but that will be up to you.

The variables that we will use:

```
Texture2D vehicle;
Texture2D tire;
Vector2 position;
Vector2 frontTire, backTire;
float direction;
float speed;
float angle;
float wheelBase = 32;

```

In our Update method:

```
KeyboardState kbstate = Keyboard.GetState();
if (kbstate.IsKeyDown(Keys.Up))
    speed += 10;
else if (kbstate.IsKeyDown(Keys.Down))
    speed -= 100;
if (kbstate.IsKeyDown(Keys.Left))
    angle -= 0.03f;
else if (kbstate.IsKeyDown(Keys.Right))
    angle += 0.03f;

if (speed < 0)
    speed = 0;
if (speed > 300)
    speed = 300;

frontTire = position + wheelBase / 2 * new Vector2((float)Math.Cos(direction), (float)Math.Sin(direction));
backTire = position - wheelBase / 2 * new Vector2((float)Math.Cos(direction), (float)Math.Sin(direction));

backTire += speed * elapsed * new Vector2((float)Math.Cos(direction), (float)Math.Sin(direction));
frontTire += speed * elapsed * new Vector2((float)Math.Cos(direction + angle), (float)Math.Sin(direction + angle));

position = (frontTire + backTire) / 2;
direction = (float)Math.Atan2(frontTire.Y - backTire.Y, frontTire.X - backTire.X);

```

And then draw:

```
spriteBatch.Begin();
spriteBatch.Draw(vehicle, position, null, Color.White, direction, new Vector2(vehicle.Width/2,vehicle.Height/2), 1, SpriteEffects.None, 0);
spriteBatch.Draw(tire, frontTire, null, Color.White, direction, new Vector2(tire.Width/2, tire.Height/2), 1, SpriteEffects.None, 0);
spriteBatch.Draw(tire, backTire, null, Color.White, direction, new Vector2(tire.Width/2, tire.Height/2), 1, SpriteEffects.None, 0);
spriteBatch.End();

```

This will provide you with the similar behavior as shown in your video. Again, you will need to tinker greatly with this code in order to get the exact behavior you are looking for.
> 2 votes

---
Tags: c#, physics, .net, car
---


title: Artificial player evaluation

text:
# Question
Title: Artificial player evaluation
I have a problem concerning a board game I'm creating. I plan on making an artificial player for the game using MiniMax with AlphaBeta prunning, but I'm not sure how to evaluate ir the player is good at the game. Since it's a new game I can't get a player who is good to give feedback. So I'd like to know if there is any technique to determine objectively if the artificial player is actually good. Thank you in advance.

# Answer
The problem is that "good" is always a relative term. Good compared to what?

To evaluate the strength of a game AI you need to compare it to other players by letting it play against them. These players can either be humans or other game AIs which were developed independently.

And even then you have only proven that it is good at countering the strategies employed by these players. A player which uses an entirely new strategy might have completely different results.

You can prove that an AI is perfect, when the game is deterministic and the AI is able to calculate every possible game in advance and thus always select the move which results in the best possible outcome. But when the game is too complex for that, you can't mathematically prove its strength.
> 3 votes

# Answer
Your question, in essence: "Can I rate something without a point of reference?"

No, you cannot.

The game has to be played a certain number of times before you have any reference point at all. Once a certain number of games has been played given one set of AI parameters, you can then, from a human standpoint, gauge the difficulty. And of course you need people -- if only yourself -- to do so.
> 2 votes

# Answer
If a game has perfect information at any point and the game flow is perfectly determinable based upon the finite amount of decisions that could be made, MiniMax with maximum depth will always be the best player in the game(obv. not taking time into account). If you need heuristic approaches and the game does lack some of the properties mentioned above, "good" or "bad" relies on your heuristic.

If your game does not match the criteria mentioned above, you have to try and play against it to improve your heuristic. If it does and time is not a skill-defining factor for a player, MiniMax is objectively "good".
> 0 votes

---
Tags: ai
---


# Question
Title: Game Development AI, NPC & Entities Definition using Scripting Languages
i am developing a Multiplayer(actually MMORPG) architecture for learning purpose.

I do have some game developement background, but all my engines were very rigid and completly developed for the game itself.

That being said, i wanted to experiment so i designed a generic Entity/Component Model Architecture where i would like to extend the game logic, npc, ai, entities and game objects definition(monsters, characters, weapons, items, etc...) using a Scripting language for Code-Reuse and Hot Load/Reload purpose.

My questions are as follow: Considering that i want a scripting language with the best performance possible and that it need to be actually compatible with both .NET/Mono, what are my options? What would you suggest? I know Lua and Javascript are common, but how about performances? What would be my other options? What managed interpreter library would you use?

How would you proceed to implement such scripting language support in an engine? I plan to actually update the server-side simulation about 10 times per second.

Thanks in advance! ;)

# Answer
> 1 votes
I've been using LuaInterface from c#/XNA. Mostly thus far I've been using it for entity creation (I too am using an entity-component system). That's been working pretty well. I can't speak to the speed as entity-creation is a comparatively rare event, though soon I intend to script collision handling, etc. I suspect it should be fast enough, I understand that Civ and quite a few others use it. It's quite quick in creating the entities (script time is negligible vs the asset loading).

I'm considering switching to CS-Script. I'm not dissatisfied with Lua, but there's some basic impedence in switching between the two. I figure if I can do my scripting in C# it would just make things that much easier. And since the C# script is compiled into an assemby, speed shouldn't be an issue.

---
Tags: c#, scripting, lua, .net, mono
---


# Question
Title: Questions about the details of implementing a component-based entity system
I started reading about component-based entities, and overall it seems like a good idea, but many of it seems to skip over a lot of details and not give many real examples, so there are things that don't really make sense to me. Note that I'm also mainly talking about the architecture where components only hold data and act as keys that trigger systems to be run for that entity, but this still mostly applies with each component having an update method that's called by the entity.

* When to think if it, many entities have things in common (like, for example, enemies with collision and physics), plus behavior that's specific to only that one kind of entity. Do I need to create lots of systems that are only good for one kind of entity, and are not at all generic/reusable?
* How should components interact with each other? I heard of using message queues, but that seems like it would be slow, plus how would I stop it from queueing messages that will never be read? Or is just setting fields in the component (to be checked by the other system) considered good?
* What's the best way to handle collision detection? A system that checks for collisions and sends events/stores the colliding objects in a component? Would just giving the world/entity manager a method (that would freely be used by different systems) to find colliding entities that have a certain component be a good idea? Or is there another way?
* How to handle animations changing based on events? if I have a component telling the animation component to switch to a certain animation, doesn't that make it so that the component can't be used with a different animation?
* In 2D, how would drawing order be handled? Especially if there are multiple kinds of drawing systems?
* With OOP you can store a reference to an object in another object, and call methods on it. How would the equivalent be done with an entity/component system, considering entities are not guaranteed to have certain components?

So how are these issues normally solved? Or am I thinking about this completely the wrong way?

# Answer
> 2 votes
> When to think if it, many entities have things in common (like, for example, enemies with collision and physics), plus behavior that's specific to only that one kind of entity. Do I need to create lots of systems that are only good for one kind of entity, and are not at all generic/reusable?

If you put together all your different entity designs, you'll probably realize that there's a lot more behaviour than you think that you can generalize. If not, it's fine to create systems specific to certain types of entity.

> How should components interact with each other? I heard of using message queues, but that seems like it would be slow, plus how would I stop it from queueing messages that will never be read? Or is just setting fields in the component (to be checked by the other system) considered good?

This depends on how you are going to structure your framework. I prefer keeping components as pure data and defining behaviour through systems. If you need two components to interact, just make a system that operates on those two component types.

> What's the best way to handle collision detection? A system that checks for collisions and sends events/stores the colliding objects in a component? Would just giving the world/entity manager a method (that would freely be used by different systems) to find colliding entities that have a certain component be a good idea? Or is there another way?

I'd personally store contact information in the collision component itself. This way, many different systems can access the collisions and use the information. For example, the damage system could check for collisions with certain weapons and deduct the appropriate amount of health.

> How to handle animations changing based on events? if I have a component telling the animation component to switch to a certain animation, doesn't that make it so that the component can't be used with a different animation?

This type of logic should be done in systems. I'd add an extra layer of abstraction, so the system only needs to decide the "purpose" of the animation. The animation data stored in the component maps "purpose" to the given animation. For example, the "run left" purpose could map to a series of frames that show the sprite running left, but this data could be different for each sprite.

> In 2D, how would drawing order be handled? Especially if there are multiple kinds of drawing systems?

Just give the sprite component a depth field. There should be a central renderer that knows how to render a sprite with a given depth, and the rendering systems should just issue commands to the central renderer, not straight to your graphics library.

> With OOP you can store a reference to an object in another object, and call methods on it. How would the equivalent be done with an entity/component system, considering entities are not guaranteed to have certain components?

This is why I make components pure data and constrain logic to systems. Basically, each system has a "mask" that states its required component types. For example, the rendering system requires both a position component and a sprite component. Each entity is also associated with a mask that states the component types it has. When the rendering system is invoked, it only loops through the entities that have masks that are compatible with its mask.

---
Tags: component-based, entity-system
---


# Question
Title: Checking if a click happened "off" an object
Having made the first game in Game Maker, Catch the Clown, I realised there was no way to win or lose.

Winning is easy enough, set a maximum score and a test that fires whenever a score increments, but losing has proved challenging. I had an idea; if the player attempts to click on the clown but misses he/she loses a life. I have tested every check, read the manual and looked through forums but I can't find a way to do this.

I also can't figure out where to put the event. I tried on the clown; tests like checking to if there would be a collision between where the click occurred and where the clown is... nothing works. I am at a complete loss so any help would be greatly appreciated.

# Answer
This question concerns the order of events (when they are relatively called to one another). My answer takes advantage of the fact that mouse click events occur between Begin Step and End Step events. That means one solution would be the following:

1. Have an obj\_controller (bad name and design practice, but fairly commonly done with GM) that has a `clicked` variable and a `hit` variable.
2. In obj\_controller's Begin Step, set `hit` and `clicked` to false
3. In obj\_controller's Global Mouse Left Pressed event (this would indicate there has been a hit somewheres on screen, possibly a misfire, possibly not), set the `clicked` variable to true
4. Have an object called obj\_clown that is the target your user is trying to hit.
5. In obj\_clown's Left Pressed event, increment score, tell obj\_controller that there has been a verified hit by setting obj\_controller's `hit` variable to true (this can be done using the following GML:

```
///Tell the obj_controller a hit was made
with(obj_controller) {
    hit = true;
}

```

), and destroy itself (so the clown is gone).
6. In obj\_controller's End Step event, check if `clicked` is true and `hit` is false. This means there has been a click somewheres that isn't a clown (because the clown would've told it that the hit was good) and we can decrement a life

I hope that's not too confusing. I've slapped together a GM:S example for you to look at (it works! although it's kind of ugly and there's no sound or polish and losing all your lives or killing all the clowns doesn't mean anything)
> 3 votes

---
Tags: game-maker
---


# Question
Title: Can't show an object in a tapped coordinate
So hi, I have a problem. I want to show an object (Texture2D) in an area tapped by user. This is my fields :

```
List<Texture2D> list = new List<Texture2D>();
List<Vector2> list2 = new List<Vector2>();
List<int> list3 = new List<int>();

```

list, is used to store the object. list2, used to store tapped coordinate. and list3, is used to store object timeout (after 100ms, the shown object vanishes)

This is my update method

```
protected override void Update(GameTime gameTime)
{
    TouchCollection touchState = TouchPanel.GetState();

    foreach (TouchLocation t in touchState)
    {
        if (t.State == TouchLocationState.Pressed)
        {
            list.Add(Content.Load<Texture2D>("base_grass"));
            list2.Add(new Vector2 { X = t.Position.X, Y = t.Position.Y });
            list3.Add(100);

            System.Console.WriteLine("added : " + t.Position.Y + "," + t.Position.X);
        }
    }

    for (int i = 0; i < list3.Count; i++)
    {
        list3[i]--;

        if (list3[i] <= 0)
        {
            list.RemoveAt(i);
            list2.RemoveAt(i);
            list3.RemoveAt(i);
        }
    }
    base.Update(gameTime);
}

```

(base\_grass is the name of my object. It is a plain rectangle image)

The "for" statement is to remove the object when the time expires.

And this is my draw method

```
protected override void Draw(GameTime gameTime)
{
    GraphicsDevice.Clear(Color.White);

    _spriteBatch2.Begin();

    for (int i = 0; i < list.Count; i++)
    {
        _spriteBatch2.Draw(list[i], list2[i], new Rectangle(0, 0, 64, 64),
                Color.White, 0, Vector2.Zero, 1f, SpriteEffects.None, 1);
    }
    _spriteBatch2.End();

    base.Draw(gameTime);
}

```

Nothing shown when I clicked on the screen.

But if I change the \_spriteBatch2.Draw into this

```
 _spriteBatch2.Draw(list[i], new Vector2((64 * 0),(64 * i)), new Rectangle(0, 0, 64,64), Color.White, 0, Vector2.Zero, 1f, SpriteEffects.None, 1);

```

It worked, but shown vertically, not on the tapped / clicked coordinate.

Anyone know where my problem is? Thanks

# Answer
> 0 votes
I read an article here : https://github.com/mono/MonoGame/issues/1046

and adding this code to the first line of update method

```
 if (_firstUpdate)
 {
      typeof(Microsoft.Xna.Framework.Input.Touch.TouchPanel).GetField("_touchScale", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static).SetValue(null, Vector2.One);
      _firstUpdate = false;
 }

```

And voila! **It works**. The position value is not infinity anymore. Still, although I can make it right, but I still don't know what essentially the problem is. Anyone figured it out?

# Answer
> 2 votes
Despite this being just a proof-of-concept, you should still follow correct programming practices. Create a new class that has the texture, position, and TTL (time-to-live). This will make it much easier for you and others to debug and work with.

Your object class:

```
public class TapMarker
{
    public TapMarker(Vector2 position)
    {
        Position = position;
        TTL = TimeSpan.FromMilliseconds(100);
        IsComplete = false;
    }

    public Vector2 Position { get; private set; }
    public TimeSpan TTL { get; private set; }
    public bool IsComplete { get; private set; }

    public void Update(GameTime gameTime)
    {
        TTL -= gameTime.ElapsedGameTime;

        if (TTL < TimeSpan.Zero)
            IsComplete = true;
    }

    public void Draw(SpriteBatch _spriteBatch, Texture2D texture)
    {
        _spriteBatch.Draw(texture, Position, Color.White);
    }
}

```

Your main game code:

```
    private List<TapMarker> markers;
    private Texture2D grassTexture;

    protected override void Update(GameTime gameTime)
    {
        base.Update(gameTime);

        TouchCollection touchState = TouchPanel.GetState();

        // Add a marker for each touch...
        foreach (TouchLocation t in touchState)
        {
            if (t.State == TouchLocationState.Pressed)
                markers.Add(new TapMarker(t.Position));
        }

        // Iterate backwards...
        for (int i = markers.Count; i >= 0; i--)
        {
            // Update the marker...
            markers[i].Update(gameTime);

            // Remove it if it is complete.
            if(markers[i].IsComplete)
                markers.RemoveAt(i);
        }
    }

    protected override void Draw(GameTime gameTime)
    {
        base.Draw(gameTime);

        GraphicsDevice.Clear(Color.White);

        _spriteBatch2.Begin();

        // Draw each marker
        foreach (var marker in markers)
            marker.Draw(_spriteBatch2, grassTexture);

        _spriteBatch2.End();
    }

```

As you can see, using a single class is much easier, and doesn't take that long to create.

Your initial draw call was too complicated, so I corrected that. Also, I noticed that your method to decrement the TTL was using the number of updates instead of the actual milliseconds. Make sure you utilize the `GameTime` parameter in the `Update` method.

To reduce the number of iterations through a loop, iterate backwards so removing an element will not effect the elements that come before it.

Finally, make sure that your classes can handle themselves. Giving them their own `Update` and `Draw` methods will help keep everything organized.

To answer your other question, the reason no output is shown is because `Console.WriteLine` will not work on Windows Phone 8. There are other alternatives, but I find conditional breakpoints to be easier to use.

---
Tags: xna-4.0, monogame, windows-phone-8
---


# Question
Title: What methods are there for representing 3D terrain?
I'm making a terrain system which needs to be procedurally generated and would like to know my options. So far I know of: Height-field terrain, Vector-field terrain, and Voxel terrain. Is there anything missing from that list?

# Answer
> 6 votes
Just a quick note about voxel landscapes. It is a wide field and there are a variety of representations and algorithms for display.

**Heightfield voxel terrain**: stored as a heightmap, but rendered with vertical strips rather than polygons. Check out "Outcast"

**Cuboid terrain**: I believe stored in terrain chunks as run-length encoded strips. Displayed as a bunch of quads, separating empty voxels from solid ones. We all know minecraft.

**Polygonised scalar field**: A voxel field of real values representing signed distance from surface. Surface is extracted with a polygonisation algorithm like "marching cubes", "marching tetrahedrons" or "dual contouring". See this GPU Gems article.

**Sparse voxel octrees**: Stored as a memory efficient octree, and rendered by raycasting the tree directly. This technique has great potential but is still in its infancy. Check out Atomontage

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


title: OpenGL / Assimp oddity or error?

text:
# Question
Title: OpenGL / Assimp oddity or error?
A friend and I are working on developing a game engine in C++. He doesn't live anywhere near me, so we use Dropbox to sync our files. I opened his project to test his code, and I kept getting errors saying that the program could not start with an error that stated "This application could not start. 0xc015002." I used a dependency walker to find that ILUT.dll was causing some issues. I have done just about everything suggested on most forums to make ILUT work, and I have not had any success. I've re-downloaded it, put the DLL just about everywhere I could, and I still had issues. We then tried to compile it without Assimp, and the program compiled without errors. This was not the end of our problems though. I made a class to create a primitive cube using OpenGL. When I tested it out, there was no cube on the screen. I had my friend test the program out, and to our surprise, there was a perfectly rendered cube on his screen. So I'm honestly not sure where things could possibly be going wrong. Any help at all would be greatly appreciated. Thank you for taking the time to read this long question. I'll be happy to provide anyone with necessary info needed to help with this question!

My OpenGL version is 4.2. He has an nVidia graphics card, and I have an AMD Radeon graphics card. We are using Visual Studios 2012 as our IDE.

# Answer
I figured out what I had to do. I had to get the Assimp SDK, replaced the include files with the ones supplied by the SDK, and things started to work perfectly. Thanks for your help!
> 2 votes

---
Tags: opengl, assimp
---


# Question
Title: Independent blending with DXGI_FORMAT_R16G16_SINT
I'm implementing direct volume rendering engine with volume bricking, but I'm stuck with this problem:

For each volume brick I render to color render target \[CRT\] (for visualization) and to data render target \[DRT\] (used for isosurface object picking). DRT is of the DXGI\_FORMAT\_R16G16\_SINT format. All works fine and smooth except wrong handling of blending DRTs of multiple volume bricks together. Closer brick always occludes further brick DRT.

Here are the pictures to illustrate my point (if the object has proper DRT data it's outlined - as you can se in the highlighted area, there are objects/parts with no data)

Could somebody please give me a tip, how to handle this? Of course I could always render every brick to separate DRT and write own shader to merge them properly, but isn't there a way of only properly setting blending modes?

(now I'm rendering with blending disabled for DRTs)

Thanks

# Answer
Direct3D 11 does not support blending for `DXGI_FORMAT_R16G16_SINT` or any of the other `_UINT` or `_SINT` formats. Blending is only available for the `_UNORM`, `_SNORM`, and `_FLOAT` formats. See the full list on MSDN.

I don't know exactly how you're using this data buffer, but it might be simplest to switch to `R16G16_FLOAT` \- it should require no modifications to your shaders or other code, assuming you don't actually need the full range and precision of 16-bit integer values.

If you *do* need that much precision, you could try `R16G16_UNORM` or `_SNORM`, which use 16-bit integers internally but scaled to/from the \[0, 1\] or \[-1, 1\] range, respectively, on read/write. Alternatively you could switch to `R32G32_FLOAT`, which would give you all the range and precision you could want (and more) but would take up twice the memory, and likely also be slower.
> 1 votes

---
Tags: directx11, blending
---


# Question
Title: Programmatically creating a 3d mesh in XNA
Surprise! Another question related to Minecraft. Anyways:

Rather than drawing thousands of blocks each frame, I remember reading somewhere that Minecraft breaks the map into 16x16x256 chunks, and every time one of the chunk's blocks is updated, it reconstructs a mesh for that chunk to be used in rendering. The idea is that you'll only ever see a handful of chunks at a time, which equates to only a few meshes being drawn.

This is all fine and well, but XNA doesn't seem to have built in support for creating meshes on the fly. It seems that my only option is to mess around with TriangleLists and the like. Is that the only option, or is there some alternative I'm not seeing?

# Answer
I don't know. Other then that, what you can do it simply construct a cache of these files, of which you can draw meshes on and tell xna to read them. This may be sorta slow but I actually think Minecraft does it. It constantly reads and writes data files, doubt you game is gonna be slowed down.
> -3 votes

---
Tags: xna, c#, 3d-meshes
---


# Question
Title: Android cocos2d getting a sprite to continuously move to a dynamic position
I tried using the MoveTo method in cocos2d to get a sprite to continuously follow my player sprite:

```
CCMoveTo actionMove = CCMoveTo.action(actualDuration, player.getPosition());
CCSequence actions = CCSequence.actions(actionMove);
enemy_sprite.runAction(actions);

```

However when the sprite spawns it just goes to the position the player sprite was at when it spawned, therefore it doesn't follow it continuously. So I tried using a recursive function to get the sprite to follow the player sprite continuously:

```
CCMoveTo actionMove = CCMoveTo.action(actualDuration, player.getPosition());
CCCallFuncN actionMoveDone = CCCallFuncN.action(this, "enemySpriteMoveFinished");
CCSequence actions = CCSequence.actions(actionMove, actionMoveDone);
enemy_sprite.runAction(actions);

```

Where "enemySpriteMoveFinished" is:

```
    public void enemySpriteMoveFinished(Object sender) {
    CCSprite sprite = (CCSprite)sender;
    CCMoveTo actionMove = CCMoveTo.action(0.5f, player.getPosition());
    CCCallFuncN actionMoveDone = CCCallFuncN.action(this, "enemySpriteMoveFinished");
    CCSequence actions = CCSequence.actions(actionMove, actionMoveDone);
    sprite.runAction(actions);
    }

```

But this method turns out to be rather choppy. Anyone have any solution to getting cocos2d to move a sprite to a dynamic position continuously that's smoother?

# Answer
> 0 votes
I found out how to do it by updating the enemy sprite in my games update method by adding a fraction of the distance between the enemy sprite and player sprite to the enemy sprites position.

```
for (CCSprite enemySprite : _enemySprites) {
        CGPoint enemySpritePosition = enemySprite.getPosition();
        CGRect enemySpriteRect = CGRect.make(enemySprite.getPosition().x - (enemySprite.getContentSize().width),
                enemySprite.getPosition().y - (enemySprite.getContentSize().height),
                enemySprite.getContentSize().width,
                enemySprite.getContentSize().height);

        if (CGRect.intersects(playerRect, enemySpriteRect))
            CCDirector.sharedDirector().replaceScene(GameOverScreen.scene());

        enemySpritePosition.x += (player.getPosition().x - enemySprite.getPosition().x) / 50;
        enemySpritePosition.y += (player.getPosition().y - enemySprite.getPosition().y) / 50;
        enemySprite.setPosition(enemySpritePosition.x, enemySpritePosition.y);
    }

```

---
Tags: android, sprites, movement, cocos2d
---


title: Terrain Generation - Advanced

text:
# Question
Title: Terrain Generation - Advanced
I need to generate terrain. Easy enough you might say, but I need to create Biomes if you will(Can't link of another name) lakes. Trees and on a height map.

So I have really no idea how to use a height map or even perlin noise. If you could help me out. I need 3D and 2D help. If you could explain the math behind it, really help me understand this for good.

# Answer
> 3 votes
Can I just suggest that you absolutely forget about biomes if you can't make and use height-maps yet.

Step by step is the way to go.

```
A +---+---+ B
  |\..|\..|
  |.\.|.\.|
  |..\|..\|
  +---+---+      Y
  |\..|\..|      |
  |.\.|.\.|      |
  |..\|..\|      |
C +---+---+ D    ---------x

```

imagine the +'s as the vertices of your mesh. Simply randomize the height of the corner verts (A,B,C,D), then average the mid-verts between these, with a little randomness as well. Keep doing this foreach mid-vert until all your verts are positioned in the z direction. You'll end up with a fairly natural looking terrain. There are all sorts of ways in which you can modify your height algorithm, using various noise and smoothing methods.

There's not really any math behind generating a simple terrain mesh. Not until you look at more complex methods, when you're after more interesting results. But you have to be comfortable with generating height maps first.

# Answer
> 2 votes
I agree with the people in the comments. It's very hard to do these kinds of things. I recommend looking into Perlin Noise more before you attempt anything. Another thing is to look into Simplex Noise, but I'd start with Perlin Noise, just classier :).

1. Perlin Noise Info
2. How it works
3. This should give you a slight idea about using it
4. Perlin Worms - This is what they used to make caves in Minercraft
5. A tutorial/info page about Perlin Noise

Hope this gets you started. Good luck!

---
Tags: java, lwjgl, terrain, perlin-noise
---


# Question
Title: Implementing water effects (splashes) into XNA 4.0 game
I am creating a 2D XNA game and came across a tutorial on adding water effects (splashes) to an XNA game but after implementing it into my game I can't get it to scale down. Currently it takes up the entire screen.

The Water class looks like this

```
class Water
{
    struct WaterColumn
    {
        public float TargetHeight;
        public float Height;
        public float Speed;

        public void Update(float dampening, float tension)
        {
            float x = TargetHeight - Height;
            Speed += tension * x - Speed * dampening;
            Height += Speed;
        }
    }

    PrimitiveBatch pb;
    WaterColumn[] columns = new WaterColumn[201];
    static Random rand = new Random();

    public float Tension = 0.025f;
    public float Dampening = 0.025f;
    public float Spread = 0.25f;

    RenderTarget2D metaballTarget, particlesTarget;
    SpriteBatch spriteBatch;
    AlphaTestEffect alphaTest;
    Texture2D particleTexture;

    private float Scale { get { return spriteBatch.GraphicsDevice.Viewport.Width / (columns.Length - 1f); } }

    List<Particle> particles = new List<Particle>();
    class Particle
    {
        public Vector2 Position;
        public Vector2 Velocity;
        public float Orientation;

        public Particle(Vector2 position, Vector2 velocity, float orientation)
        {
            Position = position;
            Velocity = velocity;
            Orientation = orientation;
        }
    }

    public Water(GraphicsDevice device, Texture2D particleTexture)
    {
        pb = new PrimitiveBatch(device);
        this.particleTexture = particleTexture;
        spriteBatch = new SpriteBatch(device);
        metaballTarget = new RenderTarget2D(device, device.Viewport.Width, device.Viewport.Height);
        particlesTarget = new RenderTarget2D(device, device.Viewport.Width, device.Viewport.Height);
        alphaTest = new AlphaTestEffect(device);
        alphaTest.ReferenceAlpha = 175;

        var view = device.Viewport;
        alphaTest.Projection = Matrix.CreateTranslation(-0.5f, -0.5f, 0) *
            Matrix.CreateOrthographicOffCenter(0, view.Width, view.Height, 0, 0, 1);

        for (int i = 0; i < columns.Length; i++)
        {
            columns[i] = new WaterColumn()
            {
                Height = 240,
                TargetHeight = 240,
                Speed = 0
            };
        }
    }

    // Returns the height of the water at a given x coordinate.
    public float GetHeight(float x)
    {
        if (x < 0 || x > 800)
            return 240;

        return columns[(int)(x / Scale)].Height;
    }

    void UpdateParticle(Particle particle)
    {
        const float Gravity = 0.3f;
        particle.Velocity.Y += Gravity;
        particle.Position += particle.Velocity;
        particle.Orientation = GetAngle(particle.Velocity);
    }

    public void Splash(float xPosition, float speed)
    {
        int index = (int)MathHelper.Clamp(xPosition / Scale, 0, columns.Length - 1);
        for (int i = Math.Max(0, index - 0); i < Math.Min(columns.Length - 1, index + 1); i++)
            columns[index].Speed = speed;

        CreateSplashParticles(xPosition, speed);
    }

    private void CreateSplashParticles(float xPosition, float speed)
    {
        float y = GetHeight(xPosition);

        if (speed > 120)
        {
            for (int i = 0; i < speed / 8; i++)
            {
                Vector2 pos = new Vector2(xPosition, y) + GetRandomVector2(40);
                Vector2 vel = FromPolar(MathHelper.ToRadians(GetRandomFloat(-150, -30)), GetRandomFloat(0, 0.5f * (float)Math.Sqrt(speed)));
                CreateParticle(pos, vel);
            }
        }
    }

    private void CreateParticle(Vector2 pos, Vector2 velocity)
    {
        particles.Add(new Particle(pos, velocity, 0));
    }

    private Vector2 FromPolar(float angle, float magnitude)
    {
        return magnitude * new Vector2((float)Math.Cos(angle), (float)Math.Sin(angle));
    }

    private float GetRandomFloat(float min, float max)
    {
        return (float)rand.NextDouble() * (max - min) + min;
    }

    private Vector2 GetRandomVector2(float maxLength)
    {
        return FromPolar(GetRandomFloat(-MathHelper.Pi, MathHelper.Pi), GetRandomFloat(0, maxLength));
    }

    private float GetAngle(Vector2 vector)
    {
        return (float)Math.Atan2(vector.Y, vector.X);
    }

    public void Update()
    {
        for (int i = 0; i < columns.Length; i++)
            columns[i].Update(Dampening, Tension);

        float[] lDeltas = new float[columns.Length];
        float[] rDeltas = new float[columns.Length];

        // do some passes where columns pull on their neighbours
        for (int j = 0; j < 8; j++)
        {
            for (int i = 0; i < columns.Length; i++)
            {
                if (i > 0)
                {
                    lDeltas[i] = Spread * (columns[i].Height - columns[i - 1].Height);
                    columns[i - 1].Speed += lDeltas[i];
                }
                if (i < columns.Length - 1)
                {
                    rDeltas[i] = Spread * (columns[i].Height - columns[i + 1].Height);
                    columns[i + 1].Speed += rDeltas[i];
                }
            }

            for (int i = 0; i < columns.Length; i++)
            {
                if (i > 0)
                    columns[i - 1].Height += lDeltas[i];
                if (i < columns.Length - 1)
                    columns[i + 1].Height += rDeltas[i];
            }
        }

        foreach (var particle in particles)
            UpdateParticle(particle);

        particles = particles.Where(x => x.Position.X >= 0 && x.Position.X <= 800 && x.Position.Y - 5 <= GetHeight(x.Position.X)).ToList();
    }

    public void DrawToRenderTargets()
    {
        GraphicsDevice device = spriteBatch.GraphicsDevice;
        device.SetRenderTarget(metaballTarget);
        device.Clear(Color.Transparent);

        // draw particles to the metaball render target
        spriteBatch.Begin(0, BlendState.Additive);
        foreach (var particle in particles)
        {
            Vector2 origin = new Vector2(particleTexture.Width, particleTexture.Height) / 2f;
            spriteBatch.Draw(particleTexture, particle.Position, null, Color.White, particle.Orientation, origin, 2f, 0, 0);
        }
        spriteBatch.End();

        // draw a gradient above the water so the metaballs will fuse with the water's surface.
        pb.Begin(PrimitiveType.TriangleList);

        const float thickness = 20;
        float scale = Scale;
        for (int i = 1; i < columns.Length; i++)
        {
            Vector2 p1 = new Vector2((i - 1) * scale, columns[i - 1].Height);
            Vector2 p2 = new Vector2(i * scale, columns[i].Height);
            Vector2 p3 = new Vector2(p1.X, p1.Y - thickness);
            Vector2 p4 = new Vector2(p2.X, p2.Y - thickness);

            pb.AddVertex(p2, Color.White);
            pb.AddVertex(p1, Color.White);
            pb.AddVertex(p3, Color.Transparent);

            pb.AddVertex(p3, Color.Transparent);
            pb.AddVertex(p4, Color.Transparent);
            pb.AddVertex(p2, Color.White);
        }

        pb.End();

        // save the results in another render target (in particlesTarget)
        device.SetRenderTarget(particlesTarget);
        device.Clear(Color.Transparent);
        spriteBatch.Begin(0, null, null, null, null, alphaTest);
        spriteBatch.Draw(metaballTarget, Vector2.Zero, Color.White);
        spriteBatch.End();

        // switch back to drawing to the backbuffer.
        device.SetRenderTarget(null);
    }

    public void Draw()
    {
        Color lightBlue = new Color(0.2f, 0.5f, 1f);

        // draw the particles 3 times to create a bevelling effect
        spriteBatch.Begin();
        spriteBatch.Draw(particlesTarget, -Vector2.One, new Color(0.8f, 0.8f, 1f));
        spriteBatch.Draw(particlesTarget, Vector2.One, new Color(0f, 0f, 0.2f));
        spriteBatch.Draw(particlesTarget, Vector2.Zero, lightBlue);
        spriteBatch.End();

        // draw the waves
        pb.Begin(PrimitiveType.TriangleList);
        Color midnightBlue = new Color(0, 15, 40) * 0.9f;
        lightBlue *= 0.8f;

        float bottom = spriteBatch.GraphicsDevice.Viewport.Height;
        float scale = Scale;
        for (int i = 1; i < columns.Length; i++)
        {
            Vector2 p1 = new Vector2((i - 1) * scale, columns[i - 1].Height);
            Vector2 p2 = new Vector2(i * scale, columns[i].Height);
            Vector2 p3 = new Vector2(p2.X, bottom);
            Vector2 p4 = new Vector2(p1.X, bottom);

            pb.AddVertex(p1, lightBlue);
            pb.AddVertex(p2, lightBlue);
            pb.AddVertex(p3, midnightBlue);

            pb.AddVertex(p1, lightBlue);
            pb.AddVertex(p3, midnightBlue);
            pb.AddVertex(p4, midnightBlue);
        }

        pb.End();
    }
}

```

Then in the Game1.cs I have the following LoadContent method

```
protected override void LoadContent()
    {
        // Create a new SpriteBatch, which can be used to draw textures.
        spriteBatch = new SpriteBatch(GraphicsDevice);
        font = Content.Load<SpriteFont>("Font");
        particleImage = Content.Load<Texture2D>("metaparticle");
        backgroundImage = Content.Load<Texture2D>("sky");
        rockImage = Content.Load<Texture2D>("rock");
        water = new Water(GraphicsDevice, particleImage);
        .
        .
        .
    }

```

In my update method I have the following (along with other code for the game, i am just showing water part)

```
protected override void Update(GameTime gameTime)
    {
        lastKeyState = keyState;
        keyState = Keyboard.GetState();
        lastMouseState = mouseState;
        mouseState = Mouse.GetState();

        water.Update();

        Vector2 mousePos = new Vector2(mouseState.X, mouseState.Y);
        // if the user clicked down, create a rock.
        if (lastMouseState.LeftButton == ButtonState.Released && mouseState.LeftButton == ButtonState.Pressed)
        {
            rock = new Rock
            {
                Position = mousePos,
                Velocity = (mousePos - new Vector2(lastMouseState.X, lastMouseState.Y)) / 5f
            };
        }

        // update the rock if it exists
        if (rock != null)
        {
            if (rock.Position.Y < 240 && rock.Position.Y + rock.Velocity.Y >= 240)
                water.Splash(rock.Position.X, rock.Velocity.Y * rock.Velocity.Y * 5);

            rock.Update(water);

            if (rock.Position.Y > GraphicsDevice.Viewport.Height + rockImage.Height)
                rock = null;
        }

```

Then in the Draw method I have the following (when the active enum is InGame)

```
case ActiveScreen.InGame:

                water.DrawToRenderTargets();
                level.Draw(gameTime, spriteBatch);
                DrawHud();
                spriteBatch.Begin();
                spriteBatch.Draw(backgroundImage, Vector2.Zero, Color.White);

                if (rock != null)
                    rock.Draw(spriteBatch, rockImage);
                spriteBatch.End();
                water.Draw();

                break;

```

My problem is this obviously takes up the entire screen. I realise why it takes up the entire screen but I can't figure out how to scale it down and set it on a fixed location in the game. If anyone could read through this and direct me towards how I would go about scaling this down successfully, I'd greatly appreciate it.

# Answer
Well, there are two ways of doing this:

1. Draw the entire `Water` object to a render target, then draw the final water target scaled and on the position you want. (this is the simplest way).
2. Draw the `Water` in a constrained area. For this you'll need do to something like this:
    * Create the `Water` by specifying a `Rectangle` as target in the constructor.
    * Every reference to `GraphicsDevice.Viewport` should be replaced with the target rectangle
    * I assume that you will give the 'right' - real - position as the `Splash` method parameter (`xPosition`) so everything else will be fine when drawn.

PS: You said something about `OutOfBoundsException`. Please gives us more details if that's the case anymore.
> 0 votes

---
Tags: xna, c#, 2d, xna-4.0, water
---


title: chasing , zone range

text:
# Question
Title: chasing , zone range
here is an image show what I am gonna to do in my XNA game , I want to check if the player is inside zone range and if yes then attack the player , I tried to do this using checking ray but it's odd and give null results as player must be in front of enemy so he can be detected !

hey every body , I want instead view angle for each enemy ( 3D dimension ):

# Answer
When you use the XNA class Vector2 to represent the positions of the player and the enemies, you can use its method Distance to calculate the distance to another Vector2. Then you just have to check if this is smaller than the radius of the attack circle.

To calculate the distance between two points yourself, you can use the pythagorean theorem.

```
// first get the horizontal and vertical distance.
double distanceX = player.x - enemy.x;
double distanceY = player.y - enemy.y;
// then calculate the length of the hypotenuse of the triangle they form
double dist = sqrt( (distanceX * distanceX) + (distanceY * distanceY) );
if (dist < enemy.attackZoneRadius) {
    enemy.attack(player);
}

```

This example is overly verbose for clarity. The distanceX and distanceY calculations can be put right into the calcualtion of dist:

To improve the performance, you can save the attack zone radius of the enemy already squared. You can then omit the call to sqrt (calculating square-roots is a quite expensive operation) or use the faster XNA Vector2 method DistanceSquared.

**Edit:** You didn't mention that you need this in 3-dimensional space. The XNA Vector3 class supports the methods Distance and DistanceSquared just like the 2d version. When you want to do this manually, the pythagorean theorem still applies in 3d space (I think it applies to any number of dimensions, but that's rather a question for math.stackexchange.com).

```
double distX = player.x - enemy.x;
double distY = player.y - enemy.y;
double distZ = player.z - enemy.z;

double dist = sqrt( (distX * distX) + (distY * distY) + (distZ * distZ) );

```
> 1 votes

---
Tags: xna, geometry
---


title: How to make a fan like behavior

text:
# Question
Title: How to make a fan like behavior
I am making a game in Unity. I have an object e.g. cube. I want to release air from it like fan so that when other cubes come closer, it throws them away. What velocity,force etc I will need to do that?

# Answer
While the aerodynamic effects caused by a fan can be quite complex to model accurately, it is sufficient for most cases to model the force it applies after the Inverse-Square Law.

It means that the force it applies to another object is divided by the distance multiplied with itself.

Another factor you could or could not model depending on how physically correct you want to be is the wind drag of the objects which are pushed by the fan. Wind drag means that objects with a large surface exposed to the wind direction receive more force from the wind than those with a smaller surface (again, overly simplified. The aerodynamics are a lot more complex in reality). When you want to model this, you also need to multiply the force with the surface area of the object which is pushed.

The complete formula would then be:

```
appliedForce = fanForce / (distance * distance) * surfaceArea

```

There is, however, a pitfall in this formula: it has a singularity when the distance is 0. When the distance is below 1, the force will be more than the intended maximum. When the distance gets very small, the force can become extremely strong. This could lead to quite glitchy behavior. To fix this issue, add 1 to your distance calculation, or cap the distance at 1:

```
appliedForce = fanForce / (1.0 + distance * distance) * surfaceArea

```

or

```
if (distance < 1.0) distance = 1.0;
appliedForce = fanForce / (1 + distance * distance) * surfaceArea;

```

More accurate results could be reached by an actual physical simulation of aerodynamics, but this is a highly complex field, both in regards to development time and computational resources. Unless physically accurate aerodynamics are a core gameplay-element of your game, it is unlikely to be worth the hassle.
> 11 votes

# Answer
You could simply calculate the distance ( you can use any mesh for collision clipping to represent the "air flow" limits), the closer it gets the higher the force you apply to it in that direction. Of course this isn't as accurate, but you could add noise to the direction of the velocity.
> 1 votes

---
Tags: unity, physics
---


# Question
Title: Good resources for 2.5D and rendering walls, floors, and sprites
I'm curious as to how games like Prelude of the chambered handle graphics. If you play for a bit you will see what I mean. It made me wonder how it works. (it is open-source so you can get the source on this page) I did find a few tutorials, but I couldn't understand some of it, though it did help with some things. However, I don't like using code that I don't understand. Does anyone know of any good tutorials for this kind of 2.5D? Any help is appreciated.

# Answer
> 4 votes
http://www.permadi.com/tutorial/raycast/index.html

Best tutorial on raycasting i could find when i was researching the topic a couple years back. It's pure theory, no programming. Other than that i suggest you read about the Doom engine and the Build engine. Reading the source code is IMHO far too time consuming (it's pure C and ASM, plus plenty of irrelevant technology quirks) if you just want to understand raycasting. Reading ABOUT the engines however can give you ideas on how to solve advanced issues like doors (as funny as that sounds), check the wiki first.

Here's a great code review by Fabien Sanglard: http://fabiensanglard.net/doomIphone/doomClassicRenderer.php

# Answer
> 4 votes
Here's a very detailed tutorial: Creating pseudo 3D games with HTML 5 canvas and raycasting. The key search term is "pseudo 3d game."

---

Also I posted the text of the tutorials scgrn mentioned. (I think I read these a long time ago. I remember the ASCII diagrams!)

# Answer
> 3 votes
There are a couple of (very) old tutorials on Wolfenstein-style raycasting written by Peroxide. Search for "pxdtut7.zip" and "pxdtut8.zip". The code is written in Pascal but the concepts are explained very well.

# Answer
> 0 votes
I'm not sure on the specifics, but I got a few ideas just by browsing through the source-code of the game @ https://github.com/skeeto/Prelude-of-the-Chambered/tree/master/src/com/mojang/escape

Maybe you can find some things there that will help you.

EDIT: I noticed you had linked to the page, but I meant to specifically link to this file: https://github.com/skeeto/Prelude-of-the-Chambered/blob/master/src/com/mojang/escape/gui/Bitmap3D.java

# Answer
> 0 votes
I'm currently following the tutorial by Lode Vandevenne: http://lodev.org/cgtutor/raycasting.html. Note that this is only part 1 (basic raycasting and textured walls). Part 2 (ceiling and floor textures) and 3 (sprites) can be found by clicking the link "Back to Index".

I think it's great. It contains everything I needed to make my own engine. The tutorial is based on C++, but the concepts are described so well that translation to any language is easy. I'm coding in Java myself.

(I'm doing the vector calculus it a little differently than Lode, however. I'm using 2-element arrays to represent vectors, and a class of static (void) methods to manipulate them, as is done in this more advanced 3D raytracing tutorial by Michael Birken: http://meatfighter.com/juggler/ (also brilliant))

---
Tags: graphics, 2.5d
---


# Question
Title: How would I apply gravity to a bullet so that it would drop slightly the longer that it travels?
How would I apply gravity to a bullet so that it would drop slightly the longer that it travels?

I somewhat understand how the gravity works, Im just asking for second opinions for more optimized ways of doing this.

```
VOID update()
{
    veloc_Y += gravity;//0.5f
    posX += veloc_X;
    posY += veloc_Y;

       if(posY > 650)
       {
           posY = 650.0f;
           veloc_Y = 0.0f;
           on_g = true;//lets my game know im on the ground
       }
}

```

so, would I apply gravity to bullet veloc\_Y?

ex:

```
b_veloc_Y += gravity;
b_pos_Y += b_veloc_Y;

```

would this make my bullet drop?

thanks for help in advance

# Answer
> 1 votes
You'll want to more than just add velocity every frame. That's basic Euler math, but doesn't work properly in a time sliced environment. Specifically, a variable framerate means that you'll get different results.

You'll want to do basic integration. There's a good article that goes into depth on that subject here: http://gafferongames.com/game-physics/integration-basics/

# Answer
> 0 votes
Yes, that's how simplified gravity (or acceleration in general) works. You might want to limit your velocity (and gravity) to something (in reality: terminal velocity), e.g.

```
b_veloc_Y = std::max(-max_veloc_y, std::min(b_veloc_Y + gravity, max_veloc_y));

```

You might want to add some friction as well (maybe even make it velocity dependant) to lower acceleration over time.

---
Tags: c++, physics
---


title: enemy View Range , chase player

text:
# Question
Title: enemy View Range , chase player
for 3D:

Q1 : I want to make zone range for each enemy in the game , so that when the player in the view range he will be chased .

Q2 :if I want to make enemy walk a little bit around his position ( from -10 to 10 ) for example , i.e as he is searching for some one , can you give me just steps ! thanks

Q3 : How to make enemy moves toward Player if he is being detected ?

Sorry for question , but I am new to this world :)

# Answer
**Disclaimer:** This answer is based on the book Artificial Intelligence for Games by Millington and Funge. You should take a look at it for details, and implementations notes at AI4G.com and it's aimed to give readers the general idea trying to avoid copyright infringement.

---

I'm going to answer in reverse order because I think that's the level of difficulty.

Q3: This is called **Seek** behavior.

```
Vector3 character, target;
float maxSpeed;

character.velocity = target.position - character.position;
character.velocity.normalize();
character.velocity *= maxSpeed;
if (velocity.lenght() > 0)
  character.orientation = atan2(-character.velocity.x, character.velocity.z);

```

Q2: This is called **Wander** behavior.

```
float randomBinomial () {
  return random() - random();
}

Vector3 character;
float maxSpeed, maxRotation;
// this is the vector that indicates to where you are looking at
// sometimes it is similar to where you are going (velocity), but not necessarily
character.velocity = maxSpeed * character.orientation.asVector();
// rotation is the speed at which you change the orientation per frame
character.rotation = randomBinomial() * maxRotation;

```

It's important to note that if Wander behavior is not exactly what you're trying to achieve (because you want to be always inside the area), the best option I can offer is to apply the Seek behavior to a random target in the circumference. Once you reach the target (or are pretty close to it), generate a new point. This way you can monitor a given area and avoid getting similar random points inside the circle.

EDIT: You can checkout my implementations of some of those behaviors in XNA here. They are in the GLaDOS class. However, you can checkout the code from the book and translate it from C++ into C# with almost no problem at all. A little bit of patience :)

Q1:

This one is a bit tricky and could be solved differently. You can shoot several rays to where you are looking at given a threshold (cone aperture), ray distance and number of rays (one per degree, maybe). If the ray hits the target, apply seek behavior.

A cheaper way is to shoot the ray and, given the threshold, you check collision detection inside the area of the rectangle (is not that precise, but gives the same idea).

Finally, you can shoot the ray and create two triangles. If the object collides with either one of them, that's it.

EDIT: 3D collision detection is well covered in Stack Overflow here and here. They helped a friend of mine last year.
> 6 votes

---
Tags: xna, ai, geometry
---


title: Roulette Table Ball Movement Creation

text:
# Question
Title: Roulette Table Ball Movement Creation
I am developing following type of game Roulette Royale.

I am basically ready with wheel and number table. When user move wheel table then ball also move on that table and stop at particular number and reply to number table with that number.

Right now I only used RotationModifier and there is no position change at present only ball rotate and stop at randomly selected number. This thing work well.

But I want ball start its movement from out side the wheel and slowly move inside in to the wheel. It perform rotation as well as smoothly move towards the center of the wheel. This functionality I don't able to conceptualise how to create?

I think there is no need to put any code snippet here because I need only concept how to perform this task. Thanks in advance efforts you take for me.

# Answer
> 0 votes
I have found solution for my problem, here I paste it to help other members.

```
             ballSprite = new Sprite(wheelSprite.getWidth() * 0.5f,
                            wheelSprite.getHeight() * 0.5f, ballRegion.getWidth() * 0.6f,
                            ballRegion.getHeight() * 0.6f, ballRegion.deepCopy(),
                            getVertexBufferObjectManager()) {

                    @Override
                    protected void onManagedUpdate(float pSecondsElapsed) {

                            if (isMoveInside)
                                    ballSprite
                                                    .setAnchorCenterY(pAnchorCenterY -= (pSecondsElapsed * 0.25f));
                            super.onManagedUpdate(pSecondsElapsed);
                    }

            };
            ballSprite.setAnchorCenterY(pAnchorCenterY);
            wheelSprite.attachChild(ballSprite);

            ballSprite.registerEntityModifier(new LoopEntityModifier(
                            new RotationModifier(5f, 0f, 360f), 2,
                            new IEntityModifierListener() {

                                    @Override
                                    public void onModifierStarted(IModifier<IEntity> pModifier,
                                                    IEntity pItem) {
                                            isMoveInside = true;
                                    }

                                    @Override
                                    public void onModifierFinished(
                                                    IModifier<IEntity> pModifier, IEntity pItem) {
                                            isMoveInside = false;
                                    }
                            }));

```

---
Tags: andengine
---


title: Creating 2D polygons in XNA

text:
# Question
Title: Creating 2D polygons in XNA
I am trying to implement collisions using the separating axis theorem. However All I have ever used in terms of polygons is the Rectangle class included in XNA already. How can I make multi-sided polygons?

# Answer
You can draw triangles directly using DrawUserIndexedPrimitives and other similar functions. Yes, it is much more work than simply drawing rectangles.

Example code: http://msdn.microsoft.com/en-us/library/bb196414(v=xnagamestudio.40).aspx
> 1 votes

---
Tags: xna, collision-detection
---


# Question
Title: Determining which edge a collision occurred on in a platformer
First of all, this will be Open Source, and you will be mentioned for the help.

---

We've been programming a Super Mario Remake for the iPhone with Cocos2d for school.
It looks pretty great, and we decided to make it Open Source, because we can't get any profit because of Copyright issues.

We programmed the physics on our own, but it has a few issues.

Collisions are constantly checked, and this is how I do it:

---

## Collision Handling

```
- (void)updateCollisions:(ccTime)delta {
    for (STGameObject *child in self.gameObjects) {
        for (STGameObject *child2 in self.gameObjects) {
            // Don't check same object
            if (child == child2) {
                break;
            }

            if (STRectIntersect(child.boundingBox, child2.boundingBox)) {
                // Position objects
                STRectEdge edge1 = [self updateCollisionOfGameObject:child withGameObject:child2 delta:delta];
                STRectEdge edge2 = [self updateCollisionOfGameObject:child2 withGameObject:child delta:delta];

                // Send notifications
                [child collisionWithGameObject:child2 edge:edge1];
                [child2 collisionWithGameObject:child edge:edge2];
            }
        }
    }
}

- (STRectEdge)updateCollisionOfGameObject:(STGameObject *)gameObject
                           withGameObject:(STGameObject *)gameObject2
                                    delta:(ccTime)delta {

    STRectEdge rectEdge;
    float edgeLeft = (gameObject.boundingBox.origin.x - gameObject2.boundingBox.origin.x - gameObject.boundingBox.size.width) * -1;
    float edgeRight = (gameObject.boundingBox.origin.x + gameObject2.boundingBox.size.width - gameObject2.boundingBox.origin.x);
    float edgeTop = (gameObject.boundingBox.origin.y + gameObject.boundingBox.size.height - gameObject2.boundingBox.origin.y);
    float edgeBottom = (gameObject.boundingBox.origin.y - gameObject2.boundingBox.size.height - gameObject2.boundingBox.origin.y) * -1;

    float offset = 0.0;
    if (edgeLeft < edgeRight) {
        rectEdge = STRectEdgeMinX;
        offset = edgeLeft;
    } else {
        rectEdge = STRectEdgeMaxX;
        offset = edgeRight;
    }

    if (edgeTop < edgeBottom) {
        float cached = edgeTop;
        if (cached < offset) {
            rectEdge = STRectEdgeMaxY;
            offset = cached;
        }
    } else {
        float cached = edgeBottom;
        if (cached < offset) {
            rectEdge = STRectEdgeMinY;
            offset = cached;
        }
    }

    if (gameObject.bodyType != STGameObjectBodyTypeStatic) {
        if (gameObject2.bodyType != STGameObjectBodyTypeStatic) {
            offset /= 2.0;
        }

        if ([gameObject bodyType] != STGameObjectBodyTypeNonColliding && [gameObject2 bodyType] != STGameObjectBodyTypeNonColliding) {
            switch (rectEdge) {
                case STRectEdgeMinX:
                {
                    [gameObject move:ccp(offset, 0)];
                }
                    break;
                case STRectEdgeMaxX:
                {
                    [gameObject move:ccp(-offset, 0)];
                }
                    break;
                case STRectEdgeMinY:
                {
                    [gameObject move:ccp(0, offset)];
                }
                    break;
                case STRectEdgeMaxY:
                {
                    [gameObject move:ccp(0, -offset)];
                }
                    break;
            }

            if (rectEdge == STRectEdgeMinY && gameObject.velocity.y < 0) {
                gameObject.velocity = ccp(gameObject.velocity.x, 0);
            }
            if (rectEdge == STRectEdgeMaxY && gameObject.velocity.y > 0) {
                gameObject.velocity = ccp(gameObject.velocity.x, 0);
            }
        }
    }

    return rectEdge;
}

```

---

It basically checks which collision edge of the rect is the smallest (easiest to adjust).
The problem now is the following

As you can see, if Mario collapses a brick at it's bottom edge, it will look like there was a collision at the minimum Y edge. However, this is not the case. This causes to constantly destroy blocks, even though there was no real collision at this edge, but rather at the minimum X edge.

Any ideas how to resolve this?

# Answer
Ok, i'm assuming your existing collision detection has determined that a corner collision has occurred and the only question that remains is "Which edge hit first".

This is equivalent to the question "which has been inside the edge the least time". This is because if you imagine the edge as being an infinite length then for a collision to occure between object A and object B BOTH edges of object B must be inside the infinite lines of A. The second component to achieve this "makes" the collision and is the colliding edge. Note that for a usual collision on say just the low X edge the object has been inside the infinite Y edges for a very long time (maybe the entire game)

```
TimeInsideObject=CollisionDepthOnAxis/RelativeVelocityOnAxis

```

(eg if something is 1 metre inside and is travelling at 10m/s it has been inside for 0.1 seconds)

So if the penitration depths are:

```
 x=0.1m and y=0.2m

```

and the relative velocities are:

```
 xV=10m/s and yV=0.1m/s

```

the times inside the object (on each axis) are:

```
X: TimeInsideobject=0.1/10=0.01 seconds
Y: TimeInsideobject=0.2/0.1=2 seconds

```

So axis X "made" the collision so its a low or high X edge that actually had the collision.

Before Collision:
After Collision:

You should also resolve your collisions in the order they occure based upon this value, for example, mario collided with the lower bricks low X side before he collided with the upper bricks low Y side, if the lower brick collision is resolved first then no collision with the upper bricks occures
> 2 votes

# Answer
Now that you are implementing the physics on your own, as well as the collision code, I think the best answer lies within this tutorial. After the effect from the collision is calculated, you just consider the closest edge based on the average X position.
> 1 votes

# Answer
Don't collide against inner edges. A simple pass over your tiles can determine if the tile borders an open space on any particular edge. Set a glag for each edge in a given tile marking if its an outer edge (collideable) or inner edge (ignored).

One nice trick while testing this and other physics is to have a debug draw mode that renders all outer edges. If you turn off regular tile drawing you should see the outline of your world.
> 1 votes

---
Tags: collision-detection, iphone, collision-resolution, platformer
---


title: animating roulette ball

text:
# Question
Title: animating roulette ball
I'm trying to achieve something like netent's roulette (which is a great product in my opinion). It's going to be implemented in html5.

I wonder which path should I take to have such a great animation for spinning ball. My problem is that the random number is generated on the server, thus using any of currently available physics engines means loose control of the ball, I mean that it will be hard to apply forces in such a manner that ball hits the right slot. Another option is to make my own a pseudo physics. "Pseudo" because it should always keep track of destination point. It is pretty much like playing animation generated backwards.

# Answer
Here's a trick to simplify things, based on the fact that all slots are the same size and shape:

1. Run a physics simulation with random input parameters but instead of rendering it just store the ball position and wheel rotation for each frame so you can replay it later.
2. Work out which slot the ball has landed in.
3. Calculate the angle between that slot and the one you actually want it to land in. This will be one of 37 values if there's a single zero on the wheel {0, 360/37 ..., (360\*36)/37}.
4. Render the animation sequence you recorded, but with the wheel rotated by that angle from step 3. The ball will now land in the correct slot.
> 1 votes

---
Tags: javascript, animation, html5, physics-engine
---


# Question
Title: Gamemaker: Making a bullet Spawn at the enemy it was called from
I'm making a gamemaker game with gml. In this game I have multiple enemies (same object) on screen at the same time. I want them to all spawn a bullet at their location. But instead each enemy spawns a bullet at one single enemy. They all shoot but the bullets appear in the wrong location. I want the bullet to spawn at the location of the instance is was called for. How do I do this?

Thank you for reading my question.

Code: obj\_carrier is the enemy I want to spawn from. obj\_carrier\_bullet is the bullet I want to spawn at location of the carrier There are multiple carriers around the stage. In the step event of the carrier following an if statement:

```
   instance_create(obj_carrier.x, obj_carrier.y, obj_carrier_bullet)

```

# Answer
> 2 votes
If you are creating/spawning the bullet from within the obj\_carrier that is to create the bullet (ie inside its step event, or alarm event, etc), you can just use x and y:

```
instance_create(x, y, obj_carrier_bullet);

```

If you are creating it from a different object, you will have to figure out which object it is and create it from there (ie:

```
var objectThatWillCreateBullet = instance_create(random(room_width), random(room_height), obj_carrier);
instance_create(objectThatWillCreateBullet.x, objectThatWillCreateBullet.y, obj_carrier_bullet);

```

This is probably not what you are doing though).

If you want all obj\_carrier's to create a bullet at once, you can do:

```
with(obj_carrier) {
    instance_create(x,y,obj_carrier_bullet);
}

```

---
Tags: game-maker
---


title: Farseer: How can I remove a body?

text:
# Question
Title: Farseer: How can I remove a body?
I have many sensors(coins) in each level and I want to remove the sensors(coins) when the player rectangle(Mario) touches them. I check in OnCollision if Mario touches a coin, if he touches it, it should be removed. But I don't know how to remove a body.

What is the best way to remove a body?

How can I remove a coin in this example?

```
bool Player_OnCollision(Fixture fixtureA, Fixture fixtureB, FarseerPhysics.Dynamics.Contacts.Contact contact)
    {
      if (fixtureB.CollisionCategories == Category.Cat10)
        {

        }
        return true;
    }

 coinrect = BodyFactory.CreateRectangle(world, 0.64f, 0.64f, 1.0f);
 coinrect.BodyType = BodyType.Static;
 coinrect.Position = new Vector2(1.60f, 4.16f);
 coinrect.CollisionCategories = Category.Cat10;

 coinrect2 = BodyFactory.CreateRectangle(world, 0.64f, 0.64f, 1.0f);
 coinrect2.BodyType = BodyType.Static;
 coinrect2.Position = new Vector2(2.60f, 3.16f);
 coinrect2.CollisionCategories = Category.Cat10;

 playerrect = BodyFactory.CreateRectangle(world, 0.64f, 0.64f, 1.0f);
 playerrect.BodyType = BodyType.Dynamic;
 playerrect.Position = new Vector2(0.22f, 0f);
 playerrect.FixedRotation = true;

 playerrect.OnCollision += Player_OnCollision;

```

# Answer
Body.Dispose(bodyhere) is what you are looking for. It removes the body as well as all attached features. If you do not want to move Body.Dispose you can use World.RemoveBody(bodyhere) which removes the body after the current step. I would recommend you use the latter though.
> 1 votes

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


# Question
Title: Changing color of a moving image without lowering the fps
I just added an option to my game that makes it so that all the enemies will have a random color for their clothes instead of the regular blue. I use this code to draw rectangles over the shirt of the enemy.

```
BufferedImage image = new BufferedImage(z.getWidth(), z.getHeight(),
    BufferedImage.TYPE_4BYTE_ABGR);
try{
    image = ImageIO.read(new File("C:\\Program Files (x86)\\ZombieGame\\
        Zombie.png"));
}catch (IOException ex) {
}
int j, k, red, green, blue;
    for(j = 0; j < z.getWidth(); j++){
        for(k = 0; k < z.getHeight(); k++){
            Color c = new Color(image.getRGB(j, k));
            red = c.getRed();
            green = c.getGreen();
            blue = c.getBlue();
            if(red == 0 && green == 0 && blue == 178){
                g2d.setColor(Color.red);
                Rectangle r = new Rectangle(j,k, 1, 1);
                Path2D.Double rect = new Path2D.Double(r, at);
                g2d.fill(rect);
            }
        }
    }

```

The thing is that when I apply this the game will run twice as slow (before I added this code I got a solid 80 fps but as fast as I added it I got around 30 fps). Is there a better way in which I could change the color of specific parts of the image without lowering the fps drastically?

# Answer
You would probably be better off having your artists produce variations on the default color set, and decide which one to use when the zombie is initially created. The implementation you are using now performs per texel checks to only change a specific color, and say your image is 100x100, that is 10,000 color checks per zombie, on top of the final draw calls. This is a ton of run time overhead just for changing a color. Instead, you could simply select a random texture when the zombie is initially created using a single call to a random function.
> 2 votes

# Answer
Evan seems correct. It may also be possible to divide the zombies into two textures; one consisting of any parts of them not likely to change color (ie, skin) simply floating in midair, and another for parts of them that may change tint (ie, shirt). You could draw these on top of each other, and specify a tint color only for the second texture in the SpriteBatch call.

I still feel like there may be a better option; I'm fairly sure there was some innovative approach to this in RTS's like Age of Empires and Starcraft (in which each side's units have bits of a certain color on them).
> 0 votes

# Answer
You could reserve a certain color value in your image to be the "tint color", something you are unlikely to actually use like (0, 255, 0). Then create a function that copies the image and loops through all the pixels, every time you find the tint color replace it with some other color using setRGB().

Then for each zombie variant, create a new variation of the image:

```
BufferedImage redZombie = tintImage(image, red);
BufferedImage greenZombie = tintImage(image, green);

```

If you were using openGL or DirectX I would have recommended just doing it in a pixel shader.
> 0 votes

# Answer
Evan is right if you have the artist bandwidth, otherwise, you could make this algorithm a lot more efficient. The issue you have is that you're twiddling individual bits in about the most expensive possible way you could.

Right now, you're testing each pixel individually to see if it's blue and changing it if it is - however, you said that you're drawing rectangles

A) Consider making a Boolean, say `IsBlueEnemy` that indicates that the enemy instance is in fact blue - or you could make this a color property with value 0,0,178, eg `EnemyColorProperty`

B) If the enemies are all of the same size, then either define constants that give the X and Y origin and the width and height of the rectangle, or define a static rectangle that you reuse (I did the former to illustrate, but the latter is preferable)

C) Now fill the whole rectangle in one fell swoop (note I am not defining g2d and at since you didn't either :-) )

```
 if(IsBlueEnemy)
 {
     g2d.setColor(Color.red);
     Rectangle r = new Rectangle(RECT_ORIGIN_X,RECT_ORIGIN_Y, COLORWIDTH,COLORHEIGHT);
     Path2D.Double rect = new Path2D.Double(r, at);
     g2d.fill(rect);
     IsBlueEnemy = false;
}

```

If you don't really have a solid rectangle, i.e. there are occlusions you don't want to paint, then you need to dig into the image and get a hold of the raw bits and manipulate those - the bottom line is that the routines you're using are very expensive and are really only useful for messing with a few bits at a time if you're concerned with performance
> 0 votes

---
Tags: java, graphics, image, color
---


# Question
Title: How to design a GUI / controls system classes
I'm at the stage when I need to develop some kind of GUI with windows, clickable buttons, etc. It's going to be a RPG game so these components will be used extensively so I want them to be as flexible as possible.

I was thinking about something like winform controls funcionality though much simpler, I don't think I'll need anything more than a window/panel, button, label and image controls.

So far I made abstract Component class which basic attributes like position, width/height and two events - mouseover and click. All controls will be derived from this base class.

```
public abstract class Component
{

    public event EventHandler MouseOver;
    public void OnMouseOver()
    {
        if(MouseOver != null)
            MouseOver(this, null);
    }

    public event EventHandler Click;
    public void OnClick()
    {
        if (Click != null)
            Click(this, null);
    }

    private Rectangle componentRectangle;
    private bool isVisible;

}

```

My question is how to integrate my controls with the rest of the game, I was thinking about something like GUIManager class that would contain the list of controls and manage displaying them and firing events. I'll be calling the update method somewhere in the game loop.

```
public class GUIManager
{
    private List<Component> componenets;

    public void Update(Vector2 mouseLocation)
    {
        foreach (Component component in componenets)
        {
            if (component.IsVisible)
            {   // mouse is over component
                if (component.ComponentRectangle.Contains((int)mouseLocation.X, (int)mouseLocation.Y))
                {
                    component.OnMouseOver();
                }
            }
        }
    }
}

```

Now lets say I want to show character's inventory screen. Is it a good way to just create the controls, add events and then them to GUIManager's controls list to take care of it? Or maybe you can suggest some entirely diffrent approach?

# Answer
There's a number of things you're sort of missing, but it's not something I blame you for - to be honest, UI frameworks involve quite a lot of logic you wouldn't quite think of, depending on how advanced they need to be. For one thing, to avoid having 'MouseOver' when the user's mouse is simply sitting still, you may want to save the last MouseState value, and make comparisons from the currentMouseState to lastMouseState (make sure it moved)

You'll also likely want a sorting order for UI Components, so you could display submenus over main menus. (Equip Large Shield to which character?) and probably some sort of system to determine which object in your game will "receive" the player's input - and it can only be one object at a time (you don't want your game's character moving around as someone is navigating a menu)

If you're willing to consider the idea of coding your menus in HTML and CSS, another answer I recall linked to this, which appears to be free for indie developments.
> 2 votes

# Answer
I use Neoforce controls. They act just like winform controls. If you can use winform, you can use NF.

Works great in my XNA 4.0 project.
> 2 votes

# Answer
I agree with Katana, making a GUI system is harder than it may appear. I was working on one until I found that I was spending more time writing & fixing the GUI library than working on my game.

Alternatives that I looked at were Ruminate XNA, and Awesomium (more specifically Awesomium .NET). I ended up picking Awesomium, and MindWorX and I built an Awesomium component for XNA. Personally, I love it. Working with HTML, CSS, and JavaScript libraries like jQuery, jQueryUI, and AngularJS have really made UI development much nicer for me.

If you really want to develop your own GUI for personal reasons, I'd take a quick peek at my abandoned project on BitBucket, just to get a sense of what you're getting in to. It has buttons, panels that can be moved around, list boxes (partially implemented), text boxes (wow hard), and the concept of screens that you can transition between. Your code above looks like a good start.
> 0 votes

---
Tags: xna, gui
---


title: Why DirectInput is not recommended?

text:
# Question
Title: Why DirectInput is not recommended?
I have read that the Windows messages are recommended way over DirectInput to control mouse and keyboard.

From http://msdn.microsoft.com/en-us/library/windows/desktop/ee416842(v=vs.85).aspx

> The use of DirectInput for keyboard and mouse input is not recommended. You should use Windows messages instead.

Why is it so? Because the DirectInput is still in version 8? Isn't it extending anymore?

# Answer
> 7 votes
Well, it's deprecated, so that's the biggest reason you'd want to avoid it.

All it does is sit on top of other Windowing APIs (Raw Input in particular) and never really provided a significantly useful abstraction that justified bothering with it, especially since for everything except (non-360) joysticks and whatnot, everything you could do with it you could probably do more efficiently and more readily with Windows messages or Raw Input itself.

A Windows game has to have a Windows message pump anyway, so you may as well use that. DirectInput additionally had poor internationalization and multi-window support (which in practice could become an issue if you ever embedded your game engine into a tool, for example).

---
Tags: directx
---