title: How do I reset a game level

text:
# Question
Title: How do I reset a game level
I have managed to implement a screen state system which I use to access the game. When the the character has collided with an enemy tile the game ends by going to a seperate game over screen. After being re-directed to the start screen the player can choose to start a new game. However the old level is still loaded and the old player character is still in contact with the enemy tile and the game over screen is loaded instantly.

How can I reload the level as new rather than load the previous game?

I have included the main game class below, Thanks

```
using FarseerPhysics.Dynamics;
using FarseerPhysics.Factories;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using FarseerPhysics.DebugViews;
using FarseerPhysics.HelloWorld.Physics;
using System.Collections.Generic;
using FarseerPhysics.HelloWorld.GameObjects;
using TiledLib;
using System;

namespace FarseerPhysics.HelloWorld
{
    /// <summary>
    /// This is the main class for our game, most of the work ealier on in the project will
    /// be done in this class but we should move some of the work into level classes.
    /// </summary>
    public class Sum :Game
    {
        //Graphics
        private GraphicsDeviceManager graphics;
        //Sprite Batch- used to draw texture2D to the screen
        private SpriteBatch spriteBatch;
        //Holds the previous input state
        private KeyboardState oldKeyState;
        private GamePadState oldPadState;
        //For drawing text to the screen, mainly debug info
        private SpriteFont gameFont;
        public float playerSpeed;
        public float jumpHeight;
        public int jumpTimes;
        public float gravity;
        private int count = 0;
        private int count2 = 0;
        public float friction;
        public float bounce;
        public float velocity;

        //World, this is the physics simulation, we will use this to add
        //remove objects from the physics
        private World world;

        // Simple camera controls
        private Matrix view;
        private Vector2 cameraPosition;
        private Vector2 screenCenter;

        //Physics debug overlay, shows what has been added to the simulation
        private DebugViewXNA debugPhysicsView;
        private Matrix debugProjection;
        private Matrix debugView;

        //Holds every game sprite on the screen, this has been loaded by us and
        //not from the map
        List<GameSprite> displayList;

        //The Sprite we are controlling, is there a better way to control something
        GameSprite playerSprite;
        MenuComponent menuComponent;

        KeyboardState keyboardState;
        KeyboardState oldKeyboardState;

        GameScreen activeScreen;
        StartScreen startScreen;
        ActionScreen actionScreen;
        OptionsScreen optionsScreen;
        PopUpScreen quitScreen;

        public bool game = false;
        public bool gameEnds = false;
        public bool playerDead = false;

        //The Tiled Map we are using at the moment
        Map gameMap;

        GameSprite movingPlatform;

        //If we are not on the XBOX360 platform
#if !XBOX360
        //Some instruction text to show
        const string Text = "Press A or D to rotate the ball\n" +
                            "Press Space to jump\n" +
                            "Press Shift + W/S/A/D to move the camera"+
                            "Press F1 to enable/disable physics debug";
#else
                const string Text = "Use left stick to move\n" +
                                    "Use right stick to move camera\n" +
                                    "Press A to jump\n"+
                                    "Press Back to enable/disable physics debug";
#endif
        /// <summary>
        ///
        /// </summary>
        public void VariableChanger()
        {
            string[] lines = System.IO.File.ReadAllLines("Content/TextEditor.txt");

            foreach (string line in lines)
            {
                string[] chart = line.Split('=');
                if (chart[0].ToLower() == "playerspeed")
                {
                    playerSpeed = float.Parse(chart[1]);
                }
                if (chart[0] == "jumpHeight")
                {
                    jumpHeight = float.Parse(chart[1]);
                }
                if (chart[0] == "jumpTimes")
                {
                    jumpTimes = int.Parse(chart[1]);
                }
                if (chart[0] == "gravity")
                {
                    gravity = float.Parse(chart[1]);
                }
                if (chart[0] == "friction")
                {
                    friction = float.Parse(chart[1]);
                }
                if (chart[0] == "bounce")
                {
                    bounce = float.Parse(chart[1]);
                }
                if (chart[0] == "velocity")
                {
                    velocity = float.Parse(chart[1]);
                }
            }
        }

        public Sum()
        {
            VariableChanger();
            //Initialise the graphics system
            graphics = new GraphicsDeviceManager(this);
            //Width and Height of the screen
            graphics.PreferredBackBufferWidth = 1200;
            graphics.PreferredBackBufferHeight = 880;

            //The root directory for all assets
            Content.RootDirectory = "Content";
            //This holds sprites that are loaded by us and not from the tiled Map
            displayList = new List<GameSprite>();
            //Create Physics Simulation with Gavity of 9.8. We should load this
            //value from a text file
            world = new World(new Vector2(0, gravity));
        }

        public void LoadGame()
        {
            VariableChanger();
            // Initialize camera controls
            view = Matrix.Identity;
            cameraPosition = Vector2.Zero;

            //Calculate screen centre
            screenCenter = new Vector2(graphics.GraphicsDevice.Viewport.Width / 2f, graphics.GraphicsDevice.Viewport.Height / 2f);

            //Create Sprite batch for drawing our sprites later
            //batch = new SpriteBatch(GraphicsDevice);
            //load font from drawing text
            gameFont = Content.Load<SpriteFont>("font");

            //Create our debug physics view
            debugPhysicsView = new DebugViewXNA(world);
            debugPhysicsView.Enabled = true;
            debugPhysicsView.LoadContent(GraphicsDevice, Content);
            debugPhysicsView.DebugPanelPosition = new Vector2(600.0f, 0.0f);
            debugPhysicsView.AppendFlags(DebugViewFlags.Shape);
            debugPhysicsView.AppendFlags(DebugViewFlags.Joint);
            debugPhysicsView.AppendFlags(DebugViewFlags.DebugPanel);
            debugPhysicsView.AppendFlags(DebugViewFlags.ContactPoints);
            debugPhysicsView.AppendFlags(DebugViewFlags.AABB);
            debugPhysicsView.AppendFlags(DebugViewFlags.PolygonPoints);
            debugPhysicsView.AppendFlags(DebugViewFlags.CenterOfMass);

            //Load our game map, we should probably load the level name(map) from
            //a text file
            gameMap = Content.Load<Map>("Test Map");

            //we have loaded the map, we need to add Physics Objects
            //to represent this. We have decided that layer called Game
            //will have physics
            TileLayer tileLayer = gameMap.GetLayer("Main Level Layer") as TileLayer;

            int xindex = 0;
            int yindex = 0;
            //Start position of tiles
            float xPos = 0f;
            float yPos = 0f;
            //Nested for loop to go through every tile in the layer
            for (int y = 0; y < tileLayer.Height; y++)
            {
                for (int x = 0; x < tileLayer.Width; x++)
                {
                    //if we have a tile at position x, y
                    if (tileLayer.Tiles[x, y] != null)
                    {
                        //Retrieve that tile
                        Tile currentTile = tileLayer.Tiles[x, y];
                        //Grab the propery called tile type from the tile, this was
                        //created in Tiled editor
                        int tileType = (int)currentTile.Properties["TileType"];

                        //Retrieve the size of the tile
                        Vector2 size = new Vector2(currentTile.Source.Width,
                            currentTile.Source.Height);

                        //Get the position
                        Vector2 pos = new Vector2(xPos, yPos);
                        //We need to offset the position to the center of the tile
                        pos += size / 2;
                        //create the body for the tile
                        Body b = BodyFactory.CreateRectangle(world, PhysicsUtils.ConvertToPhysicsUnits(size.X),
                            PhysicsUtils.ConvertToPhysicsUnits(size.Y), 1f, PhysicsUtils.ConvertToPhysicsUnits(pos));

                        //Make the body static, pinned in place
                        b.BodyType = BodyType.Static;
                        //set the user type of the body, this allows us to associate some kind of data with
                        //the body and
                        b.UserData = tileType;
                        if (tileType == 3)
                        {
                            //Create Game Sprite
                            movingPlatform = new GameSprite();

                            //Load the texture and asign it to the texture property of the the new sprite
                            movingPlatform.Texture = Content.Load<Texture2D>("Test Sprite"); //  40 x 40 - 1m x 1m

                            //Convert screen center from pixels to meters, we could grab this position
                            //from a tile
                            movingPlatform.Position = PhysicsUtils.ConvertToPhysicsUnits(screenCenter) + new Vector2(-1.5f, -1.5f);

                            //Create the RigidBody of the player, we could change this to some other kind
                            //rigid body or a combination of rigid bodies
                            movingPlatform.RigidBody = b;
                            //Under simulation control
                            movingPlatform.RigidBody.BodyType = BodyType.Dynamic;
                            movingPlatform.RigidBody.OnCollision += new OnCollisionEventHandler(platform_OnCollision);
                            movingPlatform.RigidBody.IgnoreGravity = true;
                            movingPlatform.RigidBody.LinearVelocity = new Vector2(-10.0f, 0.0f);
                            movingPlatform.RigidBody.FixedRotation = true;
                            movingPlatform.RigidBody.Mass = 1000f;
                            //sprite.RigidBody.LinearVelocity = new Vector2(0,0);

                            //// Give it some bounce and friction
                            //movingPlatform.RigidBody.Restitution = bounce;
                            //movingPlatform.RigidBody.Friction = friction;

                            //Register a collision handler for the moving sprite
                            //movingPlatfrom.RigidBody.OnCollision += new OnCollisionEventHandler(RigidBody_OnCollision);
                            // sprite.RigidBody.FixedRotation = true;

                            //Add it to the display list
                            displayList.Add(movingPlatform);
                            //xindex = x;
                            //yindex = y;
                            tileLayer.Tiles[x, y] = null;
                        }

                    }

                    //Move the new position to the next tile position on the x
                    xPos += PhysicsUtils.MeterInPixels;

                }
                //reset back to the starting x position
                xPos = 0f;
                //Move the new position to the next tile position on the y
                yPos += PhysicsUtils.MeterInPixels;
            }
            tileLayer.Tiles[xindex, yindex] = null;

            //Create Game Sprite
            GameSprite sprite = new GameSprite();

            //Load the texture and asign it to the texture property of the the new sprite
            sprite.Texture = Content.Load<Texture2D>("Test Sprite"); //  40 x 40 - 1m x 1m

            //Convert screen center from pixels to meters, we could grab this position
            //from a tile
            sprite.Position = PhysicsUtils.ConvertToPhysicsUnits(screenCenter) + new Vector2(-1.5f, -1.5f);

            //Create the RigidBody of the player, we could change this to some other kind
            //rigid body or a combination of rigid bodies
            sprite.RigidBody = BodyFactory.CreateCircle(world, PhysicsUtils.MeterInPixels
                / PhysicsUtils.ConvertToGraphicsUnits(2f),
                1f, sprite.Position);
            //Under simulation control
            sprite.RigidBody.BodyType = BodyType.Dynamic;
            //sprite.RigidBody.LinearVelocity = new Vector2(0,0);

            //// Give it some bounce and friction
            sprite.RigidBody.Restitution = bounce;
            sprite.RigidBody.Friction = friction;
            //Register a collision handler for the moving sprite
            sprite.RigidBody.OnCollision += new OnCollisionEventHandler(RigidBody_OnCollision);
            // sprite.RigidBody.FixedRotation = true;

            //Add it to the display list
            displayList.Add(sprite);
            ////this is the sprite we are controlling
            playerSprite = sprite;
        }
        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content. We might change this later on when we
        /// need to load a level at a time
        /// </summary>
        protected override void LoadContent()
        {
            //string[] menuItems = { "Start", "Options", "Quit"};

            spriteBatch = new SpriteBatch(GraphicsDevice);

            startScreen = new StartScreen(this, spriteBatch, Content.Load<SpriteFont>("menufont"), Content.Load<Texture2D>("image1"));
            Components.Add(startScreen);
            startScreen.Hide();

            actionScreen = new ActionScreen(this, spriteBatch, Content.Load<Texture2D>("image4"));
            Components.Add(actionScreen);
            actionScreen.Hide();

            optionsScreen = new OptionsScreen(this, spriteBatch, Content.Load<SpriteFont>("menufont"), Content.Load<Texture2D>("image2"));
            Components.Add(optionsScreen);
            optionsScreen.Hide();

            quitScreen=new PopUpScreen(this, spriteBatch, Content.Load<SpriteFont>("menufont"), Content.Load<Texture2D>("image3"));
            Components.Add(quitScreen);
            quitScreen.Hide();

            activeScreen = startScreen;
            activeScreen.Show();

            //menuComponent = new MenuComponent(this, spriteBatch, Content.Load<SpriteFont>("menufont"), menuItems);
            //Components.Add(menuComponent);

        }

        public void movePlatform()
        {
            //movingPlatform.RigidBody.ApplyLinearImpulse(new Vector2(-1000.0f, 0.0f));
            //movingPlatform.RigidBody.Position = new Vector2(movingPlatform.RigidBody.Position.X - 0.02f, movingPlatform.RigidBody.Position.Y);
            /*count++;
            if (count > 0 && count < 120)
            {
                movingPlatform.RigidBody.Position = new Vector2(movingPlatform.RigidBody.Position.X - 0.02f, movingPlatform.RigidBody.Position.Y);
            }

            count++;
            if (count > 120 && count < 241)
            {
                movingPlatform.RigidBody.Position = new Vector2(movingPlatform.RigidBody.Position.X + 0.02f, movingPlatform.RigidBody.Position.Y);
            }

            if (count > 241)
            {
                count = 0;
            }*/

            //movingPlatform.BodyType = BodyType.Dynamic;
            //movingPlatform.IgnoreGravity = true;
            //movingPlatform.FixedRotation = true;
            //movingPlatform.ApplyForce(new Vector2(-5f,0f));

        }

        /// <summary>
        /// The Collision handler
        /// </summary>
        /// <param name="fixtureA">The fixture(contains body) which is on the left side of +=</param>
        /// <param name="fixtureB">The fixture(contains body) which has been collided by the above</param>
        /// <param name="contact">Extra contact information</param>
        /// <returns></returns>
        bool RigidBody_OnCollision(Fixture fixtureA, Fixture fixtureB, Dynamics.Contacts.Contact contact)
        {
            //Cast the user data from fixture B's body and check it
            if ((int)fixtureB.Body.UserData == 3)
            {
                //this.Exit();
                playerSprite.Position = new Vector2(movingPlatform.Position.X, movingPlatform.Position.Y);

            }

            if ((int)fixtureB.Body.UserData == 2)
            {
                //need to write code to destroy playersprite here

                displayList.Remove(playerSprite);
                playerSprite.RigidBody.IgnoreCollisionWith(fixtureB.Body);
                playerDead = true;
                gameEnds = true;
                count2 = 10;
            }

            else
            {
                count2 = 0;
            }

            return true;
        }

        bool platform_OnCollision(Fixture fixtureA, Fixture fixtureB, Dynamics.Contacts.Contact contact)
        {
            if (fixtureB.Body != playerSprite.RigidBody)
            {
                float xvel = movingPlatform.RigidBody.LinearVelocity.X;
                xvel *= -1;
                movingPlatform.RigidBody.LinearVelocity = new Vector2(xvel,0.0f);
                //return true;
            }
            return true;

        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            keyboardState = Keyboard.GetState();

            if (activeScreen == startScreen)
            {
                HandleStartScreen();
            }

            if (activeScreen == optionsScreen)
            {
                HandleOptionsScreen();
            }

            if (activeScreen == quitScreen)
            {
                HandleQuitScreen();
            }
            if (activeScreen == actionScreen)
            {
                HandleActionScreen();
            }
            if (game == true)
            {
                if (CheckKey(Keys.Escape))
                {
                    activeScreen.Enabled = false;
                    activeScreen = quitScreen;
                    activeScreen.Show();
                }
                //Call to deal with game pad controls
                HandleGamePad();
                //Call to deal with keyboard controls
                HandleKeyboard();
                movePlatform();
                //Update physics first, never lest than 30 FPS
                world.Step(Math.Min((float)gameTime.ElapsedGameTime.TotalSeconds, (1f / 30f)));
            }

            if (gameEnds == true)
            {
                game = false;
                activeScreen = actionScreen;
                activeScreen.Show();
            }

            base.Update(gameTime);
            oldKeyboardState = keyboardState;
                        //HandleKeyboard();
        }
        private void HandleActionScreen()
        {
            if (CheckKey(Keys.Enter))
            {
                actionScreen.Hide();
                activeScreen = startScreen;
                startScreen.Show();
                gameEnds = false;
            }
        }

        private void HandleStartScreen()
        {
            if (CheckKey(Keys.Enter))
            {
                if (startScreen.SelectedIndex == 0)
                {
                    activeScreen.Hide();
                    //activeScreen = actionScreen;
                    //activeScreen.Show();
                    LoadGame();
                    game = true;
                }
                if (startScreen.SelectedIndex == 1)
                {
                    activeScreen = optionsScreen;
                    startScreen.Hide();
                    optionsScreen.Show();
                }
                if (startScreen.SelectedIndex == 2)
                {
                    this.Exit();
                }
            }
        }

        private void HandleOptionsScreen()
        {
            if (CheckKey(Keys.Enter))
            {
                if (optionsScreen.SelectedIndex == 0)
                {

                }
                if (optionsScreen.SelectedIndex == 1)
                {

                }
                if (optionsScreen.SelectedIndex == 2)
                {
                    optionsScreen.Hide();
                    startScreen.Show();
                    activeScreen = startScreen;
                    //selected index has to be changed to allow user to change between menus
                    optionsScreen.SelectedIndex = 1;
                }
            }
        }

        private void HandleQuitScreen()
        {
            if (CheckKey(Keys.Enter))
            {
                if (quitScreen.SelectedIndex == 0)
                {
                    activeScreen.Hide();
                    activeScreen = startScreen;
                    activeScreen.Show();
                    game = false;
                }
                if (quitScreen.SelectedIndex == 1)
                {
                    activeScreen.Hide();
                }
            }
        }

        private bool CheckKey(Keys theKey)
        {
            return keyboardState.IsKeyUp(theKey) && oldKeyboardState.IsKeyDown(theKey);
        }
        /// <summary>
        /// This is used to update the joypad state
        /// </summary>
               private void HandleKeyboard()

        {
            if (playerDead == false)
            {

                //Get the current keyboard state
                KeyboardState state = Keyboard.GetState();

                // Switch between player and camera control
                if (state.IsKeyDown(Keys.LeftShift) || state.IsKeyDown(Keys.RightShift))
                {
                    // Move camera
                    if (state.IsKeyDown(Keys.A))
                        cameraPosition.X += 1.5f;

                    if (state.IsKeyDown(Keys.D))
                        cameraPosition.X -= 1.5f;

                    if (state.IsKeyDown(Keys.W))
                        cameraPosition.Y += 1.5f;

                    if (state.IsKeyDown(Keys.S))
                        cameraPosition.Y -= 1.5f;

                    view = Matrix.CreateTranslation(new Vector3(cameraPosition - screenCenter, 0f)) *
                            Matrix.CreateTranslation(new Vector3(screenCenter, 0f));
                }
                else
                {
                    // We make it possible to rotate the circle body
                    if (state.IsKeyDown(Keys.A))
                        playerSprite.RigidBody.ApplyLinearImpulse(new Vector2(-playerSpeed, 0f));

                    if (state.IsKeyDown(Keys.D))
                        playerSprite.RigidBody.ApplyLinearImpulse(new Vector2(playerSpeed, 0f));

                    if (state.IsKeyUp(Keys.A) && oldKeyState.IsKeyDown(Keys.A))
                    {
                        //playerSprite.RigidBody.LinearVelocity = new Vector2(velocity, playerSprite.RigidBody.LinearVelocity.Y);

                    }

                    if (state.IsKeyUp(Keys.D) && oldKeyState.IsKeyDown(Keys.D))
                    {
                        //playerSprite.RigidBody.LinearVelocity = new Vector2(velocity, playerSprite.RigidBody.LinearVelocity.Y);

                    }

                    if (state.IsKeyDown(Keys.Space) && oldKeyState.IsKeyUp(Keys.Space))
                    {

                        if (count2 < jumpTimes)
                        {
                            playerSprite.RigidBody.LinearVelocity = new Vector2(playerSprite.RigidBody.LinearVelocity.X, 0f);
                            playerSprite.RigidBody.ApplyForce(new Vector2(0, -jumpHeight * 75));
                            count2++;

                        }
                    }

                    if (!(state.IsKeyDown(Keys.A)) && !(state.IsKeyDown(Keys.D)))
                    {
                        playerSprite.RigidBody.LinearVelocity = new Vector2(playerSprite.RigidBody.LinearVelocity.X / 2 * friction, playerSprite.RigidBody.LinearVelocity.Y);
                    }

                    if (state.IsKeyDown(Keys.F1) && oldKeyState.IsKeyUp(Keys.F1))
                        debugPhysicsView.Enabled = !debugPhysicsView.Enabled;

                    if (playerSprite.RigidBody.LinearVelocity.X > playerSpeed)
                    {
                        playerSprite.RigidBody.LinearVelocity = new Vector2(playerSpeed, playerSprite.RigidBody.LinearVelocity.Y);
                    }
                    if (playerSprite.RigidBody.LinearVelocity.X < -playerSpeed)
                    {
                        playerSprite.RigidBody.LinearVelocity = new Vector2(-playerSpeed, playerSprite.RigidBody.LinearVelocity.Y);
                    }

                }

                // if (state.IsKeyDown(Keys.Escape))
                //  Exit();

                oldKeyState = state;
                //oldKeyboardState = keyboardState;
            }

        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {

            //Clear the screen
            GraphicsDevice.Clear(Color.CornflowerBlue);

            //Begin a sprite batch
            //batch.Begin(SpriteSortMode.Deferred, null, null, null, null, null, view);
            spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, null, null, null);
            spriteBatch.End();

            base.Draw(gameTime);

            if (game == true)
            {
                GraphicsDevice.Clear(Color.CornflowerBlue);

                spriteBatch.Begin(SpriteSortMode.Deferred, null, null, null, null, null, view);
                //draw map
                gameMap = Content.Load<Map>("Test Map");

                gameMap.Draw(spriteBatch);

                //Cycle through game sprites
                foreach (GameSprite s in displayList)
                {
                    // Convert physics position (meters) to screen coordinates (pixels)
                    Vector2 pos = PhysicsUtils.ConvertToGraphicsUnits(s.RigidBody.Position);
                    Vector2 origin = new Vector2(s.Texture.Width / 2f, s.Texture.Height / 2f);
                    float rotation = 0;

                    //Draw sprite
                    spriteBatch.Draw(s.Texture, pos, null, Color.White, rotation, origin, 1f, SpriteEffects.None, 0f);
                }

                spriteBatch.End();

                //Draw debug display
                debugView = Matrix.CreateTranslation(new Vector3(PhysicsUtils.ConvertToPhysicsUnits(cameraPosition - screenCenter), 0f)) *
                            Matrix.CreateTranslation(new Vector3(PhysicsUtils.ConvertToPhysicsUnits(screenCenter), 0f)); ;
                debugProjection = Matrix.CreateOrthographicOffCenter(0, PhysicsUtils.ConvertToPhysicsUnits(GraphicsDevice.Viewport.Width),
                    PhysicsUtils.ConvertToPhysicsUnits(GraphicsDevice.Viewport.Height), 0, 0, 1f);
                debugPhysicsView.RenderDebugData(ref debugProjection, ref debugView);

                //Begin Sprite batch
                spriteBatch.Begin();

                // Display instructions
                spriteBatch.DrawString(gameFont, Text, new Vector2(14f, 14f), Color.Black);
                spriteBatch.DrawString(gameFont, Text, new Vector2(12f, 12f), Color.White);

                spriteBatch.End();

                base.Draw(gameTime);
            }
        }

        public GameSprite sprite { get; set; }
    }
}

```

