# Question
Title: Hue, saturation, brightness, contrast effect in hlsl
I am new to pixel shader, and I am trying to write a simple brightness, contrast, hue, saturation effect. I have written a shader for it but I doubt that my shader is not providing me correct result, Brightness, contrast, saturation is working fine, problem is with hue. if I apply hue between -1 to 1, it seems to be working fine, but to make things more sharp, I need to apply hue value between -180 and 180, like we can apply hue in Paint.NET.

Here is my code.

```
// Amount to shift the Hue, range 0 to 6
float Hue;
float Brightness;
float Contrast;
float Saturation;
float Alpha;

sampler Samp : register(S0);

// Converts the rgb value to hsv, where H's range is -1 to 5
float3 rgb_to_hsv(float3 RGB)
{
    float r = RGB.x;
    float g = RGB.y;
    float b = RGB.z;

    float minChannel = min(r, min(g, b));
    float maxChannel = max(r, max(g, b));

    float h = 0;
    float s = 0;
    float v = maxChannel;

    float delta = maxChannel - minChannel;

    if (delta != 0)
    {
        s = delta / v;

        if (r == v) h = (g - b) / delta;
        else if (g == v) h = 2 + (b - r) / delta;
        else if (b == v) h = 4 + (r - g) / delta;
    }

    return float3(h, s, v);
}

float3 hsv_to_rgb(float3 HSV)
{
    float3 RGB = HSV.z;

    float h = HSV.x;
    float s = HSV.y;
    float v = HSV.z;

    float i = floor(h);
    float f = h - i;

    float p = (1.0 - s);
    float q = (1.0 - s * f);
    float t = (1.0 - s * (1 - f));

    if (i == 0) { RGB = float3(1, t, p); }
    else if (i == 1) { RGB = float3(q, 1, p); }
    else if (i == 2) { RGB = float3(p, 1, t); }
    else if (i == 3) { RGB = float3(p, q, 1); }
    else if (i == 4) { RGB = float3(t, p, 1); }
    else /* i == -1 */ { RGB = float3(1, p, q); }

    RGB *= v;

    return RGB;
}

float4 mainPS(float2 uv : TEXCOORD) : COLOR
{
    float4 col = tex2D(Samp, uv);

    float3 hsv = rgb_to_hsv(col.xyz);

    hsv.x += Hue;
    // Put the hue back to the -1 to 5 range
    //if (hsv.x > 5) { hsv.x -= 6.0; }
    hsv = hsv_to_rgb(hsv);
    float4 newColor = float4(hsv,col.w);

    float4 colorWithBrightnessAndContrast = newColor;

    colorWithBrightnessAndContrast.rgb /= colorWithBrightnessAndContrast.a;
    colorWithBrightnessAndContrast.rgb = colorWithBrightnessAndContrast.rgb + Brightness;
    colorWithBrightnessAndContrast.rgb = ((colorWithBrightnessAndContrast.rgb - 0.5f) * max(Contrast + 1.0, 0)) + 0.5f;
    colorWithBrightnessAndContrast.rgb *= colorWithBrightnessAndContrast.a;

    float greyscale = dot(colorWithBrightnessAndContrast.rgb, float3(0.3, 0.59, 0.11));
    colorWithBrightnessAndContrast.rgb = lerp(greyscale, colorWithBrightnessAndContrast.rgb, col.a * (Saturation + 1.0));
    return colorWithBrightnessAndContrast;
}

technique TransformTexture {
    pass p0 {
        PixelShader = compile ps_2_0 mainPS();
    }
}

```

Please If anyone can help me learning what am I doing wrong or any suggestions? Any help will be of great value.

EDIT: Images of the effect at hue 180:

On the left hand side, the effect I got with @teodron answer. On the right hand side, The effect Paint.NET gives and I'm trying to reproduce.

# Answer
```
Finally I figured it out.
This shader worked for me.

// Amount to shift the Hue, range 0 to 6
float Hue;
float Brightness;
float Contrast;
float Saturation;

sampler Samp : register(S0);
float3x3 QuaternionToMatrix(float4 quat)
{
    float3 cross = quat.yzx * quat.zxy;
    float3 square= quat.xyz * quat.xyz;
    float3 wimag = quat.w * quat.xyz;

    square = square.xyz + square.yzx;

    float3 diag = 0.5 - square;
    float3 a = (cross + wimag);
    float3 b = (cross - wimag);

    return float3x3(
    2.0 * float3(diag.x, b.z, a.y),
    2.0 * float3(a.z, diag.y, b.x),
    2.0 * float3(b.y, a.x, diag.z));
}

const float3 lumCoeff = float3(0.2125, 0.7154, 0.0721);

float4 mainPS(float2 uv : TEXCOORD) : COLOR
{
    float4 outputColor = tex2D(Samp, uv);
    float3 hsv;
    float3 intensity;
        float3 root3 = float3(0.57735, 0.57735, 0.57735);
        float half_angle = 0.5 * radians(Hue); // Hue is radians of 0 tp 360 degree
        float4 rot_quat = float4( (root3 * sin(half_angle)), cos(half_angle));
        float3x3 rot_Matrix = QuaternionToMatrix(rot_quat);
        outputColor.rgb = mul(rot_Matrix, outputColor.rgb);
        outputColor.rgb = (outputColor.rgb - 0.5) *(Contrast + 1.0) + 0.5;
        outputColor.rgb = outputColor.rgb + Brightness;
        intensity = float(dot(outputColor.rgb, lumCoeff));
        outputColor.rgb = lerp(intensity, outputColor.rgb, Saturation );

    return outputColor;
}
technique TransformTexture {
    pass p0 {
        PixelShader = compile ps_2_0 mainPS();
    }
}

```
> 2 votes

# Answer
**UPDATE** Basic maths: if your input is a variable called *X* and lies in the \[a,b\] interval, but you'd like to have it translated to the \[c,d\] interval, the common sense way of doing that is via a linear/affine transformation (affine operators are functions of the form *AoX+B* where *o* is a multiplication like operation - A and X could be matrices or other multidimensional elements).

For a scalar *x* in *\[a,b\]* we have the following transform:

```
 x <- ((x-a)/(b-a))*(d-c) + c

```

(x-a)/(b-a) takes x from \[a,b\] into the \[0,1\] range, `*(d-c)` scales it to the \[0,d-c\] interval and adding the *c* moves it to the \[c,d\] desired range. Hope my maths are right now..

If you want to go between -180 and 180 degs, you need to linearly shift the hue.. something like this should work with hues in the `[-180, 180]` interval:

```
float3 hsv_to_rgb(float3 HSV)
{
float3 RGB = HSV.z;

float h = (HSV.x+180)/60.0; //get a hue in the 0..5 interval from the -180 180 intv
float s = HSV.y;
float v = HSV.z;

float i = floor(h);
float f = h - i;

float p = (1.0 - s);
float q = (1.0 - s * f);
float t = (1.0 - s * (1 - f));

if (i == 0) { RGB = float3(1, t, p); }
else if (i == 1) { RGB = float3(q, 1, p); }
else if (i == 2) { RGB = float3(p, 1, t); }
else if (i == 3) { RGB = float3(p, q, 1); }
else if (i == 4) { RGB = float3(t, p, 1); }
else /* i == -1 */ { RGB = float3(1, p, q); }

RGB *= v;

return RGB;
}

```
> 2 votes

# Answer
Sorry ahead of time for not posting any code, but your problem might be HSV itself.

Hue is represented as a circle, called a Color Wheel. In HSV, the color wheel is based on color frequencies, evenly divided out across the visual spectrum. In other words, The Sextants your solution assumes exist are based on evenly distributing the 0-359 degrees over this Color Wheel (which is what most Display Monitors and computers assume when it divides all the color channels into 256).

But, take a look at Paint.NET and various other applications, like Photoshop. They don't use a Color Wheel, but what's often called a Painter's Wheel. It's usually a modified Wheel that doesn't evenly distribute the color frequencies.

These differences are usually caused by Display Monitors that have brighter blues and greens than is actually typical of reality. In order to color balance an image like this, it needs to be corrected or the displayed results can't match up with a real world solution.

Simply put, the HSV sextant solution may be the culprit. Try modifying your program to display the full range of the color wheel you're using and compare that to Paint.NET. You really can't compare two images that are operating in a different color space.

(Again, this is just a guess, as I'm trying to solve a similar problem)
> 1 votes

---
Tags: hlsl, fragment-shader
---


# Question
Title: Maintain proper symbol order when applying an armature in flash
I am trying to animate a character's leg in flash CS 5.5 for a game I am working on. I decided to use the bone tool because it's awesome. The problem I am having, however, is that for my character to be animated properly, the symbols that make up his leg (upper leg, lower leg, and shoe) need to be on top of each other in a specific way (otherwise the shoe looks like its next to the leg, etc). Applying the bones results in the following problem: the first symbol I apply it to is placed in the rear on the armature layer, the next on top of it, and so on, until the final symbol is already on top. I need them to be in the opposite order, but arrange \> send to back does nothing on the armature layer. How can I fix this?

tl;dr: The bone tool is not maintaining the stacking order of my objects, please help.

Thanks for helping :).

# Answer
`Modify > Arrange > Send to Back` works, however right clicking and doing an `Arrange > Send to Back` does not. Why this is the case with bones is not yet clear to me, though I think it may have something to do with the right click selecting the entire armature.
> 1 votes

---
Tags: animation, flash
---


# Question
Title: How do I create a bounding frustum from a view & projection matrix?
Given a left-handed Projection matrix, a left-handed View matrix, a ViewProj matrix of View * Projection - How do I create a bounding Frustum comprised of near, far, left, right and top, bottom planes?

The only example I could find on Google (Tutorial 16: Frustum Culling) seems to not work; for example, if the math is used as given, the near-plane's distance is a negative. This places the near-plane behind the camera...

# Answer
> 11 votes
The easiest way I know of is to construct the view frustum in post-projective space (so-called NDC space), where the frustum is a cube, then transform it through the inverse view-projection matrix and construct the planes in world space.

The frustum in NDC space runs from -1 to +1 along the x and y axes, and from -1 to +1 on z if you're in OpenGL, or 0 to 1 on z if you're in D3D. Build the eight corners of this cube (setting w = 1), then multiply them by the inverse view-projection matrix, and divide by w to convert back to regular 3D points.

