title: My Sprite comes out the screen

text:
# Question
Title: My Sprite comes out the screen
If i an action moves the sprite,how can i keep the CCSprite on the screen???? this is my code:

```
[enemy runAction:[CCSequence actions:[CCMoveBy actionWithDuration:2.0 position:ccp(-winSize.width*0.4, 0)],
                      [CCMoveBy actionWithDuration:randomValueBetween(1.0, 0.3)
                                          position:ccp(randomValueBetween(winSize.width*0.2, -winSize.width*0.2),
                                                               randomValueBetween(winSize.height*0.2, -winSize.height*0.2))],
                      [CCDelayTime actionWithDuration:0.5],
                      [CCMoveBy actionWithDuration:randomValueBetween(1.0, 0.3)
                                          position:ccp(randomValueBetween(winSize.width*0.2, -winSize.width*0.2),
                                                               randomValueBetween(winSize.height*0.2, -winSize.height*0.2))],
                      [CCDelayTime actionWithDuration:0.5],
                      [CCMoveBy actionWithDuration:randomValueBetween(1.0, 0.3)
                                          position:ccp(randomValueBetween(winSize.width*0.2, -winSize.width*0.2),
                                                               randomValueBetween(winSize.height*0.2, -winSize.height*0.2))],
                      [CCDelayTime actionWithDuration:0.5],
                      [CCMoveBy actionWithDuration:randomValueBetween(1.0, 0.3)
                                          position:ccp(randomValueBetween(winSize.width*0.2, -winSize.width*0.2),
                                                               randomValueBetween(winSize.height*0.2, -winSize.height*0.2))],
                      [CCDelayTime actionWithDuration:0.5],
                      [CCMoveBy actionWithDuration:randomValueBetween(1.0, 0.3)
                                          position:ccp(randomValueBetween(winSize.width*0.2, -winSize.width*0.2),
                                                               randomValueBetween(winSize.height*0.2, -winSize.height*0.2))],
                      [CCDelayTime actionWithDuration:0.5],
                      [CCMoveBy actionWithDuration:randomValueBetween(1.0, 0.3)
                                          position:ccp(randomValueBetween(-winSize.width*0.3,winSize.width*0.3),
                                                       randomValueBetween(winSize.height*0.3, -winSize.height*0.3))],
                      [CCDelayTime actionWithDuration:0.5],
                      [CCMoveBy actionWithDuration:randomValueBetween(1.0, 0.3)
                                          position:ccp(randomValueBetween(-winSize.width*0.2,winSize.width*0.2),
                                                       randomValueBetween(winSize.height*0.2, -winSize.height*0.2))],
                      [CCDelayTime actionWithDuration:0.5],
                      [CCMoveBy actionWithDuration:randomValueBetween(1.0, 0.3)
                                          position:ccp(randomValueBetween(-winSize.width*0.3,winSize.width*0.3),
                                                       randomValueBetween(winSize.height*0.3, -winSize.height*0.3))],
                      [CCDelayTime actionWithDuration:0.5],
                      [CCMoveBy actionWithDuration:randomValueBetween(1.0, 0.3)
                                          position:ccp(randomValueBetween(-winSize.width*0.2,winSize.width*0.2),
                                                       randomValueBetween(winSize.height*0.2, -winSize.height*0.2))],
                      [CCDelayTime actionWithDuration:0.5],
                      [CCMoveBy actionWithDuration:randomValueBetween(1.0, 0.3)
                                          position:ccp(randomValueBetween(-winSize.width*0.3,winSize.width*0.3),
                                                       randomValueBetween(winSize.height*0.3, -winSize.height*0.3))],
                      [CCDelayTime actionWithDuration:0.5],
                      [CCMoveBy actionWithDuration:randomValueBetween(1.0, 0.3)
                                          position:ccp(randomValueBetween(-winSize.width*0.2,winSize.width*0.2),
                                                       randomValueBetween(winSize.height*0.2, -winSize.height*0.2))],
                      [CCDelayTime actionWithDuration:0.5],
                      [CCMoveBy actionWithDuration:2.0 position:ccp(-winSize.width*1.5, 0)],
                      [CCCallFuncN actionWithTarget:self selector:@selector(invisNode:)], nil]];

```

but whit this code the sprite sometimes comes out the screen, i need the sprite moves randomly in the screen without comes out..

# Answer
To limit the movement within the screen bounds, get the position to ccmoveto first, here which is determined by random. Perform a check to see if the position is within the bounds of the screen. If it is, then do nothing. If the new position is out of bounds, then set it to a position within bounds.

I am not sure how your anchor/relative points are set. On my projects, negative usually means outside of the screen.

To integrate, I would suggest creating a separate function that returns the position desired:

Using my settings and taking into account the sprite/node size, for example:

```
-(CGPoint) boundPosition(CGPoint desiredPosition, CGRect spriteSize) {
  CGPoint newPosition = desiredPosition;
  //position is outside of the screen on the left
  if (desiredPosition.x < (0 + spriteSize.width/2)) {
    //set the position to the leftmost possible
    newPosition.x = spriteSize.width/2;
  }
  //position is outside of the screen on the right
  if (desiredPosition.x > (winSize.width - spriteSize.width/2)) {
    //set the position to the rightmost possible
    newPosition.x = winSize.width - spriteSize.width/2;
  }
  //position is below the screen
  if (desiredPosition.y < (0 + spriteSize.height/2)) {
    //set the position to the bottommost possible
    newPosition.y = spriteSize.height/2;
  }
  //position is above the screen
  if (desiredPostiion.y > (winSize.height - spriteSize.height/2)) {
    //set position to uppermost possible
    newPosition.y = winSize.height - spriteSize.height/2;
  }
}

```

Should be able to plug into each CCMoveBy as so:

```
[CCMoveBy actionWithDuration:randomValueBetween(1.0, 0.3)
                                          position:boundPosition(ccp(randomValueBetween(winSize.width*0.2, winSize.width*0.6),
                                                               randomValueBetween(winSize.height*0.2, winSize.height*0.6)), enemy.contentSize)]

```
> 1 votes

---
Tags: cocos2d-iphone, cocos2d
---


title: Problem switching Scenes in AndEngine

text:
# Question
Title: Problem switching Scenes in AndEngine
I am Developing a game in AndEngine Gles2. I have splash scene, loading scene, menu scene and Level1 scene. I am using a Screen Manager to manage all scenes so I can easily switch between splash, loading and menu scenes.

The level1 scene is also loaded from menu perfectly but a problem occurs when I go back to menu scene on the completion of level. The screen turns black and nothing is shown after that, but the music keeps playing and logcat logs continue. I think the problem is with unloading the resources of Level1 because the switching between other scenes is perfect. I can't give complete code, as it's too long.

I am using bitmapTexture region, Sprites, bodies, physics Word, hud and fixtures etc. Here is my unload method:

```
unload(){
    setChildrenIgnorUpdate();
    clearChildScene();
    clearEntityModifier();
    clearTouchAreas();
    clearUpdateHandler();
    BitmapTextureManager.getInstance().destroyInstance();
    destroyPhysics();
}

```

# Answer
> 3 votes
I think following link become useful to you in managing multiple scene in single game. https://sites.google.com/site/matimdevelopment/creating-and-managing-scenes

Also in AndEngine forum, we discussed about this topic that link I provide to help other guys.

http://www.andengine.org/forums/gles1/how-to-manage-multiple-scene-t10350.html

---
Tags: andengine, scene
---


# Question
Title: running GL ES 2.0 code under Linux ( no Android no iOS )
I need to code OpenGL ES 2.0 bits and i would like to do this and run the programs on my desktop for practical reasons.

Now, i already have tried the official GLES SDK from ATI for my videocard but it not even runs the examples that comes with the SDK itself, i'm not looking for performance here, even a software based rendering pipeline could be enough, i just need full support for GLES 2.0 and GLSL to code and run GL stuff.

There is a reliable solution for this under Ubuntu Linux ?

# Answer
> 2 votes
I use JOGL, it uses every OpenGL profile you can think of. You can find it at Jogamp.org.

---
Tags: glsl, opengl-es2, linux
---


# Question
Title: Is there a simpler way to create a borderless window with XNA 4.0?
When looking into making my XNA game's window border-less, I found no properties or methods under `Game.Window` that would provide this, but I did find a window handle to the form.

I was able to accomplish what I wanted by doing this:

```
IntPtr hWnd = this.Window.Handle;
var control = System.Windows.Forms.Control.FromHandle( hWnd );
var form = control.FindForm();
form.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;

```

I don't know why but this feels like a dirty hack. Is there a built-in way to do this in XNA that I'm missing?

# Answer
> 5 votes
Unfortunately there isn't a "simpler" way.

You're right in thinking that it is "hacky". It depends on internal implementation details of XNA. Which means it could break in future versions of XNA (there's nothing saying that XNA's `Game` class needs to use a `Form`). Also - in *theory* it might fail in unexpected ways - the XNA team hasn't necessarily tested this behaviour at all - let alone extensively.