# Answer
Do what your game does to start up.

The simple, dumb way would be to re-initialize all your objects and variables as they do in the initialization of your game.

You could be clever here, and only reload those elements that are modified during game-play (your models, maps, and textures likely don't change, for instance).

If your character / gameworld has an init method, extract it to a new method, and call that, and when you reload the gameworld, call it again.

Probably this bit of code:

```
    public void LoadGame() { ... }

```
> 5 votes

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


# Question
Title: best way to compute vertex normals from a Triangle's list
hi i'm a complete newbie in computergraphics so sorry if it's a stupid answer. i'm trying to make a simple 3d engine from scratch, more for educational purpose than for real use.

for now i compute only face normals. in this way:

i have a Surface object with inside a Triangle's list. i compute normals inside Triangle class, in this way:

```
triangle.computeFaceNormals() {
    Vec3D u = v1.sub(v3)
    Vec3D v = v1.sub(v2)
    Vec3D normal = Vec3D.cross(u,v)
    normal.normalized()
    this.n1 = this.n2 = this.n3 = normal
}

```

and when building surface:

```
t = new Triangle(v1,v2,v3)
t.computeFaceNormals()
surface.addTriangle(t)

```

and i think this is the best way to do that.. isn't it?

now.. this works, ok. but light it's not smoothed. i'm trying to compute also vertex normals. (i'm testing my engine with tubolar surfaces so i have almost all vertex shared with more then one triangles)

i've found this simple algorithm: flipcode vertex normal but.. hei this algorithm has.. exponential complexity? (if my memory doesn't fail my computer science background..) (bytheway.. it has 3 nested loops.. i don't think it's the best way to do it..)

any suggestion?

# Answer
> 6 votes
**"Best" is pretty subjective -- it's going to involve weighing what you need out of the algorithm versus it's inputs, runtime complexity and other properties.**

That said, both your approach and the linked FlipCode approach are reasonable in terms of producing usable results (you could quite simply copy your 'face normals' to each vertex, if you are not sharing actual vertex instances between triangles, which I'm unclear on from your code). Other techniques include weighting the contribution of each face normal by the size of the angle made with each face shared by the vertex.

You are correct in that the FlipCode approach appears suboptimal as written, but it could just be poorly specified: it's a little unclear whether or not it intends to suggest the second loop traverse *all* faces in the model, versus the handful of faces that share the vertex in question. If you have the adjacency information to reduce the search space of the second loop, it becomes less of a concern. Of course you may not have that adjacency information -- this is sort of what I mean by considering what inputs you have available to your algorithm.

If you don't just want to copy the face normal into the vertices, or you are sharing vertices and don't want to split them, you could:

```
foreach vertex:
   set vertex normal to (0,0,0)

foreach triangle:
   foreach vertex on that triangle:
      set vertex normal = normalize( vertex normal + face normal )

```

This assumes that each triangle is actually referencing each vertex rather than storing a copy of it -- I don't know what language you're using so I don't know if that's the case or not.

# Answer
> 7 votes
Josh Petrie has right. If you want to compute vertex normals, you should weight triangle contribution by angle. But you can use naive solution and just sum all normals from all faces around vertex.

So you just compute all face normals and normalize them. Then set all vertex normals to zero. Then for each face (triangle) add its normal to all of its vertices. Then normalize all vertex normals. And it's done.

It's not too correct but it could be enough.

And your face normal calculation above - it's correct but you should aware, which side normal heads. It could head up or down. It depends on cross product - AxB is not the same as BxA - it gives you opposite vector.

# Answer
> 2 votes
Let us assume that we have a cube made from 6 rectangles. We already know that the vertex normal for a cube is not the normalized sum of the connection faces because of the sharp edge. If you build a map of vertex value and it's different vertex normals for a cube you end up with 3 normals for each vertex.

Keeping the above point in mind this is how I calculate vertex normals(I have tested it and am using it).

```
class Face{
    uint vert_indices[3];
    vec3 surface_normal;
    vec3 vertex_normal[3];
}

```

Each face keep track of the vertex normals to use since two faces may share a vertex does not mean the vertex normal will be the same for each face.

Let us assume we are trying to calculate the vertex normal for **vert** when rendering **face2**.

**vert** is shared by **face0**,**face1**,**face2**,**face3** and **face4**. All the above face are neighbours in order and **face0** and **face4** connect to form a loop.

The vertex normal for **vert** is the sum of all the connected neighbour chain to **face2** normalized. The chain stops if the angle between two neighboured faces is more that 0.8 radians(angle == arccos(crossProduct(faceA.surface\_normal, faceB.surface\_normal))).

if the angle between **face0** and **face1** is more than 0.8 radian and the angle between **face3** and **face4** is more than 0.8 radian than the vertex normal for **vert** when rendering **face2** is **normalize**(**surfnormal1**+**surfnormal2**+**surfnormal3**).

---
Tags: algorithm, normals
---


# Question
Title: Questions about dynamic loading and unloading of assets and game state
I've wondered about this for a while as I worked on my project, but couldn't quite come up with the best way to expose my problem. I'll start with some context.

**Context**

I have a game that is divided into rooms. So from an asset point of view, it makes sense to load and unload them on a room by room basis. In my case this boils down to all the textures and audio files required by that room.

However, player triggered events can change the state of *any* dynamic object *in the world*, even those that are not on the current room. Furthermore, since the game is multiplayer, even if I'm not seeing the changes immediatly, other players *might*. So, even if the assets aren't loaded, I still need some way to register that change in state.

The way I'm currently handling this is to keep the *entire* game world state in memory since the start of the game, and only bother about dynamically loading and unloading its assets.

Which leads to the following questions related to resource management.

**Questions**

1. Loading and storing the entire game state at once seems reasonable for the scope of my games, but I get the feeling it wouldn't scale very well to larger projects. So how is this usually implemented in massive games such as MMOs that need to update a large amount of entities that are far away from the player?
2. Assets that are guaranteed to be needed for a particular room (such as the room's scenario and static objects) can be loaded when the player enters the room - possibly with a transition or a loading screen in between. But what about assets for unpredictable game entities that might suddenly come into your current room at *any* time, such as other players?

Would it be reasonable to treat those separately, load them all at once when the game starts, and keep them in memory the entire time, or would it be better to load them and unloaded *dynamically* in a separate thread? And in that case, does XNA handle loading assets from another thread well?

# Answer
My understanding of most multiplayer games do in fact cull data that is sent to clients. Either by distance, or visibility - if your player is not visible to me in Q3A then I don't need to know what frame of animation is playing, or even which direction you're facing, but the sounds you make could be useful.

I suspect MMOs do much the same - any time where your travel isn't completely visible (when you take a ship on WoW) you can assume you're moving to a different bit of hardware. The state of such a game is actually very simple, which is why we don't have MMOs with Quake like fighting, rather the turn-based affair that you can see happening in the background. The server only needs to send a small amount of the total game-state to the player.

However yes, some assets can be spooled (like the game-world) and others should be held in memory. Particularly player / mob related ones.

Something like Doom the game-state was linked to the gameworld, all the clients pushed up their changes and pulled down the entire world-state from one player's machine (the Green marine always had a slight edge and was always the server in Genuine Doom) - the game was hard-wired to the slowest machine's frame-rate - turn off one machine's turbo, and everyone would slow down.

More advanced games and I believe the general way things are done is with a client-server, even in single-player, one machine runs the server and connects to itself, the other machines connect to it. There is still a slight advantage to the host due to network latency, but you can now pull the server code into a separate executable and run it anywhere. Because the client and server are abstracted, players jump around when there are delays - however, one slow player will not grind down all players.

My understanding of Diablo was that the server maintained the overall game-state, but the clients offloaded much of the work. Where individual Mobs were was unimportant, just recording their state when killed, and drops when they happened. This way the 4 players could be anywhere in the huge game-world and there wouldn't be huge amounts of traffic required.
> 1 votes

---
Tags: xna, assets, asset-management
---


# Question
Title: XNA Framework HiDef profile does not support alpha blending
I am getting the following error, even though the code runs through the `Draw` could twice and then it errors:

> XNA Framework HiDef profile does not support alpha blending or ColorWriteChannels when using rendertarget format Single.

The `BlendState` that I'm using is:

```
BlendState newBlendState = new BlendState()
{
    AlphaBlendFunction = BlendFunction.Add,
    AlphaSourceBlend = Blend.One,
    AlphaDestinationBlend = Blend.One,
    ColorBlendFunction = BlendFunction.Add,
    ColorSourceBlend = Blend.One,
    ColorDestinationBlend = Blend.One
};

```

I even set the `SamplerStates` to `PointClamp` before the actual draw is called:

```
device.DrawUserIndexedPrimitives<VertexPositionTexture>(PrimitiveType.TriangleList, domeVerts, 0, 1024, ib, 0, 1860);

```

I don't understand how it can run successfully twice, and then fail. Any help would be greatly appreciated.

A screenshot of the problem:

# Answer
> 0 votes
The solution was nothing to do with the `RenderTarget`s that were currently in use, but it was the `DepthBuffer` `RenderTarget` causing the problem. Changing this resolved the issue.

# Answer
> 2 votes
The problem is that the RenderTargetFormat 'Single' does not have an alpha channel so you need to use a different format or an opaque blend state.

When I went to look up which values the RenderTargetFormat enum has I found out that someone else also asked this question in the official XNA forums, that they gave the same advice as I have and that this resolved the issue. I'm still posting this answer here so other people have a reference as well.

http://forums.create.msdn.com/forums/t/60776.aspx

edit: thought it was the same person who asked this, but as ClassicThunder pointed out this is very unlikely.

---
Tags: xna, xna-4.0
---


# Question
Title: Positioning a texture inside a 3D object with GLSL
I have a 3D object in my scene and a texture that is the same size of the screen (a render to texture). Is there a way to make the object act like a "mask" for the texture(using glsl), so the texture is aligned with the screen 2D space but only shows what is "inside" the mask object?

What I'm trying to achieve here is this: I have a 3D scene made of cubic tiles, some of these tiles are going to be water and I want to distort whatever is behind them. My idea was to pass the render to texture and then distort it to make a refraction effect. Is this going to work? Am I even suposed to do refraction like this?

# Answer
> 2 votes
This is what I did:

I used the fragment position and translated it to screen coordinates. After that I just had to pick the pixels on my render to texture from that coordinate.

```
uniform sampler2D myTexture;
uniform float time;

void main (void)
{
    vec2 pixelPos = (gl_FragCoord.xy / vec2(1024,768) ); //frag position in the screen
    gl_FragColor = texture2D(myTexture,pixelPos);
}

```

---
Tags: opengl, glsl
---


title: Intellectual rights to game concepts

text:
# Question
Title: Intellectual rights to game concepts
For a client I might be making a small puzzle game about getting a item out of a puzzle. The concept will strongly resemble this game :

http://www.alibaba.com/product-gs/355972089/Car\_Park\_Game\_Brain\_Teaser\_IQ.html

But will not be about cars or parking, and we will make our own "levels".

The game will not be a board game, but a smartphone game (iOS + Android devices).

But does ThinkFun sit on the concept so heavily that I can't make a game like this ? And where does "the line" go to what is acceptable?

The game will be free, and we are a non-US company (based in Denmark, Europe) if that makes any difference.

# Answer
> 5 votes
Link

> Copyright does not protect the idea for a game, its name or title, or the method or methods for playing it. Nor does copyright protect any idea, system, method, device, or trademark material involved in developing, merchandising, or playing a game. Once a game has been made public, nothing in the copyright law prevents others from developing another game based on similar principles. Copyright protects only the particular manner of an author’s expression in literary, artistic, or musical form.
>
> Material prepared in connection with a game may be subject to copyright if it contains a sufficient amount of literary or pictorial expression. For example, the text matter describing the rules of the game or the pictorial matter appearing on the gameboard or container may be registrable.

# Answer
> 9 votes
*You need a lawyer and this is not legal advice.*

That said,

* being free usually makes no difference at all
* "game concepts" usually cannot be subject to copyright, but in many perverted jurisdictions apparently are subject to patents
* regardless of being legal or not, remember you can be sued anyway: if you can't afford to defend yourself you'd better play safe (one way or another)

# Answer
> -2 votes
This is absolutely not a full answer (get a lawyer ;-) but I have already seen games using this "classic" concept.

I don't think you can patent a game design, just graphics, text, music and so on.

---
Tags: game-design, game-mechanics, legal, copyright, intellectual-property
---


title: C# creating a simple snake game

text:
# Question
Title: C# creating a simple snake game
I was thinking about creating a snake game with C#, so I ran ideas in my head, and some problems came up.

How can I track and output in the correct location the blocks that run after the snake's head?

If the snake is built of five blocks, and the user starts going in a circle, how can I print the snake body in the right location?

Also, how can I create an action that will run on the background, which will move the snake forward, no matter what the user does?

What structure should my code have? (code design structure)

This should be a console application, since it's the only framework I am familiar with.

I am not looking for finished code, since I want to really understand how it should work.

# Answer
> 24 votes
**Representing the Snake**

Creating a Snake game is pretty simple. The first thing you need is a way to *represent* your snake's body. If you consider your snake to be made up of blocks or tiles, your body can simply be a list of these blocks coordinates.

In your case, if you intent do a console application, each of these will be a character on the console, and the position would correspond to one line or row of the console output. So you start with this:

```
// List of 2D coordinates that make up the body of the snake
List<Point>() body = new List<Point>();

```

At this point, your list is empty, so your snake has no body. Let's say you want a snake of length 5 and the head should start in position (5,2) and grow towards the bottom. Just add those positions to the list when the game starts, for instance:

```
// Initialize the snake with 5 blocks starting downwards from (5,2)
for(int i=0; i<5; ++i)
{
    body.Add(new Point(5, 2 + i));
}

```

**Rendering the Snake**

For rendering just draw a character at each position on the body list. The example above for instance could be drawn as:

```
...................
...................
.....O............. -- y = 2
.....#.............
.....#.............
.....#.............
.....V.............
...................
     |
     x = 5

```

You can get more complicated by choosing different characters for the character's head (first element on the list) and tail (last element on the list) and even orient them depending on the positions of the adjacent blocks. But for starters, just render everything as a `#` or something.

You could for instance start with a 2D char array containing the background like this:

```
// Array with map characters
char[,] render = new char[width, height];

// Fill with background
for(x=0; x<width; ++x)
    for(y=0; y<height; ++y)
        render[x,y] = '.';

```

And then iterate over the snake's body drawing it to the array:

```
// Render snake
foreach(Point point in body)
    render[point.X, point.Y] = '#';

```

And finally iterate over the array again and write each character to the console, with a linebreak at the end of each row.

```
// Render to console
for(y=0; y<height; ++y)
{
    for(x=0; x<width; ++x)
    {
        Console.Write(render[x,y]);
    }
    Console.WriteLine();
}

```

**Moving the Snake**

Finally, movement. The first thing you need is to keep track of the `Direction` the snake is moving. This can be a simple enum:

```
// Enum to store the direction the snake is moving
enum Direction { Left, Right, Up, Down }

```

And the act of moving the snake can be done just by *removing the last block from the list and adding it on the front, in the correct direction*. In other words something like:

```
// Remove tail from body
body.RemoveAt(body.Count - 1);

// Get head position
Point next = body[0];

// Calculate where the head should be next based on the snake's direction
if(direction == Direction.Left)
    next = new Point(next.X-1, next.Y);
if(direction == Direction.Right)
    next = new Point(next.X+1, next.Y);
if(direction == Direction.Up)
    next = new Point(next.X, next.Y-1);
if(direction == Direction.Down)
    next = new Point(next.X, next.Y+1);

// Insert new head into the snake's body
body.Insert(0, next);

```

# Answer
> -3 votes
1. Each time a timer ticks you update the location of the snake and draw the shapes at the new locations
2. Use a System.Windows.Forms.Timer for the background action to trigger the game to move the snake around.
3. Use classes and inheritance for the structure

---
Tags: c#
---


title: XNA Sprite Flash Effect

text:
# Question
Title: XNA Sprite Flash Effect
I'm looking for a way to render every non-transparent pixel in a sprite solid white (to 'flash' the sprite white when the player takes damage etc). This is on Windows Phone 7.

I was using a very simple custom shader to do this under XNA 3.1, but WP7 doesn't support these and finding an alternative's proving difficult.

I'd appreciate any help or suggestions. I'd rather not have to manually create a solid white copy of every sprite in my game though.

# Answer
> 8 votes
**Method 1**

You don't have to create a solid white version of every sprite in your game *manually* \- you could just as well automate the process at load time. In other words, you can use `Texture2D.GetData()` to access the pixels of your texture (and retrieve them as a simple `Color[]`), iterate over them replacing any non-transparent pixel with solid white , and then save it to a new texture using and `Texture2D.SetData()`.

**Method 2**

I tried playing around with `BlendState` but couldn't find a way to render it all white, at least not within Reach profile's limitations. But if someone knows a way let me know. What I did find, however, was a way to to do it using the stencil buffer and the built-in `AlphaTestEffect` class. The idea is the following:

1. Create a backbuffer that has a stencil buffer.
2. Clear the stencil buffer to zero.
3. Draw the sprites you'd like to tint white and whenever they pass the alpha test, set the stencil buffer at that location to 1.
4. Draw a white quad covering the entire screen, but only where the value of the stencil buffer is 1.

Here's the code I used:

(Step 1) First make sure the backbuffer is being created with room for a stencil buffer:

```
graphics = new GraphicsDeviceManager(this) { PreferredDepthStencilFormat = DepthFormat.Depth24Stencil8 };

```

(Step 2) Create a 1x1 white texture that will be scaled to fill the entire screen:

```
private Texture2D pixel;
pixel = new Texture2D(GraphicsDevice, 1, 1);
pixel.SetData(new[] { Color.White });

```

(Step 3) And now the hard part - rendering it. Well, not really hard, but requires two `DepthStencilState` objects and one `AlphaTestEffect` object. You should create these only once.

```
// Clear stencil buffer
GraphicsDevice.Clear(ClearOptions.Stencil, Color.Black, 0f, 0);

// Prepare the alpha test effect object (create it only once on initilization)
AlphaTestEffect alphaTestEffect = new AlphaTestEffect(GraphicsDevice)
{
    DiffuseColor = Color.White.ToVector3(),
    AlphaFunction = CompareFunction.Greater,
    ReferenceAlpha = 0, World = Matrix.Identity,
    View = Matrix.Identity,
    Projection = Matrix.CreateTranslation(-0.5f, -0.5f, 0) *
    Matrix.CreateOrthographicOffCenter(0, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height, 0, 0, 1)
};

// Prepare the first DepthStencilState (create only once, or put it in a static class)
DepthStencilState beforeDepthStencilState = new DepthStencilState
{
    StencilEnable = true,
    StencilFunction = CompareFunction.Always,
    StencilPass = StencilOperation.Replace,
    ReferenceStencil = 1
};

// Draw your sprites using the structures above
spriteBatch.Begin(SpriteSortMode.Deferred, null, null, beforeDepthStencilState, null, alphaTestEffect);
spriteBatch.Draw(sprite, new Vector2(300, 150), Color.White);
spriteBatch.End();

// Prepare the second DepthStencilState (create only once, or put it in a static class)
DepthStencilState afterDepthStencilState = new DepthStencilState
{
    StencilEnable = true,
    StencilFunction = CompareFunction.Equal,
    ReferenceStencil = 1
};

// Draw a full screen white quad with the structure above
spriteBatch.Begin(SpriteSortMode.Deferred, null, null, afterDepthStencilState, null);
spriteBatch.Draw(pixel, GraphicsDevice.Viewport.Bounds, Color.White);
spriteBatch.End();

```

And the result:

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


title: Programming games for Windows

text:
# Question
Title: Programming games for Windows
I've programmed a couple simple games so far, in C++ as that's my language of choice, all using open source, cross platform libraries, they're great. I'd like to understand how are cross platform libraries written, this is why i want to write a game for windows only without using a library that provides an abstract layer for the technical side of things like input. However i have some general questions.

First of all, is the windows.h library still used (there's so many new technologies and libraries comming in, i can't tell which are outdated since i'm new to this) for the low level communication between a C++ application and Windows? This means handling input, multithreading, etc. Similarly, is winsock.h still the library for network programming under Windows? I know it's very old, though so are OS standards, i'm confused. Are all the libraries that handle networking just wrappers that use winsock.h? Are these libraries maintained by Microsoft, do i need to manualy update them, do they come with the compiler or the OS.

Do cross platform libraries like SFML or Qt use windows.h or do they go lower than that? I know you can get input straight from reading interrupts, but how do you handle f.e. multithreading.

Do Unix systems also provide a library for interfacting with the OS? Does this include things like sockets? Are these libraries used in cross platform libraries?

All of the libraries, no matter the OS, were written first, so there is a way to get to the OS directly without using them, but are low level "tricks" like these used, or do people just use the API provided by the OS for cross platform libraries and then compile apropriate parts of the code depending on the target platform.

# Answer
all your questions have same short answer, "YES".

windows.h is still used. also people still use "winsock.h", but there is "winsock2.h" which has provide same API as the "Berkeley sockets" (the one used in linux/unix/etc.) so the later is more common.

in windows working with devices is very restricted, it's either using windows API or using DirectX API. Infact DirectX was introduced to let people use devices directly. so all the libraries should use one of those two. on linux however things are a little bit different. there is a direct access to every device. But all devices usually have some libraries to handle them. for example almost everyone uses OpenAL for audio management.
> 3 votes

# Answer
Your question is so complicated, but I'll try to answer for some of sub-questions.

Yes, windows.h is still used in cross platform librares. E.g. SMFL:

> \[...\]You can't use OpenGL on Windows without windows.h included first\[...\]

Unix-like system often get more low-level libraries than Windows. Just look at Linux where you can edit kernel.

If you want to dive into some cross-platform programming just download some open-sourced library and read it's source. You can start with SMFL.
> 2 votes

---
Tags: c++, windows, cross-platform
---


# Question
Title: Increasing the probability for similar tiles to generate next to each other
I'm working on a tile map system, which insofar looks like this (green is grass, air is white, stone is grey, and blue is water):

It uses a simple random number generator so that there's a 45% chance of the tile being grass, 30% chance of it being water, and a 25% chance of it being stone.

Is there anyway I can increase the tendency for grass/stone blocks to clump together to form land masses, and make water blocks form oceans (sort of like what could be seen in a game like Minecraft)?

# Answer
You could use an algorithm that checks near blocks, and varies the probability depending on what is there - but I think it's largely the wrong approach.

What you want to be looking at is fractal noise types - in this case, perlin or simplex noise. If you generate noise, you'll get values from -1 to 1.

http://en.wikipedia.org/wiki/Perlin\_noise

You can then adjust your water level by setting the threshhold of what makes water. For the other blocks you can run a second set of noise to switch between rock and grass. (this way you can have large patches of water, but smaller clumps of stone).

```
getTerrain(x,y) {
if(perlin_noise(x,y) > 0) {
    if(perlin_noise(x * scale,y * scale) > 0) {
        return rock
    } else {
        return dirt
    }
} else {
    return water
}

```

As I think the scan and toss method is overly complicated and not overly robustly scaleable, I'll suggest another method that I enjoyed:

Lay a grid across your map, breaking the map into large squares.

Generate a random number at each intersection (between 0 and 1 will work for your percentages)

Subdivide by cutting each square into 4 even squares - follow the old lines, and where you find the subdivision lines, generate a random number between the 2 adjacent points, similarly, for the center of the cross, generate a point that lies between the highest and lowest values.

Rinse, and repeat. You will get the initial randomness from the first pass, but the latter passes will give some uniformity Sorry for the psuedo-random numbers:

```
0-------5  0---3---5 0-1-3-4-5 011233455
|       |  |   |   | | | | | | 012344555
|       |  |   |   | 0-2-4-6-5 002445665
|       |  |   |   | | | | | | 123445666
|       |  2---5---7 2-4-5-7-7 234455777
|       |  |   |   | | | | | | 233455688
|       |  |   |   | 2-3-5-5-9 223455589
|       |  |   |   | | | | | | 233455589
2-------9  2---4---9 2-4-4-5-9 234445579

```

This works even better for triangles, because you don't have the lost cross-bar when you sub-divide.

Of course, the absolute best result will come from combining these methods - layer upon layer, some techniques will give you great land-masses, others will give you awesome caves, others work for hills, and more will work for water-systems.
> 17 votes

# Answer
Noise is one good solution, as has already been mentioned. Another option is to take a second pass at the data to nudge it toward the layout you want. Gaussian Blur is one of many ways you could achieve this. Doing a pass with that should get you nice "round" blobs of each type.

No matter what method you go with though, one important thing to keep in mind is to store the results of the process in a new location. If you modify the map in place, the portions you have already processed will start to affect the algorithm and you'll end up with some strange patterns.
> 3 votes

# Answer
A relatively simple way of doing this would be to create a number of nuclei at random positions. Draw the Voronoi diagram of these points. Assign an element to each region of the result.

This results in something rather ugly and mechanical looking. Muddy up the borders a bit and you'll be in decent shape.

If you are generating for a large map, you could do this on two levels. Create your initial Voronoi diagram using, say, 20 nuclei, and call each resulting region a nation. Create another diagram using 400 nuclei and call each resulting region a vicarage.

All vicarages totally contained within a nation will have the nation's element. Vicarages partially contained in two or more nations will take one of their enclosing nations' elements at random.

This post deserves a picture, but I am too lazy to provide one.
> 2 votes

# Answer
Polygonal Map Generator would be a good read into creating map with different 'zones' which would give you a better formed maps as well. It's based on voronoi diagrams but I guess this would be a good start into it.
> 2 votes

# Answer
you can do it using this method:

* put all the tiles in unspecified list
* while there is a tile in unspecified list
* begin
* pick one tile from that list
* check neighbors of that tile, and select a type depending on it's neighbors
* remove that tile from unspecified list
* end
> 0 votes

---
Tags: java, algorithm, tiles, maps, lwjgl
---


title: XNA GameServices vs. public static

text:
# Question
Title: XNA GameServices vs. public static
I am just starting learning XNA for developing Windows Phone games. I am stumbling accross different sample codes featuring different approaches on handling things.

A question for the experts... or at least for people who already have experiences with that topic:

Does it make more sense to inject instances of SpriteBatch via the constructor of game objects or adding the SpriteBatch object to the GameServices collection and retrieving it from the game objects' constructor like so:

```
spriteBatch = Game.Services.GetService(typeof(SpriteBatch)) as SpriteBatch;

```

# Answer
> 4 votes
**Use whatever feels more practical to you, and don't think too much about it.**

There's really no *best* answer to this, because there are so many different ways of doing it, but all of the possibilities work just as well. Personally I don't think it's worth bothering with `GameServices`, so I prefer either passing my dependencies or making them static public.

For `SpriteBatch` in particular, rather than passing it to the object's constructors, I prefer passing them only to my `Draw` methods instead. Or to be more specific, instead of passing `SpriteBatch` by itself, I create a class called `DrawContext` that contains a reference to the `GraphicsDevice`, a `SpriteBatch`, a default `SpriteFont`, and provides a bunch of helper methods for doing things such as debug drawing of lines and text, and then pass that around to all `Draw` methods in my game.

But like I said, that's just personal preference. You can use `GameServices` if you want. You can create a public static reference to your `Game` instance and make the `SpriteBatch` public inside your game class, making it accessible anywhere on your application. You can pass the `SpriteBatch` to the constructor, or just the `Draw` method, or you can create a wrapper class for all graphic related objects like I did.

Since you know the alternatives, think which one you like better, and pick the one that seems less cumbersome to you.

*I* like the approach I described because I have a continuous chain of `Draw` calls starting on the `Game` and moving down the class hierarchy through the `ScreenManager`, the `Screen`s, the `Stage`, the `Layer`s, and finally to my individual `DisplayObject`s (nevermind those names, that's just the architecture I went with). And I know that within any `Draw` method I have everything I need contained in a single object. And if in the future I need a new feature, I just need to add it to that class (i.e. add to `DrawContext`).

But the biggest reason why I prefer passing my context around rather than using a public static reference to my `Game`, is because I happen to use the *same classes* for both my `Game`s and WinForms game editor which doesn't have a `Game` class. But like I said, that's just me, and my specific needs!

---
Tags: xna, spritebatch
---


# Question
Title: removing box2d objects before collision occurs
I am having a problem with a collision detection between the character and items, both created as box2d objects. What I am trying to do is to delete the item or remove item from the collision method before character hits item and bounces away. Thus, I want to detect when the item and character collided to gain item effects.

Current sources are as below :

```
mWorld.setContactListener( new ContactListener() {
        @Override
        public void endContact(Contact contact) {
        }
        @Override
        public void beginContact(Contact contact) {
            Body bodyA = contact.getFixtureA().getBody() ;
            Body bodyB = contact.getFixtureB().getBody() ;

            Box2DUserData dataA = (Box2DUserData) bodyA.getUserData() ;
            Box2DUserData dataB = (Box2DUserData) bodyB.getUserData() ;

            if( dataA.id == Box2DUserData.ID_ITEM ) {
                //mWorld.destroyBody(bodyA);
                //bodyA.setTransform(new Vector2( 0, 0 ), 0 ) ;
                bodyA.setActive(false );
            }
            else if( dataB.id == Box2DUserData.ID_ITEM ) {
                //bodyB.getWorld().destroyBody(bodyB);
                //bodyB.setTransform(new Vector2( 0, 0 ), 0 ) ;
                //mWorld.destroyBody(bodyB);
                bodyB.setActive(false );
            }
        }
    });

```

This source works okay, but the bodies are removed after collision detection. So I can get the character walk through items, after the character bumped in item and stopped for a frame or so.

I am not sure if I am supposed to use World.setContactListener or another method, it would be grateful if someone could give me the right method or another way to detect collision and the way to remove body from collision method before it actually collides.

Thanks

# Answer
The easiest way is to use a sensor instead a Body. A sensor generates a collision, but not a response. So you will be notified when they hit, but the hero will not bounce off.
> 4 votes

---
Tags: collision-detection, libgdx, body
---


# Question
Title: Transformation order when dealing with Meshes
I have created a player model out of primitive types. To do this I have created a Model class and Component (mesh) class. Each model consists of one or more components my problems start when you have to rotate the model as a whole. When you manually create a mesh, you have to also specify it's origin, my problem is that the player is not rotating, before it worked somewhat (it turned each mesh indivialy) but then I changed the order of the Matrices and now it doesn't rotate at all, I think it is my matrix order:

```
effect.Parameters["World"].SetValue(Matrix.Identity *  Matrix.CreateTranslation(component.RelativePosition) * Matrix.CreateRotationY(player.Rotation.Y) * Matrix.CreateTranslation(player.Position)  * Matrix.CreateTranslation(player.Model.Origin));

```

How can I fix this?

**Edit:**

The update code is (I added the "0, 0, -1" so I can actually see it) but it is rotating each component idividally rather then as a whole model:

```
effect.Parameters["World"].SetValue(Matrix.CreateTranslation(-player.Model.Origin)  * Matrix.CreateRotationY(player.Rotation.Y) * Matrix.CreateTranslation(component.RelativePosition) * Matrix.CreateTranslation(player.Position) * Matrix.CreateTranslation(0, 0, -1));

```

# Answer
> 5 votes
I don't really know exactly what your `RelativePosition` and `Model.Origin` stand for, so it's hard to say for certain, but usually the *origin* part should come at the beggining of the world matrix and be negated (i.e. `Matrix.CreateTranslation(-player.Model.Origin)`).

Scaling, rotation and translation usually come in SRT order, which you did right.

As for the `RelativePosition` I'm not sure what it is. But if that's like the transform of the parent object, then I think it needs to go at the end (at least that's how it worked for me here).

Anyway, for future reference, here's a rundown of what is usually the order for each situation:

**Simple Transformations**

The order of multiplication for a **world matrix** is typically:

```
// World Matrix
Scale * Rotation * Translation

```

And the order of multiplication for a **view matrix** is typically:

```
// View Matrix
-Translation * -Rotation * Zoom

```

**Transformations with Origin**

However, especially in 2D games, you frequently need to add an **origin** displacement to your transformation. That's usually added to the beggining, and must be negated too, so:

```
// World Matrix with Origin
-OriginTranslation * Scale * Rotation * PositionTranslation

```

The same thing can also be done with a view matrix, but you add it to the end and this time you don't negate it:

```
// View Matrix with Origin
-PositionTranslation * -Rotation * Zoom * OriginTranslation

```

**Transformations with Selective Origin**

There are also some cases where you want to have an origin displacement, but you want it to affect only your scale and rotation, but not your translation. The way to handle that is to undo the origin transformation before reaching the translation component. For example, with the world matrix:

```
// World Matrix with Origin for Scale and Rotation
-OriginTranslation * Scale * Rotation * OriginTranslation * PositionTranslation

```

And the view matrix:

```
// View Matrix with Origin
-PositionTranslation * -OriginTranslation * -Rotation * Zoom * OriginTranslation

```

**Orbiting around Target**

Finally, there's the special case where you want something that orbits around another point. In that situation, you simply switch rotation and translation and it becomes:

```
// Orbit matrix
Scale * Translation * Rotation

```

---

**Edit**

From your picture I now understand you're trying to create a sort of bone hierarchy where the character is composed by several pieces each with their own transformations, which in turn are grouped together and work as a whole.

In this situation it's easier to understand if you divide the process into two separate matrices, one for the character as a whole, and one for the piece, and then combine them into one as:

```
Piece Absolute World Matrix = Piece Relative World Matrix * Character World Matrix

```

So for full flexibility let's say your character has its own `Position`, `Rotation`, `Scale` and `Origin` in the world, and each piece has its own `Position`, `Rotation`, `Scale` and `Origin` *relative* to the origin of the character. You would then calculate the actual world matrix as:

```
Matrix characterMatrix = Matrix.CreateTranslation(-character.Origin) *
                         Matrix.CreateScale(character.Scale) *
                         Matrix.CreateRotationY(character.Rotation) *
                         Matrix.CreateTranslation(character.Position);

foreach(Piece piece in character.Pieces)
{
    Matrix pieceMatrix = Matrix.CreateTranslation(-piece.Origin) *
                         Matrix.CreateScale(piece.Scale) *
                         Matrix.CreateRotationY(piece.Rotation) *
                         Matrix.CreateTranslation(piece.Position);

    Matrix finalMatrix = pieceMatrix * characterMatrix;
}

```

Since you only seem to use a small subset of this values, you can remove everything that isn't being used, and if you want you can also inline everything into a single expression (the problem is that you will be recalculating the character's world matrix over and over and again for each piece, which is wasteful).

I think the result would then be, using the values you provided:

```
effect.Parameters["World"].SetValue(
    Matrix.CreateTranslation(component.RelativePosition) *   // Piece Matrix
    Matrix.CreateTranslation(-player.Model.Origin)  *        // Character Matrix
    Matrix.CreateRotationY(player.Rotation.Y) *
    Matrix.CreateTranslation(player.Position) *
    Matrix.CreateTranslation(0, 0, -1)
);

```

# Answer
> 2 votes
You should always have your transformations in order: scale * rotation * translation

It's because matrix multiplication is not commutative. For demonstration, look at this:

If you use transform and then rotation, it's different from rotation and then transform.

*EDIT: Of course if you want special behaviour like Earth rotation around Sun, you can first translate (all the time the same direction) Earth from Sun and then rotate (rotation is changing in time), which will do the trick.*

---
Tags: xna, c#, maps, matrix, rotation
---


# Question
Title: DX11 StreamOut to Vertex Buffer from GeometryShader, can't clear Buffer?
I'm trying to use a geometry shader to continuously modify the positions of vertices, and save the modfied verts in a buffer.

I have two vertex buffers, one is bound to the IA stage / the vertex shader input, the other to the SO stage / the geometry shader output. After I draw a frame, I swap those two buffers so that (ideally) the saved vertices get modified and saved by the GS again.

What actually happens though is this: I have two buffers, outVB and inVB, both are empty, and an initial, vertex generating vertex shader is set

1. (Frame 1) Draw(..), the initial vertices are processed, saved to outVB, and drawn
2. I set inVB as the SO target, and outVB as the input vertex buffer
3. (Frame 2) Draw(..), vertices are read from outVB, processed, saved to inVB, and drawn
4. I swap the buffers
5. (Frame 3) Draw(..), vertices are read from inVB, processed, (apparently not)saved, and drawn
6. I swap the buffers
7. (Frame 4) the same output appears as in Frame 2
8. I swap the buffers
9. (Frame 5) the same output appars as in Frame 3

and it continues alternating between those two frames, which lead me to believe the buffers still contain the data they held the first time they were written to.

Which makes sense, as the GS can only append new data to the provided buffer.

So I tried releasing and recreating the buffer that is to become the new stream out target before swapping them (I couldn't find any way to clear it), which makes it produce 5 unique frames (including the initial one), and it loops over the last 4 frames, which makes no sense to me at all.

Destroying the buffer holding the old data and recreating it seems to work, since it progresses beyond the states of Frame 2 and 3, but if it worked how can it revert back to the states of Frames 2 and 3 after drawing two more?

my shaders are really simple so far:

```
struct GS_OUT {
    float4 Pos : SV_POSITION;
    float4 Col : COLOR;
};

GS_OUT VS(GS_OUT input)
{
    return input;
}

[maxvertexcount(10)]
void GS(point GS_OUT input[1], inout PointStream<GS_OUT> PStream )
{
    float4 position = input[0].Pos + float4(0.1f, 0.1f, 0, 1);

    GS_OUT output;
    output.Pos = position;
    output.Col = float4(1,1,1,1);

    PStream.Append(output);
}

float4 PS(GS_OUT input) : SV_TARGET
{
    return inut.Col;
}

```

My code for flipping the buffers (not neat, I know I could just flip the pointers then assign, but I wanted to make sure everything happened in exactly the order I want):

```
void swapVBs()
{
    static bool flip = true;

    UINT bufferstride = 2*sizeof(XMFLOAT4);
    ID3D11Buffer *nobuffer = NULL;
    UINT offset = 0;

    D3D11_BUFFER_DESC vbdesc;
    vbdesc.BindFlags = D3D11_BIND_STREAM_OUTPUT | D3D11_BIND_VERTEX_BUFFER;
    vbdesc.ByteWidth = 640*360*2*sizeof(XMFLOAT4);
    vbdesc.CPUAccessFlags = 0;
    vbdesc.MiscFlags = 0;
    vbdesc.StructureByteStride = 0;
    vbdesc.Usage = D3D11_USAGE_DEFAULT;

    if (flip) // SO Target == inVB, Vertex Buffer == outVB
    {

        //clear SO target
        devcon->SOSetTargets(1, &nobuffer, 0);
        //make inVB Vertex Buffer
        devcon->IASetVertexBuffers(0, 1, &inVB, &bufferstride, &offset);

        outVB->Release();
        device->CreateBuffer(&vbdesc, NULL, &outVB);

        //make outVB SO target
        devcon->SOSetTargets(1, &outVB, 0);

    }

    if (! flip) // SO Target == outVB, Vertex Buffer == inVB
    {

        //clear SO target
        devcon->SOSetTargets(1, &nobuffer, 0);
        //make outVB Vertex Buffer
        devcon->IASetVertexBuffers(0, 1, &outVB, &bufferstride,  &offset);

        inVB->Release();
        device->CreateBuffer(&vbdesc, NULL, &inVB);

        //make inVB SO target
        devcon->SOSetTargets(1, &inVB, 0);

    }

    flip = !flip;
}

```

and the draw code is nothing more than

```
devcon->DrawAuto();
swapVBs();

```

So I guess I'm asking...how do I properly clear a ID3D11Buffer? Why in the world does releasing and creating a new buffer not give me an empty buffer?

# Answer
I found the problem, `ID3D11DeviceContext::SOSetTargets(..)` expects a pointer to an array of offsets as the third param, but I've been passing a nullpointer (thinking it would assume I don't want an offset).

The default behavoir seems to be to assume a value of -1, which makes the GS append writes to the last position in the buffer that was written to, which in my case always seems to have been the end, causing no new vertices to be written.

Passing an actual pointer to an `UINT offset = 0;` works like a charm and the geometry shader overwrites the contents of the buffer.
> 3 votes

---
Tags: c++, directx11
---


# Question
Title: flicker when drawing 4 models for the first time
i have some models that i only draw at a certain moment in the game (after some seconds since the game has started). The problem is that in that first second when i start to draw the models, i see a flicker (in the sence that everything besides those models, dissapears, the background gets purple). The flicker only lasts for that frame, and then everything seems to run the way it should.

**UPDATE** I see now that regardless of the moment i draw the models, the first frame has always the flickering aspect

What could this be about? i'll share my draw method:

```
int temp = 0;
foreach (MeshObject meshObj in ShapeList)
{
    foreach (BasicEffect effect in meshObj.mesh.Effects)
    {
        #region color elements

        int i = int.Parse(meshObj.mesh.Name.ElementAt(1) + "");
        int j = int.Parse(meshObj.mesh.Name.ElementAt(2) + "");
        int getShapeColor = shapeColorList.ElementAt(i * 4 + j);
        if (getShapeColor == (int)Constants.shapeColor.yellow)
            effect.DiffuseColor = yellow;
        else if (getShapeColor == (int)Constants.shapeColor.red)
            effect.DiffuseColor = red;
        else if (getShapeColor == (int)Constants.shapeColor.green)
            effect.DiffuseColor = green;
        else if (getShapeColor == (int)Constants.shapeColor.blue)
            effect.DiffuseColor = blue;

        #endregion

        #region lighting

        effect.LightingEnabled = true;
        effect.AmbientLightColor = new Vector3(0.25f, 0.25f, 0.25f);

        effect.DirectionalLight0.Enabled = true;
        effect.DirectionalLight0.Direction = new Vector3(-0.3f, -0.3f, -0.9f);
        effect.DirectionalLight0.SpecularColor = new Vector3(.7f, .7f, .7f);

        Vector3 v = Vector3.Normalize(new Vector3(-100, 0, -100));
        effect.DirectionalLight1.Enabled = true;
        effect.DirectionalLight1.Direction = v;
        effect.DirectionalLight1.SpecularColor = new Vector3(0.6f, 0.6f, .6f);

        #endregion

        effect.Projection = camera.projectionMatrix;
        effect.View = camera.viewMatrix;
        if (meshObj.isSetInPlace == true)
        {
            effect.World = transforms[meshObj.mesh.ParentBone.Index] * gameobject.orientation; // draw in original cube-placed position
            meshObj.mesh.Draw();
        }
        else
        {
            effect.World = meshObj.Orientation; // draw inSetInPlace position
            meshObj.mesh.Draw();
        }
    }
    temp++;
}

```

# Answer
found out what the problem was. the app was SL/XNA and it was redering the purple flicker because of the rendering of the SL UI. Still, don't know how to overcome this if you want to have objects render behind the SL s

SL draw method

```
 spriteBatch.Begin();
        elementRenderer.Render();
        spriteBatch.Draw(elementRenderer.Texture, Vector2.Zero, Color.White);

        spriteBatch.End();

```
> 1 votes

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


title: Bullet Physics Terrain

text:
# Question
Title: Bullet Physics Terrain
Im trying to Load an RGB image (.BMP) into bullet's btHeightfieldTerrainShape

Im using a loader that creates a openGL height map, it stores the data in a vector float, but I cant get the btHeightfieldTerrainShape to accept it.

I changed the vector float into a float array which contains height data according to the debugger, when loaded it takes forever to load the terrain, and when its loaded it is a flat terrain.

It is alot of code, but I can add it if needed.

The Code

# Answer
First of all, since the elements of a std::vector are guaranteed to be contiguous, you *can* pass it to Bullet with a simple trick:

```
std::vector<float> dataVector = LoadHeightMap();
float* data = &dataVector[0];

```

But realize that data is just a pointer, and the data is still stored within the vector. So make sure you keep the vector alive for as long as you need (more on this further below).

About `btHeightfieldTerrainShape` I'm not sure but I think it makes sense to assume that when passing it an array of floats, they should be normalized in the \[0-1\] range. Is that what your debugger shows you?

Other than that, make sure you're passing `PHY_FLOAT` as the `heightDataType`parameter to the constructor, and choose a reasonable `minHeight` and `maxHeight` pair of values. It would help if you showed the relevant part of your code.

Also notice this note on the documentation:

> The caller is responsible for maintaining the heightfield array; this class does not make a copy.

So make sure you're keeping your vector *alive*. So if for instance you're just using the vector inside the load method and not storing it somewhere else, your data will be gone by the time the load method returns. Store it as a member variable of your class instead, and *then* get a pointer to its data with the trick above.

In other words something like:

```
class Map
{
public:
    Map()
    {
        data = LoadHeightfieldData();
        heightfield = new btHeightfieldTerrainShape(..., &data[0], ...);
    }

private:
    vector<float> data;
    btHeightfieldTerrainShape* heightfield;
}

```

And finally, the length of your data array should obviously correspond to the `width * length` you specify when creating the heightfield.
> 2 votes

---
Tags: c++, opengl, bullet-physics
---


# Question
Title: How to draw equal length line stripes on a parabola?
Simply put I'm making a basketball game. I'm using these equations to predict the ball position and it works fine:

```
x = vx * t
y = vy * t + 0.5 * gravity * t * t

```

But I can't find a way to draw equal length line stripes on the parabola. At this moment I'm using:

```
t = t + dt

```

in which `dt` is the time elapsed in last frame. It works but the line segments would be longer if velocity is larger. Anybody know a way to draw equal length line stripes like the flying trails in Angry Bird? Thanks very much.

I suppose I should calculate the integral on the curve but I can't get it through...

# Answer
The derivative of the ball position is:

```
dx/dt = vx
dy/dt = vy + gravity * t

```

So the derivative of the parabola arc length `s` is, using Pythagora’s theorem:

```
ds/dt = sqrt(vx² + (vy + gravity * t)²)

```

It is possible to write down the integral of `s`. However, the resulting formula is so complex that it cannot be inverted (*ie.* you cannot get back `t` from a given value of `s`) without resorting to quite complex numerical programming.

However, as a reasonable approximation you could decide that `s` is only slightly varying. **For an arc length `l` and a time `t` the next point should be plotted at time `t'` such that:**

```
t' = t + l / sqrt(vx² + (vy + gravity * t)²)

```

I am confident this works pretty well in practice. If this does not give acceptable results, you could choose a smaller value for `l` (*eg.* `l/8`) and only plot one point out of 8.

Here is some code showing how it could be implemented:

```
void drawPointsAlongParabola(Point origin, float vx, float vy, float gravity,
                             float spacing, float duration)
{
    Point v(vx, vy);
    Point g(0, -gravity);

    for (float t = 0; t < duration; t += spacing / length(v + g * t))
        drawPoint(origin + v * t + 0.5 * g * t * t);
}

```
> 6 votes

# Answer
I understand the above answer works fine, but I highly doubt that Angry Birds does anything that clever :P

You should be able to just traverse the line and draw points as you reach each interval.

Something like this (not tested, just off the top of my head):

```
void drawPointsAtInterval(List<Point> points, float pointSpacing) {
    float distanceAlong = 0;

    for(int pt = 0; pt < points.count() - 1; pt ++) {
        Point a = points[pt];
        Point b = points[pt + 1];
        float lineLength = length(b - a);
        Point direction = (b - a) / lineLength;

        while(distanceAlong < lineLength) {
            Point p = a + (distanceAlong * direction);
            drawPoint(p);
            distanceAlong += pointSpacing;
        }

        distanceAlong -= lineLength;
    }
}

```
> 0 votes

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


# Question
Title: As3 Flash How to check if a bitmapdata is completely set to transparent using an eraser?
I'm trying to make a window-cleaning game with flash as3 on the timeline. (Sounds boring I know, but I realy have some fun idea's with it)

So I have: A dirtywindow movieclip on the bottom layer and a clean window movieclip on layer 2(mc1) on the layer above.

To hide the top layer(the dirty window) I assign a mask to it.

```
// this creates a mask that hides the movieclip on top
var mask_mc:MovieClip = new MovieClip();
addChild(mask_mc)

//assign the mask to the movieclip it should 'cover'
mc1.mask = mask_mc;

```

With a brush(cursor) the player wipes of the dirt ( actualy setting the fill from the mask to transparent so the clean window appears)

```
//add event listeners for the 'brush'
brush_mc.addEventListener(MouseEvent.MOUSE_DOWN,brushDown);
brush_mc.addEventListener(MouseEvent.MOUSE_UP,brushUp);

//function to drag the brush over the mask
function brushDown(dragging:MouseEvent):void{
    dragging.currentTarget.startDrag();
    MovieClip(dragging.currentTarget).addEventListener(Event.ENTER_FRAME,erase) ;
    mask_mc.graphics.moveTo(brush_mc.x,brush_mc.y);
}

//function to stop dragging the brush over the mask
function brushUp(dragging:MouseEvent):void{
    dragging.currentTarget.stopDrag();
    MovieClip(dragging.currentTarget).removeEventListener(Event.ENTER_FRAME,erase);
}

//fill the mask with transparant pixels so the movieclip turns visible
function erase(e:Event):void{
    with(mask_mc.graphics){
        beginFill(0x000000);
        drawRect(brush_mc.x,brush_mc.y,brush_mc.width,brush_mc.height);
        endFill();
    }

}

```

I hope you can help me with the following problem: The game-aspect of this should be the points the player get's for cleaning/erasing all the dirt.

Can anyone tell me how I can check if all pixels are set to transparency? So how to check if all the dirt has been erased? And than for example trace ("window cleaned")

---

I tried the compare() function but didn't have much luck with it :(...

# Answer
> 4 votes
A naive approach would be to simply perform a brute-force check on all pixels. As soon as you hit a non-transparent pixel you can stop searching further. This won't work very well with large images and can result in quite extensive searches if the last non-transparent pixels are at the end of the search.

There are two better ways I can think of:

1. Similar to a brute-force check, start in the top-left (`0, 0`) of the image and check every pixel to see if it's non-transparent. If you hit a non-transparent pixel, the image isn't clear yet. So store that position and in the next iteration, start from that pixel instead (because all previous pixels have been marked as transparent anyway, so there's no point in checking them again). Your image will be cleared as soon as your search-position reaches the last pixel in the image.
2. Calculate the sum of total pixels (eg. `image.width * image.height`) and store that in a variable. With every drawing-operation you count the amount of pixels that were set to transparent and subtract this value from the total. As soon as your total hits zero, you cleared all pixels. To count the pixels that turned transparent in one drawing-operation, you sample the brush area (for example by using `bitmap.getPixels()`) and count all the non-transparent pixels *before* you do the drawing operation.

---
Tags: flash, actionscript-3
---


# Question
Title: Which are the most complete DirectX game or technical demo with source available
I have found plenty of games with source for OpenGl, but so far I haven't found anything like that for DirectX. There are plenty of examples in the SDK, but they are very basic and usually they just expose one very specific aspect of the API at a time. So I am wondering which are the best or most complete DirectX games with source available these days.

EDIT

I am making a small study about the differences in the final output across different GPUs. I want to have games in DirectX and OpenGL. To remove any differences caused by non-determinism, like thread scheduling and timing information. I already have done it for Doom 3 which is a great example for OpenGL. I would like to have something in DirectX to perform similar tests with, and I was hoping I could find something better than the simple demos included in the SDK.

# Answer
> 1 votes
If you want to make a comparison of GPU data, it would make sense having the same game that can run on both DirectX and OpenGL. A lot of commercial games do this, but not a lot of source is available.

One suggestion I can make is to have a look at the Darwinia and Multiwinia source code. It's not exactly free, but I believe it makes use of both DirectX and OpenGL and it's not the most expensive thing in the world.

# Answer
> -1 votes
UDK has many complex demos available

---
Tags: directx, open-source
---


# Question
Title: Looking for a simple web interface with subversion support and ticket /issue tracker
I am working on a small project and we have a few programmers on the job. We are using subversion to commit updates and keep all developers up to date on their workstations.

However, we have yet to find a suitable web interface to use for it. I have tried redmine, but that installation progress was extremely bothersome and advanced. Once I got it to work I found out that it was slow and did not meet my expectations. As well as it seems a bit complex for our needs.

I would prefer to find a solution that supports lighttpd web server, however that seem to be very hard to come by, those I have found seem to only have apache support.

Functionality i wish for the website: \- login to an svn account \- view svn logs \- view & create issues, todo list etc \- view svn difference

Do you have any open source recommendations that I can try out? I will appreciate any kind of reply. :)

Edit: I wish to host the website on our own servers.

# Answer
> 4 votes
trac

# Answer
> 0 votes
Recently I dumbed this down for a hobby team game project and stuck with plain Subversion and Trello for basic issue and feature tracking. It works well, though won't scale much. To access Subversion without a client, WebSVN is deployed.

# Answer
> 0 votes
Codeplex is what I've used for this before. Worked like a charm and is completely free.

# Answer
> 0 votes
I use https://bitbucket.org/ but it’s for git or mercurial.

---
Tags: web, interface
---


# Question
Title: Necessary design skills to develop games using Unity, UDK, etc
With my question I want to know if DESIGN 2D/3D skills are necessary in order to create a game using some engine like UDK or Unity.

I have experience as a developer, and experience with openGL, I have also some experience with 3dMax, but Im NOT able to design something from scracth. I simply dont have the skills.

In this kind of engines, is there a way to create and customize levels or characters for example?

Thinking in something related, I will think in the character editor of games like World of Warcraft, etc. I would like to know if the creation of levels and characters would be like that.

# Answer
I'm going through the learning stages on character creation right now, and yes you'll need those skills to make those objects. (I'm a programmer).

I haven't used Unity in almost a year. When I was, I noticed it could only create primitives (cubes, spheres, etc...). So environment creation and character creation were out of the question.

In UDK/UE3 you can do a lot of environment work with their object brushes (create primitives, terrain, edit them, etc...), but the creation of detailed static meshes should still be done by a 3rd party modeling tool (3DSMax, Maya, Blender, etc....). Also for character creation in UDK, that must be done by a 3rd party tool because you need to rig the model.

Hope that helps
> 4 votes

# Answer
Unreal and Unity do not have the kind of feature that you're looking for. There simply isn't a way to easily create a custom character with different sliders and then import it into your game, for that you will have to learn Maya, 3dsMax, or some similar program.

However! Since you have experience as a developer, you should try and feel comfortable with using simple meshes to prototype your games. You don't need all the detail of a animated/rigged/textured cowboy to prove that your game is worth making.

If your design is good and your code is reliable, finding art assets should be the last part you need to worry about.
> 2 votes

---
Tags: game-design
---


# Question
Title: Lag compensation of projectile shooting game
I'm thinking about an algorithm for firing projectiles with lag compensation. Now I did find only one descent solution:

1. Player hits fire button.
2. Client sends input "fire".
3. Client waits for server response.
4. Server generates bullet then sends response to client.
5. Client recieves response and finally fires projectile.

Is this solution only "trueway"? I find it the only one that can be fair to all of the clients. Valve in this case, doesn't compensate lag from rocket shots. I am feeling that I will not compensate it, too. I think that with today's bandwidth I can close my eyes on this problem, because I don't see any solutions with fair logic. What do you think?

# Answer
> 4 votes
Since you mention bullets...

1. player hits fire
2. player immediately draws something
3. client sends command to server
4. server gets fire command
5. server calculates the results, hit or miss
6. server sends result to player
7. player applies the result from the server
8. player draws something to show the result

There is no physical "bullet" flying around, just a phantom drawn locally. You cannot wait 200msec for for server responses or your game will feel sluggish.

Rockets are a totally different subject: they are expected to have an "ignition time" before flying off, they move slowly, they have an area-effect when they hit, some have a small AI guiding them during flight. Bullets are not rocket science.

---
Tags: networking, actionscript-3, game-mechanics
---