The result should be the frustum corners in world space, and you can then build the planes by using groups of 3 points and the usual formula for calculating a plane equation from 3 points.

This general technique should work with any kind of view-projection matrix - perspective or orthographic, oblique or straight, any FoV or aspect ratio, etc. There are ways to simplify it by making some assumptions about the form of the matrix, but those tend to break if any of the assumptions are changed.

---
Tags: camera, frustum
---


# Question
Title: How to connect two Iphone/ipod/ipads for gameplay over local wifi network?
I would like to add the option to play against another person over my wifi network in my pong game. How do I make this happen?

Also, I would like to know how to be able to have 4 players at the same time like I would if I make a monopoly type game or something similar.

I'm a newbee so please point me in the right direction or show me some code I can use for this and study. Thanks guys David

# Answer
> 2 votes
The two main options seem to be GameKit (built on top of Bonjour) and Bonjour. If you're taking the GameKit route, use peer session mode for two players and server/client session mode for more than two. If you're taking the Bonjour route, good luck.

Also, Gamekit supports wi-fi and bluetooth.

> Peer-to-peer connectivity allows your game to create an ad-hoc Bluetooth or local wireless network between multiple iOS-based devices.

Helpful Links:
GameKit Programming Guide: Peer-to-Peer Connectivity
GameKit Examples at the iOS Developer Library \- Try the GKTank and GKRocket examples.

# Answer
> 1 votes
Take a look at Gamekit sdk. It is an Apple sdk for what you want to do.

---
Tags: iphone, networking, multiplayer
---


title: Particle effect after the bullet

text:
# Question
Title: Particle effect after the bullet
In my game, I fire a bullet from the gun along with that I generate a particle behind the bullet so that I look like fire effect after the bullet. But my problem is that the position I got from the bullet was distance in place. So basically I want to say that the bullet speed was high for that reason I got coordinate for the particle generation was far from each other like

dot dot effect. But I want continuous flow of particle behind the bullet. So please provide any guidance for my problem

# Answer
You do not talk about code so it's hard to give you the good advice.

Anyway it seems that your particles are spawned at each frame... and as your bullet travels very fast, each frame means a long distance between two draws. That's where your dot-dot effect comes from imho.

You have to find a way to "interpolate" the particle generation between each frame. Instead of spawning particles at each draw, you spawn particle for this draw and those missing back to the last draw.

EDIT: You know the position of your bullet when the frame is drawn. You also know the position of your bullet when the last frame was drawn (you have to save the position of your bullet at t-1). So you can determine the path your bullet has done, and then ask your particle generator to spawn particles along this path instead of only spawn particle while frame rendering.
> 2 votes

---
Tags: andengine
---


# Question
Title: Render 2D textures on a 3D object's face
I am not familiar with 3D graphics, and I'd like to know the right way to render some 2D figures on different points of a wider face of a 3D object. My 3D object is just a cube representing a poker table. I have a 2D png for players' placeholders, and I'd like to render these figures on the 3D object where needed. An alternative solution would be to render the whole face with a big picture containing all the placeholders figures. However, it would be a waste of memory and thus less efficient.

What do you suggest?

# Answer
To render on the cube, the images must be used as textures and in Unity that means assigning the images to materials (probably with the Diffuse shader) and assigning the material to the object's MeshRenderer.

However, it's a bit more complicated than that, because the system needs to know how to map the texture to the various vertices in the cube, and there are many different ways to go about this, including merging the various images into one texture, or having multiple textures in one material, etc. There is no right or wrong way, although making all the figures into one image instead of several is usually more efficient, not less efficient, and is likely to use less memory.

Usually the 'easiest' way to set this up is to create the object in a 3D modelling program and export that in a form that Unity can read. However even this is relatively complex for a beginner unfortunately.
> 1 votes

---
Tags: unity
---


# Question
Title: Implementing a switch statement based on user input
I'm trying to delay the time it takes for the main menu screen to pop up after a user has won / lost a match. As it stands, the game immediately displays a message stating "you won / lost" and waits for 6 seconds before loading the menu screen.

I would also like players to have the ability to press a key to advance to the menu screen immediately but thus far my switch statement doesn't seem to do the trick. I've included the switch statement, along with my (theoretical) inputs. What could I be doing wrong here?

```
if (gamestate == GameStates.End)
                    switch (input.IsMenuDown(ControllingPlayer))
                    {
                        case true:
                            ScreenManager.AddScreen(new MainMenuScreen(), null); // Draws the MainMenuScreen
                            break;

                        case false:
                            if (screenLoadDelay > 0)
                            {
                                screenLoadDelay -= gameTime.ElapsedGameTime.TotalSeconds;
                            }
                            ScreenManager.AddScreen(new MainMenuScreen(), null); // Draws the MainMenuScreen
                            break;
                    }

     /// <summary>
    /// Checks for a "menu down" input action.
    /// The controllingPlayer parameter specifies which player to read
    /// input for. If this is null, it will accept input from any player.
    /// </summary>
    public bool IsMenuDown(PlayerIndex? controllingPlayer)
    {
        PlayerIndex playerIndex;

        return IsNewKeyPress(Keys.Down, controllingPlayer, out playerIndex)
               || IsNewButtonPress(Buttons.DPadDown, controllingPlayer, out playerIndex)
               || IsNewButtonPress(Buttons.LeftThumbstickDown, controllingPlayer, out playerIndex);
    }

```