(Note that XNA games are version-specific. For example: An XNA 3 game requires XNA 3 and won't run on XNA 4. So your binary is pretty safe against framework updates - but not necessaraly your code.)

There *is* a non-hacky way, by creating your own alternative to the `Game` class. The WinForms sample shows you how. But then you lose all the helpful stuff that `Game` and its friends provides (most notably the timing stuff).

**But** \- because this is such a trivial settings change, it's probably completely safe to do in this case. And worth the risk, given the alternative is much trickier to implement. Maybe you could add some error-checking/exception handling - but even that's probably not necessary for this specific case.

I'm pretty sure XNA won't care if the `FormBorderStyle` changes out from under it.

(Of course, I've seen people pulling out the `Form` and doing some extremely *brazen* things with it. If you need to do anything beyond tweaking a few settings - I recommend going the "WinForms Sample" route.)

# Answer
> 2 votes
Not that's it's any different, but you can also do this.

```
using System.Windows.Form;

Application.EnableVisualStyles();
Form gameForm = (Form)Form.FromHandle(Window.Handle);
gameForm.FormBorderStyle = FormBorderStyle.None;

```

I think it's worth posting this here as i've never run into any problems at all with this code.

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


# Question
Title: How do I retain previously drawn graphics?
I've created a simple program that draws lines from a fixed point to a random point each frame. I wanted to keep each line on the screen. However, it always seems to be cleared each time it draws on the spriteBatch even without GraphicsDevice.Clear(color) being called. What seems to be the problem?

```
protected override void Draw(GameTime gameTime)
{
   spriteBatch.Begin();
   DrawLine(spriteBatch);
   spriteBatch.End();

   base.Draw(gameTime);
}

private void DrawLine(SpriteBatch spriteBatch)
    {
        Random r = new Random();

        Vector2 a = new Vector2(50, 100);
        Vector2 b = new Vector2(r.Next(0, 640), r.Next(0,480));

        Texture2D filler= new Texture2D(GraphicsDevice, 1, 1, false, SurfaceFormat.Color);
        filler.SetData(new[] { Color.Black });

        float length = Vector2.Distance(a, b);
        float angle = (float)Math.Atan2(b.Y - a.Y, b.X - a.X);
        spriteBatch.Draw(filler, a, null, Color.Black, angle, Vector2.Zero, new Vector2(length,10.0f), SpriteEffects.None, 0f);

    }

```

What am I doing wrong?

# Answer
> 4 votes
That is the default behavior. Imagine if the reverse was the standard: Then all sprites would leave this trail of after-images behind, which is hardly the desired behavior.

What you can do is to have a screen-filling, transparent texture. You set your RenderTarget to that texture, draw your line, then render that texture normally.

From MSDN:

> To use a render target, create a RenderTarget2D object with the width, height, and other options you prefer. Then call GraphicsDevice.SetRenderTarget to make your render target the current render target. From this point on, any Draw calls you make will draw into your render target. When you are finished with the render target, call GraphicsDevice.SetRenderTarget to a new render target (or null for the back buffer). Then at any time you can call RenderTarget2D.GetTexture to get the contents of the render target for further processing.

# Answer
> 3 votes
Just clear every frame and redraw everything - it's the way GPUs are designed to work, and trying tricksy stuff to avoid this will only cause you more and more trouble as time goes on.

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


# Question
Title: how to do sprinkle effect of water in opengl in android?
I want to achieve sprinkling effect of water in android using opengl. so, do i need to achieve it with graphics? is there any other way to do it using opengl?

or how can i start working on this,any links?

# Answer
As user827992 said you'll probably need to create a particle system. This does not mean you need a physics library in any way, however.

Spawn sparkles over the water of random size and placement between whatever specified thresholds you desire(just tinker with it till it looks purtty). Have them fade in and back out. You'll also need to control the rate at which the particle spawn.

There might be a library out there to handle particle systems for opengl-es, but I'm not sure.

Alternatively you can make an animation that plays over the water, or animate the water itself. However this is less dynamic and may look stale.
> 4 votes

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


# Question
Title: default xna 4.0 gametime don´t works well for 2D physics
I am developing a game using Visual Studio 2010 and XNA 4.0, after advancing to some extent with the project (a platform based 2d platformer msdn starter kit) I got to test it on different computers with different hardware (CPU, graphics, etc.) and I found that the speed of movement object of the game is quite different, I implemented the PSK physics msdn that are based on time,

```
            /// <summary>
            /// Updates the player's velocity and position based on input, gravity, etc.
            /// </summary>
            public void ApplyPhysics(GameTime gameTime)
            {
                    float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;
                    Vector2 previousPosition = Position;
                    // Base velocity is a combination of horizontal movement control and
                    // acceleration downward due to gravity.
                    velocity.X += movement * MoveAcceleration * elapsed;
                    velocity.Y = MathHelper.Clamp(velocity.Y + GravityAcceleration * elapsed, -MaxFallSpeed, MaxFallSpeed);
                    velocity.Y = DoJump(velocity.Y, gameTime);

                    // Apply pseudo-drag horizontally.
                    if (IsOnGround)
                            velocity.X *= GroundDragFactor;
                    else
                            velocity.X *= GroundDragFactor;
                            //velocity.X *= AirDragFactor;
                    // Prevent the player from running faster than his top speed.
                    velocity.X = MathHelper.Clamp(velocity.X, -MaxMoveSpeed, MaxMoveSpeed);
                    // Apply velocity.
                    Position += velocity *elapsed;
                    Position = new Vector2((float)Math.Round(Position.X), (float)Math.Round(Position.Y));

                    // If the player is now colliding with the level, separate them.
                    HandleCollisions(gameTime);
                    // If the collision stopped us from moving, reset the velocity to zero.
                    if (Position.X == previousPosition.X)
                            velocity.X = 0;
                    if (Position.Y == previousPosition.Y)
                    {
                            velocity.Y = 0;
                            jumpTime = 0.0f;
                    }
            }

```

tested eg with a PC (PC1) 2.13GHz Intel Core 2 6400 / ATI Radeon HD 4670 and another one: (pc2) 3.00GHz Intel Pentium D / Intel 82945G Express Chipset Family by displacement difference (moving x axis at supossed (position = velocity * gametime.ElapsedGameTime.TotalSeconds) constant velocity, for example) is 3 seconds in a total of 20 (example: moving pc1 player sprite 6000 pixels in the x-axis at 20 seconds and pc 2 runs the same distance in 17 ). Tested on a 3rd PC: i72700k / Gigabyte GTX 560 TI the results are even worse, after some time after starting the game gets like 3 times slower and showing the number of pixels in each frame moved in a debug window in the game (counting updatespersecond with counter variable for updates cuantity and gametime for counting a second show 63fps), it appears as if the number is always constant ( refreshments lose the Update method?). In this pc if I put the game in fullscreen during the course of the game, the effect of "go slow" is immediate and restore window mode sometimes yield returns to "normal" and sometimes not. Eventually I began to try a new project to test whether the movement is constant in different pc loading only one sprite and its position value in screen printing. Occur The same. I even tried moving a constant amount of pixels explicitly (position + = 5) and different speeds in different pc quantities of pixels moved in x time. I have the game loop as the default (fixedTimeStep=true;SynchronizeWithVerticalRetrace=true;). I've also tried turning off and creating another timestep as discussed in different post (eg http://gafferongames.com/game-physics/fix-your-timestep/ but i can´t achieve the desired result, move the same number of pixels in X seconds on different computers with windows. All pc used for tests use windows 7 enterprise pc1 == x86 the others are x64.

The weirdest thing is that I find information about people describing the same problem and that I wear long nights of searches.

Thanks for your help.

# Answer
Problem "solved" the pixel amount difference between computers is because i have a fixedtimestep disabled and one of the tested computers monitor refresh rate is 75hz

If the monitor run at 75hz, in xna with isfixedtimestep=false and vsync actived the game run update 75 times per second.

When the two and more tested pcs are configured at 60hz in all of them works well and at same movement velocity.
> 1 votes

---
Tags: c#, 2d, xna-4.0, movement, fixed-timestep
---


# Question
Title: Design leaderboard ratings for quiz games
Back in March 2011 i started the following post: How to design a leaderboard?

Now my quiz game have been out for approximately a year and sold pretty decently. I am working on to update the game design and is again looking into the leaderboard design to make it better as i am not happy with it.

Currently i rate players on number of correct answers, which is not good as it does not consider things like number of games, difficulty levels etc. I also have "extended" stats behind the UITableView (Leaderboard).

* A player can play based on three levels of difficulty: hard, medium or easy
* Difficulty levels can be mixed between players in a game
* Each game can be one to six players, so there can be single games or duels
* Between 2 and 30 questions per game

As i am considering integrating Game Center Leaderboard i need to design a better rating system so i would like to ask for some ideas how to do the rating based on the above.

I am thinking about how much a point would be worth and what it includes.

# Answer
Here's a few ideas:

* Create a separate leaderboard for each difficulty level.
* You might also want to consider having second set of leaderboards which auto reset say once a month.
* I'd be tempted to use something like an Elo system for ranking. That is you start with a fixed number of points, and gain or lose a variable number of points based on the difficulty of your opponents. Maybe with the maximum point gain/loss based on the question count.
* Using the Elo system would require a different design for the single player leaderboard, so that would need to be separate too. How about 1000\*(correct answers/(incorrect answers + K)) where K is there to limit the maximum score for people who've only answered a few questions. You could apply results from multiplayer games to the single player leaderboards if you want to.
> 1 votes

---
Tags: objective-c, game-center
---


title: Resurrecting XNA 3.0 projects

text:
# Question
Title: Resurrecting XNA 3.0 projects
I have some old XNA 3.0 projects that used stuff that has totally been changed in XNA 4.0.

Really I just want to revisit some of my old code, dust it off and refactor it.

Can XNA 3.0 and XNA 4.0 be installed *together* in Visual Studio 2010, or will there be problems?

Should I just install C# Express Edition 2008 with XNA 3.0, and work with my old projects that way?

# Answer
> 6 votes
While the XNA GameStudio frameworks can be installed side-by-side on the same Windows system, I don't think XNA GameStudio 3.x will work with Visual Studio 2010.

The good news (sort of) is, that you can install Visual Studio 2008 side-by-side with Visual Studio 2010. As a matter of fact, I have XNA 3.1, 4.0, and Visual Studio 2005, 2008, and 2010 all installed on my box right now.

---
Tags: xna, compatibility
---


title: Sprite sheet generator

text:
# Question
Title: Sprite sheet generator
I need to generate a sprite sheet with squared sprite for a 2D game. How can I generate a sprite sheet where each frame has x = y? The only think I have to do is to "insert" some blank space between sprites (in case y were \> x in the original sprite). Is there any program that I can use to trasform "irregular" sprite sheets to "squared" sprite sheets?

An example of non-squared sprite sheet: http://spriters-resource.com/gameboy\_advance/khcom/sheet/1138

# Answer
ImageMagick's montage command can do this. For example, to compile a bunch of irregular-sized sprites into a sheet of 32 × 32 pixel tiles, you can do:

```
montage sprite*.png  -geometry "32x32>+0+0"  -background none  sheet.png

```

The `-geometry "32x32>+0+0"` option above will resize all the sprites to 32 × 32 pixels (adding transparent space around smaller images and scaling down any that are too large) and tile them with 0 pixel gaps between them. (The double quotes are there to keep the shell from interpreting the `>` as an output redirection command.)

By default, montage will try to create a "squarish" sheet with roughly as many rows as columns. If you'd prefer, say, a single-column strip, add the option `-tile 1x` after the `-geometry "32x32>+0+0"`. If you want the sheet to have a solid color background, change the `none` to a color specifier (e.g. `white` or `"#ffffff"` for white).
> 9 votes

# Answer
You might have some luck with SpriteVortex.

From the CodePlex page:

> Sprite Vortex aims to greatly reduce the time needed to create frame based sprite animations. It covers common and useful operations such as importing a spritesheet, building spritesheet from separate images , cutting frames, building animations and more. Developed in: C#.
> 0 votes

# Answer
I don't know of a specific program, but there are some steps you can take to use whatever program you like.

1. Get the sprites as individual images. You may already have them in that format, or you'll want to export them as such from whatever program you're using.
2. Parse the images to find their max dimension (`x` or `y`).
3. Pad the images with whitespace or transparency, using the maximum dimension you found in step 2 as the `x` and `y`. Most paint tools have functionality like this, and some allow automation of tasks like this.
4. Generate a sprite sheet with your new square images. Pick your favorite sprite sheet generator and make sure it doesn't trim out the borders.
> 0 votes

---
Tags: 2d, sprites, tools, spritesheet
---


# Question
Title: Techniques for separating game model from presentation
I am creating a simple 2D game using XNA.

The elements that make up the game world are what i refer to as the "model".

For instance, in a board game, i would have a GameBoard class that stores information about the board.

This information could be things such as:

* Location
* Size
* Details about cells on the board (occupied/not occupied)
* etc

This object should either know how to draw itself, or describe how to draw itself to some other entity (renderer) in order to be displayed.

I believe that since the board only contains the data+logic for things regarding it or cells on it, it should not provide the logic of how to draw things (separation of concerns).

How can i achieve a good partitioning and easily allow some other entity to draw it properly?

My motivations for doing so are:

* Allow multiple "implementations" of presentation for a single game entity
* Easier porting to other environments where the presentation code is not available (for example - porting my code to Unity or other game technology that does not rely on XNA).

# Answer
I find that I can create more separation between objects with the least amount of code possible by letting objects draw themselves. However, when I say that, I mean that while render-able objects have a Draw() method, they certainly don't know a single thing about drawing vertices or textures. Instead, they are passed an instance of an object that does all the drawing for them.

This object can be considered a `Renderer` object. What does `Renderer` do? It renders stuff, and it's the only class that knows the ins-and-outs of rendering vertices and textures. Now your gameObjects can just tell the renderer, "Hey, draw me. Here's my data.".

For 2D games in XNA, this is already done for you with `SpriteBatch`.

You may want some sort of an interface, for example, `IDrawable`, that each of your render-able objects will inherit from. This is a guarantee being made to all of your calling code that your render-able objects will contain a specific method signature. It also helps when iterating over a list of objects as you'll see in a bit.

```
public interface IDrawable {
    void Draw( SpriteBatch batch );
}

```

In this case, we're saying that all objects of type `IDrawable` will contain a `Draw` method that takes in a `SpriteBatch` object. Make sure all of your render-able objects inherit this interface, and implement that method. Your typical `Draw` method might look something like:

```
public Draw( SpriteBatch spriteBatch ) {
    spriteBatch.Draw( myTexture2D, myDestRect, Color.White );
}

```

I don't know how you keep a list of all your game-objects, but I tend to have some sort of base class. `GameObject` tends to be the typical base that most people use. In C#, the `foreach` statement makes rendering all of our render-able objects within our `List<GameObject>` really simple:

```
List<GameObject> gameObjects;   // list of all game objects in play
SpriteBatch batch;              // our spritebatch instance

public void Draw() {
    this.batch.Begin();
    foreach( IDrawable gameObject in this.gameObjects ) {
        gameObject.Draw( renderer );
    }
    this.batch.End();
}

```

If you don't want your gameObjects to have a Draw() method *at all*, you can simply move the calling code back to the game state to achieve the same effect:

```
List<GameObject> gameObjects;   // list of all game objects in play
SpriteBatch batch;              // our spritebatch instance

public void Draw() {
    this.batch.Begin();
    foreach( IDrawable gameObject in this.gameObjects ) {
        this.batch.Draw(
            gameObject.Texture2D,
            gameObject.DestRect,
            Color.White );
    }
    this.batch.End();
}

```

There are more extreme methods of separation out there (read up on Entity Component Systems), but I find them a bit too convoluted for my tastes. Game development entails a lot of coupling between data and presentation. That's just the way it is, and sometimes *keeping it simple* works best in the long run.
> 6 votes

---
Tags: xna, architecture, design-patterns
---


# Question
Title: What causes the pre-1.8 Minecraft far lands to generate?
Before Minecraft Beta 1.8, when you reached about x:3000000 y:3000000, the terrain generator would freak out and begin generating broken scary land. What went on in the MC code to provoke this? Why didn't it just completely stop generating? Why does the game still break at locations very far from spawn? What is the cause of this game breaking bug?

# Answer
> 3 votes
> Why does the game still break at locations very far from spawn?

Everything has a limit, especially the numbers on a computer. Assuming he uses floating point numbers in most places, the precision at that point would be very low. My calculations say that it's about 0.25: http://ideone.com/xD7Tm

> the terrain generator would freak out and begin generating broken scary land

My guess is that position properties were added in the seed value, making it break a lot of calculations along the way.

---
Tags: java, minecraft-modding, procedural-generation
---


# Question
Title: How to move Objects smoothly like swimming arround
I have a Box2D project that is about to create a view where the user looks from the Sky onto Water. Or perhaps on a bathtub filled with water or something like this. The Object which holds the fluid actually does not matter, what matters is the movement of the bodies, because they should move like drops of grease on a soup, or wood on water, I can even imagine the the fluid is mercurial, extreme heavy and "lazy".

How can I manipulate the bodies (every frame or time by time) to make them move like this?

I started with randomly manipulation their linear velocity, but I turned out that this not very smooth and looks quite hard.

Is it a better idea to check their velocity and apply impulses? Is there any example?

Greetings philipp

# Answer
If you are describing a top-down, or bird's eye, view, then the solution is simple. Fill your scene with dynamic objects and do not apply gravity to the world at all (set gravity to 0). Then, each update step in your game loop (but never during b2World.step()), apply a force or impulse. This will set them in motion and Box2D will take care of the rest. If you want them to not continue moving forever, set some damping (probably a higher damping for a thicker fluid). This will allow them to slow and come to rest until you apply more forces to them. The rest is just art.
> 4 votes

# Answer
You might want to take a look at some buoyancy examples for box2d.

http://personal.boristhebrave.com/project/b2buoyancycontroller/demo

some info: b2BuoyancyController http://personal.boristhebrave.com/project/b2buoyancycontroller
> 2 votes

---
Tags: box2d
---


title: Can i add friction in air?

text:
# Question
Title: Can i add friction in air?
I have issue regarding speed in air. When i jump and move simultaneously that time speed of player increase.For jump i am using impuls and for movement i am using force.I want to slow speed when player is in air.

Thanks in advance

---

Following is my update method ih HUDLayer

```
-(void)update:(ccTime)dt :(b2Body *)ballBody :(CCSprite *)player1 :(b2World *)world
{

    if (moveRight.active==YES)
    {
            ballBody->SetActive(true);
        b2Vec2 locationworld=b2Vec2(maxSpeed,0);
        double mass=ballBody->GetMass();
        ballBody->ApplyForce(mass*locationworld, ballBody->GetWorldCenter());
      //  ballBody->SetLinearDamping(1.2f);
    }
    else if(moveLeft.active==YES)
    {
            ballBody->SetActive(true);
        b2Vec2 locationworld=b2Vec2(-10,0);
        double mass=ballBody->GetMass();
        ballBody->ApplyForce(mass*locationworld, ballBody->GetWorldCenter());
    //    ballBody->SetLinearDamping(1.2f);

    }

```

} Following is jump

```
-(void)jump:(b2Body*)ballBody:(ccTime)dt:(BOOL)touch
{
    if (touch)
    {

        if (jumpSprte.active==YES)
        {
            ballBody->SetActive(true);
            b2Vec2 locationWorld;
        //locationWorld=b2Vec2(0.0f,98.0f);
            locationWorld=b2Vec2(0,32);
//        double mass=ballBody->GetMass();
            ballBody->ApplyLinearImpulse(locationWorld, ballBody->GetWorldCenter());
      //  ballBody->ApplyForce(mass*locationWorld, ballBody->GetWorldCenter());
            ballBody->SetLinearDamping(1.2f);

        }
    }
}

```

So where i apply logic??

# Answer
Sounds like you want a friction joint. Set the two anchor points to zero so the friction doesn't have any direction. Below is vague pseudocode of how to create a friction joint and add it to your world.

Also make sure you keep the Box2D Manual handy.

```
var frictionJoint = new FrictionJoint();

frictionJoint.localAnchorA = new Vector2(0,0);
frictionJoint.localAnchorB = new Vector2(0,0);

frictionJoint.bodyA = yourBall;
frictionJoint.bodyB = ASquareAsLargeAsTheAreaYouNeedFrictionIn

frictionJoint.maxForce = 0.5; //This the most force the joint will apply to your object. The faster its moving the more force applied
frictionJoint.maxTorque = 5; //Set to 0 to prevent rotation

world.CreateJoint(frictionJoint);

```
> 5 votes

# Answer
Unlike surface friction between solids, air friction (drag) depends on the speed of the object, squared.

An easy way to model friction and drag

```
F(friction) = -k;
F(drag) = speed * speed * -k;

```

Both forces act in the opposite direction to the velocity of the object.

Notice that surface friction is a constant whereas air friction (drag) must be modified each frame according to the object speed (length of velocity vector)
> 3 votes

---
Tags: box2d
---


# Question
Title: Can networking be platform independent in a libgdx game?
LibGDX supports Desktop (Windows, Linux and Mac), Android and web applications. Can i code the network part of an online game without taking care of what kind a of application i'm running? i.e coding the network engine interdependently of the application type.

# Answer
> 6 votes
If you just want to target desktop and android devices, you can use the same networking library, as long as the library supports android.

Kryonet is a networking library, that works both on desktop and android, and it is very easy to use (just look at the example from the page).

If you want to implement networking also for HTML5 games, you would most likely need a different solution. A way to go could be working only with byte streams/arrays and implement the protocol for both javascript and java. I think Node.js has networking functionality and enables sending and receiving byte streams. This would be a more low level approach to networking, in contrast to the kryonet solution.

---
Tags: networking, libgdx
---


# Question
Title: Explicit resource loading in Ogre (Mogre)
I am just starting to learn Mogre and what I would like to do is to be able to load resources 'explicitly' (i.e. I just provide an absolute path instead of using a resource group tied to a directory).

This is very different to *manually* loading resources, which I believe in Ogre has a very specific meaning, to build up the object using Ogres methods. I want to use Ogres resource management system/resource loading code, but to have finer control over which files are loaded and in what groups they are.

I remember reading how to do this but cannot find the page again; I think its possible to do something like:

* Declare a resource group
* Declare the resource(s) (this is when the actual resource file name is provided)
* Initialise the resource group to actually load the resource(s)

Is this the correct procedure? If so, is there any example code showing how to do this?

# Answer
> 2 votes
You may try this article: http://misterblue.com/programming/dynamic-ogre-resources

---
Tags: ogre, assets, resource-management
---


# Question
Title: How do you make bullets move at an angle in different angles using delta
I'm having trouble making my bullets move at a steady pace using delta. I have the formula I used outside of slick2d, but it doesn't take delta into account. My bullets fly fast. How do I make them go slower.

```
x = x + (int) (length * Math.cos(this.angle));
y = y + (int) (length * Math.sin(this.angle));

```

# Answer
> 1 votes
If using slick2d, you can make use of the Vector2d class to do most stuff for you. Have a velocity variable (of the type vector2f) in your entity class.

Then you can do something like this:

```
//During creation of the entity
entity.position = new Vector2f(0, 0);
entity.velocity = new Vector2f(1, 0);
entity.velocity.setTheta(angle);

//During update of the entity
float speed = 0.1f;
entity.position.add(entity.velocity.copy().scale(speed * d));

```

Basically what you do is create a vector, that represents the direction in which the entity is moving. By using new Vector(1, 0), the ray of the vector is 1 "unit" long. During each update, you take this vector (I make a copy, so the initial value is not changed) and multiply it by delta and by speed. Now you can add this multiplied vector to the position vector.

If you want to change the move speed, simple adjust the speed value (smaller values result in smaller speeds).

EDIT: Just for clarification, as I don't know your knowledge with slick: Vector2d is a class, that holds a x and an y value. Vectors support some basic mathematical operations, like addition, subtraction, multiplication (scale). In addition, Vector2f has some nice helper methods, like setTheta and getTheta (keep the length of the vector the same, but change the angle) or normalise (keep the angle, but change the vector length to 1).

If you have two vectors, vecA and vecB, consider this behavior identical:

Multiplication:

```
//This:
vecA.x = vecA.x * vecB.x
vecA.y = vecA.y * vecB.y
//is the same as this:
vecA.scale(vecB);

```

And in the case of the scale with a float value

```
float scale = 0.1f;
vecA.x = vecA.x * scale;
vecA.y = vecA.y * scale;
//Is the same as:
vecA.scale(scale);

```

# Answer
> 0 votes
If you're calling the method from the update method why aren't you using delta? Call the moving forward method from the update method of the entity, along with a speed parameter.

The way you can do it is set a speed variable to your bullets, which you use to limit the movement speed which they travel through.

```
       float hipothenus = movementSpeed * (float) delta;
       x = this.getX() + hipothenus * (float) Math.sin(Math.toRadians(rotation));
   y = this.getY() - hipothenus * (float) Math.cos(Math.toRadians(rotation));

```

Bear in mind that you will also need to clamp the delta rate with setMinimumLogicUpdateInterval and setMaximumLogicUpdateInterval functions.

# Answer
> 0 votes
Try this:

```
x += Math.cos(Math.toRadians(rotation)) * ((speed/100)*delta);
y += Math.sin(Math.toRadians(rotation)) * ((speed/100)*delta);

```

I used it in ym game to work out x and y positions, thought it might be helpful...

---
Tags: java, graphics, game-mechanics, slick
---


title: Arcball Problems with UDK

text:
# Question
Title: Arcball Problems with UDK
I'm trying to re-create an arcball example from a Nehe, where an object can be rotated in a more realistic way while floating in the air (in my game the object is attached to the player at a distance like for example the Physics Gun) however I'm having trouble getting this to work with UDK.

I have created an LGArcBall which follows the example from Nehe and I've compared outputs from this with the example code.

I think where my problem lies is what I do to the Quaternion that is returned from the LGArcBall.

Currently I am taking the returned Quaternion converting it to a rotation matrix. Getting the product of the last rotation (set when the object is first clicked) and then returning that into a Rotator and setting that to the objects rotation.

If you could point me in the right direction that would be great, my code can be found below.

```
class LGArcBall extends Object;

var Quat StartRotation;
var Vector StartVector;
var float AdjustWidth, AdjustHeight, Epsilon;

function SetBounds(float NewWidth, float NewHeight)
{
    AdjustWidth = 1.0f / ((NewWidth  - 1.0f) * 0.5f);
    AdjustHeight = 1.0f / ((NewHeight - 1.0f) * 0.5f);
}

function StartDrag(Vector2D startPoint, Quat rotation)
{
    StartVector = MapToSphere(startPoint);
}

function Quat Update(Vector2D currentPoint)
{
    local Vector currentVector, perp;
    local Quat newRot;

    //Map the new point to the sphere
    currentVector = MapToSphere(currentPoint);

    //Compute the vector perpendicular to the start and current
    perp = startVector cross currentVector;

    //Make sure our length is larger than Epsilon
    if (VSize(perp) > Epsilon)
    {
        //Return the perpendicular vector as the transform
        newRot.X = perp.X;
        newRot.Y = perp.Y;
        newRot.Z = perp.Z;

        //In the quaternion values, w is cosine (theta / 2), where
        //theta is the rotation angle
        newRot.W = startVector dot currentVector;
    }
    else
    {
        //The two vectors coincide, so return an identity transform
        newRot.X = 0.0f;
        newRot.Y = 0.0f;
        newRot.Z = 0.0f;
        newRot.W = 0.0f;
    }

    return newRot;
}

function Vector MapToSphere(Vector2D point)
{
    local float x, y, length, norm;
    local Vector result;

    //Transform the mouse coords to [-1..1]
    //and inverse the Y coord
    x = (point.X * AdjustWidth) - 1.0f;
    y = 1.0f - (point.Y * AdjustHeight);

    length = (x * x) + (y * y);

    //If the point is mapped outside of the sphere
    //( length > radius squared)
    if (length > 1.0f)
    {
        norm = 1.0f / Sqrt(length);

        //Return the "normalized" vector, a point on the sphere
        result.X = x * norm;
        result.Y = y * norm;
        result.Z = 0.0f;
    }
    else //It's inside of the sphere
    {
        //Return a vector to the point mapped inside the sphere
        //sqrt(radius squared - length)
        result.X = x;
        result.Y = y;
        result.Z = Sqrt(1.0f - length);
    }

    return result;
}

DefaultProperties
{
    Epsilon = 0.000001f
}

```

I'm then attempting to rotate that object when the mouse is dragged, with the following update code in my PlayerController.

```
    //Get Mouse Position
    MousePosition.X = LGMouseInterfacePlayerInput(PlayerInput).MousePosition.X;
    MousePosition.Y = LGMouseInterfacePlayerInput(PlayerInput).MousePosition.Y;

    newQuat = ArcBall.Update(MousePosition);

    rotMatrix = MakeRotationMatrix(QuatToRotator(newQuat));
    rotMatrix = rotMatrix * LastRot;

    LGMoveableActor(movingPawn.CurrentUseableObject).SetPhysics(EPhysics.PHYS_Rotating);
    LGMoveableActor(movingPawn.CurrentUseableObject).SetRotation(MatrixGetRotator(rotMatrix));

```

# Answer
> 1 votes
If I understand your problem correctly then it's the most typical problem while implementing any arcballs :)

**Problem:** Currently if you're moving left-right you will rotate your object around some axis. BUT when you move slightly up or down, then your local axes will change. Now, when you move left-right again you will get the different rotation than before and that produces an unwanted roll rotation.

**Solution:** It's really simple - instead of rotating slightly your object with every mouse move just remember your mouse X,Y and object rotation at some 'MouseDown' event. Then for every mouse movement compute X,Y difference and use it to modify your initial orientation. All math equations are the same, but always use the orientation from beginning of mouse dragging, instead of last frame.

I'm not sure if I explained it simply enough, if you still have any doubts just ask.

---
Tags: rotation, udk, quaternion
---


# Question
Title: With Slick, how to change the resolution during gameplay?
I am developing a tile-based strategy game using Java and the Slick API.

So far so good, but I've come to a standstill on my options menu. I have plans for the user to be able to change the resolution during gameplay (it is pretty common, after all).

I can already change to fullscreen and back to windowed, this was pretty simple...

```
//"fullScreenOption" is a checkbox-like button.
if (fullScreenOption.isMouseOver(mouseX, mouseY)) {
   if (input.isMouseButtonDown(Input.MOUSE_LEFT_BUTTON)) {
      fullScreenOption.state = !fullScreenOption.state;
      container.setFullscreen(fullScreenOption.state);
   }
}

```

But the container class, contrary to my previous beliefs, does not seem to have any resolution-change functions! And that's pretty much the situation...I know it's possible, but i don't know how to do it, nor what is the class responsible!

The AppGameContainer class, used on the very start of the game's initialization as of Slick's examples and tutorials, is the only place with any functions for changing the display-mode that I've found so far, but it's only used at the very start, and i haven't found a way to travel back to it from my options menu.

```
  //This is my implementation of it...
  public static void main(String[] args) throws SlickException {
    AppGameContainer app = new AppGameContainer(new Main());
//    app.setTargetFrameRate(60);
    app.setVSync(true);
    app.setDisplayMode(800, 600, false);
    app.start();
  }

```

I can define it as a static global on the Main, but it's probably a (very) bad way to do it...

# Answer
You have to cast the GameContainer object, that is passed in the update method into AppGameContainer, then you can access setDisplayMode... I tested it right now, and it works.

```
AppGameContainer gc = (AppGameContainer) container;
gc.setDisplayMode(800, 600, false);

```

But I think you need to use the dev branch of slick, as the "official" version from their page is pretty outdated, and if I'm not mistaken, the resizing capabilities are only supported in the dev branch (but I'm really not sure about this, as I have never used it before).