# Answer
> 1 votes
(I'm not familiar with XNA but AFAIK there's nothing like an input listener so I'm assuming you are using flags to represent input)

With input flags (that could be as simple as booleans) it makes more sense to check for them at the start of the games' main loop. That way, for each cycle you know any current input.

Something like this should then work:

```
set Delay=0;

main loop

{

[...]

Gather input flags.

if(gamestate == GameStates.End) then

 if (Desired_Flag == true || Delay > 6)

  Delay = 0; ShowMenu();

 else Delay += Last_TimeSlice

else KeepPlaying //the game is not in .End state

[...]

Last_TimeSlice = current_elapsed;

}

```

# Answer
> 1 votes
Treat your message dialog as just another "enemy" or "npc" object that has animations. Think of it as having an animation that lasts 6 seconds.

```
MessageDialog message = new MessageDialog();

public override Update(GameTime gameTime)
{
    if(gamestate == PLAYING)
    {
        // check game win or lose
        if(player_now_wins_or_lose)
        {
            message.show("You Win or Lose!");
            gamestate == PLAYER_WIN_OR_LOSE;
        }
        else
        {
            // TODO: Run the game logic
            RunGameLogic();
        }
    }
    else if(gamestate == PLAYER_WIN_OR_LOSE)
    {
        // update the animations in the message dialog.
        // this can be some fade-in/out; icon spinning; text shimmering effects
        // on the message box that completes in 6 secs.
        message.Update(gameTime);

        if(Keyboard.GetState() == SOME_KEY_PRESSED || message.state == SIX_SECONDS_UP)
        {
           message.hide();
           gamestate == MAIN_MENU;
           // TODO: Add main menu screen
        }
    }
}

```

The MessageDialog

```
public class MessageDialog
{
    public MsgDialogState state = IDLE;
    float totalTime = 0;
    string TextToShow = string.Empty;

    void Show(string text)
    {
       TextToShow = text;
       state = RUNNING;
       totalTime = 0;
    }

    void Update(GameTime gametime)
    {
       totalTime += gametime.elapsedTime;
       if(totalTime >= 6000)
       {
           totalTime = 6000;
           state = SIX_SECONDS_UP;
       }
    }

    void Draw()
    {
       // TODO: Draw the message box with the text;
    }
}

```

# Answer
> 0 votes
For starters, you might consider just making your switch statement an if/else statement since it's only checking for true or false. Also, correct me if I'm wrong, but it looks like you're trying to do the delay if the switch is false. The problem is that after your if statement completes it still executes the next line.

```
ScreenManager.AddScreen(new MainMenuScreen(), null); // Draws the MainMenuScreen

```

You may instead try this:

```
if (screenLoadDelay > 0)
    screenLoadDelay -= gameTime.ElapsedGameTime.TotalSeconds;
else
    ScreenManager.AddScreen(new MainMenuScreen(), null); // Draws the MainMenuScreen

```

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


title: Units of measurement in a tile world

text:
# Question
Title: Units of measurement in a tile world
I've started to make a 2D sidescroller, the camera and world rendering works as I expect, but now comes the physics part of world.

What I need is that one tile in x or direction should correspond to **1 meter**. Since I have a variable time step (Android mobile game), I can't figure it out, since the timing and velocity always will be dependent of the device. So, is there any good way to make one tile to correspond 1 meter? This would be good, otherwise the physics implementation would later be weird.

# Answer
Velocity does indeed relate to both time and distance. However, distance, time and even velocity will remain the same between all your devices, the only thing different will be the span between updates. Of course, I need to link the required documentation for anything talking about physics and time. As long as you maintain `x units of movement = x number of pixels` you're fine. This brings up the issue of scaling your art assets for different size screens. Just scale your distance units in the same way as your art assets. You can just have global scaling variables that reflect what the "native" size of your game has been scaled to, then apply those to all updates that utilize drawing, position, physics or movement.
> 1 votes

---
Tags: android, physics, tilemap
---


title: Simultaneous AI in turn based games

text:
# Question
Title: Simultaneous AI in turn based games
I want to hack together a roguelike. Now I thought about entity and world representation and got to a quite big problem.

If you want all the AI to act simultaneously you would normally(in cellular automa for examble) just copy the cell buffer and let all action of indiviual cells depend on the copy. Actions which are not valid anymore after some cell before the cell you are currently operating on changed the original enviourment(blocking the path) are just ignored or reapplied with the "current"(between turns) environment. After all cells have acted you copy the current map to the buffer again.

Now for an environment with complex AI and big(datawise) entities the copying would take too long. So I thought you could put every action and entity makes into a que(make no changes to the environment) and execute the whole que after everyone took their move. Every interaction on this que are realy interacting entities, so if a entity tries to attack another entity it sends a message to it, the consequences of the attack would be visible next turn, either by just examining the entity or asking the entity for data. This would remove problems like what happens if an entity dies middle in the cue but got actions or is messaged later on(all messages would go to null, and the messages from the entity would either just be sent or deleted(haven't decided yet)

But what would happen if a monster spawns a fireball which by itself tracks the player(in the same turn). Should I add the fireball to the enviourment beforehand, so make a change to the environment before executing the action list or just add the ball to the "need updated" list as a special case so it doesn't exist in the environment and still operates on it, spawing after evaluating the action list?

Are there any solutions or papers on this subject which I can take a look at?

EDIT: I don't need information on writing a roguelike I need information on turn based ai in respective to a complex enviourment.

# Answer
One game I remember dealt with the problem in a similar fashion of what you described:

* Each agent had a "preferred" action (if a player was controlling it, the action the player chose) and a list of alternative actions in descending order or priority (automated but configurable);
* The choice of the next action, when applicable, would be constrained by the current state only;
* After all agents made their choice, the game would sort them in "speed" order, to determine who would act first;
* The first one would then act, and the consequences would apply immediatly;
* When it's time for the next one to act, the preferred action would check if it's preconditions still hold and, if not, would move to the next action in the priority list; if there is no action with valid preconditions, the agent skips its turn;
* Repeat until all agents acted or skipped, then begin next turn.

One thing interesting to note is that agents might be added or removed from the list mid-turn: for instance, if a character that still hasn't acted died, but before its time to act another one had "revive any dead character in my party" as its preferred action, that action would execute and the once-dead character would still be able to perform normally in the same turn. In your example, you could treat the fireball as just another agent, and add it to the list when the monster would normally act (after checking the corresponding preconditions: monster is alive, monster has mana, monster is not silenced/paralyzed, etc).

Likewise, some actions would have "character alive" as a precondition, while others would not: for instance, a physical attack on multiple enemies would be interrupted if one of them retaliates and kill the agent before all targets are affected; a magic attack that is supposed to happen simultaneously (a thunderstorm for instance) would continue to affect other enemies even if one of them reflected it and killed the caster mid-action. So, even though the action was split in multiple steps (attack one, attack other, etc) by the implementation, the resulting effect would be that of a simultaneous event.
> 2 votes

---
Tags: ai, turn-based
---


title: Cropping a line (laser beam) in XNA

text:
# Question
Title: Cropping a line (laser beam) in XNA
I have a laser sprite that I wish to crop. I want to crop it so when it collides with an item, I can calculate the distance between the starting point, and the ending point, and only draw that. This eliminates the "overdraw" of a laser drawing past an item.

Essentially, I'm trying to crop a line, but also keep that line "attached" to the nose of my ship. The line should not be drawn past the nose of my ship, that should be the starting point. There is no rotation to worry about.

Currently, I thought that doing this through `SpriteBatch` would be best. This is my current Spritebatch code:

```
    spriteBatch.Draw(Laser.sprite, new Rectangle((int)Laser.position.X, (int)Laser.position.Y,
Laser.sprite.Width, LaserHeight),
new Rectangle(0, 0, (int)(Laser.sprite.Width), LaserHeight),
new Color(255, 255, 255, (byte)MathHelper.Clamp(Laser.Alpha, 0, 255)),
Laser.rotation, new Vector2(Laser.sprite.Width/2, LaserHeight/2), SpriteEffects.None, 0);

```

But this doesn't quite work. It does only draw part of the sprite, but when `LaserHeight` is incremented, it lengthens the line **in both ways!** I believe this is due to some stupid error on my part with the Origin of the draw.

**Quick recap**: I need to have my laser sprite drawn with the bottom of it at the nose of my ship, and then use `LaserHeight` to crop the image so only part of it is drawn.

I have a feeling my explanation is a bit...lacking. So if you require more information, please say so and I will try to provide more information.

Thanks in advance!

# Answer
Actually, I had a brainwave and it worked out. I used the size (specifically, a Vector2) to scale it instead of crop it.

Here's the final code:

```
    spriteBatch.Draw(Laser.sprite, Laser.position + new Vector2(0, Laser.sprite.Height / 2),
null,
new Color(255, 255, 255, (byte)MathHelper.Clamp(Laser.Alpha, 0, 255)),
Laser.rotation,
new Vector2(Laser.center.X, Laser.sprite.Height),
new Vector2(Laser.StretchableSize.X, ChangeRange(LaserHeightMAX, 1, LaserHeight)),
SpriteEffects.None,
0);

```

`ChangeRange` is simply a function that converts a range into 0 to 1 for the size.

However, if there is another way, I'm still open to hearing it!
> 3 votes

# Answer
The reason it's expanding in both directions is because you're setting the origin as the centre point of the texture (`new Vector2(Laser.sprite.Width/2, LaserHeight/2)`). When you increase or decrease the size of the texture being drawn, it's still drawn in the same spot, it's just smaller in general.

If you want to shorten it based on the destination (or source) rectangle, you should set the origin to the bottom-centre (`new Vector2(Laser.sprite.Width/2, LaserHeight)`). Then, the position you draw it at will just be the front of your ship.

Let me know if this is not clear and I'll make a diagram.
> 0 votes

---
Tags: xna, 2d, spritebatch
---


# Question
Title: 45° Slopes in a Tile based 2D platformer
I want to have simple 45° slopes in my tile based platformer, however I just cant seem to get the algorithm down. Please take a look at the code and video, maybe I'm missing the obvious?

```
//collisionRectangle is the collision rectangle of the player with
//origin at the top left and width and height
//wantedPosition is the new position the player will be set to.
//this is determined elsewhere by checking the bottom center point of the players rect
if(_leftSlope || _rightSlope)
{
    //Test bottom center point
    var calculationPoint = new Vector2(collisionRectangle.Center.X, collisionRectangle.Bottom);
    //Get the collision rectangle of the tile, origin is top-left
    Rectangle cellRect =
        _tileMap.CellWorldRectangle(
            _tileMap.GetCellByPixel(calculationPoint));
    //Calculate the new Y coordinate depending on if its a left or right slope
    //CellSize = 8
    float newY = _leftSlope
                            ? (calculationPoint.X % CellSize) + cellRect.Y
                            : (-1 * (calculationPoint.X % CellSize) - CellSize) + cellRect.Y;
    //reset variables so we dont jump in here next frame
    _leftSlope = false;
    _rightSlope = false;
    //now change the players Y according to the difference of our calculation
    wantedPosition.Y += newY - calculationPoint.Y;
}

```

Video of what it looks like: http://youtu.be/EKOWgD2muoc

# Answer
> 10 votes
From what I understand reading your question, you want to calculate the correct `Y` position, given a `X` position of the player. This is rather trivial. Have a look at this image:

Assuming your slope-tile is at a given position `x,y` (origin is bottom left as in the image). You have the player position `x1` and the width and the height of the sloped tile (`u, v`). `x, y` and `x1` are world coordinates.

Given these parameters, your players Y-position (`y1`) would be:

```
y1 = y + (x1 - x) * (v / u)

```

If you're only dealing with 45 degree angles, then it gets even simpler:

```
y1 = y + (x1 - x)

```

If the slope is the other way round, it's:

```
y1 = y + (v - (x1 - x))

```

# Answer
> 8 votes
Although this is already answered, allow me to offer another equation: `y = mx + b`, where y is the coordinate calculated, m is the slope (-1 for down at 45 degrees, 1 for up at 45 degrees), and b is the y-intercept -- the y-coordinate where x=0.

This allows you slightly more flexibility; you can change m to calculate a different slope other than 45-degrees. For example, an m of pi/3 gives you a slope of 30 degrees.

# Answer
> 4 votes
You may find a lot of value in this site: http://info.sonicretro.org/Sonic\_Physics\_Guide

Specifically for what you are looking for check out the Solid Tiles: Slopes and Curves section. It basically shows you how it is believed this was accomplished in the early Sonic games.

# Answer
> 2 votes
You might want to look into the Seperate Axis Theorm, It will solve your slope issue, but it does require quite a bit of maths and the theory itself takes a while to get your head round. I've linked you to a tutorial and a book which explains it better

metanetsoftware Tutorial

Real-Time-Collision-Detection

# Answer
> 2 votes
I think you either have an off-by-one error somewhere else, or you aren't setting \_leftSlope/\_rightSlope flags at the right time. This code does not touch the X movement at all, but that seems to be your problem in the video.

You should check if those flags are triggered at all. Then check your horizontal collision detection: you don't want it to trigger on a slope.

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


title: pygame.Rect around circle

text:
# Question
Title: pygame.Rect around circle
I'm trying to make a pong game in pygame, but I can't figure out how to put a ball circle, which I can create with `pygame.draw.circle` into a `pygame.Rect` object so i can use the colliderect function to manipulate the ball's position.

For example, a rectangle, I can do something like this:

```
rect = pygame.Rect(255, 255, 100, 100)
pygame.draw.rect(screen, yellow, rect)

```

When I change the `pygame.Rect` object position, the drawing primitives position also changes.

How can the same effect be achieved when I want to draw a circle, instead of a rectangle?

# Answer
Presumably you're using a center position and a radius to draw the circle. Just create a rect like this:

```
crect = pygame.Rect(center[0]-radius, center[1]-radius, \
                    radius*2, radius*2)

```

Then draw the circle like this:

```
pygame.draw.circle(screen, yellow, crect.center, radius)

```
> 4 votes

---
Tags: python, pygame
---


# Question
Title: Retrieving model position after applying modeltransforms in XNA
For this method that the goingBeyond XNA tutorial provides, it would be really convenient if I could retrieve the new position of the model after I apply all the transforms to the mesh. I have edited the method a little for what I need. Does anyone know a way I can do this?

```
    public void DrawModel( Camera camera )
    {
        Matrix scaleY = Matrix.CreateScale(new Vector3(1, 2, 1));
        Matrix temp = Matrix.CreateScale(100f) * scaleY * rotationMatrix * translationMatrix * Matrix.CreateRotationY(MathHelper.Pi / 6) * translationMatrix2;
        Matrix[] modelTransforms = new Matrix[model.Bones.Count];
        model.CopyAbsoluteBoneTransformsTo(modelTransforms);
        if (camera.getDistanceFromPlayer(position+position1) > 3000) return;
        foreach (ModelMesh mesh in model.Meshes)
        {
            foreach (BasicEffect effect in mesh.Effects)
            {
                effect.EnableDefaultLighting();
                effect.World = modelTransforms[mesh.ParentBone.Index] * temp *  worldMatrix;
                effect.View = camera.viewMatrix;
                effect.Projection = camera.projectionMatrix;
            }
            mesh.Draw();
        }
    }

```

# Answer
The drawn model's position is:

```
Vector3 drawnModelPosition = (temp * worldMatrix).Translation;

```
> 1 votes

---
Tags: xna, c#, matrix, models
---


# Question
Title: Help Decide between C#/XNA client or Java
The game runs on a client/server architecture currently setup for TCP, and the client code was built in AS3 to be web based.

What we're running into is 3 problems for the client.

1. AS3 has no hardware acceleration so we are having some issues with slowdown when implementing some features
2. TCP is really frustrating for a sidescroller when you're talking with a server. I'm having a heck of a time with the interpolation/extrapolation to make everyone else look smooth while minimizing lag. I would much rather be able to use UDP and throw in something similar to the age old Quake interpolation/extrapolation.
3. No right click

I work professionally with C#, and I did all my University (almost 2 years ago) with Java. Java really appeals to me because of the compatability while C# appeals to me because I've heard so much good about XNA and I love visual studio.

For a Client/Server based MMOish sidescroller in your opinion should I stick with AS3 and the TCP protocol, or should I abandon some of my audience, ramp up the graphics and hit C#, or journey back to the land of Java.

Thanks :D

# Answer
I have no experience in C#, but Microsoft seems like a "bind the developer to our very own platform"-company to me. So I'd avoid XNA, but if you target only Windows, it's okay for sure. I'm also not an AS3 programmer or fanboy, so I'd tell you to step back from Flash, too. :P

I can talk a bit more about Java. When you develop games with Java, LWJGL is probably the one and only standard for desktop games out there. While using OpenGL is a great thing, it is not as convenient as using a more high level framework, of course. I recommend LibGDX here, it puts no restriction on the usage of Java while trying to make the whole game platform independent with cross-compilation (Android and Desktop uses Java, iOS is also available I guess and it runs in the browser with HTML5/JS/WebGL). I've created several game prototypes in Java and my throughput was quite good.

Another option for you might be HTML5 in combination with Javascript and WebGL. When using for example Google Chrome (which runs V8), carefully programmed Javascript can reach the speeds of Java, but is certainly fast enough for a simple sidescroller. WebGL is hardware accelerated OpenGL ES 2.0 and there are some engines written in JS out there. But I am not sure if JS features UDP.
> 0 votes

# Answer
I've done some simple games, but I've been looking at some different platforms. Unity seems to be something that you might want to look at. You can publish games to a lot of different platforms and program in C#. It's not entirely free, though.
> 1 votes

---
Tags: c#, java, udp
---


title: Checkers AI Algorithm

text:
# Question
Title: Checkers AI Algorithm
I am making an AI for my checkers game and I'm trying to make it as hard as possible. Here is the current criteria for a move on the hardest difficulty:

1: Look For A Block: This is when a piece is being threatened and another piece can be moved in behind it to protect it. Here is an example:

Black Moves
`|W| |W| |W| |W| |`
`| |W| |W| |W| |W|`
`|W| | | |W| |W| |`
`| | | |W| | | | |`
`| | | | |B| | | |`
`| |B| | | |B| |B|`
`|B| |B| |B| |B| |`
`| |B| |B| |B| |B|`

White Blocks
`|W| |W| |W| |W| |`
`| |W| | | |W| |W|`
`|W| |W| |W| |W| |`
`| | | |W| | | | |`
`| | | | |B| | | |`
`| |B| | | |B| |B|`
`|B| |B| |B| |B| |`
`| |B| |B| |B| |B|`

2: Move pieces out of danger: if any piece is being threatened, and a piece cannot block for that piece, then it will attempt to move out of the way. If the piece cannot move out of the way without still being in danger, the computer ignores the piece.

3: If the computer player owns any kings, it will attempt to 'hunt down' enemy pieces on the board, if no moves can be made that won't in danger the king or any other pieces, the computer ignores this rule.

4: Any piece that is owned by the computer that is in column 1 or 6 will attempt to go to a side. When a piece is in column 0 or 7, it is in a very strategic position because it cannot get captured while it is in either of these columns

5: It makes an educated random move, the move will not indanger the piece that is moving or any piece that is on the board.

6: If none of the above are possible it makes a random move.

---

This question is not really specific to any language but if all examples could be in Java that would be great, considering this app is written in android. Does anyone see any room for improvement in this algorithm? Anything that would make it better at playing checkers?

# Answer
> 17 votes
If you're trying to make a good AI for your checkers program, then the first place to look is what's known as *Alpha-Beta* game tree search. The short version is that any AI that only takes into account static features of the current position is bound to run into trouble, especially in the early-to-mid game, because it simply can't understand what's presently happening in the game and what the threats are. Instead, what you want to do is to write an algorithm that searches all possible moves-and-replies for some number of moves ahead (5 to 10 would be typical), evaluates the position at the end of each branch of this move-and-reply tree (in terms of 'how many pieces ahead or behind am I?), and then makes the move that gives it the best chance - in other words, the move that *maximizes* its possible value, where the possible value is calculated as the *minimum* possible value across all of your opponent's replies (assuming, in other words, that they'll make the move that's best for them), etc. - this is why this algorithm is often called the *Minimax* algorithm.

What you'll find is that many of the elements you're talking about - moving pieces to the side, moving pieces out of danger, etc. - will become elements of the *positional evaluation function* of the game tree search. Essentially, instead of asking the simple question 'how many pieces ahead is one side or the other?', you'll say 'what is the value of this position?' and then give point values to various features of the board (e.g., whether a piece is on the side, whether it's vulnerable, etc.) in terms of partial pieces - for instance, you might decide that the difference between an edge and a center piece is worth possibly .1 piece, so in a position where you're a man behind but have an extra edge piece the overall value to you will be -0.9.

One critical advanced notion for checkers AI specifically is the concept of *Quiescence search*: imagine that you go down six moves into your tree, and at the tail end your opponent has just made a capture where your (forced) reply is an immediate recapture. Unfortunately, the positional evaluation function can't see the recapture, so it evaluates the position as being a piece up for your opponent even though you're about to regain parity. Quiescence search is an attempt to solve this problem by forcing the evaluator to go down into a branch until all possible forced captures have been made, and only then evaluate the position.

This may all sound fairly complicated, but I think you'll find it's more straightforward than it looks - once you write your evaluator function, the tree search is relatively easy; there are a lot of smart concepts (things like *transposition tables*) that you can apply to it, but it should be easy to get something working and then continue to improve it. For more details, I suggest searching on pretty much any of the key terms (alpha-beta search, minimax, quiescence search, game tree, etc); there's plenty of good information on all of these concepts out on the web.

---
Tags: algorithm, ai
---


title: Loadbalancing Questions

text:
# Question
Title: Loadbalancing Questions
I have been learning networking for about 4 months. Wrote a single standalone Multiplayer server and succeeded with authoritative approach. Now I want to extend it by splitting the single server into clusters to allow even more players to log in to avoid latency issues. Now I have protyped the Loadbalancing server and its running pretty good so far.

This is my architecture, I have a master server which acts as a proxy, every sub servers(chat, login, game) connect to the master server as well as all the clients. when a client connects,

**Client Request: Send Request -\> MS(Master) -\> Decides which SS(SubServer) to forward to -\> Forwards Request to SS -\> SS -\> Analyze Message -\> Send Response to MS -\> Decides which Client to forward to -\> Forwards Response to Client**

Well, it looks like its going through lots of stages. it takes double the time to process the message than a single server approach. i feel like my model isnt the best or i may be wrong. is there any better model or the one they use in professional games? I still want a **Master-SubServer** approach.

I just want to clarify that I'm going in the right direction before writing all my codes. Thanks for any answer :)

# Answer
Loadbalancing in that manner works best if the work performed in the backend is far more than the work to reroute the messages, if the clients messages are along the line of "Moving Right"/"Jumped"/"Fired", then this method will be spending a lot of time routing messages that basically only result in a flag being changed on the backend server.

Instead of hiding the gameserver behind the loadbalancer you can instead send a message to the game client to connect to a specific IP:port. By giving it a random one-time key that it then gives to the second server in a handshake sequence you can securely and quickly route players to different servers.

Should you need to rebalance you can have the loadbalancer request gameserver A to pass X number of clients to the gameserver B, the servers then perform a handshake to transfer any necessary information, and then the client is sent a new key and IP:port to connect to. This last part may not be possible during an ongoing game, but that depends on the nature of the game, in a MMO you would send players from one server to another as they reach certain transition areas for instance.
> 2 votes

# Answer
I would imagine that it is better to have one game server per "zone", of the game to avoid unnecessary complicated chit-chat between game servers.

I'd recommend that the clients connect directly to individual servers, and the master server just handles authentication and tells them which server to go to (depending on which zone they're in or other criteria).

In fact, having the master server as a "proxy" is probably a bad idea. Using a proxy is only helpful if you want the choice of destination server to be transparent to the client, or hidden from it.

If your game client is a custom client, this is not necessary, it can connect to whichever server you want.
> 1 votes

# Answer
There's nothing wrong or uncommon with your approach. Having proxy servers is definitely useful for facilitating automatic migration from one server to another, for being able to restart servers without the client being disconnected, for implementing encryption or compression on an otherwise untaxed host, for reducing the networking overhead on game logic servers, etc. You will incur a latency penalty and that's unavoidable. But sometimes it is worth it.

The real question is: how do you decide which sub-server to forward a message to? There are two major approaches:

1. By location - the traditional approach (if you can't fit it all on one server) is to handle different zones on different servers. All the game's logic is available on each server, but each one only handles a small part of the world. This is very simple to implement since each server is identical except for the data and acts like a monolithic server would, but doesn't scale so well if some areas are used much more than others. You can work around this a bit by having multiple zones per server and load-balancing zones across servers, which is useful but tricky. For seamless worlds you might divide the geography up using a grid rather than by arbitrary zones that don't actually exist, but bear in mind that you now start entering into the complex realm of having different servers negotiating with each other over game logic that involves 2 entities on adjacent servers - such as ranged combat, trade, etc. Managing the seamless boundary between 2 areas represented on different servers is one of the main problems facing MMO developers.
2. By service - some games have different server processes for different aspects of play, such as a Chat service, a Combat service, a Trade service, etc. The logic gets complex in areas where 2 things overlap as 2 or more services need to start exchanging data between them. Imagine that entering combat causes a trade to cancel - the Combat service must send a message to the Trade service to tell it to cancel the trade, and that in turn might have to send messages to the Inventory service to return items to a player's inventory, which in turn may need to inform the Persistence service that it needs to save the player's inventory data, etc. The reason for choosing such a complicated architecture is that it scales very well - just add extra machines for extra services where needed
> 0 votes

---
Tags: architecture, networking, mmo, server, client-server
---


# Question
Title: List has no value after adding values in
I am creating a a ghost sprite that will mimic the main sprite after 10 seconds of the game. I am storing the users movements in a `List<string>` and i am using a `foreach` loop to run the movements. The problem is when i run through the game by adding breakpoints the movements are being added to the `List<string>` but when the `foreach` runs it shows that the list has nothing in it. Why does it do that? How can i fix it?

this is what i have:

```
public List<string> ghostMovements = new List<string>();

    public void UpdateGhost(float scalingFactor, int[,] map)
    {

        // At this foreach, ghostMovements has nothing in it
        foreach (string s in ghostMovements)
        {
            // current position of the ghost on the tiles
            int mapX = (int)(ghostPostition.X / scalingFactor);
            int mapY = (int)(ghostPostition.Y / scalingFactor);

            if (s == "left")
            {
                switch (ghostDirection)
                {
                    case ghostFacingUp:
                        angle = 1.6f;
                        ghostDirection = ghostFacingRight;
                        Program.form.direction = "";
                        break;

                    case ghostFacingRight:
                        angle = 3.15f;
                        ghostDirection = ghostFacingDown;
                        Program.form.direction = "";
                        break;

                    case ghostFacingDown:
                        angle = -1.6f;
                        ghostDirection = ghostFacingLeft;
                        Program.form.direction = "";
                        break;

                    case ghostFacingLeft:
                        angle = 0.0f;
                        ghostDirection = ghostFacingUp;
                        Program.form.direction = "";
                        break;

                }
            }
        }
    }

    // The movement is captured here and added to the list
    public void captureMovement()
    {
        ghostMovements.Add(Program.form.direction);
    }

```

EDIT:

```
    // Ghost is the name of the class that creates the ghost sprite
    // as well as where captureMovement() is in.
    Ghost ghost = new Ghost();

    // This update is in a class named turtle
    public void Update(float scalingFactor, int[,] map)
    {
        // current position of the turtle on the tiles
        int mapX = (int)(turtlePosition.X / scalingFactor);
        int mapY = (int)(turtlePosition.Y / scalingFactor);

        //The rest of the code that contains the captureMovement method being called
        //looks the same as the if statement with just different directions.
        if (Program.form.direction == "left")
        {
            ghost.captureMovement();
            switch (turtleDirection)
            {
                case turtleFacingUp:
                    angle = 1.6f;
                    turtleDirection = turtleFacingRight;
                    Program.form.direction = "";
                    break;

                case turtleFacingRight:
                    angle = 3.15f;
                    turtleDirection = turtleFacingDown;
                    Program.form.direction = "";
                    break;

                case turtleFacingDown:
                    angle = -1.6f;
                    turtleDirection = turtleFacingLeft;
                    Program.form.direction = "";
                    break;

                case turtleFacingLeft:
                    angle = 0.0f;
                    turtleDirection = turtleFacingUp;
                    Program.form.direction = "";
                    break;

            }
        }
    }

    // This update is in the game1 class (main class)
    protected override void Update(GameTime gameTime)
    {
        // Allows the game to exit
        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
            this.Exit();

        turtle.Update(scalingFactor, map);
        ghost.UpdateGhost(scalingFactor, map);

        base.Update(gameTime);
    }

```

# Answer
> 4 votes
You may have several problems:

A)

Using string for directions is not a good idea... because the string comparation is slow and case insensitive... is much better using an enumeration or integers.... I prefer enums...

```
   public enum Directions {None, Left, Right, Up, Down }

```

B)

Are sure you are calling to captureMovement()?

Are you clearing the list every frame? Before or After calling updateGhost()?

EDIT

C) Is the ghost instance you are using in the turtle class the same you are using in the game1 class?

D) I'm worried about the clearing of ghostmovements... where do you clear it?

E) I have redone your ghost code using enums and a data driven approach

```
public enum Direction { None, Left, Up, Right, Down }
struct RotData
{
    public float Angle;
    public Direction newDir;
    public RotData( float angle, Direction newdir ) { Angle = angle; newDir = newdir;  }
    public static readonly RotData Empty = new RotData( );
}

public class Ghost
{
   public List<Direction> ghostMovements = new List<Direction>( );

    Vector2 ghostPostition;
    Direction ghostDirection;
    float angle;

    RotData[][] rotationData = new RotData[][]
    {
       new RotData[] { //Left
            new  RotData(0, Direction.Up),    // Left
            new  RotData(MathHelper.PiOver2, Direction.Right),    // Up
            new  RotData(MathHelper.Pi, Direction.Down),          // Right
            new  RotData(-MathHelper.PiOver2, Direction.Left),    // Down
       }
       , new RotData[] {...} // Up
       , new RotData[] {...} // Right
       , new RotData[] {...} // Down

    };

    public void UpdateGhost( float scalingFactor, int[,] map )
    {
        // At this foreach, ghostMovements has nothing in it
        foreach ( Direction s in ghostMovements )
        {
            if ( s!=Direction.None && ghostDirection!= Direction.None )
            {
                RotData data = rotationData[( int ) s - 1][( int ) ghostDirection -1];
                angle = data.Angle;
                ghostDirection = data.newDir;
                Program.form.direction = Direction.None;
                break;
            }
        }
    }

```