Here is the wiki page explaining, how you can check out the latest dev version of slick from their repository: Keeping up with the Slick Development Branch

Here is my test class. Should run out of the box. It opens a window in 640x480 resolution, if you press enter, the resolution is changed to 800x600.

Here is my test class:

```
package ch.digitalmeat.prototypes.slicksim.tests;

import org.newdawn.slick.AppGameContainer;
import org.newdawn.slick.BasicGame;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Input;
import org.newdawn.slick.SlickException;

public class ResizeTest extends BasicGame {

    public static void main(String[] args) throws Exception
    {
        ResizeTest test = new ResizeTest();
        AppGameContainer container = new AppGameContainer(test);
        container.setDisplayMode(640, 480, false);
        container.start();
    }

    public ResizeTest() {
        super("Resize Test");
    }

    @Override
    public void render(GameContainer container, Graphics g)
            throws SlickException {}

    @Override
    public void init(GameContainer container) throws SlickException {}

    @Override
    public void update(GameContainer container, int delta)
            throws SlickException {
        if(container.getInput().isKeyDown(Input.KEY_ENTER)){
            AppGameContainer gc = (AppGameContainer) container;
            gc.setDisplayMode(800, 600, false);
        }
    }

}

```
> 5 votes

---
Tags: java, lwjgl, slick, resolution
---


title: how to create texture for modelmesh?

text:
# Question
Title: how to create texture for modelmesh?
Is there a possibiltiy to create a texture from a meshpart in xna. By getting a flat version of the mesh. So I can create a texture for it and edit that texture(via rendertarget)? I need to get the texture(wich is not yet a texture) so I can put another texture on it.

I can create a texture and put it on a certain mesh. But I just cant figure out how I can create a texture with the right size.

I also already found out i can use text2dproj in hlsl. But when i do this i get a gray stripe in the look.

Is there a better solution?

# Answer
> 0 votes
I was trying to put an image over my model. I have finally done this with text2dproj. I was going wrong with the matrixes :$ But i finaly made it right.

---
Tags: xna, c#, textures, hlsl
---


# Question
Title: How do I make my Slick2D game fullscreen?
How do I make my game fullscreen? It's always in windowed mode. I'm using Eclipse on a Mac.

# Answer
At one place in your code, you create your game container. If you followed the tutorials, that part will look something like this:

```
AppGameContainer container = new AppGameContainer(game);

```

Now you can call setDisplayMode on the container object:

```
container.setDisplayMode(640, 480, true);

```

The first two parameter define the window resolution, the third if slick should be opened in windowed or fullscreen mode (true for fullscreen mode).

You should head to the slick2d wiki, as it has some beginner tutorials explaining such things. For example in this tutorial the basic things are explained step by step (also your question is answered there): Creating a Basic Game tutorial