This can be done easier if you always turn to right and/or the relation between angle and direction is fixed, then you only should use Directions and an array to convert directions to angles.

```
    public void UpdateGhost( float scalingFactor, int[,] map )
    {
        // At this foreach, ghostMovements has nothing in it
        foreach ( Direction s in ghostMovements )
        {
            if ( s!=Direction.None && ghostDirection!= Direction.None )
            {
                ghostDirection = (Directions)(((int)ghostDirection % 4)+1); // Turn right
                angle = DirectionsToAngles[(int)ghostDirection-1];
                Program.form.direction = Direction.None;
                break;
            }
        }
    }

```

# Answer
> 1 votes
Well could you show the constructor for the class you're using ? Also i would generally
initialize a List ghostMovements in the constructor ,because it's less error prone also the garbage collector might do some weird things sometimes.And the issue might actually lie there ,but this is just a hunch.

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


# Question
Title: How important is c# for game programming?
> **Possible Duplicate:**
> Does C# have a future in games development?

Presently I'm learning c++ and in starting stage of opengl . My ultimate goal is to be game programmer. I want to stick with c++ but my doubt is how important is to learn c# or XNA? What's their future compared to c++ in game development? What about the career prospective?

# Answer
> 3 votes
According to Microsoft (Herb Sutter talks at build), as hardware gets more mobile (tablets & phones) we are suddenly facing hardware that lacks performance compared to our laptops and PCs. This makes the performance of software more important. A less performant language may come up against the hardware's performance boundry sooner.

C#, although considered higher rated in productivity than c++, generaly runs at a performance handicap to c++.

Since it is felt than in the coming years performance will outweigh productivity in software development due to hardware going mobile, Microsoft seems to be putting c# game development on the back burner and turning the heat up on c++ game development.

It is unclear whether we will see another update to Xna. Most likely Xna development will not be a part of windows phone 8. Since Xna was not invited to be a part of WinRT, it leaves us wondering if it will be invited to the next xbox.

I'm sure the AAA game studios are content using c++ for the forseeable future.

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


# Question
Title: Building a shape out of an Texture with Farseer
I have already looked at the Documentation on there Website, but the code provieded to create a shape out of an Texture is outdated for the newest version. The body is very simple so maybe i can do it with just 2 rectange but i have no idea how to do, because I just started with Farseer. Here my texture: Texture

# Answer
> 1 votes
First, you need to get the color data as uint's in an array, so:

```
Texture tex = Content.Load<Texture>("texture");
uint[] texData = new uint[tex.Width * tex.Height];
tex.GetData<uint>(texData);

```

After, you can use Farseer's `TextureConverter` to convert the data into `Vertices` (from `FarseerPhysics.Common`)

```
Vertices vertices;
vertices = TextureConverter.DetectVertices(texData, tex.Width);

```

Finally, you want to decompose those Vertices into something usable so they can be used to create polygons, using one of the many Farseer Decomposers

```
List<Vertices> vertexList = FarseerPhysics.Common.Decomposition.BayazitDecomposer.ConvexPartition(vertices);

```

There are many different methods under `FarseerPhysics.Common.Decomposition`, you can play around with the different methods to see which one you like best. Now you have the list of vertices needed for `BodyFactory.CreateCompoundPolygon(...)`, which will return a body with the shape of your texture!

You might need to scale your vertices appropriately (since the result is in pixels and Farseer uses "meters") so you can do something like this

```
Vector2 vertScale = new Vector2(ConvertUnits.ToSimUnits(1));
foreach (Vertices vert in vertexList)
  vert.Scale(ref vertScale);

```

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


# Question
Title: Material usage, one per model or per object?
Is it better (memory, time (of developer), space) to use single model that is unwrapped and uses a single material or to break a model down into appropriate bits, each with their own smaller texture/material?

Or does it depend on the target platform as to what is acceptable - ie PC vs tablet?

An example: Say you have a typical house with a tiled roof.

1. Model it, make sure everything is attached, unwrap the walls/roof so in your UV template the walls and roof would be in one texture file, side-by-side in say a 512x512 file.
2. Model the roof/walls as separate objects, unwrap them individually and have two UV templates. You could then have a 256x256 file for each one.

# Answer
> 2 votes
The short answer is it depends, or use a bit of both.

Now days I don't think you even really do textures on objects, instead you do 'materials' or 'effects' on objects.