All tutorials: Slick2d Tutorials Index
> 4 votes

---
Tags: java, slick
---


title: Stats on Screen Size for Flash Games

text:
# Question
Title: Stats on Screen Size for Flash Games
I'm working on a Flash game after many, many years. I'm trying to figure out size to make my application run (eg. 600x800). Because it's a tall (not wide) game, I'm confused.

I know about (and love) the Steam hardware stats. However, for Flash gaming, I have two nit-picks with their survey sample:

1) Caters to more hardcore gamers with better hardware (overall) 2) Captures only a subset of Flash gamers. Doesn't capture people who play at school, work, etc. or not netbooks and lighter machines.

Are there any sort of statistics I can use to determine which size to use? Ideally, I would like to know something like:

* 800x600 will fit 94% of users screens
* 1024x768 will fit 74% of users screens
* 1200x960 will fit 53% of users screens
* etc.

# Answer
> 6 votes
Google has done some analysis on this: http://browsersize.googlelabs.com

This link has been deprecated, and instead, it will be available as a feature in Google Analytics. I have taken a screenshot of the front-page sample, just in case:

As stated in the about link:

> Google Browser Size is a visualization of browser window sizes for people who visit Google. For example, the "90%" contour means that 90% of people visiting Google have their browser window open to at least this size or larger.
>
> This is useful for ensuring that important parts of a page's user interface are visible by a wide audience. On the example page that you see when you first visit this site, there is a "donate now" button which falls within the 80% contour, meaning that 20% of users cannot see this button when they first visit the page. 20% is a significant number; knowing this fact would encourage the designer to move the button much higher in the page so it can be seen without scrolling.

---
Tags: hardware, statistics
---


# Question
Title: 2D Car Simulation with Throttle Linear Physics
I'm trying to make a simulation game for an automatic cruise control system. The system simulates a car on varying inclinations and throttle speeds.

I've coded up to the car physics but these do note make sense.

The dynamics of the simulation are specified as follows:

```
a = V' - V

T = (k1)V + θ(k2) + ma

V' = (1 - (k1 / m) V) + T - ( k2 / m) * θ

```

Where

* T = throttle position
k1 = viscous friction
V = speed
V' = next speed
* θ = angle of incline

k2 = m g sin θ
a = acceleration
m = mass

Notice that the angle of incline in the equation is not chopped up by sin or cos. Even the equation for acceleration isn't right.

Can anyone correct them or am I misinterpreting the physics?

---

Source: "scribd.com/doc/105335356/124/INDUSTRIAL-APPLICATIONS"; Page 508. Number 13.2.

# Answer
I agree that parts of this might not make sense initially. Disclaimer, I am not sure of the following, this is just my "gut feeling" of how these equations should probably work :)

I guess that you would prefer to have an equation on the form V' = V + a*dt which is equivalent to a = (V - V')/dt. When applying this you would probably use a*dt in most applications. If you use a fixed timestep then you would always be able to calculate the "correct" value of the acceleration whenever you need it and can use this expression instead. You could read more of this in the first paragraph in the article Advanced character physics, using Verlet integration, that i was made aware of in this thread: How to implement friction in a physics engine based on “Advanced Character Physics”

I find it odd that there are two usages of θ, I wonder if you maybe should use just the expression for k2 instead of θ(k2), this feels sort of right when calculating the throttle position.

In the real world I belive most car manufacturers use PID-controllers for their cruise control systems.
> 1 votes

---
Tags: physics, simulations, racing, car
---


# Question
Title: How are "game rules" considered as data, in data-driven engines?
I've read the definition of a data-driven game engine, in several places, and one item usually mentioned is the game rules: separating them from the logic of the engine. What is meant by a "game rule"? How could it be considered data?

# Answer
> 3 votes
A data-driven game engine is one that successfully separates game-specific logic (what you call "game rules") such as weapon types, HUD layouts, keybindings, etc. from the engine's core functionality. This is achieved by having scripts or code outside of the engine that call upon the engine's functionality to build the gameplay. An example would be a game-specific HUD element that is implemented by calling upon the game engine's Sprite/2D graphic functionality. The reason data-driven engine architecture is important is because it allows the same game engine/code base to be used to support multiple game types, without having to strip out or modify core components. Below are a few articles I think you may find helpful in understanding data-driven game engine design:

# Answer
> 0 votes
The only way a game rule can be data is if it's an external script. But this method has its drawbacks like simplified cheating.

P.S. It's the first time I hear that a data driven game engine has a solid definition. Anything that includes the word "driven" is usually just a bunch of buzzwords glued together.

---
Tags: data-driven
---


title: Buffer System For Items

text:
# Question
Title: Buffer System For Items
##

I am going to reference this image of what I want to accomplish in **JavaScript**.

---

This is the Diablo buffer system. This question may be a bit advanced (or possibly not even allowed). But I was wondering how you might go about implementing this type of system in a JavaScript game. Currently to implement such a system in JavaScript escapes me, and I am turning to SO to get some suggestions, ideas, and hopefully some insight in how I could accomplish this without being to costly on the CPU.

Some thoughts of mine for implementing such a system would be to:

* Create DIVS within a DIV that hold each position of the inventory
* Go through each item you own in a container and see which DIV it belongs to
* Make said item images the DIVs image

This type of system might possibly work if **ALL** items were 1x1, but for this example its not going to work out.

I am at a complete lost of ideas how to even accomplish this. Although, maybe rendering directly to the canvas and checking mouse cords could work, there would more than likely be A HUGE annoyance when checking if other items are overlapping each other (meaning you cant place the item down, and possibly switching item with the cursor item ).