A material can have multiple textures (1 or more basic image textures possibly with transparency, another for normals/bump mapping, another for specular reflections (The shiny part of metal will reflect light more than the scratched dirty bits) another texture for parts that should 'glow'. Another for ambient light (although that will often be the glow texture). They will have inputs (so you can swap between multiple different textures for the 1 material, modify the colour (maybe depending on the team the model is on), change animation speeds.

You're likely to use bother depending on what kind of object you are dealing with. And you can also do hybrids between 1 texture over the whole object and individual textures and so on.

If you are talking about limited hardware (mobile/web). Or a game with simpler graphics (although in that case optimizing is less important then anyway), I think it really depends.

Firstly, how close are you going to get to the object. Something like a house will need multiple textures if you are going to be walking up close to the walls, standing on the ceiling etc... but if it's a top down game where the house never gets closer than a specific distance then it's fine to use 1 texture. Maybe you use both methods depending on which LOD model is loaded.

It will depend on the kinds of objects you are going to be using. Some more 'organic' things can only really be done with 1 big texture (think of a tree trunk). Of course something like a face will

It will also depend on how many objects you are going to be seeing on the screen at once. If you have a RTS with armies of people vs a smaller number.

For the point of view of which is easiest to implement programmer wise, there about the same. In fact if you implement the multiple texture system, that will implement the single texture option.

It should also be possible for you to use multiple different materials/textures on one continuous mesh via extra vertex attributes. One of those can be a texture id. This is much easier on modern OpenGL where you can share uniform variables between shaders (I don't know about DirectX but I assume it's possible there too). Of course if you have different properties for your shaders then this will be harder. It also takes more memory. And you have to make the meshes have that metadata (although that can be done automatically).

It's also about the content creation pipeline rather than the programming side of things. Are you (or your artist) happier making a model, unwrapping the mesh then paining on it. This will mean each model is individually textured and unique, kind of hand crafted. A Blizzard game might do something like this, it allows fast creation of simple content, that's low performance, just knock together single mesh models then paint on them with a tablet. They use a simple cartoonish painting style.

Or are you likely to share textures between various models. A game that uses tiles might want the stone brick texture on 90% of them but mix in a few extra bits on most of them. And unwrapping tile objects is going to be harder in may ways due to the geometry.

# Answer
> 3 votes
With the current graphics hardware one of the simplest performance optimization rule is to minimize the amount of state changes and to draw as much as possible with the least possible amount of calls. That's also why it is wise to use a texture atlas: you need to bind the texture less often and thus can render more things at once.

Following that rule means: the fewer times the material needs to be changed the better. The best possible case would be one material for all models. You could just render all models at once: a huge speed boost.

# Answer
> 2 votes
This can depend on how detailed the textures need to be for some of the models, especially if text is included on the texture, and possible texture reuse. It is not uncommon to have a simple piece of texture that is repeated on multiple different models but may still be large enough that you do not want to duplicate it in multiple image files.

For the most part, as Mr. Beast answered, you want to limit the number of operations needed to draw things. But you may sometimes need to trade performance for ease of use, this is a common theme between programmers and artists. As such you may want to use multiple materials but make sure that you optimize the order of model before rendering as much as possible, i.e. render all of your walls, then all of your roofs.

---
Tags: 3d, textures, performance
---


# Question
Title: Is it better to cut and store all sprites needed from a spritesheet in memory, or cut them out just-in-time?
I'm not sure what's best practice here as I have little experience with this. Essentially what I am asking is...

if it's better to get your single PNG with all your different sprites on it for use in-game, cut out every sprite on startup and store them in memory, then access the already-cut-out sprite from memory quickly

**or**

Only have the single PNG with all the different sprites residing in memory, and when you need, for example, a tree. You cut out the tree from the PNG and then continue to use it as normal.

I imagine the former is more CPU friendly than the latter but less memory friendly, vice versa for the latter. I want to know what the norm is for game dev. This is a pixel based game using 2D art. Each PNG is actually an avatar's sprite sheet with each body part separated and then later joined to form the full body of the avatar.

# Answer
> 6 votes
Usually there is nothing like "cut out every sprite", because you aren't working with the data itself, but just with references. The hero sprite is not known to the application as "\[...insert huge data array here...\]" but as "Position 0,64 with size of 48x64 on Texture 5". And that data is trivial to generate nothing you could or should sweat over.

For GPU acceleration (something you should do) it's way better to have one big texture than many very small ones. Because with one texture you could just draw all sprites in one batch, the more you can draw at once the better. That's even more true for 2D because the amount of data is so little, puny 4 vertices per sprite. It's no problem for the GPU to draw four million vertices, but if you have one million sprites and you are going drawing them one by one instead of all at once you will have really bad performance due to the enormous overhead.

# Answer
> 0 votes
Typically if you have the memory to spare you want to load/cache as much info as possible up front to gain speed later. This is the cause of most loading screens when starting a level in a game.

This can however be very dependent on your graphics library. For something like OpenGL you would typically use the image file to texture a poly. In this case you only need to store texture coordinates for each sprite so there isn't much of a memory hit.

In short, cut out the sprites ahead of time if at all possible.

---
Tags: sprites, spritesheet
---


# Question
Title: Farseer: Only allow the collision one time with the object
I have there serveral platforms. I would like to allow the player to collide only one time with the object! Hope you can help me

# Answer
> 2 votes
Farseer Bodies have a method like so:

```
body1.IgnoreCollisionWith(body2);

```

What you are asking for is so that a body will only collide with another body once, so once those two bodies are separated from each other, they will no longer collide. Luckily, Farseer bodies come with an `OnSeparation` event.

```
body.OnSeparation += OnSeparation;

private void OnSeparation(Fixture fixtureA, Fixture fixtureB)
{
     fixtureA.Body.IgnoreCollisionWith(fixtureB.Body);
}

```

This will allow those two bodies to collide once, but after they separate they will no longer collide.

Depending on how your game works though, the `OnSeparation` event might be too sensitive, so you could handle it differently by keeping track of bodies that are colliding in the `OnCollision` event and then triggering something after a certain period of time, for example. The principle will remain the same however, still using the `IgnoreCollisionWith(body)` method.

You might also want to look into Collision Categories. You can define a Body's collision category and also which categories it collides with. This way, a body can avoid collisions with a whole group of other bodies, without having to use `IgnoreCollisionWith` against every single one of those bodies.

# Answer
> 0 votes
Well you can always attach an event to the bodies and when they collide with something check their ID's and only allow the collision if that was the first time (could do that with a bool)

```
   bool thingy=true;
      Body1.OnCollision += new OnCollisionEventHandler(Body_OnCollision);
      bool Body_OnCollision(Fixture fixtureA, Fixture fixtureB, Contact contact)
        {
            if (fixtureA.FixtureId == 1 && fixtureB.FixtureId == 2 && thingy == false)
            {
                thingy = true;
                return true;

            }
            else
                return false;
        }

```

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


# Question
Title: multiplayer tic-tac toe checking if other player is in game or not
I am developing a multiplayer tic tac toe game. The issue I'm facing at the moment is knowing whether the other player is in the game or not. Each player is running their own session, and should a player's session not exist, the game should end. How can I know whether the other player session exists or not?

# Answer
Simply have a timer. For example if a player gets 5 seconds then show a countdown for that 5 seconds and if the player hasn't made their turn by then I would say there is a 90% chance that the player has disconnected - so they automatically 'lose'.

In multiplayer games you must have some sort of timer or some players simply disconnect instead of losing.
> 1 votes

---
Tags: databases, php, analytics
---


# Question
Title: Collision representation in game overworlds
I'm implementing a 2D overworld where one can walk through an area that is not tile based. I was wondering the best way to implement collisions. In the past when I've done similar things, I've used one image (or set of images) to show an elaborately drawn world and then a second binary image that does nothing but differentiate "wall" and "not wall". Then, I'd use the first for all drawing to the screen, but the second for collision detection. Having another image of the same size to represent collisions seems like lots of overhead. Is there a better way to handle this?

(I'm currently using C++ with SDL, although I'm more interested in general concepts)

# Answer
You can use a tile based collision approach independently whether the landscape itself is tile based or not. It's basically as fast as it can get and also as easy to implement as it can get.

If you need a really high precision and memory usage is a issue you can use a quad tree instead of a simple array. (A data structure with almost O(1) performance but which is more flexible in how much detail is stored.)

If you want more complex physics you probably want a collision polygon, so you can handle slopes, rotations etc. better.
> 1 votes

---
Tags: collision-detection
---


# Question
Title: What are the possible options for AI path-finding etc when the world is "partitionned"?
If you anticipate a large persistent game world, and you don't want to end up with some game server crashing due to overload, then you have to design from the ground up a game world that is partitioned in chunks. This is in particular true if you want to run your game servers in the cloud, where each individual VM is relatively week, and memory and CPU are at a premium.

I think the biggest challenge here is that the player receives all the parts around the location of the avatar, but mobs/monsters are normally located in the server itself, and can only directly access the data about the part of the world that the server own. So how can we make the AI behave realistically in that context?

It can send queries to the other servers that own the neighboring parts, but that sounds rather network intensive and latency prone.

It would probably be more performant for each mob AI to be spread over the neighboring parts, and proactively send the relevant info to the part that contains the actual mob atm. That would also reduce the stress in a mob crossing a border between two parts, and therefore "switching server".

Have you heard of any AI design that solves those issues? Some kind of distributed AI brain? Maybe some kind of "agent" community working together through message passing?

# Answer
Spacial partitioning is a big subject with entire books devoted to it which makes a general form answer difficult, but I will try to address each one of the major types. I will talk about the collision resolution to talk about the agent resolution (an agent field of vision is essentially a collision test)

**Tree Based Partitioning**(BSP, Quadtree, OctTree):

I know that BSP would typically get its own section, but it acts similar enough to the others so it is here. for collisions these tend to have fast resolution at the leaves, but can have slow resolution when the object in question is across the root partition (though this is an edge case) it eliminate some of the benefits of the tree partitioning.

when using such for AI applications these have the same benefits as the collisions, but are far more likely to experience the edge cases of crossing partitions mainly because agent field of view is a bigger radius then the collisions, and tree partitioning tends to lend itself more to objects that are equal, or smaller then the surrounding objects. though you could spend some time optimizing n (depth from root).

If your planning to have a different AI controller for each leaf. this will require a great deal of messaging due to the high likelihood of the edge cases, and if your basing all messages on player/enemy-agent location then you will have to not only know what leaves are adjacent (which is counter intuitive to the vary structure to have a graph underneath a tree), or do the AI FOV tests from the player, but that means you would have to do back end checks for if you want mod dynamics, or group level behavior.

**Hierarchic Based Partitioning** (BVH)

You could lump these in with tree based, but they have a different methodology of construction (leaf to root instead of root to leaf), and a disadvantage (wrt AI) that is unique to them so I am breaking it off. these are vary fast for things that are spread out, and converge quickly know what is adjacent, and relatively easy to move things around, but can suffer from maybe having to be rebuilt every physics iteration.

for AI this is a late resolution system because the system is designed to not really do anything until your at a leaf (typically only 2 objects), and doesn't care about distance from one to another until it is making its root for the next parent (as these are usually built from leaf to root), and then you don't actually know where the entity is wrt to the dimensions of the leaf.

for this approach it is best if every agent had their own controller, but I would greatly discourage from using this approach for AI as its drawback is quite enormous for the purpose of AI unless you are going to run it twice with FOV data as apposed to collision data which apart from reusing existing code artifacts has little merit.

**Grid based**

for collisions (presuming that geometry accommodates) this approach tends to having a graph feel to it, and is designed specifically to alleviate the problems of a tree partitioning edge case (mainly because an object in more then one grid section means that a collision will happen. though these do have a draw back of being data intensive. where a tree based system would rarely have nothing in a node, and a BVH would never have nothing in a node. the grid system is essentially a 2-3 dimensional array of object arrays, and has a high likelihood that a majority of them will be empty.

Not to lose objectivity, but I would greatly endorse this system for AI. even though it can have a large memory foot print for collisions it lends itself easily to FOV tests (and could even replace the FOV tests with an adjacency test (is there a player n nodes away then react). though this approach does disallow for a unified controller system in that you would either have to overlay a tree onto the grid which loses versatility if the tree has to great of an n.

there are other spacial partitioning systems, but they do not come to mind if someone would wish to add them in an edit it is acceptable

**general recommendation** (this can be taken as conjecture)

a high suggestion if feasible would be to have a zone type system (areaX is a zone with its own stuff, and then adjacent areaY is a zone with its own stuff), and then inside each zone have a grid. these zones can be based on a secondary partitioning system. composition of systems is not unheard of, and is quite extensible, but just avoid redundancy of systems (systemX does all the work, but needs to cross reference systemY that needs to do the same extent of work).

When the discussion gets to the point of AI controllers (one controller for many agents, or agent groups) the point of grids do not lend themselves to unified controllers, but what you can do is have a controller for a group of agents (this is where mobs can come in), and then when one agent in the group "locates" the player/enemy agent the entire group can react. though maybe a threat processing, or something

\[tangent\] for some originality have the agent controller for the group do a threat calculation on the enemy, and then have tiers of responses. so you don't have the classic "playerX pulls the mob while the other players setup to ambush the mob"\[/tangent\]
> 2 votes

# Answer
I have never done this before but these are my two cents:

The AI Pathfinding algorithm is limited to a relatively small area around the mobs' spawn location e.g. 1km radius. If the player runs out of this area, the mob gives up chase. This is usually what is observed. This means that the player-visible areas and the pathfinding map the mob use are different maps. Also means you can design in a way where no mobs will cross servers.

The algorithm also does not need the massive data of texture, geometries etc that the player sees. The algorithm only needs to see a very simplified representation of the mob's immediate area so while only small part of the game world (textures, geometries, music etc) is loaded, for the player's view, a larger but simplified "obstacle map" for each mob can be loaded.

Mobs usually also can have fixed waypoint sets. If you have a large number of these waypoints, then the mob can appear to walk randomly.

If a Mob is chasing the player, the same "obstacle map" can be used for player collision detection and mob AI pathfinding (or player-chasing).

One thing I observed in WoW (although I can be wrong) is that if you ride on a very fast flying mount and try to run away from a mob's fireball, it appears that the fireball track your taken path so that it does not need to do it's own path finding.

If your AI algorithm is deterministic, you may not have to synchronise mob locations (that often) across servers for areas near the seamless boundary. Alternatively, just don't make it seamless, do a "now loading map..." splash screen when travelling across servers. On the otherhand, you still may have to sync the mob locations server to clients at some point so you might be able to reuse that code.
> 2 votes

---
Tags: ai, space-partitioning
---


# Question
Title: Detecting wins in peer to peer RTS games like Starcraft
A typical RTS game is implemented with the standard networking model: peer to peer lockstep.

Consider Starcraft 2, given that Battle.net presumably doesn't know anything about the state of game given that there is only communication between the two players in a peer to peer model, how does Battle.net know who was the winner in the end. Relying on the two peers to not try to cheat and report accurate results is naive.

# Answer
> 3 votes
If I remember correctly, SC2 actually isn't peer-to-peer; it's client-server with Battle.net (still deterministic lockstep though) so this is a non-issue. In the real world however, getting all peers to agree to some state or the result of some operation ("winner" is certainly shared state in this point) is provably impossible in bounded time. Take a look at the formal proof for the Byzantine Generals problem and also the Fischer consensus problem. This is a decent starting point (look at the citations and read those): Consensus (Computer Science)

# Answer
> 0 votes
If all players agree, then that's obviously accurate. Else, the game's state is invalid and nobody "won". However, note that you can use SSL to encrypt communications between BNet and the game client- which obviously must exist, else how can features like in-game chat exist? There's no reason to believe that the clients do not communicate with Battle.NET during a game.

---
Tags: networking, multiplayer, rts
---


title: Moving 2d camera in the y direction

text:
# Question
Title: Moving 2d camera in the y direction
I'm developing a simple game for the iphone and am struggling to work out the best way for the camera to follow the main character. The following picture hightlights the three main components:

There are 3 components to this:

* Circle - the main character
* Green line - terrain
* Black background

The terrain is simply made from an array of points (approx 20 points per screen width). The terrain is moved in the x direction relative to the black background in order to keep the circle in its position shown. The distance to move the terrain is simply:

movex = circle.position.x - terrain.position.x

with a constant to fix the circle at some distance from the left of the screen.

I am struggling to determine the best way to position the terrain in the y plane keep the focus in the character. I want to move the terrain in the y direction smoothly and not fix it to the position of the circle, so the circle can move in the y plane.

If I take the same approach as the x positioning, the character is fixed at a point on the screen and the terrain moves. I could sample some terrain points either side of the character and produce an average, but in my implementation this was not smooth. I thought another approach might be to create a camera 'line' that is a smooth version of the terrain line and make the camerea follow this, but I'm not sure if this is the optimum solution. Any advice is much appreciated!

# Answer
What you could do is determine where the character is within the viewport and only move the camera up if it is within (say) the top 20% or down if it's within the bottom 20%. Take this image for example:

The red and blue lines here represent the spot where the player would move the camera. For example, when the ball's position hits the red line, the camera would move up with the player. If the ball's position hits the blue line, the camera would move down with the player. This would allow the ball to bounce and move within the area between the red and blue lines but still keep the camera following the ball if, for example, it bounced really high.

You could move the blue line up if you wanted to make it centered on screen most of the time.
> 2 votes

# Answer
I would let the ball move in the camera-relative y plane within a certain range. Say the screen is 100px tall (I don't recall the actual specs); if the ball's y is above a certain threshold, maybe 70px above the bottom of the screen, move the camera up with the player. If the ball is below 30px, move the camera down with the player. Otherwise just keep the camera steady and let the ball move.

You may want to slowly recenter the camera on the player if he remains "stuck" at one of the thresholds.
> 1 votes

---
Tags: iphone, box2d, cocos2d-iphone, camera
---


# Question
Title: Can a local multiplayer iOS game display differently for each device?
I've seen games which display different data for two devices, but not more than two.

If possible, can it be accomplished using GameKit?

EDIT:
More specifically, I was thinking local multiplayer via bluetooth or wi-fi on an iOS device. Most games I've seen display the same screen synchronized across all of the devices.

I understand games that network across the internet do this, often using a server, but I haven't seen any examples of a 3+ device local multiplayer iOS game. I just want to make sure it wasn't some kind of limitation.

# Answer
Yes, of course. The devices are communicating data so they're both kept up to date on each other (or at least, on the information you choose to share). They are *not* necessarily keeping absolutely in synch, and nothing is saying they must use that data in the exact same way. There's nothing stopping you from displaying that data completely differently between the two apps - just program your app that way. Each device has its completely individual app running, completely separate from the others, and it can do what it wants.

After all, how could you possibly have, say, a multiplayer game with fog of war if your games weren't displaying data differently?

As for the "more than two" - I don't quite understand what you're implying since you're not communicating well, but again it's just a matter of what data you want to share and what you want to display and how.
> 4 votes

---
Tags: ios, multiplayer
---


# Question
Title: Mobile 3D engine renders alpha as full-object transparency
I am running a iOS project using the isgl3d framework for showing pod files.

I have a stylish car with 0.5 alpha windows, that I wish to render on a camera background, seeking some augmented reality goodness.

The alpha on the windows looks okay, but when I add the object, I notice that it renders the entire object transparently, where the windows are. Including interior of the car.

Like so (in example, keyboard can be seen through the dashboard, seats and so on. should be solid)

The car interior is a seperate object with alpha 1.0.

I would rather not show a "ghost car" in my project, but I haven't found a way around this.

Have anyone encountered the same issue, and eventually reached a solution ?

# Answer
> 3 votes
**SOLVED:** Thanks to Demi. Here is the final code:

```
// Render opaque objects
        [_scene render:renderer opaque:true];

        // First planar shadow pass (if needed)
        [self renderPlanarShadows:renderer];

        // Render transparent objects
        glColorMask(1, 1, 1, 0);
        if (_zSortingEnabled) {
            [_scene renderZSortedAlphaObjects:renderer viewMatrix:&viewMatrix];

        } else {
            [_scene render:renderer opaque:true];
        }
        glColorMask(1, 1, 1, 1);

```

# Answer
> 5 votes
(No experience with 3D programming on iOS, but this should work on regular OpenGL devices.)

I can think of 2 options that might fix this.

Try separating the model in 2 parts, first render the opaque part and then render the transparent part.

Another option might be to disable alpha writing when rendering the object. What I think is happening is that when the window is rendered the alpha value is simply written to the color buffer. When then rendering the color buffer over the camera image the windows are alpha blended with the image behind it, causing ghost cars.

---
Tags: 3d, rendering, transparency
---


title: How to update a game off a database

text:
# Question
Title: How to update a game off a database
I am currently writing a sports strategy management game (cricket) in PHP, with a MYSQL database, and I have come across one stumbling block - how do I update games where neither player is online?

Cricket is a game played between two players, and when they (or one of them) is online then everything is fine; but what if neither player is online? This occurs when championship games are played, and these games need to happen at certain times for game reasons.

At the moment I have a private web page that updates every 5 seconds, and each time it loads all games are updated; but then I have the problem that when my private web page stops (for example my computer crashes or my web browser plays up) the game stops updating!

# Answer
As some of the comments mentioned, the issue is that you are trying to get the behaviour of a real-time simulation via an event-driven application.

Your options are basically these:

1. Create fake events to ensure the web page is accessed when you need to perform these updates. This could be a cron job that polls a certain page. (However, if you have a system capable of running periodic cron jobs to access a web page, you should probably just have that system perform the update itself. See below.)
2. Make the system perform 'just-in-time' updates. Games don't actually need to occur when nobody is looking at the page - they just need to have seemed to have occurred whenever someone next looks at the site. So, you have a routine, usually included on every page in your game, which checks for overdue updates and executes them immediately, before returning the rest of the page as usual. So if nobody accessed the site for a week, the next visitor would trigger off one week's worth of updates, and would see those events as expected. This is probably the easiest route and I expect it would work well for you.
3. Have the database perform timed updates. MySQL offers events that can run stored procedures. This is ok, providing that you can write all your game logic in your database's stored routine syntax. Usually this is impractical.
4. Use your own long-running process (ie. a daemon as mentioned in comments) to host your game instead of one that only runs for the duration of serving up a page. There are many languages and systems that can do this, almost all of them arguably better for programming games in than PHP, but usually not as quick to get started with. They also tend to require more expensive hosting. But since they run permanently in the background while waiting for incoming HTTP connections, it is usually easy to implement background jobs that perform timed updates of your choosing, whether someone has connected to the site or not.
> 7 votes

---
Tags: game-design
---


# Question
Title: Problem with drawing textures in OpenGL ES
I'm developing a 2D game for Android and i'm using the framework which has been told in the book which named Beginning Android Games by Mario Zechner.So my framework is well designed and using OpenGL 1.1.It's similar to libgdx.

When i put my textures adjacent each other in my 2d surface,there are some spaces size as 1 px.But this problem only occur on my tablet.There aren't a problem like this on my phone.It's like in this picture:

What can be the problem?I can't fix it from one week.

# Answer
It's hard to say what the problem is for certain. However, there are some particular things that can cause trouble at edges of tiles:

* If you are using a texture atlas (that is, graphics for multiple tiles stored in a single texture), then adjacent texture tiles *may* “leak through” borders due to numerical error; but more to the point, they *will* show through if you are using `GL_LINEAR` magnification (which it appears you are), because that essentially “blurs” the image by half a texel width. The sign of this problem is that the edge shows colors of the tiles which are adjacent in the texture to the tiles which are being drawn.

In order to avoid this, you must either inset your texture coordinates by half a texel width (thus avoiding the region of blending) or enlarge the tile in the texture by one pixel (thus blending to appropriate colors); these will give slightly different visual results due to the texel centers being on or off the edge of the tile.
* If you have `GL_POLYGON_SMOOTH` enabled, turn it off; that mode is not good for abutting objects. If you need antialiasing, use multisampling instead. The sign of this type of problem is that the line will have some amount of the color of the graphics *behind* it. (This may not even be available in OpenGL ES; I don't know.)
* Make sure you are computing the positions of your tiles in a numerically robust fashion. OpenGL only guarantees edges will line up if the vertex positions are *identical*. A simple way to ensure this is to use only integer-valued coordinates (i.e. the corner coordinate and the index of a tile are the same) when specifying the geometry of the tiles, and use the matrices to scale as needed.
> 1 votes

# Answer
possibly you can get better results by setting smth like: **GL\_TEXTURE\_WRAP\_S/T** to **GL\_REPEAT** rather than **GL\_CLAMP\_TO\_EDGE**

*Edited:* is your texture is power of two?
> 1 votes

---
Tags: android, opengl-es
---


# Question
Title: How many textures can I usually bind at once?
I'm developing a game engine, and it's only going to work on modern (Shader model 4+) hardware. I figure that, by the time I'm done with it, that won't be such an unreasonable requirement.

My question is: how many textures can I bind at once on a modern graphics card? 16 would be sufficient. Can I expect most modern graphics cards to support that number of textures?

My GTX 460 appears to support 32, but I have no idea if that's representative of most modern video cards.

# Answer
> 63 votes
The number of textures that can be bound to OpenGL is *not 32* or *16*. It is not what you get with `glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &texture_units);`. That function retrieves the number of textures that can be accessed *by the fragment shader*.

See, each shader has *its own limit* of the number of textures it can use. However, there is also a total number of textures that can be used, period. This is defined (in OpenGL) by `GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS`.

So there are two limits: the textures-per-stage, and the textures-total-bound.

OpenGL 3.x defines the minimum number for the per-stage limit to be 16, so hardware cannot have fewer than 16 textures-per-stage. It can have a higher limit, but you know you get at least 16. 3.x defines the minimum number for the textures-total-bound as 48. AKA: 16 * 3 stages. Similarly, GL 4.x defines the numbers to be 16 textures-per-stage, and 96 textures-total-bound (ie: 16 * 6 stages, including compute shaders).

Again, these are the *minimum* numbers. Hardware can (and does) vary.

As for specific hardware, you can expect any DX10-class hardware to match these numbers. DX11 class hardware has some variance; NVIDIA (GeForce 4xx+) and higher-end AMD chips (aka: GCN-cores) may have more than the 16-per-stage.

# Answer
> 4 votes
I believe 32 is the maximum number of textures that can be bound currently. As far as I can tell even the 8800 series had 32 texture units.

As far as I know, for openGL 4.x support you will need a Fermi or newer nvidia card(or corresponding amd card), the higher end models all seem to have 32 units, while the lowest end cards (GT 430, for example) have 16. However, looking at AMD spec sheets they list numbers like 80 or 128 texture units, but list 32 color ROP units which seem to have remained constant through generations.

The GTX 480 on the other hand is listed with 60 texture units and 48 ROP units, while lower end cards like the 430 reportedly only have 16 texture units and 4 ROP inits. So on the whole I'm not really convinced either of those is the number you are actually looking for.

You can check the number of texture units available for non-fixed function pipeline rendering with `glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &texture_units);`, though, so if you have access to some diverse hardware you could check yourself.

EDIT: this site lets you compare the reported openGL capabilities of all sorts of video cards, that should give you the numbers you need: http://feedback.wildfiregames.com/report/opengl/device/GeForce%20GTX%20580

PS: AMD and nvidia have recently introduced "bindless textures", (amd has a different name for it) which allows you to use large numbers of textures without binding them to textutre units, at the moment this is only available in openGL.

---
Tags: opengl, textures, graphics-programming, hardware
---


# Question
Title: simplest way of making a sphere roll in a realistic way
rather than just moving a sphere across a plane, I want to make it roll like a ball. What is the simplest way of doing this? I assume it will have something to do with the circumference of the ball and rotating + moving it at a calculated rate.

What is the relevant maths here?

# Answer
The simplest way is to calculate how much ball is moved and rotate the ball that much divided by it's radius!

And the reason: we all know how they calculate PI. imagine a circle with radius of one unit, it's perimeter is 2\*PI as shown in this picture:

Now in your case the ball may move in any direction. but it's movement speed is always a 2d vector (note that it's rolling not flying!) and to rotate a ball you need a 2d vector. these 2d vectors have the same value except you need to divide speed vector by sphere diameter.

and as a sidenote, I've assumed that rotating the ball doesn't need any force. if you want a real physical simulation thing get a little more harder than this.
> 15 votes

# Answer
Gajet's answer does an excellent job of covering the '2d' case, where your ball moves in one dimension; if you want to roll it across a plane then things get decidedly more complicated, but still very manageable.

Here the ball is rolling across a plane in the direction of the green arrow, with (instantaneous) velocity V; the rotation is around the axis of the red arrow, and the normal to the plane is represented by the blue arrow (N). The instantaneous axis of rotation can be found by finding the cross product of the velocity vector with the normal vector, R=VxN; by combining this with something like Gajet's method (using V*t as the amount moved, where t is the time from the last frame to this one) you can construct a quaternion q representing the rotation the ball underwent over the course of the frame: basically, normalize your axis-of-rotation vector R to get R\_n, find the amount of rotation Theta as V*t/2\*pi*b, where b is the ball's radius, and build the quaternion q=(R*sin(Theta/2), cos(Theta/2)). Then you can compose this quaternion with the ball's previous rotation to get its new rotation.

But be careful - for most rolling-ball style games, this approach is actually exactly backwards! For instance, if you determine your ball's rotation by how far it's moved in contact with the ground, then you'll never see any 'spin' in the ball while it's in the air. Instead, I've found it works better to go the other way: keep track of your ball's angular velocity, have the player's controls actually (behind the scenes) control that angular velocity, and then while the ball is in contact with a surface, use the presumption that you're rolling without slipping to 'unroll' the motion like in Gajet's diagram and figure out where your ball ought to move to next frame. This gives you better physics because it gives you the option to roll *with* slipping, or to spin along the ground, or a number of other subtleties.
> 6 votes

# Answer
For 2D could use something like:

```
totalMovementVector = previousPosition - currentPosition;
distanceMoved = totalMovementVector.magnitude;
circumfrenceOfCircle = circleRadius * 2 * PI;
amountToRotateInDegrees = distanceMoved / circumfrenceOfCircle * 360;
thingThatIsBeingRotated.rotation += amountToRotateInDegrees;

```

if you don't have vectors i.e. flash

```
totalXMovement = previousX - currentX;
totalYMovement = previousY - currentY;
distanceMoved = squareRoot((totalXMovement * totalXMovement) + (totalYMovement * totalYMovement));
circumfrenceOfCircle = circleWidth * PI;
amountToRotateInDegrees = distanceMoved / circumfrenceOfCircle * 360;
thingThatIsBeingRotated.rotation += amountToRotateInDegrees;

```
> 0 votes

---
Tags: c++, mathematics, physics, directx, directx10
---