That said, what am I left with? Do I need to makeshift my own hack system with messy code, or is there some source out there (that I don't know about) that has replicated this type of system in their own game.

I would be very grateful to get some replies on how you might go about doing this, and will accept answers that can logically explain how you might implement such a system (code is not required).

P.S. Id like to use pure JavaScript, and nothing else (even though it might be "reinventing the wheel", I also like to learn).

# Answer
*Only talking about the lower part of your image, since that seems to be what your question is about.*

You should separate your model from its view.

One suggestion for the model would see each `InventoryItem` have an inventory-X,Y-coordinate. In that case you only need to check if there are collisions when you add an `Item` to the inventory (creating an `InventoryItem` which references the `Item`), or when you move an `InventoryItem` around. An `Inventory`-object representing your inventory would contain a list of `InventoryItem`s, and could expose an interface similar to this:

* `addItem(Item, x, y)`
* `getItemAt(x, y) -> InventoryItem`
* `moveItemTo(InventoryItem, x, y)`
* `removeItem(InventoryItem)`.

The view can be anything you want, but like MarkR I'd suggest you use the canvas if you're using that anyway. It's arguably more "pure JavaScript" than using HTML (`<div>`s) with JS (a.k.a. DHTML).
> 1 votes

# Answer
You can certainly implement an interface such as this using Javascript. You could use the DOM and Drag & Drop events, but that has a lot of problems with browser-compatibility (particularly MSIE).

However, I would imagine that most games programmers would simply use canvas and use the same canvas for the inventory screen as for the rest of the game. This is certainly what Diabolo does (Of course, for DirectX software rendering on Windows, originally).

There are a lot of libraries which might help you with the UI.

I would imagine that you have a multi-dimensional array to store the inventory items' position. You can then store the dimensions of individual items to check for (and prohibit) overlapping items in the inventory.

Likewise, you'd need some game logic to determine which items can be equipped in which locations, as such games normally implement a complex system of rules about what can be equipped where. For example, you can't have someone putting a glove on their head, right?
> 0 votes

# Answer
My solution is based on div manipulation, not canvas or anything new and fancy.

I would start with defining the data structure for stuff like "storage" and "items". Every item and the storage should be separate matrix or two dimensional array if you prefer. so lets say you have a storage which is 20x20 squares big, you just create an array or object containing 400 empty positions.

Then when defining items you have to decide how many squares is going to occupy each item, so you cut the image in smaller images each of them should fit a single square and you define another matrix for each item containing these images and their position relative to each other. ex: sword taking 5 spots \[0\]\[0\] =\> "img1.png", \[0\]\[1\] =\> "img2.png", \[0\]\[2\] =\> "img3.png", \[0\]\[3\] =\> "null", \[0\]\[4\] =\> "null"

After doing this you basically need to drag-drop an item on specific spot, check if the spot is empty, check if the item could fit in nearby squares and if so you read each image from the item\`s image array and put it in the storage array (and in the matrix of divs of course). You will have to mark each image with some kind of identifier which should tell you that "these" group of images are from one item and "these" are parts from another item.

When you drag an object from the storage you can immediately remove the object (or hide it) on mousedown and attach to the mouse cursor div containing the "assembled" image of the item.

It is kind of hacky but i think this is the easiest way to accomplish what you need.
> 0 votes

---
Tags: javascript, gui, browser-based-games
---


# Question
Title: error X3501: 'main': entrypoint not found
I am trying to learn DX10 by following this tutorial. However, my shader won't compile. Below is the detailed error message.

```
Build started 9/10/2012 10:22:46 PM.
     1>Project "D:\code\dx\Engine\Engine\Engine.vcxproj" on node 2 (Build target(s)).
         C:\Program Files (x86)\Windows Kits\8.0\bin\x86\fxc.exe /nologo /E"main" /Fo "D:\code\dx\Engine\Debug\color.cso" /Od /Zi color.fx
     1>FXC : error X3501: 'main': entrypoint not found

         compilation failed; no code produced
     1>Done Building Project "D:\code\dx\Engine\Engine\Engine.vcxproj" (Build target(s)) -- FAILED.

Build FAILED.

Time Elapsed 00:00:00.05

```

I can easily compile the downloaded code, but I want to know how to fix this error myself.

My color.fx looks like this

```
  ////////////////////////////////////////////////////////////////////////////////
  // Filename: color.fx
  ////////////////////////////////////////////////////////////////////////////////

  /////////////
  // GLOBALS //
  /////////////
  matrix worldMatrix;
  matrix viewMatrix;
  matrix projectionMatrix;

  //////////////
  // TYPEDEFS //
  //////////////
  struct VertexInputType
  {
      float4 position : POSITION;
      float4 color : COLOR;
  };

  struct PixelInputType
  {
      float4 position : SV_POSITION;
      float4 color : COLOR;
  };

  ////////////////////////////////////////////////////////////////////////////////
  // Vertex Shader
  ////////////////////////////////////////////////////////////////////////////////
  PixelInputType ColorVertexShader(VertexInputType input)
  {
      PixelInputType output;

     // Change the position vector to be 4 units for proper matrix calculations.
      input.position.w = 1.0f;

     // Calculate the position of the vertex against the world, view, and projection matrices.
      output.position = mul(input.position, worldMatrix);
      output.position = mul(output.position, viewMatrix);
      output.position = mul(output.position, projectionMatrix);

     // Store the input color for the pixel shader to use.
      output.color = input.color;

     return output;
  }

  ////////////////////////////////////////////////////////////////////////////////
  // Pixel Shader
  ////////////////////////////////////////////////////////////////////////////////
  float4 ColorPixelShader(PixelInputType input) : SV_Target
  {
      return input.color;
  }

  ////////////////////////////////////////////////////////////////////////////////
  // Technique
  ////////////////////////////////////////////////////////////////////////////////
  technique10 ColorTechnique
  {
      pass pass0
      {
          SetVertexShader(CompileShader(vs_4_0, ColorVertexShader()));
          SetPixelShader(CompileShader(ps_4_0, ColorPixelShader()));
          SetGeometryShader(NULL);
      }
  }

```

# Answer
> 9 votes
VS2012 now includes fxc in it's build process, defaulting it to enabled and a non-fx target.

You can either

**Disable it completely** as Pasha suggested, by changing the item in the project to Do Not Bulid

*or*

**Change the compile settings to what you want**. The easiest way to do this is right click on the .hlsl file, go to *properties* and then *HLSL Compiler*. You'll want to remove the entry point, change the type to *Effect* and whatever shader model you're using (fx\_4\_0 for d3d10)

# Answer
> 2 votes
Right clicking on the file "color.fx", going to properties and changing the Item Type to "Does not participate in build" made the error go away.

# Answer
> -1 votes
May be your problem is Shader Type in settings. Try this http://www.zettabyte.ws/viewtopic.php?f=41&t=1015. For me it was helpful.

---
Tags: directx10
---


# Question
Title: Do I really need to "learn" C# for XNA if I know Java?
I want to start developing in XNA. As of now, I do not know C#, but I would consider myself "good" at Java. I have looked at some C# code and it looks almost identical to Java. After looking at Java and C# Comparison, it looks like they are basically the same. Obviously some function names are going to be different, but I think I can handle it. Now if I want to learn game development in XNA, do I really need to "learn" and master C#, or can I just jump right in and learn along the way? I should also mention, I also know PHP which looks very similar.

# Answer
> 21 votes
You don't need to master *any* language before jumping right in an making something. Jump right in and learn on the way. It's likely your best option for learning the relevant parts of the language anyway.

# Answer
> 42 votes
C# and Java are not "basically the same". A lot of basics are just similar, and it's not a coincidence: C# was influenced by Java and they were both influenced by C++.

Whilst this means you'd already recognise a lot of stuff, it doesn't mean you suddenly know C#.

* Do you know much about its standard library? A lot of the collection classes are named completely differently in C#.
* Do you know about the features C# has that Java doesn't? C# has delegates, LINQ and lambda expressions, and is in part a functional language, not just an OOP language.
* Do you know how C#'s OOP works? C# uses properties instead of Java's get/set, for starters.
* Do you know the basics? Probably, a lot of them.

## So can you use C# right now without trying to learn it?

Yes, you can use C#, but you'd be using C# like you'd use Java, which would be pretty poor use of the language and would be making things hard for yourself. For instance, earlier I mentioned getters and setters. Let me give you an example of why you should actually learn C# and not presume you already know it:

### Java:

```
private int score;

public int getScore() {
    return score;
}

protected void setScore(int s) {
    this.score = s;
}

// Usage:
int x = derp.getScore();
derp.setScore(x + 1);

```

### C#:

```
public int Score { get; protected set; }

// Usage
int x = derp.Score;
derp.Score = x + 1;

```

I'm sure you're glad you know that one now.

## So SHOULD you learn C# before using it?

Yes. Right now, there are a lot of concepts offered by C# (and not Java) you are probably unaware of which you should be using; properties are one example. You don't need to master the language before you begin programming in it, but you should definitely look through some tutorials to get an overview of the language and to be introduced to those features.

Since those features are ones you don't know about, you can't actually just research them on the fly. You don't know about them, so you can't research them! So by all means, research them later to get a better understanding, but at least make sure you're aware of them now.

It will make your life easier using C#.

# Answer
> 3 votes
If you know Java real good(understand how to use it, understand your basic data structures), and know how to solve problems(programming/software engineering). You should have no problem picking up C#. The language is only a tool.

# Answer
> 1 votes
If you know core java language , C# seems to be easier and you can learn it more fast Lets look in to the detail

C# and Java are actually quite similar, from an application developer's perspective.

* all Objects are References
* there exist Garbage Collection
* both are Type-Safe Languages
* they rely on pure OOP
* have Unicode Support
* Execption handling is there and lets compare some of the keyword

C#keywords Java keywords namespace package Base super Bool boolean Is instanceof
lock syncronised using import internal private and lets look some differences also the keywords in C# that have no equivalent base support in Java In C# there is "as" keyword
In C# there is "decimal" keyword
In C# there is "enum" keyword
In C# there is "delegate" keyword
In C# there is "fixed" keyword these keywords have no atomic support in java there are also some keywords in java that are not in C# like "native", "transient" lets look on a example

in java a sample hello world program

```
package hello;
public class HelloWorld {
   public static void main(String[] args) {
      String name = "Java";
      System.out.println("Hello world in , " + name + "!");
    }
}

```

in C# it look like

```
using System;
namespace Hello {
   public class HelloWorld {
      public static void Main(string[] args) {
         string name = "C#";
         Console.WriteLine("Hellow world in , " + name + "!");
      }
   }
}

```

In a mere look both are similar , so i prefer you to learn C#

# Answer
> 1 votes
I am doing just this in my current job. Previously, I was doing J2ME and Android development. I am now in an environment where C# is used for Windows desktop development with a bit of Office interop. I have no experience with XNA specifically.

You should be able to dive in and get productive quite quickly. The similarities in the languages meant that my early java-like code didn't incur performance hits (like it might have in Python for example).

C# does have some fabulous new developments such as Properties, Delegates, and LINQ. I have found it easy to pick these up on the fly. It may have helped that I was already a bit cranky about java's callbacks and getter/setter situation beforehand.

Overall, I'd say that learning my way around Microsoft's extensive libraries/apis is a much larger job than picking up the language. You might as well get started coding.

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


# Question
Title: How do I drag my widgets without dragging other widgets?
I have a bunch of drag-able widgets on screen. When I am dragging one of the widgets around, if I drag the mouse over another widget, that widget then gets "snagged" and is also dragged around.

While this is kind of a neat thing and I can think of a few game ideas based on that alone, that was not intended. :-P

## Background Info

I have a `Widget` class that is the basis for my user interface controls. It has a bunch of properties that define it's size, position, image information, etc. It also defines some events, `OnMouseOver`, `OnMouseOut`, `OnMouseClick`, etc. All of the event handler functions are `virtual`, so that child objects can `override` them and make use of their implementation without duplicating code.

Widgets are not aware of each other. They cannot tell each other, "Hey, I'm dragging so bugger off!"

## Source Code

Here's where the widget gets updated (every frame):

```
public virtual void Update( MouseComponent mouse, KeyboardComponent keyboard ) {
    // update position if the widget is being dragged
    if ( this.IsDragging ) {
        this.Left -= (int)( mouse.LastPosition.X - mouse.Position.X );
        this.Top -= (int)( mouse.LastPosition.Y - mouse.Position.Y );
    }
    ... // define and throw other events
    if ( !this.WasMouseOver && this.IsMouseOver && mouse.IsButtonDown( MouseButton.Left ) ) {
        this.IsMouseDown = true;
        this.MouseDown( mouse, new EventArgs() );
    }
    ... // define and throw other events
}

```

And here's the `OnMouseDown` event where the `IsDraggable` property gets set:

```
public virtual void OnMouseDown( object sender, EventArgs args ) {
    if ( this.IsDraggable ) {
        this.IsDragging = true;
    }
}

```

## Problem

Looking at the source code, it's obvious *why* this is happening. The `OnMouseDown` event gets fired whenever the mouse is hovered over the `Widget` and when the left mouse button is "down" (but not necessarily in that order!). That means that even if I hold the mouse down somewhere else on screen, and simply move it over anything that `IsDraggable`, it will "hook" onto the mouse and go for a ride.

So, now that it's obvious that *I'm Doing It Wrong™*, how do I do this correctly?

# Answer
> 2 votes
It seems that you need some kind of a boolean variable telling you whether you are dragging something at this exact time, or not. Assuming that you can only drag one widget at a time, just check if `draggingSomething` is true, and if so, don't "hook" any new widgets on.

# Answer
> 2 votes
Only trigger the `OnMouseDown` event if the mouse was up before and is *now* down (all over the same element). Meaning you only trigger when the mouse is clicked on the current widget, and not by dragging a clicked mouse across multiple widgets. Means you need to keep track of the mouse state.

Keeping track of which widget the mouse is currently over would likely be very useful to you if you're not doing it already. When a mouse press is detected it can be picked up by whatever your GUI controller class is. The GUI controller will then send the event to the currently selected widget.

The currently selected widget gets updated something like so (this code is run by your GUI controller):

```
poll mouse position
walk tree into children and find bottom most child widget mouse is in
if underMouseWidget is different than the currentWidget
   currentWidget.mouseLeave()
   currentWidget = underMouseWidget
   currentWidget.mouseEnter()

```

Now that you have the current widget your GUI controller can handle events much easier. Like, a mouse click:

```
currentWidget.mouseClick(Button, Position)

```

This also means you always know where your mouse is, and your widgets know if they were the ones currently under the mouse when it was pressed.

---
Tags: c#, xna-4.0, .net, events
---


title: Questions about an Engine Java

text:
# Question
Title: Questions about an Engine Java
I am going to start developing Java games (3D) but I have a few questions.

I dont know if I should use an engine or make my own. I feel like I am "cheating" if I use an engine to make my game. Is it frowned upon in the game developing world? What are some advantages and disadvantages to using an engine for my game and is it really that much harder to make my own engine? I know that engines have built in models and textures with easy drag and drop interfaces, would I have any of that if I were to code my own engine? Thanks guys.

# Answer
> 1 votes
Well, this really depends on what you count as an engine. Technically, JOGL is an engine, which is used very frequently. Unity and UDK are also game engines, if that's what you mean. Plenty of games are made with all three of these options, along with other engines (so long as they are obtained legally), so it wouldn't necessarily be "frowned upon." Using these engines are almost always easier than making your own. For built-in texture/models, though, you need to be a bit careful with copyright infringement, because sometimes companies will give you those only for educating yourself with use of the engine.

As for making your own engine in Java, it can be moderately difficult to make a code-only engine yourself, and it will most likely not be as good as something like JOGL. These are generally more easier to adapt if you're using your own as opposed to something like JOGL. It really just depends on what your game needs. However, making your own engine with a user-interface takes significantly longer and is much harder, but it can be easily re-used and it is easier to start new projects with it.

---
Tags: java
---


title: Struct Method for Loops Problem

text:
# Question
Title: Struct Method for Loops Problem
I have tried numerous times how to make a do-while loop using the float constructor for my code but it seems it does not work properly as I wanted. For summary, I am making a TBRPG in C++ and I encountered few problems. But before that, let me post my code.

```
#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>

using namespace std;
    int char_level = 1; //the starting level of the character.
    string town; //town
    string town_name; //the name of the town the character is in.
    string charname; //holds the character's name upon the start of the game
    int gems = 0; //holds the value of the games the character has.
    const int MAX_ITEMS = 15; //max items the character can carry
    string inventory [MAX_ITEMS]; //the inventory of the character in game
    int itemnum = 0; //number of items that the character has.
    bool GameOver = false; //boolean intended for the game over scr.

    string monsterTroop [] = {"Slime", "Zombie", "Imp", "Sahaguin, Hounds, Vampire"}; //monster name
    float monsterTroopHealth [] = {5.0f, 10.0f, 15.0f, 20.0f, 25.0f}; // the health of the monsters
    int monLifeBox; //life carrier of the game's enemy troops
    int enemNumber; //enemy number

    //inventory[itemnum++] = "Sword";

    class RPG_Game_Enemy {
        public:
            void enemyAppear ()
            {
                srand(time(0));
                enemNumber = 1+(rand()%3);
                    if (enemNumber == 1)
                        cout << monsterTroop[1]; //monster troop 1
                    else if (enemNumber == 2)
                        cout << monsterTroop[2]; //monster troop 2
                    else if (enemNumber == 3)
                        cout << monsterTroop[3]; //monster troop 3
                    else if (enemNumber == 4)
                        cout << monsterTroop[4]; //monster troop 4

            }

            void enemDefeat () {
                cout << "The foe has been defeated. You are victorious." << endl;
            }

                    void enemyDies()
                { //if the enemy dies:
                //collapse declaration
                    cout << "The foe vanished and you are victorious!" << endl;
                }
};

         class RPG_Scene_Battle {
    public:
  RPG_Scene_Battle(float ini_health) : health (ini_health){};
  float getHealth()
    {
      return health;

      }
  void setHealth(float rpg_val){ health = rpg_val;};

private:
  float health;
};

//---------------------------------------------------------------//
// Conduct Damage for the Scene Battle's Damage
//---------------------------------------------------------------//

  float conductDamage(RPG_Scene_Battle rpg_tr, float damage) {
  rpg_tr.setHealth(rpg_tr.getHealth() - damage);
  return rpg_tr.getHealth();
  };

  // ------------------------------------------------------------- //

  void RPG_Scene_DisplayItem ()
  {
    cout << "Items: \n";
    for (int i=0; i < itemnum; ++i)
        cout << inventory[i] <<endl;
  };

```

In this code I have so far, the problem I have is the battle scene. For example, the player battles a Ghost with 10 HP, when I use a do while loop to subtract the HP of the character and the enemy, it only deducts once in the do while. Some people said I should use a struct, but I have no idea how to make it. Is there a way someone can display a code how to implement it on my game?

Edit:

I made the do-while by far like this:

```
do
  RPG_Scene_Battle (player, 20.0f);
  RPG_Scene_Battle (enemy, 10.0f);
  cout << "Battle starts!" <<endl;
  cout << "You used a blade skill and deducted 2 hit points to the enemy!"
  conductDamage (enemy, 2.0f);
while (enemy!=0)

```

also, I made something like this:

```
#include <iostream>
using namespace std;

int gems = 0;

class Entity {
public:
  Entity(float startingHealth) : health(startingHealth){}; // initialize health
  float getHealth(){return health;}
  void setHealth(float value){ health = value;};
private:
  float health;
};

float subtractHealthFrom(Entity& ent, float damage) {
ent.setHealth(ent.getHealth() - damage);
return ent.getHealth();
};

int main () {

Entity character(10.0f);
Entity enemy(10.0f);

cout << "Hero Life: ";
cout << subtractHealthFrom(character, 2.0f) <<endl;
cout << "Monster Life: ";
cout << subtractHealthFrom(enemy, 2.0f) <<endl;
cout << "Hero Life: ";
cout << subtractHealthFrom(character, 2.0f) <<endl;
cout << "Monster Life: ";
cout << subtractHealthFrom(enemy, 2.0f) <<endl;

```

};

Struct method, they say, should solve this problem. How can I continously deduct hp from the enemy? Whenever I deduct something, it would return to its original value -\_-

# Answer
> 5 votes
There are two reasons the damage resets each time. First of all, you declared your `RPG_Scene_Battle` variables inside the loop, which means they get destroyed and recreated each time around the loop. You probably wanted something like:

```
RPG_Scene_Battle player(20.0f);
RPG_Scene_Battle enemy(10.0f);
do {
  cout << "Battle starts!" << endl;
  cout << "You used a blade skill and deducted 2 hit points to the enemy!" << endl;
  conductDamage(enemy, 2.0f);
} while (enemy.getHealth() > 0);

```

Here, the `RPG_Scene_Battle`s are created once and the same variables are used each time around the loop, so changes will be retained.

Second, your `conductDamage` function is intended to modify the `RPG_Scene_Battle` that's passed in - but it doesn't, because that parameter is being passed by value; each call to `conductDamage` is effectively making a new copy of the `RPG_Scene_Battle`, modifying that copy, then throwing it away. To fix this, either pass the parameter by reference or (better yet) make `conductDamage` a method of `RPG_Scene_Battle` instead of a free function.

---
Tags: c++
---


# Question
Title: Implementing fog of war in opengl es 2.0 game
Hi game development community, this is my first question here! ;)

I'm developing a tactics/strategy real time android game and I've been wondering for some time what's the best way to implement an efficient and somewhat nice looking fog of war to incorporate in it.

The style of fog of war i'm looking for is to darken the areas where there is no visibility at a certain moment. \[not the solid black, unexplored area, kind of fog of war\] Note that this has nothing to do with which units are visible to the player. This is merely a visual effect.

My experience with OpenGL or Android is not vast by any means, but I think it is sufficient for what I'm asking here.

So far I have thought in some solutions:

1. Draw white circles to a dark background, corresponding to the units visibility, then render to a texture, and then drawing a quad with that texture with blend mode set to multiply. Will this approach be efficient? Will it take too much memory? (I don't know how to render to texture and then use the texture. Is it too messy?)
2. Have a grid object with a vertex shader which has an array of uniforms having the coordinates of all units, and another array which has their visibility range. The number of units will very probably never be bigger then 100. The vertex shader needs to test for each considered vertex, if there is some unit which can see it. In order to do this it, will have to loop the array with the coordinates and do some calculations based on distance. The efficiency of this is inversely proportional to the looks of it. A more dense grid will result in a more beautiful fog of war... but will require a greater amount of vertexes to be checked. Is it possible to find a nice compromise or is this a bad solution from the start?

Which solution is the best? Are there better alternatives? Which ones?

Thank you for your time.

**Edit**

I have (kinda) tried the second option with only one unit, and the shadows were getting too pixelated.. If I increased the number of vertexes, the fps started to drop. I tried doing the tests in the fragment shader and the results were better in terms of smoothness (that was expected) but also in terms of performance (comparing to the denser grid), which got me a little surprised. But I don't know if testing each pixel against 50 units might be viable to do in the fragment shader. Probably not!

I'm gonna bring a third option that I don't know if is valid, but maybe you people can enlighten me:

* 3.Use the stencil buffer in some way to draw the invisible areas in white (this would be done by having the stencil buffer initialized in white, and then draw black circle textured quads on it corresponding to units visibility) and then use that to make a kinda "clipping mask" effect on a full black somewhat transparent quad that would darken the invisible areas.

I don't even know if this is possible, and I'm not 100% sure that every android with opengl 2.0 supports stencil buffer. I also don't know very well what is the stencil buffer or when it is used... But apparently this might be a perfect solution. Does anyone have an idea?

# Answer
> 4 votes
I managed to do it with stencil buffer.

Here's how to do it: In GLSurfaceView constructor, put:

```
setEGLConfigChooser(5,6,5,0,16,8);

```

before setting the render. This makes sure you have stencil buffer active.

Then in the draw method:

```
    GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_STENCIL_BUFFER_BIT);

    //draw other unrelated stuff here

    GLES20.glEnable(GLES20.GL_STENCIL_TEST);
    GLES20.glStencilFunc(GLES20.GL_ALWAYS, 0x1, 0xffffffff);
    GLES20.glStencilOp(GLES20.GL_REPLACE, GLES20.GL_REPLACE, GLES20.GL_REPLACE);
    GLES20.glColorMask(false, false, false, false);

    for(Unit u: ownUnitsToDraw)
        Drawings.drawUnitVisionMask(u); //This is a quad with a texture of a white circle

    GLES20.glColorMask(true, true, true, true);
    GLES20.glDepthMask(true);
    GLES20.glStencilFunc(GLES20.GL_NOTEQUAL, 1, 1);
    GLES20.glStencilOp(GLES20.GL_KEEP, GLES20.GL_KEEP, GLES20.GL_KEEP);

    Drawings.drawFog(); //This is a black quad with some transparency

    GLES20.glDisable(GLES20.GL_STENCIL_TEST);

    //draw other unrelated stuff here

```

So what happens here is that the black fog is masked to the zone outside the vision of the units which is exactly the intended. If we set glStencilFunc to GLES20.GL\_EQUAL it would be the space around the units that would have fog, but that is not wanted.

Also, in order for this to work, the mask quad fragmentation shader needs to be something like this:

```
    precision mediump float;
    uniform sampler2D u_Texture;
    varying vec2 vTexCoordinate;
    uniform vec4 vColor;
    void main() {
      gl_FragColor = vColor * texture2D(u_Texture, vTexCoordinate);
      if(gl_FragColor.a < 0.5)
        discard;
    };

```

This will allow the pixels in the quad that are transparent (alpha \< 0.5) not to make part of the mask (otherwise the mask would not be circular but squared).

# Answer
> 3 votes
You can have a vertex grid for the ground.

For every movement of your player, you can check for all the vertices if they are within the range and blend the shadow color. I don't think that would slow down the game even for a dense grid.

Or else just change the Color of only those vertices that have changed. When you move your units, notice the coordinates (based on player position and range) which have entered the range. Use those coordinates as indices to refer to the vertex itself and change its Color.

To get the coordinates which have entered the range, you don't need to check all the vertices.

```
*----*----*----*----*----*----*
|    |    |    |    |    |    |
|    |    |    |    |    |    |
*----*----*----A----*----*----*
|    |    |    |    |    |    |
|    |    |    |    |    |    |
*----*----A----A----A----*----*
|    |    |    |    |    |    |
|    |    |    |    |    |    |
*----A----A----O----A----A----*
|    |    |    |    |    |    |
|    |    |    |    |    |    |
*----*----A----A----A----*----*
|    |    |    |    |    |    |
|    |    |    |    |    |    |
*----*----*----A----*----*----*
|    |    |    |    |    |    |
|    |    |    |    |    |    |
*----*----*----*----*----*----*

O = player position
A = vertices within range

```

So if you are at (0, 0) and range is 3, then you can check for vertices between (-3,-3) to (+3, +3).

**Note**: When you move your unit, some vertices enter the range and **some leave it too**. So you have to consider both the cases.

Hope this is clear

---
Tags: android, opengl-es, performance, rts, fog-of-war
---


# Question
Title: How can I get a 2D texture to rotate like a compass in XNA?
I'm working on a small maze puzzle game and I'm trying to add a compass to make it somewhat easier for the player to find their way around the maze. The problem is: I'm using XNA's draw method to rotate the arrow and I don't really know how to get it to rotate properly. What I need it to do is point towards the exit from the player's position, but I'm not sure how I can do that.

So does anyone know how I can do this? Is there a better way to do it?

# Answer
The secret is `atan2`:

```
Vector2 exitPosition = whatever;
Vector2 currentPosition = whatever;

Vector2 direction = exitPosition - currentPosition;
float angle = (float)Math.Atan2(direction.Y, direction.X);

```

**atan2** (MSDN) gives you the angle of a vector, with the positive X axis being at an angle of zero, and moving in the positive direction towards the positive Y axis (which is π/2). Simply pass this as the `rotation` parameter to `SpriteBatch.Draw` (MSDN).

Make sure your compass needle texture is pointed the correct way for an angle of zero (ie: to the left), or add an appropriate angular offset in your code. Set the `origin` parameter of the `SpriteBatch.Draw` call to the pivot point of your needle texture.
> 9 votes

---
Tags: xna, mathematics, rotation
---


# Question
Title: Is it possible to update the livetile in XNA WP7 game?
( I'm not sure if this question belongs here, but since it is related to game development and I have no idea where else I should post this, I will post this here )

As the title says, what I am basically asking is if it is possible to update the livetile of an pure XNA game ( not SL + XNA hybrid )?

I've been thinking something like that whenever user launches the game, I would create an texture dynamically and then update the livetile to show that texture. Even better would be if I could schedule this code to run for example once a day, without requiring user to even launch the game.

Is this possible in WP7 or in WP8 ( is the WP8 SDK even publicly released yet? ) in pure XNA game? What about in XNA + SL hybrid?

# Answer
I managed to update the tile using following code:

```
public static class ApplicationInfo
{
    public static ShellTile ApplicationLiveTile
    {
        get { return ShellTile.ActiveTiles.FirstOrDefault(); }
    }

    public static void UpdateTile(Texture2D texture)
    {
        const int TextureSize = 173;
        const string FilePath = "/Shared/ShellContent/tile.jpg";

        // Save texture to isolated storage
        IsolatedStorageFile isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
        using (IsolatedStorageFileStream stream = isolatedStorage.CreateFile(FilePath))
        {
            texture.SaveAsPng(stream, TextureSize, TextureSize);
        }

        // Update the tile
        ShellTile tile = ApplicationInfo.ApplicationLiveTile;
        if (tile != null)
        {
            tile.Update(new StandardTileData()
            {
                BackgroundImage = new Uri("isostore:" + FilePath, UriKind.Absolute),
            });
        }
    }
}

```

I haven't yet tried to make scheduled updating of the live tile as I described in the OP, but it possibly can be done by using Windows Phone Scheduled Task Agent.
> 2 votes

---
Tags: xna, windows-phone-7
---


# Question
Title: Physics not synchronizing correctly over the network when using Bullet
I'm trying to implement a client/server physics system using Bullet however I'm having problems getting things to sync up.

I've implemented a custom motion state which reads and writes the transform from my game objects and it works locally but I've tried two different approaches for networked games:

1. Dynamic objects on the client that are also on the server (eg not random debris and other unimportant stuff) are made kinematic. This works correctly but the objects don't move very smoothly
2. Objects are dynamic on both but after each message from the server that the object has moved I set the linear and angular velocity to the values from the server and call btRigidBody::proceedToTransform with the transform on the server. I also call btCollisionObject::activate(true); to force the object to update.

My intent with method 2 was to basically do method 1 but hijacking Bullet to do a poor-man's prediction instead of doing my own to smooth out method 1, but this doesn't seem to work (for reasons that are not 100% clear to me even stepping through Bullet) and the objects sometimes end up in different places.

Am I heading in the right direction? Bullet seems to have it's own interpolation code built-in. Can that help me make method 1 work better? Or is my method 2 code not working because I am accidentally stomping that?

EDIT: Another problem with method 1 I just noticed is that the collision response will be way off for collisions against non-synchronized objects. Kinetic bodies kind of shoot stuff to infinity sometimes since they can't be knocked back.

# Answer
> 5 votes
You need proper client-side prediction.

You should really read in details the link Roy T. provided you in his comment. It describes what to do with player input & character physics, but the principle stays the same for "server-driven physics".

This isn't trivial to implement but in a few words, for game objects that need to be in sync:

* Run the physics on both the server and the client;
* Server sends updates regularly;
* Client continuously & smoothly re-adjusts its physics world to the server values.

So yes, you're heading in the right direction with your method 2. Just overriding the values isn't enough though, you will get jumps on the client, what you need to do is smoothly & continuously interpolate to the server values.

For your actual bug, I'm not familiar with Bullet, but you're probably missing some values e.g. you've set the linear and angular velocities, but have you set the accelerations?

# Answer
> 4 votes
What I do personally is whoever is hosting the game creates the phsyics world and sync objects with the clients. Even if its a p2p network scheme I still base the physics engine on one of the players clients.

Other physics that I use that is purely eye candy doesn't even need to be synchronized.

In a prototype I made a while back called "boilerzerker", I ran physics on the host and particle effects(also using physics) were not synced across a network but independent for each client because they were eye candy.

# Answer
> 3 votes
It is impossible to implement network synchronous physics worlds. Small difference in step N course much more bigger difference in step N+1 You can't apply forces or impulses to keep it sync and look realistic.

Solutions:-

1. You can consider to sync only few objects like characters or racing cars especially if they are kinematic. But most part of the world would not be in sync to look realistic.
2. You can have one physics worlds on server and broadcast object positions and velocities to clients.

---
Tags: physics, networking, bullet-physics
---


# Question
Title: Can I debug XNA Xbox 360 games on my PC?
If I made an Xbox 360 game with XNA, would I need to debug it on the Xbox 360 as I was coding it? Or would there be a small emulator on my computer to debug it?

# Answer
> 11 votes
You need to register as an XBLIG Developer in order to run and debug on your Xbox.

To debug on your PC you can set up an additional windows game project (XNA runs on Windows as well). Then you would have two projects, one XBox and one Windows that run the same game. You just want to make sure that your solution is set up to be cross platform. The only problem with this is that it doesn't emulate an XBox entirely as in you aren't limited by hardware in any way and as such you have a good chance of experiencing bugs on your XBox that you can't reproduce on your PC.

# Answer
> 0 votes
Yes, you don't need an XBox 360 to run or debug an XNA game. In fact, even if you have a developer account and are running it on an XBox360, you would still debug on a PC.

We have the professional dev kits in our studio which give you extra power to compensate for the extra bits you run while in debug builds, but we STILL debug on PC.

Also just to make it super clear - you can use a normal 360 to test and run games you make, it doesn't have to be a dev kit.

# Answer
> -6 votes
To debug an XBOX 360 game you need a devkit and here is how you can buy one.

You can run the game on your *standard* XBOX 360 if you have payed a subscription for your developer account.

---
Tags: xna, debugging, xbox
---


title: XNA: Check if the sound is playing

text:
# Question
Title: XNA: Check if the sound is playing
Quick question:

I have a `SoundEffect` instance, and I would like to know if it is playing at the moment or not. But there's neither a method, nor a property that would allow to check it...

So, is there a way to know it?

# Answer
Found the answer myself :)

Apparently you have to do this:

```
SoundEffectInstance qwe = yourSound.CreateInstance();
qwe.State ...

```

And that state will contain... well, the state of the sound. Also SoundEffectInstance countains bunch of other useful data.
> 8 votes

---
Tags: xna, c#, sound, sound-effects
---